$shibayu36->blog;

クラスター株式会社のソフトウェアエンジニアです。エンジニアリングや読書などについて書いています。

emacsで編集中のファイルをデフォルトブラウザで開く

 emacsで編集しているファイルのディレクトリをFinderで開く - $shibayu36->blog;をやってたら、デフォルトブラウザで開くのもできた。適当にhtmlとかuserscriptとか書いてたら便利かもしれない。

default-browser

 http://www.leancrew.com/all-this/2012/04/default-browser-script/ あたりから、default browserを取得するスクリプトを持ってくる。~/bin/辺りに置く。

elisp

(defun browse-current-file ()
  (interactive)
  (let ((data-url
         (concat "file://" (buffer-file-name)))
        (default-browser
          (replace-regexp-in-string "[\n\r]+$" ""
            (shell-command-to-string (expand-file-name "~/bin/default-browser")))))
    (shell-command (concat "open -b " default-browser " " data-url))))

こんな感じ。

  • txtでもなんでも開けるように、openが自動的にdefault browserを使う機能は使わない
  • expand-file-nameを使って~とかを絶対パスに変換する
  • shell-command-to-stringを使うと、コマンドの出力を文字列として受け取れる
  • chompするにはreplace-regexp-in-stringとかしないとできない

chompが一番苦労して辛かった。