Raúl Benencia


Emacs server, systemd and XAUTHORITY

Running Emacs as a systemd service should be relatively straightforward if using its Debian package, given that it comes with a systemd unit.

Here’s a fragment:

$ cat /usr/lib/systemd/user/emacs.service | head -n7
[Unit]
Description=Emacs text editor
Documentation=info:emacs man:emacs(1) https://gnu.org/software/emacs/

[Service]
Type=notify
ExecStart=/usr/bin/emacs --fg-daemon

However, I’ve faced the following problem: when running emacsclient from a graphical interface, nothing happened, and it was not clear what to do next.

To unravel these kind of problems, we should always start by checking the logs. An interesting line showed up:

$ journalctl  --user -u emacs.service
...
May 18 16:51:51 zorzal emacs[1308]: Authorization required, but no authorization protocol specified
...

After some digging, I realized this happens because the Emacs server was started before the XAUTHORITY variable was set, and we need that variable to communicate with the display server.

A quick search didn’t show a straightforward or clean solution. Remediating this problem should be relatively simple: we just need to instruct systemd to start the Emacs server after the graphical session. systemd comes preloaded with a special target that can be used for this purpose: graphical-session.target.

A systemd drop-in file can be used to establish this dependency:

$ cat ~/.config/systemd/user/emacs.service.d/override.conf
[Unit]
Requires=graphical-session.target

To pick-up the override, we must remember to run: systemd --user daemon-reload.

Why isn’t this a default in the shipped unit file? I suppose we can’t assume the user will always have a graphical session when launching an Emacs server, so it wouldn’t be safe to make it a default.