org-mode はやっぱり便利

Emacs の org-mode はやはり便利だ。構造化文書を書くための機能が充実している。今回久しぶりに はてな でブログを書くにあたっては、下記サイトを参考に org-mode で下書きを作った。

org-modeからはてなダイアリーに投稿するelispを書いた
http://d.hatena.ne.jp/r_takaishi/20100211/1265888107


simple-hatena-mode を導入していなかったのと、個人的な都合もあって以下のように変更して使った。

(defvar org-export-hatena-notation-section '("^\\* \\([^\t\n\r\f]*\\)\n\\[.*$" "* \\1"))
(defvar org-export-hatena-notation-subsection '("^\\*\\* \\([^\t\n\r\f]*\\)$" "** \\1"))
(defvar org-export-hatena-notation-subsubsection '("^\\*\\*\\* \\([^\t\n\r\f]*\\)$" "*** \\1"))
(defvar org-export-hatena-notation-quote '("[ ]*#\\+BEGIN_QUOTE[ \t]*" ">>" "[ ]*#\\+END_QUOTE" "<<"))
(defvar org-export-hatena-notation-super-pre '("[ ]*#\\+BEGIN_EXAMPLE[ \t]*" ">||" "[ ]*#\\+END_EXAMPLE" "||<"))
(defvar org-export-hatena-notation-src '("[ ]*#\\+BEGIN_SRC[ \t]*\\([^\t\n\r\f]*\\)" ">|\\1|" "[ ]*#\\+END_SRC" "||<"))
(defvar org-export-hatena-temp-buffer-name "*Org Hatena Export*")

(defun org-export-hatena-section (notation)
  (goto-char (point-min))
  (while (re-search-forward (nth 0 notation) nil t)
    (replace-match (nth 1 notation))))

(defun org-export-hatena-begin-to-end (notation)
  (goto-char (point-min))
  (while (re-search-forward (nth 0 notation) nil t)
    (replace-match (nth 1 notation)))
  (goto-char (point-min))
  (while (re-search-forward (nth 2 notation) nil t)
    (replace-match (nth 3 notation))))

(defun org-export-hatena (beg end)
  (interactive "r")
  (let ((diary (buffer-substring beg end))
        (begin-to-end `(,org-export-hatena-notation-quote
                        ,org-export-hatena-notation-super-pre
                        ,org-export-hatena-notation-src))
        (section `(,org-export-hatena-notation-section
                   ,org-export-hatena-notation-subsection
                   ,org-export-hatena-notation-subsubsection))
        (buffer (get-buffer-create
                 (generate-new-buffer-name
                  org-export-hatena-temp-buffer-name))))
    (set-buffer buffer)
    (insert diary)
    (mapc (function org-export-hatena-begin-to-end) begin-to-end)
    (mapc (function org-export-hatena-section) section)
    (switch-to-buffer-other-window buffer)))

上記を .emacs に追記した。変換リージョンを選択して M-x org-export-hatena とすれば、はてな記法に変換されたものが *Org Hatena Export* というテンポラリバッファに格納される。これをコピペしてブラウザからはてなへ投稿。ほんとは simple-hatena-mode を導入して投稿まで自動化させるべきですね。