General advice on creating maps
Vim maps are extremely powerful, but as we know, with great power comes great responsibility!
When beginner Vimmers first discover maps, they tend to go crazy with them and create them for absolutely everything. There’s nothing wrong with this, but you should be aware of the trade offs if this is the path you decide to follow.
Here’s some general advice I’d like to pass on. Keep in mind that all of the points below are my personal opinion — other Vimmers might disagree.
Don’t create maps that override the defaults
Generally speaking, you should try to avoid overriding Vim’s built-in functionality with your own mappings — even the built-ins that you think you’ll never use. The reasoning is:
- Vim has plenty of key combinations that are unbound, making them a sensible choice for new keymaps
- even if you think you’ll never use a built-in keymap, trust me: you probably will, especially as you become more adept with the editor
We’re going to learn how we can avoid overriding built-in maps in the coming sections.
… unless the default keymap has synonyms
The exception to the rule above is if the built-in keymap has synonyms — that is, other keymaps which do the exact same thing. In that case, it’s usually fine to override one of the alternatives. For example, Q and gQ do the exact same thing in Vim — they drop you into Ex mode, which isn’t particularly useful in this day and age anyway (so we’re not going to discuss it here). In this situation, I think it’s fair game to override Q, because:
- you’re unlikely to be using Ex mode anyways — practically no Vim users use it any more
- if you ever do need to access Ex mode, you can just use
gQ
There’s no hard and fast rule, but as you learn more about Vim, your judgement will improve.
Don’t create overly-complicated maps
If you have a complex operation you want to give a keymap, it’s tempting to write a really long mapping that does it for you. For example:
nnoremap \s mmgg/import<cr>vip:sort<cr>`m
That mapping tries to sort the imports at the top of the file. It works, but it’s pretty long and ugly. If you find yourself writing maps like this, then it’s probably time to stop and rethink. Nine times out of ten, you’re better off writing a Vimscript function for this type of thing.
Try to avoid side effects
Try to avoid making your maps:
- quietly overwrite the contents of registers
- quietly overwrite marks
This will cause you confusion down the line.