5

I have an alias in bash that runs emacsclient if emacs daemon is already running and start emacs otherwise. However, in the event that a fresh instance of emacs is fired up, can I make it run in the background so I can still use that terminal (or close it)? In my bash profile, I have

alias ec="/usr/bin/emacsclient.emacs-snapshot -n -c -a /usr/bin/emacs-snapshot"

And I might be at the terminal and type

$ ec newfile

If emacs daemon is not already running, is there an alias I can create to make the line above do the equivalent of

$ emacs newfile &

instead of

$ emacs newfile

(I should also mention that I am using Linux Ubuntu and emacs-snapshot is assigned to the alias, 'emacs').

Thanks much!

hatmatrix
  • 42,883
  • 45
  • 137
  • 231

2 Answers2

5

Instead of calling /usr/bin/emacs-snapshot directly, write a script that calls /usr/bin/emacs-snapshot in the background and then returns:

#!/bin/sh
case $# in
  0) /usr/bin/emacs-snapshot &
  *) /usr/bin/emacs-snapshot "$@" &
esac

Then you call the script in the ordinary way; it will launch a background emacs process and return immediately.

If you want to get fancy you can use /bin/bash and disown the process after the esac (get the pid with $!).

Norman Ramsey
  • 198,648
  • 61
  • 360
  • 533
  • 1
    Why the `case`? Just using `myscript "$@"` will work the same as `myscript` when $# is o. – dubiousjim Feb 17 '10 at 12:29
  • 1
    @profjim: maybe in bash but not in older versions of `/bin/sh`. The `case` guarantees portability. In older versions, `myscript "$@"` behaves as `myscript ""` when `$#` is 0. When you're as old as I am, you learn to retain "bug-for-bug compatibility"... – Norman Ramsey Feb 17 '10 at 17:13
  • Thanks - is it necessary for me to disown the process? – hatmatrix Feb 17 '10 at 21:06
  • @Stephen: I don't understand `disown` as well as I would like. I would go with the simpler solution, but then if you find that your shell will not exit or your emacs goes down inexplicably (or your emacs goes down when your shell exits), then I would try disowning it. – Norman Ramsey Feb 18 '10 at 00:01
  • Thanks - appears to work as is without having to disown..., though my .emacs file is not loaded with this method. I'll look into it... but thank you. – hatmatrix Feb 18 '10 at 05:44
3

While this is not the direct answer to your question, this is the more elegant way to "start emacs deamon or run emacsclient otherwise". Create the following alias: alias emacs=emacsclient -c -a "". As of man emacsclient:

-a, --alternate-editor=EDITOR ... If the value of EDITOR is the empty string, run `emacs --daemon' to start Emacs in daemon mode, and try to connect to it.

Mirzhan Irkegulov
  • 17,660
  • 12
  • 105
  • 166