Saturday, September 18, 2010

Reopen a buffer as root prompting for password if necessary

(defun find-alternative-file-with-sudo ()
"Open current buffer as root!"
(when buffer-file-name
(concat "/sudo:root@localhost:"

(global-set-key (kbd "C-x C-r") 'find-alternative-file-with-sudo)

My Emacs Files At GitHub

1 comment:

  1. I took this and ran with it.

    (defun toggle-sudo-edit (&optional buf)
    "Toggle BUF between editing as root and normal user.

    Default BUF is current buffer. The positions of point and mark
    are preserved through the toggle."
    (let* ((buf (or buf (current-buffer)))
    (old-point (with-current-buffer buf (point)))
    (old-mark (with-current-buffer buf (mark)))
    (filename (buffer-file-name buf))
    (root-string "/sudo:root@localhost:")
    (currently-root (string-match-p (concat "^" root-string) filename))
    (new-filename (if currently-root
    (substring filename (length root-string))
    (concat root-string filename))))
    (find-alternate-file new-filename)
    (goto-char old-point)
    (set-mark old-mark)))