In my last article I listed some options for getting the emacs daemon to run automatically on OS X. There were some great tips added in the comments. This time I want to look at an improvement – running the Emacs daemon via launchd.
launchd is OS X’s answer to init, rc.d, crond and a host of other unix services. It’s the proper way to run a service on OS X and I wanted to see if I could run the emacs daemon this way. It’s actually pretty simple and so far it seems to work just fine.
First, I created a plist file like this one:
<?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>gnu.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>Gnu Emacs Daemon</string>
<key>UserName</key>
<string>farra</string>
</dict>
</plist>
Couple of important points: first, this assumes you’ve created the Emacs.app application as I explained in the last post and installed it in /Applications. The service also needs to run as your local user in order to pick up your emacs configuration. This could be done by passing in the -u parameter, but I chose to have launchd simply run the application under my user account. If you use this plist example, make sure you change the username!
To install, you should be able to save the plist in /Library/LaunchAgents and run:
sudo launchctl load -w /Library/LaunchAgents/gnu.emacs.daemon.plist
But I’ll admit to cheating by simply using Lingon to create and install the service.
Once loaded, you should now have emacs running as a daemon on restart. This should get rid of both the Terminal app instance that started on launch via the last approach and should also improve shutdown (in which case the AppleScript would sometimes hang). You might still want to use the Emacs Client applescript I provided in the last example though. Otherwise, to launch emacs, you’ll need to run either:
/Applications/Emacs.app/Contents/MacOS/bin/emacsclient -c -n # starts a new emacs frame
/Applications/Emacs.app/Contents/MacOS/bin/emacsclient -t # starts a new emacs in the terminal
Let me know if you have any trouble by leaving a comment.
Commentary