Emacs Client on Mac OS X

I have been using J Aaron Farr’s approach to an emacsclient app on the Mac for a while, but it has always bugged me that it behaved differently than other apps. It would open a frame any time the app was launched (say via quicksilver or its ilk).

I finally took some time to munge the applescript to get the normal behavior, that is open a frame if there is no open frame, otherwise bring emacs to the front. Along the way I added “and start the emacs server if it is not already running.”

tell application "Terminal"
	try
		-- we look for <= 2 because Emacs --daemon seems to always have an entry in visibile-frame-list even if there isn't
		set frameVisible to do shell script "/Applications/Emacs.app/Contents/MacOS/bin/emacsclient -e '(<= 2 (length (visible-frame-list)))'"
		if frameVisible is not "t" then
			-- there is a not a visible frame, launch one
			do shell script "/Applications/Emacs.app/Contents/MacOS/bin/emacsclient -c -n"
		end if
	on error
		-- daemon is not running, start the daemon and open a frame		
		do shell script "/Applications/Emacs.app/Contents/MacOS/Emacs --daemon"
		do shell script "/Applications/Emacs.app/Contents/MacOS/bin/emacsclient -c -n"
	end try
end tell

-- bring the visible frame to the front
tell application "Emacs" to activate

The script assumes that Emacs.app is version 23 or higher and is installed under /Applications – if it isn’t you will need to modify it accordingly. Assuming it is, you can use this built version, otherwise grab the source from github and adjust strings accordingly.