Vim Tips For Intermediate Users
I know from experience starting with Vim can be somewhat discouraging. Let's face it - Vim was made for power-users and, man, the learning curve is steep! That said, I can guarantee you taking time to learn this infinitely configurable yet surprisingly lightweight editor will pay off.
Here's a few productivity tips that make the Vim experience even better (and I use them literally every day).
Turn On Relative Line Numbers
Most of Vim’s editing supercow powers lie in motion commands which are composable and, well, essentially form a little language. As an example, a pretty usual move is to, say, cut and paste N lines from somewhere to somewhere else. In Vim this is a breeze:
d<N>j to delete and
p to paste. Now, the only hindrance sometimes is to figure out the
<N>, especially when N > 5 or so. In other words, it's just annoying to count the lines.
And that’s when
:set relativenumber saves the day. As the name suggests, it makes Vim display relative line numbers instead of absolute (see the image); that way you can easily tell how many lines you want your motion to span.
Of course, often it’s useful to see absolute numbers too. For that I use the airline plugin that shows the absolute line number in the status bar. An alternative is to use a command to switch between relative and absolute line numbering. See e.g. this great blog post for details on how to do that.
Save Work On Focus Lost
This feature works best in combo with infinite undo.
The idea here is that everytime you leave your Vim window, all your open files are automatically saved. I find this to be extremely helpful, for example when I’m working on a laptop and continuously run unit tests in terminal. My laptop is 13'' so I prefer to run Vim full screen and with this feature, I don’t have to explicitly save my source code file; I just cmd+tab to the terminal, Vim saves the file for me and my unit tests watcher re-runs the suite. If you save unwanted changes by accident you can easily remedy that with undo.
To turn autosaving on, add:
:au FocusLost * silent! wa
silent! flag prevents Vim from complaining when you have open unititled buffers (see this article for details).
Use Vertical buffers
When I’m working on a bigger screen - think external monitor instead of a laptop - I often find it useful to open two (or more) files in vertical buffers next to each other. Even though this is fairly easy to do with Vim, I realised I consistently fail to remember what the relevant command is. So I just remaped it in my
nnoremap <leader>w <C-w>v<C-w>l
I also remaped
<leader> from default backslash to comma just because it’s way easier for me to reach that on my Kinesis keyboard (warning: links to Amazon). I suggest you remap it too.
let mapleader = ","
That way, I can easily open vertical buffers and see more files next to each other.
Happy Viming! I'm @tomasbrambora.