In other words, can I start emacs once, and whenever I type emacs whatever in terminal, have it open as a buffer in my existing emacs instance?
[rant]This yet another of those features that is a no-brainer and enabled by default on many other editors, but proves to be quite difficult in Emacs.[/rant]
Anyway, here's how I have done it. First, as jwernerny mentioned, EmacsClient does the trick. All you have to do to edit foo.txt is
emacsclient --alternate-editor='' foo.txt
This command will try to connect to a running Emacs server. If there is no server, it will start one. It will then connect to the server and instruct it to open the specified file.
The server runs as a daemon (background process). If you run
ps x | grep emacs you'll see a process with the command-line
emacs --daemon. The problem I had was that Emacs only runs in a terminal if you do it like this, so if you want to run it in a graphical window, read on... (and kill that daemon process first)
Here's what I have added to my .bashrc:
alias e='emacsclient --no-wait --alternate-editor ~/.emacs.d/start.sh'
and the contents of
#!/bin/sh emacs --eval '(server-start)' $* &
e alias can then be used to open a file, either by starting a fresh Emacs instance (with a server), or using an existing one.
For an editor command that waits until you're finished with the file (good for Git commits etc), remove the
--no-wait option. I do this in my .bashrc:
export EDITOR='emacsclient --alternate-editor ~/.emacs.d/start.sh'
C-x # when you're done editing the file. Good old
C-x k will ask the annoying question "Buffer foo.txt still has clients; kill it?"