Updated: 2022-01-23

I finally (2007) bit the bullet and commited to learning a real text editor. Having muddled on and off with vi since the late 90s, decided on Vim. Once you break through its initial, steep, learning curve its truly life changing. Level up and become a text surgeon today.

Vim is incredibly customisable. Its important to take the time to craft your own vimrc. Type :options to understand the various levers you can pull to make Vim your editor. Almost 15 years later, I’m still constantly fine tuning things.

Help

Vim has brilliant built-in help. Its only one :help away, :h operator or :h motion.

  • :h cmd normal mode cmd help
  • :h i_cmd insert mode cmd help
  • :h v_cmd visual mode cmd help
  • :h c_cmd command line cmd help

Basics

  • :enew new buffer
  • :edit! revert buffer to reflect file on disk

Operators

Trigger Effect
c change
d delete
y yank
g~ swap case
gu lower case
gU upper case
g? ROT13 encode
> shift right
< shift left
= autoindent
! filter through a program

See :h operator for more. All of these support being combined with a motion (or a visual mode selection). Some examples:

  • gUaw - make a word shout case
  • dap - delete entire paragraph
  • g?ap - ROT13 encode paragraph
  • gUgU - shout case entire line (factoid: when two operators are invoked in duplicate, applies to current line)

Object Selection

Learning object selectors is one of the best ways of becoming more efficient with Vim. Commands that start with i select inner objects without white space, and thus always select less text than their a equivalents. When you discover these can be paired with operators (discussed above), life changing, e.g. daw delete a word, gUis uppercase inner sentence, and so on.

Selector Effect
aw a word
iw inner word
as a sentence
is inner sentence
ap a paragraph
ip inner paragraph
a] a[ a [] block
i] i[ inner [] block
a) a( a block
i) i( inner block
a> a< a <> block
i> i< inner <> block
at tag block, as in XML tags <a> to </a>
it inner tag block
a} a{ a {} block
i} i{ inner {} block
a" a' quoted string including back ticks
i" i' quoted string including back ticks

Windows

Leverage the built-in windows manager, which can do splits to view multiple files at the same time.

  • :sp horizontal split
  • :vs vertical split
  • ctrl+w o - close all windows other than the active one.
  • ctrl+w x - exchange active window with the next one.
  • ctrl+w c - close the current window.
  • ctrl+w r - rotate windows clockwise (or counter clockwise).

The Edit (e) Command

Vim’s built-in edit command, will present you with a nice file system explorer, for example :e . to present the current working directory.

relativenumber

Makes line numbering relative. So good! Makes it fast to figure out how many lines up or down you need to move, to get to the line you want. Example, 14j to jump 14 lines down.

  2 I usually clone my `scripts` git repo straight into my home
  1 ¬
13      ln -nfs ~/git/scripts/linux/vim/vimrc ~/.vimrc¬
  1     ln -nfs ~/git/scripts/linux/vim ~/.vim¬
  2 ¬
  3 Vim has brilliant built-in help. Its only one `:help` away.

Calculator

By typing <C>r= in insert mode, can do quick calculations are spit the out into the buffer.

For example, <C>r=16*4<CR> will output 128 where the cursor is currently located.

Spell checking

Built in spell checker, enable with :set spell.

  • ]s jump to next error
  • [s jump to previous error
  • z= suggest corrections for current word
  • zg add word to dictionary
  • zw remove word from dictionary
  • zug undo zg or zw for current word

Sudo Save

Editing a file, but don’t have privileges to save.

:w !sudo tee %

:w writes to sudo tee %. tee flows the output of the file write to %, the name of the current file. I have a handy key binding w!! to do this:

cmap w!! w !sudo tee %

Jumps

Vim records the location before and after making a jump.

  • <C-o> go back
  • <C-i> go forward
  • :jumps show jump list
Jump command Effect
[count]G Jump to line
% Jump to matching parenthesis
( or ) Jump to prev/next sentence
{ or } Jump to prev/next paragraph
H or M or L Jump to top/middle/bottom of screen
gf Jump to file name under cursor
<C-]> Jump to definition of keyword under cursor
'{mark} or backtick{mark} Jump to mark

Registers

Handy named memory slots, using :registers to list them.

  • "" the unnamed register, general dumping register
  • "0 the yank register

When in insert mode use <C-r><register> to paste in a register content on the cursor position, such as <C-r>" for the unnamed register or <C-r>0 for the yank register.

Macros

To record, hit q<register>. For example to use the a register qa, followed by the sequence of actions, finalise recording with another q.

To see the contents of a register :reg a

To append to an existing macro, capitalise its register (e.g. for reg a use A). qA starts recording in append mode.

To edit a macro, is easy, its just stored in the corresponding register. For example a macro recorded with qa is stored into the a register.

  • Paste the macro into the buffer with :put a or "ap
  • Edit it as needed
  • Yank it back into the register 0"ay$

Macros over a collection of files

:cd ~/code/ruby_mod     "set context
:args *.rb              "set target file list
:args                   "show list
:first                  "jump to first item in list
:last                   "jump to last item in list
:next                   "jump to next item
:prev                   "jump to previous item
qa                      "record macro
:argdo normal @a        "apply macro a to all files in list
:wall                   "save all files in buffer list
:argdo write            "only save files in arglist

Key maps

{cmd} {attr} {lhs} {rhs}
  • {cmd} is one of ‘:map’, ‘:map!’, ‘:nmap’, ‘:vmap’, ‘:imap’, ‘:cmap’, ‘:smap’, ‘:xmap’, ‘:omap’, ‘:lmap’, etc.
  • {attr} is optional and one or more of the following: <buffer> <silent> <expr> <script> <unique> <special>. More than one attribute can be specified to a map.
  • {lhs} left hand side, is a sequence of one or more keys that you will use in your new shortcut.
  • {rhs} right hand side, is the sequence of keys that the {lhs} shortcut keys will execute when entered.

Mode specific maps:

:nmap - Display normal mode maps
:imap - Display insert mode maps
:vmap - Display visual and select mode maps
:smap - Display select mode maps
:xmap - Display visual mode maps
:cmap - Display command-line mode maps
:omap - Display operator pending mode maps

n  Normal mode map. Defined using ':nmap' or ':nnoremap'.
i  Insert mode map. Defined using ':imap' or ':inoremap'.
v  Visual and select mode map. Defined using ':vmap' or ':vnoremap'.
x  Visual mode map. Defined using ':xmap' or ':xnoremap'.
s  Select mode map. Defined using ':smap' or ':snoremap'.
c  Command-line mode map. Defined using ':cmap' or ':cnoremap'.
o  Operator pending mode map. Defined using ':omap' or ':onoremap'.

<Space>  Normal, Visual and operator pending mode map. Defined using ':map' or ':noremap'.
!  Insert and command-line mode map. Defined using 'map!' or 'noremap!'

Normalise line endings

The classic #!/bin/bash no such file or directory error message. Shebang is busted likely due to encoding problems.

Litmus test:

$ head -1 <your_file> | od -c

Should show:

0000000   #   !   /   b   i   n   /   b   a   s   h  \n

Vim to the rescue:

vim <your_file>
:set ff=unix
:set nobomb
:wq

Plugins Im loving of as 2022

While core Vim functionality is like a rock, changing rarely, the plugin eco-system is where you can make Vim level up to doing tasks you commonly do with it. Consequently plugin selection can be quite personal based on specific langs one works with.

The Vim community seems obsessed with writing new plug-in managers, there’s quite a bit of choice and tradeoffs, I have used a few in the past (Pathogen, Vundle) and as of 2020 have settled with vim-plug, which balances minimalism and functionality nicely.

Coming from bloated power tool IDE’s like awesome JetBrains tools, in order to be remotely productive, I need to be able to efficiency locate and jump between files within a large code base.

nnn - file browser

My #1 fav.

Ditch NERDTree, and instead surface the awesome nnn terminal file manager within Vim, genius.

  • <leader>n start nnn in window
  • ^G discard selection

nvim-lspconfig - auto-completion

An LSP (Language Server Protocol) provides deep language specific knowledge, supporting functionality such as autocompletion, linting and syntax highlighting. It is editor agnostic and underpins other editors such as vscode.

The nvim-lspconfig plugin provides common configuration for many servers.

Once the client plugin is done, install a language server.

python

  1. npm i -g pyright
  2. Add require'lspconfig'.pyright.setup{} to init.lua

golang

  • Make sure gopls is installed and on the PATH go install golang.org/x/tools/gopls@latest
  • Patch init.vim to include a supported client lspconfig

rust

telescope - fuzzy finder

Brilliant fuzzy finder. Picker sources include a range of file pickers (e.g. git files, find files, live grep), Vim pickers (e.g. buffers, tags), LSP pickers (e.g. symbols, references, actions) and Git pickers (commits, branches).

Make sure rg is installed <3!!!

Default keymaps:

nnoremap <leader>ff <cmd>Telescope find_files<cr>
nnoremap <leader>fg <cmd>Telescope live_grep<cr>
nnoremap <leader>fb <cmd>Telescope buffers<cr>
nnoremap <leader>fh <cmd>Telescope help_tags<cr>
Mappings Action
<C-n>/<Down> Next item
<C-p>/<Up> Previous item
j/k Next/previous (in normal mode)
H/M/L Select High/Middle/Low (in normal mode)
‘gg/G’ Select the first/last item (in normal mode)
<CR> Confirm selection
<C-x> Go to file selection as a split
<C-v> Go to file selection as a vsplit
<C-t> Go to a file in a new tab
<C-u> Scroll up in preview window
<C-d> Scroll down in preview window
<C-/> Show mappings for picker actions (insert mode)
? Show mappings for picker actions (normal mode)
<C-c> Close telescope
<Esc> Close telescope (in normal mode)
<Tab> Toggle selection and move to next selection
<S-Tab> Toggle selection and move to prev selection
<C-q> Send all items not filtered to quickfixlist (qflist)
<M-q> Send all selected items to qflist

fugitive - git

The crown jewel of Fugitive is :Git (or just :G), which calls any arbitrary Git command. If you know how to use Git at the command line, you know how to use :Git. It’s vaguely akin to :!git but with numerous improvements:

  • The default behavior is to directly echo the command’s output. Quiet commands like :Git add avoid the dreaded “Press ENTER or type command to continue” prompt.
  • :Git commit, :Git rebase -i, and other commands that invoke an editor do their editing in the current Vim instance.
  • :Git diff, :Git log, and other verbose, paginated commands have their output loaded into a temporary buffer. Force this behavior for any command with :Git --paginate or :Git -p.
  • :Git blame uses a temporary buffer with maps for additional triage. Press enter on a line to view the commit where the line changed, or g? to see other available maps. Omit the filename argument and the currently edited file will be blamed in a vertical, scroll-bound split.
  • :Git mergetool and :Git difftool load their changesets into the quickfix list.
  • Called with no arguments, :Git opens a summary window with dirty files and unpushed and unpulled commits. Press g? to bring up a list of maps for numerous operations including diffing, staging, committing, rebasing, and stashing.
  • This command (along with all other commands) always uses the current buffer’s repository, so you don’t need to worry about the current working directory.

And more:

  • View any blob, tree, commit, or tag in the repository with :Gedit (and :Gsplit, etc.). For example, :Gedit HEAD~3:% loads the current file as it existed 3 commits ago.
  • :Gdiffsplit (or :Gvdiffsplit) brings up the staged version of the file side by side with the working tree version. Use Vim’s diff handling capabilities to apply changes to the staged version, and write that buffer to stage the changes. You can also give an arbitrary :Gedit argument to diff against older versions of the file.
  • :Gread is a variant of git checkout -- filename that operates on the buffer rather than the file itself. This means you can use u to undo it and you never get any warnings about the file changing outside Vim.
  • :Gwrite writes to both the work tree and index versions of a file, making it like git add when called from a work tree file and like git checkout when called from the index or a blob in history.
  • :Ggrep is :grep for git grep. :Glgrep is :lgrep for the same.
  • :GMove does a git mv on the current file and changes the buffer name to match. :GRename does the same with a destination filename relative to the current file’s directory.
  • :GDelete does a git rm on the current file and simultaneously deletes the buffer. :GRemove does the same but leaves the (now empty) buffer open.

surround - symbol surrounding

Surround chunks of text with quotes or tags.

  • ysiw" surround word with double quotes
  • v$S" surround visual selection with double quotes
  • vipS<p> surround paragraph with <p></p>
  • cs"' change double quotes to single quotes

vim-commentary - code aware comment motions

Smart commenting based on the file type.

  • gcc comment current line
  • gc<motion> comment motion based selection e.g. gcap for paragraph selection

vim-better-whitespace - redundant whitespace

Utilities to highlight and remove redundant use of whitespace.

  • :EnableWhitespace
  • :DisableWhitespace
  • :ToggleWhitespace
  • :StripWhitespace

neoformat - code formatter

To use run Neoformat in command mode. It will reformat the current buffer.

A language agnostic code formatter. Its a neovim frontend to formatter backends. Tons of langs/formatters supported.

For example, for python files I use 3 formatters:

let g:neoformat_enabled_python = ['autopep8', 'yapf', 'docformatter']

I bind <leader>p as my shortcut:

nnoremap <leader>p <cmd>Neoformat<cr>

vim-css-color - hex codes coloriser

Colorise hex codes in the buffer based on CSS standards.

nvim-lsp - code symbol awareness goto def

  • <c-]> definition
  • K hover
  • gD implementation
  • <c-k> signature_help
  • 1gD type_definition
  • gr references
  • g0 d()ocument_symbol
  • gW workspace_symbol
  • gd definition
  • ga suggested code action

For example if I git ga on a rust error, it will auto add the use statement for the trait I need:

Code actions:
1: Line : Add `use std::str::FromStr;\n\n`
Type number and <Enter> or click with the mouse (q or empty cancels):

vim-markdown - folding and ToCs

The goto markdown plugin, supports folds and generating table of contents based on headings.

Folding:

  • zr reduces fold level throughout the buffer
  • zR opens all folds
  • zm increases fold level throughout the buffer
  • zM folds everything all the way
  • za open a fold your cursor is on
  • zA open a fold your cursor is on recursively
  • zc close a fold your cursor is on
  • zC close a fold your cursor is on recursively

Commands:

  • :InsertToc
  • :TableFormat
  • :HeaderIncrease and :HeaderDecrease

tabular - intuitive text aligning

TODO: http://vimcasts.org/episodes/aligning-text-with-tabular-vim/

vim-matchup - code aware %

Highlight, navigate and operate on sets of matching text. It extends the % key to language-specific words instead of just single characters.

Example, hit % on the while keyword, it will bounce you down its matching endwhile.

vim-sneak - precise motioning

The missing motion for Vim

Jump to any location specified by two characters.

Sneak is invoked with s (or z if you have surround.vim) followed by exactly two characters:

s{char}{char}
  • Type sab to move the cursor immediately to the next instance of the text “ab”.
    • Additional matches, if any, are highlighted until the cursor is moved.
  • Type ; to go to the next match
  • Type 3; to skip to the third match from the current position.
  • Type ctrl-o or ```` to go back to the starting point.
    • This is a built-in Vim motion; Sneak adds to Vim’s jumplist only on s invocation so you can abandon a trail of ; or , by a single ctrl-o or ````.
  • Type s<Enter> at any time to repeat the last Sneak-search.
  • Type S to search backwards.

Getting my setup behind a corporate proxy

TODO: Containerise everything including transitive dependencies

Resources