We've already discussed editing root-owned files here a few times; it's one
of those tasks where in a reflex I still open a terminal and use vi
to do
the job… the only way to overcome that seems to be to make it really
easy to do the same from within my running emacs:
(defun djcb-find-file-as-root () "Like `ido-find-file, but automatically edit the file with root-privileges (using tramp/sudo), if the file is not writable by user." (interactive) (let ((file (ido-read-file-name "Edit as root: "))) (unless (file-writable-p file) (setq file (concat "/sudo:root@localhost:" file))) (find-file file))) ;; or some other keybinding... (global-set-key (kbd "C-x F") 'djcb-find-file-as-root)
We could take it one step further still – overload the normal
(ido-)find-file
with a version that checks the permissions first, and if
needed, use the above function to open it. But maybe that is too easy; we
should be careful with root-owned files after all.
9 comments:
i use a little bit complicated stuff:
(defcustom find-file-root-prefix "/sudo::"
"Tramp root prefix to use.")
(defadvice find-file-noselect
(before add-root-prefix (filename &optional nowarn rawfile wildcards))
"Add tramp prefix to filename"
(and (bound-and-true-p root-prefix)
(yes-or-no-p "Use root privileges? ")
(setq filename (concat root-prefix filename))))
(ad-activate 'find-file-noselect)
(defun find-file-as-root ()
"Find file using root privileges"
(interactive)
(let ((root-prefix find-file-root-prefix))
(call-interactively (if ido-mode 'ido-find-file 'find-file))))
(defun find-current-as-root ()
"Reopen current file as root"
(interactive)
(set-visited-file-name (concat find-file-root-prefix (buffer-file-name)))
(setq buffer-read-only nil))
(global-set-key (kbd "M-s C-x C-f") 'find-file-as-root)
(global-set-key (kbd "M-s C-x C-v") 'find-current-as-root)
// see https://github.com/a13/emacs.d/blob/master/lib/mine.el
Awesome; thanks!
I have the same reflex, though with nano instead of vi.
Let’s see if your code helps me overcome it. Thanks a lot!
I run into the same problem all the time and end up reverting to vi. Using your idea I came up with this which I will try to stick to using.
(defun stw-find-file-as-root ()
(interactive)
(find-file (concat "/sudo::" (buffer-file-name))))
Thanks for the idea!
Even if you're on a terminal there's no reason to use vi. I use a simple alias
alias E='sudo -e'
Of course your $EDITOR variable has to be pointing to emacslient, but I'm sure it is already...
Thanks Anonymous of "a little bit complicated stuff". Great idea. I've copied it over to .emacs.
I use "sudoedit". As David pointed out in a previous comment, if your $VISUAL and $EDITOR are set to emacsclient -t and -c respectively, it works beautifully.
Post a Comment