Toggle between root & non-root in Emacs with Tramp

I love that I can edit files on remote hosts right from the comfort of my local Emacs session. Even better, you can edit those same files as root, given the proper configuration.

Unfortunately, the interface for this is a bit fiddly. I find myself taking one of two approaches:

  1. Open a file as non-root, then hit C-x C-v and edit the filename to use /sudo:root@….
  2. Hit C-x C-f, edit the directory to use /sudo:root@…, then open the file I want.

Since I didn’t like either of these, I wrote two functions to assist:

I bind these to C-c C-x C-q and C-c x f, respectively.

There are two caveats. The first is that you must have tramp-default-proxies-alist configured for the sudo method to work on remote hosts. The second is that it is impossible to know for sure what the previous file name was after invoking toggle-alternate-file-as-root. Any buffer-local values are lost after replacing the buffer with the sudo version, and if I used a persistent structure outside of the buffer, it would require more complexity to prevent it from going stale. So instead, it just make a best effort to come up with something reasonable. Edge cases are going to fail, such as when you are editing a file as another non-root user. Patches are welcomed.

2011/01/18
Previously On Atomized:

Discussion

Monkey patching tramp allows to bypass the need for proxy setup entirely. You can simply C-x C-f /sudo:user@remote:/path/to/file. Ok monkey patching ain’t pretty, but it beats having to setup proxy alist hands down as far as I’m concerned :)

http://paste.lisp.org/display/118788

dim
2011/01/19

Can you publish the code to your find-file-as-root function?

Thanks

Edge
2011/01/19

Edge, it’s embedded in a Gist in my post. You can also find it here: https://gist.github.com/785600

Ian
2011/01/19

Participate