My new emacs setup (no .emacs here, don’t worry)

After having used emacs for a couple of months now, I discovered the emacs --daemon option today and was astonished. Having quite a big emacs config, it takes ages for emacs to start preventing me from using it as the standard editor for config files etc. The --daemon mode starts emacs in the background acting as a server and allows one to create emacs frames using the emacsclient in various ways. EMacs shows up lightning-fast then and becomes an option for the always-to-use text editor.



Here is my setup on how to work with emacs and use it as an editor for quickly editing files on the command line.

Starting the daemon using systemd

I switched from sysVinit to systemd some time ago, so the most convenient thing to do is to start the emacs daemon using a custom systemd service file. Put the following code into the file /etc/systemd/system/multi-user.target.wants/emacs.service:

[Unit]
Description=Emacs: the extensible, self-documenting text editor

[Service]
Type=forking
ExecStart=/usr/bin/emacs --daemon
ExecStop=/usr/bin/emacsclient --eval "(progn (setq kill-emacs-hook 'nil) (kill-emacs))"
Restart=always
User=YOUR_USERNAME

Make sure you insert your username in the bottom line. Now, enable the service executing systemctl enable emacs.service and after the next boot the daemon is started automatically.

Shell aliases and sudo-ing

One thing you will quickly notice is that sudo emacsclient ... doesn’t work since the daemon runs under your username. To be able to edit files as root, we need to load the tramp plugin of emacs. Put the following line somewhere in your .emacs or .emacs.d/init.el:

(require 'tramp)

Now, you would use emacsclient -c /sudo::/etc/somefile which is still a bit too long for quick file editing. (As well as the emacsclient command itself). This is why we create shell aliases. I am using zsh which is why I will use its syntax here.

export EDITOR="emacsclient -t -n -a nano"
alias ec='emacsclient -c -n -a nano'
alias et='emacsclient -t -a nano'
ecs() { emacsclient -c -n -a emacs "/sudo::$*" }
ets() { emacsclient -t -a emacs "/sudo::$*" }

It sets emacs as the default editor and defines the commands ec (emacs in a separate window) and et (emacs in the terminal) as well as its sudo friends for write-protected files, ecs and ets. Simply put the code in your .zshrc or .bashrc (after editing it to fit bash’s syntax) and restart the terminal. Then you can use ec/et/ecs/ets /some/directory/some/file to edit the file. I think tramp uses ssh to connect to your pc as root, so you might need to install ssh to use it.

4 Responses to “My new emacs setup (no .emacs here, don’t worry)”


Leave a Reply