Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a file with su/sudo inside Emacs

The nice thing about Tramp is that you only pay for that round-trip to SSH when you open the first file. Sudo then caches your credentials, and Emacs saves a handle, so that subsequent sudo-opened files take much less time.

I haven't found the extra time it takes to save burdening, either. It's fast enough, IMO.


Tramp does not round-trip sudo via SSH, it uses a subshell. See the manual: https://www.gnu.org/software/tramp/#Inline-methods

Therefore, I recommend that you stick with TRAMP.


If you use helm, helm-find-files supports opening a file as root with C-c r.


Not really an answer to the original question, but here's a helper function to make doing the tramp/sudo route a bit easier:

(defun sudo-find-file (file-name)
  "Like find file, but opens the file as root."
  (interactive "FSudo Find File: ")
  (let ((tramp-file-name (concat "/sudo::" (expand-file-name file-name))))
    (find-file tramp-file-name)))

At least for saving, a sudo-save package was written exactly for that kind of problem.


Your example doesn't start ssh at all, at least not with my version of TRAMP ("2.1.13-pre"). Both find-file and save-buffer work great.


I recommend you to use advising commands. Put this function in your ~/.emacs

(defadvice ido-find-file (after find-file-sudo activate)
  "Find file as root if necessary."
  (unless (and buffer-file-name
               (file-writable-p buffer-file-name))
    (find-alternate-file (concat "/sudo:root@localhost:" buffer-file-name))))