The SSH host key has changed on 8 April, 2022 to this one: SHA256:573uTBSeh74kvOo0HJXi5ijdzRm8me27suzNEDlGyrQ
Sources of the site gergely.polonkai.eu, Jekyll version
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1.7 KiB

Edit file as another user in Emacs

date

2016-11-10T08:57:12Z

category

blog

tags

development,emacs

url

2016/11/10/edit-file-as-other-user-in-emacs/

save_as

2016/11/10/edit-file-as-other-user-in-emacs/index.html

status

published

author

Gergely Polonkai

I have recently found this article by Bozhidar Batsov on opening the current file as root. I barely use tramp for sudo access, but when I do, I almost never use root as the target user. So I decided to fix it for my needs.

(defun open-this-file-as-other-user (user)
  "Edit current file as USER, using `tramp' and `sudo'.  If the current
buffer is not visiting a file, prompt for a file name."
  (interactive "sEdit as user (default: root): ")
  (when (string= "" user)
    (setq user "root"))
  (let* ((filename (or buffer-file-name
                       (read-file-name (format "Find file (as %s): "
                                               user))))
         (tramp-path (concat (format "/sudo:%s@localhost:" user) filename)))
    (if buffer-file-name
        (find-alternate-file tramp-path)
      (find-file tramp-path))))

If the user is not specified, the default is still root. Also, if the current buffer is not visiting a file, I prompt for a filename. As I’m not an ido user, I didn’t bother calling ido-read-file-name; helm overrides read-file-name for me anyway.

Unlike Bozhidar, I barely use this feature, so I didn’t bind this to a key.