« October 2008 | Main | March 2009 »

February 13, 2009

New and improved emacs launcher

I'm much happier with this combination. /usr/local/bin/editor is:

#!/bin/bash ALTERNATE_EDITOR=/usr/local/bin/editor2 emacsclient -c "$*"

/usr/local/bin/editor2 is:
#!/bin/bash
EMACS=/usr/bin/emacs
EMACSCLIENT=/usr/bin/emacsclient
SOCKET=/tmp/emacs`id -u`/server

$EMACS --daemon

count=25

while [ $[ count-- ] -gt 0 ]; do
if [ -e $SOCKET ] && [ ! (lsof $SOCKET &> /dev/null) ]; then
$EMACSCLIENT -c "$*"
break
fi
sleep .2
done

Among the advantages here over the old one:

emacs --daemon is only run if emacsclient can't find a socket, as opposed to emacsclient encountering any error

The old one slept for 1 second after launching the daemon. This was occasionally too short, but usually too long. This one checks for the socket five times a second, and gives up after five seconds. (There are imaginable race conditions that could give undesirable results, but I don't expect to ever actually encounter them.)

February 3, 2009

Daemon Emacs

A nifty feature in the current development version of Emacs (now available in a pretest release candidate) is that you can start it as a daemon, to which graphical and terminal clients alike can attach. A not so nifty lack of feature is there being no easy standard way to do the obvious: launch a client if the daemon's running; if it's not, start the daemon, and then launch the client. So everyone cobbles together their own. Here's mine, which cribs from here.

#!/bin/bash
if [ -z $DISPLAY ] ; then
OPT="-t"
else
OPT="-c"
fi

if [ -z "$*" ]; then
OPT="$OPT -e (raise-frame)"
else
OPT="$OPT $@"
fi
emacsclient $OPT 2>/dev/null || (
(emacs --daemon)
sleep 1
emacsclient $OPT)

I have that as /usr/local/bin/editor. To stop emacs nicely, and get prompted to save unfinished business, I have another script with:

/usr/local/bin/editor -e '(save-buffers-kill-emacs)'