One of the times when many emacs-users still reach for vi
is when editing
system configuration files – the stuff in /etc/
, etc. I think that is
because of the now mostly false impression that emacs
startup is slow, and
because people don't want to run an open-ended program as emacs as root
.
There is truth in that last point – but it applies just as well to, say,
vim. Anyway, running emacs
as root is not a good idea.
So how what can we do it? Easy! Using the tramp
package (included with
GNU/Emacs since version 22), you can run emacs as a normal user, but edit
root-and-other-owned files. It does its magic using sudo, but you won't
normally notice. It does require you to have sudo
-rights of course.
How does this work? Well, instead of
C-x C-f /etc/hosts
to open a file as a normal user, you use:
C-x C-f /sudo:root@localhost:/etc/hosts
or even shorter, as noted by Alexander Kojevnikov (because Tramp defaults to
root@localhost
):
C-x C-f /sudo::/etc/hosts
It asks for a password - and you should use your user password for that (not
the root password!). This usually works fine, but due to way Tramp works, it
can get confused if root has some very weird command prompt. If
so, you of course configure tramp. Also note that sudo usually remembers
that you logged in, an does not require you to re-enter you password when
opening ('visiting') another file for some time period – but you can change
this. See the sudo(8)
.
This automatically invokes tramp
which does all the magic for you. If you
don't like the somewhat longer (pseudo)paths for files, you can of course use
the emacs bookmarks facilty. After you load the file, you can use it like any
other file.
Note, this is only of the many useful things you can do with Tramp. Tramp
was actually written for editing files on remote machines (using ssh
or
other protocol), and I very happily used it to edit files on some European
machine whilst in Australia. It caches the file locally, and only sends it
over when you save it, so it very fast – it simply makes you forget your file
is so far away.