Best programming tips for Vim - Vim for programmers
This article contains some of the most powerful Vim commands for programming in my opinion.
Small tips:
- Duplicate a line: yyp
Block mode:
- To use block mode until the end of the file, or the top of the file, it is not possible to use G or gg since the column would be lost. Instead, one can just input a crazy large number of displacements to the bottom/top: Ctrl-v 9999j or Ctrl-v 9999k
Increasing numbers in block mode
The command below extends to fonctionality of Ctrl-a to column mode. This is extremely useful when you have write a line, say with a variable x1. You duplicate the lines 3 times yy3p. Then you use block mode on the "1"s, and press Ctrl-a to increase the numbers and obtain x1 x2 x3 respectively on each line.
function! Incr()
let a = line('.') - line("'<")
let c = virtcol("'<")
if a > 0
execute 'normal! '.c.'|'.a."\<C-a>"
endif
normal `<
endfunction
vnoremap <C-a> :call Incr()<CR>
File completion
Nothing worse than mistyping a filename. In insert mode, use type Ctrl-x and then Ctrl-f to use filename completion. Ctrl-n and Ctrl-p can be used to navigate through the list. The command can be repeated. as many times as needed to go through a directory hierarchy.Editing/Re-editing your macros
Here's a typical workflow when working with macros. The dumping and editing at the end of the list is extremely useful in particular if you messed-up your macro by a small detail. It is also easy to store your favorite macros into a file and then loads them into your macro buffer.- Recording a macro in buffer a : qa
- Stop recording: q
- Applying the macro: @a
- Applying the macro 10 times: 10@a
- Dumping the macro at your cursor position (insert mode): Ctrl-r a
- Edit your macro or store it in a file
- Select the macro using v and then put it into the register a (visual mode): "ap
- Check that register a is correct: :reg