Skip to content

Instantly share code, notes, and snippets.

@kobapan
Last active January 10, 2018 08:11
Show Gist options
  • Save kobapan/1e79bfe2d1e64f4faa8362c22e7e5e1e to your computer and use it in GitHub Desktop.
Save kobapan/1e79bfe2d1e64f4faa8362c22e7e5e1e to your computer and use it in GitHub Desktop.
一般ユーザでemacsを起動しているのに、root権限のフィルを編集したくなることが多かったらこれ
;;; sudo.el ---
;; Author: kobapan <[email protected]>
;; Keywords: emacs,lisp
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; -------------------------------------------------
;; 書き込み権限のないファイル/ディレクトリを開くときに、自動的にsudoで開く
;; sudoで開き直すときは、M+x sudo
;; -------------------------------------------------
(defun find-file--sudo (orig-fun &optional filename &rest r)
(if (and (not (file-writable-p filename)) ; 書き込み権限がなかったら
(y-or-n-p (concat filename " is read-only. Open it as root? "))) ; y だったら
(sudo filename) ; /sudo:: で開く
(apply orig-fun `(,filename)) )) ; その他通常のfind-fileで開く
(advice-add 'find-file :around #'find-file--sudo)
(defun sudo (&optional file)
"Open read-only FILE with sudo."
(interactive)
(if file ; find-fileから呼ばれたら
(find-file (concat "/sudo::" file)) ; /sudo:: で開く
(let ((pos (point)))
(find-alternate-file ; /sudo:: で開き直す
(concat "/sudo::" (or (buffer-file-name) list-buffers-directory)))
(goto-char pos))) ; カーソル位置復元
(rename-buffer (concat "sudo:" (buffer-name)))) ; バッファ名の先頭にsudo:を付ける
;; --------------------------------------
(provide 'sudo)
;;; sudo.el ends here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment