Zed Lopez

All Emacs (Almost) All the Time

(For those not so familar with Emacs vs Vi, let’s just say this is like the social situation between Republicans and the Democrats or the Roman Catholics and Southern Baptists: You live next door to them, but you know they’re going to hell.)

Emacs can run in the background as a daemon, so it starts lickety-split when you need to spawn an editor. But what if it’s not running yet? I needed a convoluted method for the Emacs 23.0.60 I was running in Ubuntu Intrepid; the Emacs 23.1.1 in Ubuntu Karmic’s emacs23 package includes an improved emacsclient that’ll launch an emacs daemon for you if you pass it an empty string for the alternative editor (-a parameter).

That’s why this goes in /usr/local/bin/editor:

#!/bin/sh
exec emacsclient -c -a "" “$@”

You’re going to want to use this as your editor alternative and use that as your EDITOR environment variable, but there’s a problem — now if you

sudo visudo
, you’re launching emacs and you’re left with an emacs daemon running as root. Oops.

So you

sudo visudo

and add

!env_editor,editor=/usr/bin/zile
to the end of your

Defaults
line.

Now:

sudo update-alternatives —install /usr/bin/editor editor /usr/local/bin/editor 99
cat >> ~/.bashrc
export EDITOR=“/usr/bin/editor”
export VISUAL=“/usr/bin/editor”
export SUDO_EDITOR=“/usr/bin/zile”

You’ll want to be able to kill the emacs daemon, so this goes in /usr/local/bin/killemacs

#!/bin/bash
emacsclient -e “(progn (setq kill-emacs-hook ’nil) (kill-emacs))” && rm -rf “/tmp/emacs`id -u`”

And you’ll want to automatically kill them on shutdown, so here’s /etc/init.d/killemacsdaemons:

#!/bin/sh
exec find /tmp -maxdepth 1 -type d -name ‘emacs*’ -exec find {} -type s -name server \;|perl -ne ‘s/[^\d]//g; print scalar getpwuid($_), "\
"’|xargs -n 1 su -c /usr/local/bin/killemacs -

Then:

sudo update-rc.d killemacsdaemons stop 1 0 1 6 .