EmacsWiki: Sudo Save (original) (raw)

Overview

sudo-save.el is a quick package to save files as root on the local box. If you have ‘sudo’ installed and you have permission to edit files (and can cache passwords) then Emacs will run chmod on the file before and after you save it. This comes in handy for a local laptop when TrampMode and HoboMode are overkill. On my machine at least these have characteristics that are undesirable (including IO block).

Lisp:sudo-save.el

Thanks to DryiceLiu for saving this package, as the original url is dead. His mirror:

To use

sudo-save must be loaded before opening the file you want to edit via sudo. Place sudo-save.el somewhere in your LoadPath. If you want it ready for use all the time, add (require 'sudo-save) to your .emacs. Else load it up before use with M-x load-library RET sudo-save RET. Open files as usual with C-x C-f and save files as usual with C-x C-s.

It appears that sudo-save only works if sudo already has your password cached or you have NOPASSWD set.


There is another sudo wrapper here:

It handles password queries from sudo and allows you to find files you could not otherwise open. – ScottVokes

For sudo.el: Integration with standard file save hooks:

(defun sudo-before-save-hook () (set (make-local-variable 'sudo:file) (buffer-file-name)) (when sudo:file (unless(file-writable-p sudo:file) (set (make-local-variable 'sudo:old-owner-uid) (nth 2 (file-attributes sudo:file))) (when (numberp sudo:old-owner-uid) (unless (= (user-uid) sudo:old-owner-uid) (when (y-or-n-p (format "File %s is owned by %s, save it with sudo? " (file-name-nondirectory sudo:file) (user-login-name sudo:old-owner-uid))) (sudo-chown-file (int-to-string (user-uid)) (sudo-quoting sudo:file)) (add-hook 'after-save-hook (lambda () (sudo-chown-file (int-to-string sudo:old-owner-uid) (sudo-quoting sudo:file)) (if sudo-clear-password-always (sudo-kill-password-timeout))) nil
t
)))))))

(add-hook 'before-save-hook 'sudo-before-save-hook)

FedorZhigaltsov

Unfortunately for me, sudo.el does not switch read-only mode off when root files are opened from a terminal in emacsclient. And WARNING: if you try to set read-only flag off yourself and save the file then it will error out and leave the file chowned as normal user, rather than root. Can anyone else confirm this is the case? Or do I have some conflicting elisp in my configs?

– rodyaj


There is another way to save a file using sudo. This is the function I am using:

(defun sudo-save () (interactive) (if (not buffer-file-name) (write-file (concat "/sudo:root@localhost:" (ido-read-file-name "File:"))) (write-file (concat "/sudo:root@localhost:" buffer-file-name))))

– erreina