fnwiya's quine

自分自身を出力するブログ

emacsでルート権限が必要なファイルを開く

emacs上でファイルを開くときにルート権限が必要だとReadOnlyになったりしてつらいです。
そこでroot権限が必要なときは自動で切り替えてくれる設定を導入しました。

(defun th-rename-tramp-buffer ()
  (when (file-remote-p (buffer-file-name))
    (rename-buffer
     (format "%s:%s"
             (file-remote-p (buffer-file-name) 'method)
             (buffer-name)))))

(add-hook 'find-file-hook
          'th-rename-tramp-buffer)


(defadvice find-file (around th-find-file activate)
  "Open FILENAME using tramp's sudo method if it's read-only."
  (if (and (not (file-writable-p (ad-get-arg 0)))
           (y-or-n-p (concat "File "
                             (ad-get-arg 0)
                             " is read-only.  Open it as root? ")))
      (th-find-file-sudo (ad-get-arg 0))
    ad-do-it))

(defun th-find-file-sudo (file)
  "Opens FILE with root privileges."
  (interactive "F")
  (set-buffer (find-file (concat "/sudo::" file))))

この状態でroot権限が必要なファイルを開こうとすれば、
Open it as root?と尋ねてくれるのでyes/yで開けます。
いちいちsudoしたりchmodしなくてよくなるので非常に快適です。

こちらを参考にさせていただきました。
Re-open read-only files as root automagically | Tassilo's Blog