Reusing Emacs instances with gnuserv
Posted by Steve on Wed 28 Sep 2005 at 13:03
One of the nice features of GNU Emacs is that you can "reuse" existing windows, and cause new files to be loaded there. This avoids waiting for a whole new editor to startup.
I'm not about to start a flame-war. I'm a happy user of both GNU Emacs, and Vim - so don't even think about it!
The Emacs editor is very customisable. It can be tweaked on a site-wide, or on a per-user basis.
Almost every aspect of the editor can be tweaked via the built-in scripting language, Lisp. At one point I was managing to load around 2Mb of tweaks every single time that my editor started up!
Whilst most people won't take the customisation that far it does add to the slow startup time that many people accuse Emacs of having.
One solution is to take advantage of one of the available extension packages for Emacs, gnuserv. This package allows you setup your Emacs instance as a server, which you can connect to.
If you're running XEmacs you don't need to install anything; for Emacs users you should install it with:
apt-get install gnuserv
Once installed you can modify your startup file ~/.emacs to use it by adding the following lines:
;; ;; Start GNUServe process when starting up. This lets us send new files ;; to previously spawned emacs process. ;; (load "gnuserv-compat") (load-library "gnuserv") (gnuserv-start)
This loads the library, and starts the server. Now you can take advantage of it.
- Firstly restart your editor "emacs &".
- Now load a new file into it with "gnuclient /etc/passwd"
Notice in the second step you received a new window? That is actually the same Emacs process! You've avoided waiting for a new process to startup.
If you wish to cause new files to be loaded into the same "window", (this is a frame in Emacs-speak), you can add the following lines to your ~/.emacs file:
;; When loading files reuse existing frames. (setq gnuserv-frame (car (frame-list)))
The only problem now is making sure that you remember to type gnuclient rather than emacs when you open a new file from the shell. To make this simpler you can save the following to ~/bin/emacs - assuming that your PATH is setup correctly you now don't need to change anything:
#!/bin/sh # ~/bin/emacs # # "apt-get install lsof" - if you're missing "lsof". # lsof /usr/bin/emacs | grep $USER >/dev/null 2>&1 if [ "$?" -eq "1" ]; then /usr/bin/emacs $* & else /usr/bin/gnuclient $* & fi
This script attempts to detect if you already have an emacs process running. If so it will connect to it with gnuclient. If not it will start a new instance.
The script uses the lsof tool to test for the open process rather than running:
ps -ef |grep [e]macs
This is because we wish to call the script ~/bin/emacs, and this would always cause your list of processes to include the word emacs making the test unreliable.