僕ぐらいのものぐさ男になるとターミナル開くのもめんどくさくなって、簡単なキーボード操作でサクッと新規投稿を始めたくなります。というわけであまり使ったことのないAppleScriptをひさびさに書いてみました。
動作の流れ
- ダイアログにスラッグ(yyyy-mm-dd-slug.mdのslugの部分)を入力
- ファイル作成
- ファイルにテンプレートを書き込み
- エディターでファイルを開く
設定
環境に応じて3つの変数の内容を変更してください。
postdir
はHFSパスなので注意してください。
ソースコード
-- 設定
set timezone to "+09:00"
set postdir to "Macintosh HD:Users:kerotaa:Sites:kerotaa.github.com:_posts"
set editor to "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl"
-- 日付取得
set dt to (current date)
on date_to_iso(dt)
set {year:y, month:m, day:d} to dt
set y to text 2 through -1 of ((y + 10000) as text)
set m to text 2 through -1 of ((m + 100) as text)
set d to text 2 through -1 of ((d + 100) as text)
return y & "-" & m & "-" & d
end date_to_iso
on date_time_to_iso(dt, timezone)
set {year:y, month:m, day:d, hours:h, minutes:min, seconds:s} to dt
set y to text 2 through -1 of ((y + 10000) as text)
set m to text 2 through -1 of ((m + 100) as text)
set d to text 2 through -1 of ((d + 100) as text)
set h to text 2 through -1 of ((h + 100) as text)
set min to text 2 through -1 of ((min + 100) as text)
set s to text 2 through -1 of ((s + 100) as text)
return y & "-" & m & "-" & d & "T" & h & ":" & min & ":" & s & timezone
end date_time_to_iso
-- 置換
on replaceText(theText, serchStr, replaceStr)
set tmp to AppleScript's text item delimiters
set AppleScript's text item delimiters to serchStr
set theList to every text item of theText
set AppleScript's text item delimiters to replaceStr
set theText to theList as string
set AppleScript's text item delimiters to tmp
return theText
end replaceText
-- ファイル作成
on create_post_file(postdir, filename)
tell application "Finder" to make new file with properties {name:filename} at alias postdir
end create_post_file
-- ファイル書き込み
on write_post_file(postdir, filename, iso_datetime)
set filepath to {postdir & ":" & filename} as text
set input_text to {"---
title:
layout: post
date: " & iso_datetime & "
categories: []
tags: []
---
"} as text
try
set fn to open for access file filepath with write permission
set eof of fn to 0
write input_text to fn
close access fn
end try
end write_post_file
-- エディターで開く
on open_file_with_editor(postdir, filename, editor)
set filepath to {postdir & ":" & filename} as text
set filepath_std to replaceText(replaceText(filepath, ":", "/"), "Macintosh HD", "")
do shell script {"'" & editor & "' '" & filepath_std & "'"} as text
end open_file_with_editor
-- メイン
display dialog "スラッグを入力してください:" default answer ""
set slug to text returned of result
set iso_date to date_to_iso(dt)
set iso_datetime to date_time_to_iso(dt, timezone)
set filename to {iso_date & "-" & slug & ".md"} as text
create_post_file(postdir, filename)
write_post_file(postdir, filename, iso_datetime)
open_file_with_editor(postdir, filename, editor)
enjoy wink