When you have to edit system files, it's an usual situation that you launched Emacs with a normal user before, so the file will be write-protected. What can I do to gain root privileges? I mean something like M-x sudo from dired.

I don't want to launch Emacs as super-user and I don't want to quit it.

up vote 41 down vote accepted

Use C-x C-f and type out /su::/etc/hostname or /sudo::/etc/hostname as applicable.

This uses the TRAMP package, which is distributed with Emacs. This package provides access to remote files, and more generally to files that Emacs can't open directly.

  • 1
    Thanks. What is the meaning of the :: ? – smonff Sep 23 '14 at 22:29
  • 6
    The : is a separator; we supply it the second time to indicate that there are no more arguments. You can /su:otheruser@localhost:, for instance. – artagnon Sep 23 '14 at 22:51
  • 2
    /sudo:: is tramp shorthand for sudo:root@<hostname>: – phils Oct 6 '17 at 6:48

Use find-file with tramp. At the prompt /sudo::/etc/ssh/ssh_config will use sudo and a subshell to open that file with root privileges. When sudo is first used it will prompt for a password, but until that session closes you can edit any file with those permissions by prefixing with the existing /sudo:: command.

See http://www.gnu.org/software/tramp/ for more details.

For later readers of this question I share this package that gives an interesting solution to this problem.

You will find the dired-toggle-sudo package on Melpa. After asking this question, I found this solution unpackaged from Damien Cassou, that has been packaged later.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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