Search code examples
linuxterminalemacsdot-emacs

Emacs loading user configuration file after su to root


On my ArchLinux number cruncher I have two accounts: A user account (benj) and the root account.

For administrative tasks I ssh into the machine using my user account. With the shell open, I switch to root using su .

Running emacs now shows an error that something went wrong during initialisation

Warning (initialization): An error occurred while loading ‘/home/benj/.emacs.d/init.el’:

File is missing: Cannot open load file, No such file or directory, ~/.emacs.d/init-modules/emacs-lisp-package-archive.el

To ensure normal operation, you should investigate and remove the cause of the error in your initialization file.  Start Emacs with the ‘--debug-init’ option to view a complete error backtrace.

My ~benj/.emacs.d/init.el is modular while ~root/.emacs.d/init.el is not. I don't understand why emacs is trying to load my user's configuration file.

echo $HOME              # Shows /root
alias | grep emacs      # Shows nothing
which emacs             # /user/bin/emacs
emacs --version         # GNU Emacs 26.1
                        # Copyright (C) 2018 Free Software Foundation, Inc.
                        # GNU Emacs comes with ABSOLUTELY NO WARRANTY.
                        # You may redistribute copies of GNU Emacs
                        # under the terms of the GNU General Public License.
                        # For more information about these matters, see the file named COPYING.

However, when logging into root on TTY1 , M-x describe-variable on user-init-file returns the expected /root/.emacs.d/init.el


Solution

  • C-hig (emacs)Find Init says:

    How Emacs Finds Your Init File

    Normally Emacs uses the environment variable ‘HOME’ (*note HOME: General Variables.) to find ‘.emacs’; that’s what ‘~’ means in a file name. If ‘.emacs’ is not found inside ‘~/’ (nor ‘.emacs.el’), Emacs looks for ‘~/.emacs.d/init.el’ (which, like ‘~/.emacs.el’, can be byte-compiled).

    However, if you run Emacs from a shell started by ‘su’, Emacs tries to find your own ‘.emacs’, not that of the user you are currently pretending to be. The idea is that you should get your own editor customizations even if you are running as the super user.

    More precisely, Emacs first determines which user’s init file to use. It gets your user name from the environment variables ‘LOGNAME’ and ‘USER’; if neither of those exists, it uses effective user-ID. If that user name matches the real user-ID, then Emacs uses ‘HOME’; otherwise, it looks up the home directory corresponding to that user name in the system’s data base of users.