2013-03-17

editing with root-privileges -- once more

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.