Right now, I have the following in my init

(defun my-edit-file-as-root ()
  "Find file as root"
  (find-alternate-file (concat "/su:root@localhost:" buffer-file-name)))

(defun my-edit-file-as-root-maybe ()
  "Find file as root if necessary."
  (unless (and buffer-file-name (file-writable-p buffer-file-name))
    (when (y-or-n-p "File is not writable. Open with root? ")

(add-hook 'find-file-hook #'my-edit-file-as-root-maybe)

(a distant child of this code)

Unfortunately, this obviously doesn't work if I'm already using TRAMP (because it blindly concatenates the /su... at the beginning).

I don't know TRAMP internals well enough to determine how to flexibly parse TRAMP filenames and determine what to add to get root access.

How can I modify this to work when already using TRAMP (possibly with multi-hops already in use)?

2 Answers 2


Based on the advice of politza and wvxvw:

(defun my-edit-file-as-root ()
  "Find file as root"
    ((sudo (/= (call-process "sudo" nil nil "-n true") 0))
        (if (tramp-tramp-file-p buffer-file-name)
          (with-parsed-tramp-file-name buffer-file-name parsed
              (if sudo "sudo" "su")
              (let ((tramp-postfix-host-format "|")
          (concat (if sudo
    (find-alternate-file file-name)))

This seems to work perfectly in all the cases I tested.


Tramp can jump over multiple hops separated by pipe, here's the relevant documentation: http://www.gnu.org/software/tramp/#Ad_002dhoc-multi_002dhops

  • 1
    Yes, and I could potentially implement my function as a bunch of regex driven transforms, but that strikes me as being pretty hacky. I'll need to skip back to the last pipe, if there is a pipe, and if that pipe is not escaped. Then I'll need to skip forward to the last colon of that block (might be the first or second colon, depending on the format) if that colon is not escaped etc. If that's the only way, then I'll dive in, but I'm hoping there's some way to get TRAMP to parse its own filenames, and simplify things.
    – PythonNut
    Commented May 7, 2015 at 19:36
  • with-parsed-tramp-file-name ?
    – politza
    Commented May 7, 2015 at 20:46
  • @PythonNut either as politza said, or you could use tramp-dissect-file-name and a bunch of tramp-file-name-* functions which will work on the parsed file name. The macro mentioned above uses this function internally.
    – wvxvw
    Commented May 7, 2015 at 21:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.