Emacsのorg-modeを保存すると自動的にhtmlにexportされブラウザーが更新されるようにする

org-modeで文書を書いていてhtmlにexportする際は,C-e h oとするわけだが,段々とこれが面倒になってくることがある.そこで,ネットを探ってみると,やはり,なんでも載ってるredditにhtml exportを自動化する関数の記事があった.

toggle-org-html-export-on-save

例によって,下記のようにinit.orgに書き込めばよい.

#+begin_src emacs-lisp
(defun toggle-org-html-export-on-save ()
  (interactive)
  (if (memq 'org-html-export-to-html after-save-hook)
      (progn
        (remove-hook 'after-save-hook 'org-html-export-to-html t)
        (message "Disabled org html export on save for current buffer..."))
    (add-hook 'after-save-hook 'org-html-export-to-html nil t)
    (message "Enabled org html export on save for current buffer...")))
#+end_src

これで,toggle-org-html-export-on-saveで,htmlを自動で出力するかどうかを切り替え可能となる.しかし,これだけでは,org文書を保存するたびにブラウザーを手動でreloadしないといけなくなり,面倒である.自動でreloadしてくれるコマンドがあれば便利である.探してみると,これもネットに転がっていた.

directoryの内容が変更されると,自動でhtmlを再読込する.

#!/usr/bin/env ruby
# watch.rb by Brett Terpstra, 2011 <http://brettterpstra.com>
# with credit to Carlo Zottmann <https://github.com/carlo/haml-sass-file-watcher>

trap("SIGINT") { exit }

if ARGV.length < 2
   puts "Usage: #{$0} watch_folder keyword"
   puts "Example: #{$0} . mywebproject"
   exit
   end

   dev_extension = 'dev'
   filetypes = ['css','html','htm','php','rb','erb','less','js']
   watch_folder = ARGV[0]
   keyword = ARGV[1]
   puts "Watching #{watch_folder} and subfolders for changes in project files..."

   while true do
         files = []
         filetypes.each {|type|
files += Dir.glob( File.join( watch_folder, "**", "*.#{type}" ) )
                        }
         new_hash = files.collect {|f| [ f, File.stat(f).mtime.to_i ] }
         hash ||= new_hash
         diff_hash = new_hash - hash

         unless diff_hash.empty?
         hash = new_hash

         diff_hash.each do |df|
             puts "Detected change in #{df[0]}, refreshing"
         %x{osascript<<ENDGAME
                tell app "Safari" to activate
                tell app "System Events"
                     keystroke "r" using command down
                end tell
ENDGAME
           }
         end
         end

         sleep 1
         end
  • このスクリプトにwatch_safari.rbという名前をつけてパスが通っている/usr/local/binに保存し,chomod a+x watch_safari.rbとして実行権限を付けた.
  • Usage: /usr/local/bin/watch_safari.rb watch_folder keyword
  • パスを通しておけば,watch_safari.rb watch_folder keyword で大丈夫

使用方法

  • /Data/Hoge/Fuga/hogefuga.orgを書いているとすると以下のようにそのディレクトリをみはらせておく.
$ cd /Data/Hoge
$ watch_safari.rb Hoge hogefuga.html
  • org-modeでhogefuga.orgを書きはじめるときに,M-x toggle-org-html-export-on-save として保存するたびに自動的に新たなhtmlがexportされるようにする.
  • 最初だけは,C-e h oでhtmlをexportして,safariでhogefuga.htmlを開いておく.
  • 以降は,hogefuga.org文書を保存するたびに,現在見ている場所に戻った状態で最新のhtmlに更新されるようになる.便利である.

以上はOSX上のSafariを使用している場合であるが,他のブラウザーでも少し変更するだけで同じことができるはずである.

Avatar
taipapa
本人ではありません (^^)

Related

Next
Previous
comments powered by Disqus