Vim anti-patterns



I’ve used Vim for years, but nonetheless know that I have Vim habits that are not efficient. Today I caught myself going into insert mode, using backspace to delete a character and then hitting escape to go back to normal mode, instead of just pressing x. Another example was when I recently wanted to append a letter to the end of a word. I pressed e, then the arrow key and then i, instead of just ea.

Background of Vim commands used in this post



To return to the last position when opening a file, you can use something like, au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif. However, you can also use,

Visual mode

To make the selection include quotes, parenthesis and braces change i for a.

To select between parenthesis, braces and curly braces, one can also you % in combination with v.

Vim patterns

Upper- and lowercase:

Automatically adjust text to column width

If you have pasted or edited text, it might no longer fit nicely into the set column width of your document. You can adjust this with shift + v + gq, learn more with :h gq.

Vim commands

The normal command (norm)

From :help norm:

			Execute Normal mode commands {commands}.  This makes
			it possible to execute Normal mode commands typed on
			the command-line.  {commands} are executed like they
			are typed.  For undo all commands are undone together.
			Execution stops when an error is encountered.

Similar to :substitute (:s) :norm operates on the current line or the current highlighted lines. E.g., :norm ihello world! will insert hello world!.

:norm A \\ does the same as :s/$/ \\\\/.

Macros in Vim

Press q to start recording a macro, then the key that you want to save the macro to, e.g., v. This will yield “recording @v” in the Vim status bar. You can type what you want, jump in and out of instert and normal mode. You can also press : and record a command. If you use general patterns, such as {, } or %, you can apply this macro to several parts in the file you are editing. End the macro by again pressing q and to run the macro you press @v. If you just ran a macro @@ will run it again and if you type 5@@ the macro will run 5 times. This also works with . which runs the previous operation, and 5. runs the previous operation 5 times. It is possible to end the macro with @v and make it recursive, the macro will end when it hits an error, e.g., if you use } but there is no more paragraphs. The macro is saved to v also after you quit Vim and is only removed once you record over it.