Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer
    
But then it means that one has to keep track and remember whether he/she already started a server or not... Is there a better way? –  Dror Jul 11 at 7:11
    
@Dror not at all, when you add this to your emacs configuration file, it will simply launch the server the first time you run emacs and then open all subsequent files in that instance. You don't need to keep track of anything at all. –  terdon Jul 11 at 9:26
    
But if emacs was not started, then emacsclient will yield an error. –  Dror Jul 11 at 9:58
    
@Dror ah, yes, I see what you mean. See updated answer. –  terdon Jul 11 at 10:08

I'm afraid I cannot recall where I found the following solution. Sorry. However, since it worked optimally for me I add it here.

Make sure that your .emacs starts the emacs server.

(server-start)

Next, in your .bashrc define the function:

function run_emacs
{
/usr/bin/emacsclient "$1" &
}

and set the environment variables:

export EDITOR=emacsclient
export ALTERNATE_EDITOR=emacs

Finally, define the alias:

alias emacs='run_emacs'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.