Mac – How to open a file from bash command line in the already open Emacs instead of a new instance

bashcommand lineemacs

How to open a file from bash command line in the already open Emacs instead of a new instance? When I type

$ emacs file.txt

it opens a new Emacs instance, instead of opening the file in the existing Emacs instance. Mac OS X 10.6.8. and

GNU Emacs 23.4.1 (x86_64-apple-darwin10.8.0, NS apple-appkit-1038.36)

of 2012-02-27 on beta.macosforge.org

Best Answer

what you are looking for is emacs server mode. Add this line to your .emacs file:

(server-start)

Then, open the file using emacsclient:

emacsclient foobar.txt

Have a look at this page for more information.


To avoid having to start emacs manually or setting it to auto-start, you could write a little function that tries connecting to a running server (by running emacsclient) and if not, runs emacs instead. Add this to your shell's configuration file (e.g. ~/.bashrc):

emacs(){ 
    emacsclient "$@" 2>/dev/null || /usr/bin/emacs "$@" 
}

Now, simply running emacs file will either start the server or connect to an existing instance.