Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I start emacs from the command line but use emacsclient if a server is already running?

I'm using emacs under Ubuntu

If I want to edit a.txt then I either click on the emacs icon or use

$ emacs  --geometry 10x10 --fullscreen --no-splash ~/a.txt &

from bash. My .emacs file starts the emacs server.

If I then want to edit another file from the command line, I use

$ emacsclient -n ~/b.txt

to load the file into the existing emacs.

but I keep getting it wrong, and all hell breaks loose in various ways.

How would I make a bash command 'e', that checks whether the emacs server is already running, and executes the appropriate command?

Attempts to use the emacsclient -a switch invariably produce undesirable and ill-determined behaviour.

Extra points if it can 'do the right thing' when run on a console too.

like image 785
John Lawrence Aspden Avatar asked Nov 28 '25 09:11

John Lawrence Aspden


1 Answers

So far this function definition in .bashrc seems to be a perfect solution:

function e #open emacs in background and disown it, or if already running use emacsclient
{
 echo "emacs function backgrounds and disowns emacs, or calls client if server already running; see .bashrc";
 local FLUFFY="$@";
 local SERVERSOCKET=/tmp/emacs${UID}/server ;
 echo "trying to open: " $FLUFFY 
 echo " checking: " $SERVERSOCKET "for emacs server " ;
 # test for existence of emacs server socket 
 if [ -e $SERVERSOCKET ]; then
     echo "using emacsclient"
     emacsclient -n $FLUFFY;
 else
     echo "starting emacs: make tea..."
     emacs  --geometry 10x10 --fullscreen --no-splash $FLUFFY & disown ;
 fi;
}

which was derived from this incantation:

FLUFFY=~/b.txt ; if [ -e /tmp/emacs1000/server ]; then emacsclient -n $FLUFFY; else emacs  --geometry 10x10 --fullscreen --no-splash $FLUFFY & fi;

which does what I want by checking for the existence of the emacs server socket for user 1000.

like image 82
John Lawrence Aspden Avatar answered Nov 30 '25 00:11

John Lawrence Aspden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!