Wednesday, March 21, 2007

Emacs and emacsclient (Ruby script to call them both)

I usually call one single emacs server (I've got (server-start) at the very beginning of my .emacs), then connect to it with some emacsclient.

Unfortunately enough emacsclient just quits if there is no active emacs server.

I need a process that tries to run emacsclient: if there is no active server, it runs emacs.Moreover, emacsclient has a -n switch that makes it return ASAP, so the terminal is available for more commands.emacs has not such a switch, but that behaviour is the one I want.

So I decided to write a small ruby script that does just this:
  1. Tries to run emacsclient with the -n option.
  2. If it succeeds, we are done. Otherwise we run Emacs doing some standard posix process manipulation in order to return to the shell as soon as possible.

This is the script:

#!/usr/bin/env ruby

fork do
    exec('emacsclient', '-n', *$*)
end

Process.wait
    if $?.exitstatus != 0
        fork do
        Process.setsid
        Signal.trap('HUP', 'SIG_IGN')
        exec('emacs', *$*) if fork.nil?
        exit!(0)
    end
    
    Process.wait
end

No comments: