运行 emacs 处于 sudo 模式时保留用户的配置

Keep the user's configuration when running emacs in sudo mode

我必须在 sudo 模式下 运行 emacs,以编辑我的 /var/www 目录中的一些 .html 或 .php 文件。 当我在普通用户模式下 运行 它时,语法和颜色都没有问题(我安装了 php-mode.el 扩展)。不幸的是,当我 运行 它处于 sudo 模式时,我丢失了这个配置。 有什么办法可以取回吗?

Unfortunately when I run it in sudo mode, I loose this configuration, which is sad.

这完全符合预期。当您 运行 使用 sudo 的命令时,您 运行 将其作为不同的用户使用,通常是 root。在大多数情况下,将使用目标用户的配置。

Is there any way to get it back ?

我认为这里最好的选择是正常 运行 Emacs,然后使用 TRAMP将文件 编辑为 root。在这种情况下,我认为在文件前加上 /sudo:: 就可以了,例如C-x C-f /sudo::/var/www/html/foo.php RET。 Emacs 会提示您输入密码,就像 sudo 在命令行中一样。

TRAMP 的功能远不止让您通过 sudo 将某些文件编辑为 root,您可能值得花时间浏览它的手册。

您不太可能需要 运行 sudo emacs,并且不必要地 运行 root 权限是一种不好的做法。

sudoedit命令/sudo -e选项的存在是为了编辑其他用户拥有的文件。将使用的编辑器在手册 (man sudo) 的 -e 选项说明下进行了描述:

The editor specified by the policy is run to edit the temporary files. The sudoers policy uses the SUDO_EDITOR, VISUAL and EDITOR environment variables (in that order). If none of SUDO_EDITOR, VISUAL or EDITOR are set, the first program listed in the editor sudoers(5) option is used.

使用这种方法,您将以普通用户身份编辑文件,因此使用普通编辑器配置。

或者,根据 Chris 的回答,使用 Emacs 中内置的 Tramp 方法(如果您正在编辑许多文件,这很可能更简单)。

如果这些文件是您通常需要具有写入权限的文件,也许您应该将自己分配到具有写入权限的组。