Integrate iTerm2 in your Emacs setup

The terminal experience inside emacs being what it is — ie really slow and kinda difficult to use — , I use iTerm2 as my main terminal. I put up three little emacs-lisp functions using AppleScript. They allow me to quickly switch between iTerm and emacs.

This one return the directory of the file currently opened. If it is a *scratch* buffer or something like that, it simply returns the home directory.

(defun get-file-dir-or-home ()
"If inside a file buffer, return the directory, else return home"
(interactive)
(let ((filename (buffer-file-name)))
(if (not (and filename (file-exists-p filename)))
"~/"
(file-name-directory filename))))

This one allow me to cd to the directory of the file I am editing in emacs. If I am in a *scratch* buffer or something like that, it cd to the $HOME directory. It then focus the iTerm2 app.

(defun iterm-goto-filedir-or-home ()
"Go to present working dir and focus iterm"
(interactive)
(do-applescript
(concat
" tell application \"iTerm2\"\n"
" tell the current session of current window\n"
(format " write text \"cd %s\" \n" (get-file-dir-or-home))
" end tell\n"
" end tell\n"
" do shell script \"open -a iTerm\"\n"
))
)

This last one just focus the iTerm2 app, without modifying the working directory.

(defun iterm-focus ()
(interactive)
(do-applescript
" do shell script \"open -a iTerm\"\n"
))

I have mapped it to SPC ‘ and SPC ? using general.el.

(general-define-key
:states '(normal visual insert emacs)
:prefix "SPC"
"'" '(iterm-focus :which-key "focus iterm")
"?" '(iterm-goto-filedir-or-home :which-key "focus iterm - goto dir")
)

Originally published at sam217pa.github.io on September 1, 2016.

Like what you read? Give Samuel BARRETO a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.