David Furnes is a software engineer based in Brooklyn, New York. 🎹

Using the ⌘Command Key For Vim Shortcuts

It turns out binding some keys in Vim & iTerm2 isn't as easy as you'd think!

After years of faithful Vim usage, I've started using Visual Studio Code more and more for my everyday work. It took a long while to rebuild my Ctrl-P muscle memory to ⌘P, but I finally did it!

However, I still use Vim to make quick edits to files here and there. And that's where that newly acquired muscle memory betrayed me – as all my attempts to quickly open files ended up mired in iTerm's "Print" dialogue! No good!

Re-mapping ⌘P to Ctrl-P in MacVim

According to the Vim documentation, you can theoretically map the "command" key using the <D- prefix. When using MacVim, it actually is that simple!

" In ~/.vimrc: 
map <C-p> :CtrlP<cr>
map <D-p> :CtrlP<cr>

" In ~/.gvimrc:
if has('gui_macvim')
  " This removes the Cmd-P binding from 'Print':
  macmenu &File.Print key=<nop>

Alas, the terminal doesn't know about the Command key and so that doesn't help us when using classic Vim. The best we can do is tell iTerm, a modern graphical application, to intercept our ⌘P keystroke and turn it into another key combination that the terminal can understand, like Ctrl-P.

Re-mapping ⌘P to Ctrl-P in iTerm2

iTerm allows us to add custom key bindings in our profile. Open Preferences and head to Profiles β†’ Keys. Click the "+" button to add a new mapping:

iTerm's Preferences window, editing the

Click the box next to "Keyboard Shortcut" and then press ⌘P – you should see it appear in the box. Then, choose the "Send Text with 'Vim' Special Characters" option from the "Action" dropdown.

Then, simply type the Vim binding you want to map this key to, like \<C-p> or \<C-s>. Don't forget the leading backslash – otherwise it'll just print literally.

And that's it! When you press ⌘P, iTerm will now interpret it as Ctrl-P.

Hacker Mode

While I was researching how to do this, I came across this StackOverflow answer which suggested using the "Send Hex Code" action. (That's actually how I stumbled upon the "Vim Special Characters" option!)

This approach involves asking iTerm to sending the hex codes for a different pair of keys to the shell, as if we'd hit those buttons on the keyboard instead. Unlike the Vim bindings, though, it can be difficult see at-a-glance how we'd adapt this to other keys. For that, we'd have to use a program like xxd to inspect the hex codes for different keys on the keyboard.

So, to emulate Ctrl-P via a hex code, we'd map ⌘P to 0x10. Neat!

Sadly, there's no hex representation for the command key, so this doesn't help us with our original problem. But in exchange for less readability, it does unlock more potential keybindings – for example, you could re-bind βŒ˜β† to 0x01 to move the cursor to the beginning of your terminal prompt, or βŒ˜β†’ to 0x05 to jump to the end.

Happy hacking!