Run Emacs Server on MacOS
Ping Zhou, 2019-08-27
Ok, I’ve been using Emacs for a long time and my Emacs config file is getting bigger and more complex. Emacs is a powerful tool, but it can take longer time to start up with a big config file. However, I want Emacs to be my go-to editor instead of just a heavy-weight IDE. I want to use Emacs when I want to quickly edit something (like “vim <something>” or “nano <something>”). How do I do that with Emacs?
One possible option is to start Emacs with “-Q” argument. This tells Emacs to skip all init script so it can start as quickly as possible. The downside is that you lose all your precious Emacs configuration and your favorite themes. 🙂
Another option is to start Emacs as a server, and just launch a client (“emacsclient”) when you need the editor. In this way you get both quick startup time and a fully configured Emacs environment. I already use this approach on Linux, can I do this on MacOS?
Create “plist” file
First, I created a “plist” file in my LaunchAgents folder: ~/Library/LaunchAgents/emacs.daemon.plist
Here is an example of the plist file for Emacs server. Assuming Emacs binary is at /Applications/Emacs.app/Contents/MacOS/Emacs and the argument “–daemon” launches Emacs in server (daemon) mode.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>emacs.daemon</string> <key>ProgramArguments</key> <array> <string>/Applications/Emacs.app/Contents/MacOS/Emacs</string> <string>--daemon</string> </array> <key>RunAtLoad</key> <true/> <key>ServiceDescription</key> <string>Emacs Daemon</string> </dict> </plist>
Add to launchctl
Load the “plist” file to launchctl, so that it will be launched automatically.
launchctl load -w ~/Library/LaunchAgents/emacs.daemon.plist
If you need to manually start/stop the daemon:
launchctl start emacs.daemon launchctl stop emacs.daemon
To unload the “plist” file:
launchctl unload ~/Library/LaunchAgents/emacs.daemon.plist
That’s it! Emacs should be running as a server now. You can check this with a “ps” command:
ps aux|grep "[Ee]macs"
Launch Emacs client
Now that Emacs server is up and running, you can launch emacsclient just like any other editor. E.g. emacsclient ~/.bashprofile
One caveat is that if you have multiple emacs installed (e.g. MacOS comes with an old version of Emacs, and you installed Emacs 26.x), you need to make sure client and server are from the same Emacs installation. For example, if Emacs server is at:
/Applications/Emacs.app/Contents/MacOS/Emacs
You need to run emacsclient from the same installation:
$ which emacsclient /Applications/Emacs.app/Contents/MacOS/bin/emacsclient
Launching Emacs client from a different installation won’t work.
A note about GUI – By default emacsclient is launched in console. To launch emacsclient with GUI, use the “–c” argument:
emacsclient --c