Vim tip: “polymorphic” key bindings

If you use vim daily, you probably have a bunch of maps for your most common tasks. You should also remember you can assign the same key to do different things according to which mode you are
in. For example, let’s say you have a mapping to open a new tab:

map <leader>t :tabnew<cr>

You can also map t to open a new tab using the selected text as a filename. You just need to define two mappings:

nmap <leader>t :tabnew<cr>
vmap <leader>t :call Foo()<cr>

nmap stands for normal (mode) map, vmap for visual. How to get the text under the cursor is a bit more complex and out of scope for this vim tip, but you might want to check http://vim.wikia.com/wiki/Mapping_keys_in_Vim_-_Tutorial_%28Part_1%29.
Remember to check “:help map” for a list of all mode mappings.

Advertisements

One Comment on “Vim tip: “polymorphic” key bindings”

  1. […] grep to vim. We can improve it a little bit with very simple changes. Using this tip to have different key binding for different modes we can do something a bit smarter . Let’s create two functions, one for normal mode that […]


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