在 Tramp 中切换成 root 用户编辑当前文件

我以普通用户访问了远程文件后,如 /ssh:xcy@vps:/etc/nginx/nginx.conf,发现需要切换成 root 用户修改文件,手动从输入一次文件名有点麻烦,所以我写了一个命令自动化这个简单的需要:

(defun chunyang-edit-file-as-root ()
  (interactive)
  (let ((file buffer-file-name))
    (and file
         (file-remote-p file)
         (not (string= "root" (file-remote-p file 'user)))
         (find-alternate-file
          (tramp-make-tramp-file-name
           (file-remote-p file 'method)
           "root"
           (file-remote-p file 'host)
           (file-remote-p file 'localname))))))

基本上就是把

(find-file "/ssh:xcy@vps:/etc/nginx/nginx.conf")

转换成

(find-file "/ssh:root@vps:/etc/nginx/nginx.conf")

ELPA 上有个 sudo-edit,可以以 sudo 编辑当前的文件。如果你的远程主机上有装 sudo 并且配置好了的话,可以用它。

我发现用 Emacs 原生的 find-file 很容易解决——直接在 minibuffer 中改成 root 就完了,之所以之前没想到是因为我把 C-x C-f 绑定到了 Ivy 的 counsel-find-file,它好像把 /ssh:xcy@vps: 设成不可编辑。