I'm using the C-x C-f option to use SSH to edit a file.

The file I'm editing requires my SSH user to use sudo.

When I start editing the file it says read-only. How can I remotely edit files requiring sudo?

  • 2
    I'm not 100% sure what is the convention for dealing with questions already answered elsewhere in the stackexchange network ("cross-site duplicates"), but this question on stackoverflow has a detailed (and looking at the current manual, still up-to-date) answer.
    – aplaice
    Nov 21 '17 at 15:14

Using TRAMP multi-hops. For instance, if you want to edit the remote file /root/salary.txt


The example is taken from the Mastering Emacs book.


I wrote a command for automating @Manuel Uberti's answer. The second one is the one I'd use. It uses the first one for remote files and uses crux for local files.

(require 'crux)
(require 's)

(defun my--reopen-remote-file-as-root ()
  "Reopen a remote file as root over tramp."
  (find-alternate-file (let* ((parts (s-split ":" buffer-file-name))
            (hostname (nth 1 parts))
            (filepath (car (last parts))))
           (concat "/ssh" ":" hostname "|" "sudo" ":" hostname ":" filepath))))

(defun my/reopen-file-as-root ()
  "Reopen a local or remote file as root."
  (if (file-remote-p default-directory)
  • It doesn't check if current buffer is already opened with sudo(contains "sudo" in its name). May 1 '20 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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