Using VI Inside of Emacs with ansi-term

As I’m still in the transition to use Emacs more often, I find myself often wanting to do a quick-and-dirty edit in vi. Rather than open another terminal (which can be disruptive if I have a tiling window manager with a particular layout configured), I like to have an ansi-term shell open in another Emacs frame. I usually use C-x 2 to split the window vertically, then C-x o to switch to the second frame, and M-x ansi-term RET to start an ansi-term shell. It will prompt for the shell to use, defaulting to the current shell of that user, in my case it will be /bin/bash or /bin/zsh depending on which system I’m using.

One great thing about ansi-term is that aside from the control/meta keystrokes, it’s a true ANSI-compliant terminal shell. You can still use C-x C-f and other key sequences (which in that case will open a new file in a new buffer) but you can also use C-c to cancel the current command, interrupt the running process, etc., except you have to hit it twice to tell ansi-term that you wanted to pass that control-c into the shell, not for Emacs itself to process. One of the only differences I’ve found, and it suits my needs just fine.

Now, for the quick-and-dirty edits — using vi or vim works perfectly fine within the Emacs ansi-term. The only issue I’ve found is that if I’m inside the file long enough, I often forget that I’m in VI and I will try to save the file with C-x C-s, and VI doesn’t really like that very much. Another thing of note — often I’m sudo’ed to root in the ansi-term window for various reasons, and vi’ing a file then will edit it as root, but using C-x C-f to open the file inside a new Emacs buffer will open it as the user ID that initiated the Emacs client (as I run Emacs in daemon mode almost exclusively), so I won’t have permissions to edit system files natively. I could use tramp/sudo, but sometimes it’s just faster to edit with VI. I’ve found this handy for multiple occasions so far.

One thing to note — using VI inside another Emacs shell (shell, term, iterm) can have strange results when attempting to save, enter/exit command mode, etc., so use at your own risk!

Leave a Reply