Current File and Directory in Emacs and Z Shell

My work environment is the command line (Z shell) and Emacs, bouncing back and forth between the two. The minor, but frequent, annoyance is when I am working on a file (or directory) in one, and need to do something on it in the other, and need to “manually” copy or type the file name between the environments.

This happened moments ago, when I was editing code for Cabin Notebook, and wanted to look at the current Git diff of the file. (Yes, I know I could do that exclusively in Emacs with the vc- functions, but my command line habits are deeply ingrained, and I like seeing the two side by side.)

So I was looking at the file in Emacs, and would have done what I always have, to just type out the name on the command line, probably the 24,000th time that I’ve done that.

I already had a Z shell function, cde, that changes to the directory of the current file in Emacs, with the code:

cde () {
   cd ${(Q)~$(emacsclient -e '(with-current-buffer
                              (window-buffer (selected-window))
                              default-directory) ')}
}

So that’s the basis of what I wrote. The first function displays the name of the current file (buffer) in Emacs:

ecf() {
    echo ${(Q)~$(emacsclient -e '(with-current-buffer 
                                  (window-buffer (selected-window))
                                  buffer-file-name) ')}
}

And the function that echoes the directory of the current buffer (yes, this could just be dirname `ecf`, but the below keeps in as all Emacs Lisp code):

ecd() {
    echo ${(Q)~$(emacsclient -e '(with-current-buffer
                                  (window-buffer (selected-window))
                                  default-directory) ')}
}

So now cde is just:

cde () {
    cd `ecd`
}

So there you have it, some tighter integration between the almighty Emacs and Z shell. More Z shell blithering of mine can be found here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s