97

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.

smonff
  • 1,575
  • 1
  • 15
  • 20

5 Answers5

125

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.

artagnon
  • 2,237
  • 1
  • 15
  • 17
14

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.

dgtized
  • 4,169
  • 20
  • 41
13

There are today many packages that solve this problem (as of 2018). Some of them are:

  • sudo-edit, allows to switch editing rights on an already opened read-only file. Just M-x sudo and type a password and you're done. After many years of use of this one, I think it is the more convenient for this need. sudo-edit allows you to open a file as any user, but it default on sudo if none provided.
  • dired-toggle-sudo. It was the first packaged solution I found after asking this question. It is Dired oriented, so if you prefer the file oriented version, see the first bullet of this list.
  • Other solutions exists on Melpa
smonff
  • 1,575
  • 1
  • 15
  • 20
7

If you use Helm. You don't need any external package / additional config. it works out of the box.

Inside helm-find-files you can invoke find file as root which bound to C-c r. This works for files or directories in helm-find-files session.

If you don't want to type password every time you open root files/dirs. Put the following line to your ~/.authinfo.gpg

machine localhost port sudo login root password xxxxxx
machine your_machine_name port sudo login root password xxxxx

source

azzamsa
  • 634
  • 7
  • 16
6

If you use the ivy package, and have configured counsel-find-file to replace find-file, then one of the "ivy actions" pre-configured for you already is to edit the file as root. The default hydra keystroke for that action is r.

user1404316
  • 769
  • 5
  • 12