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
 - Basics
 - Operators
 - Motions
 - Windows
 - Tabs
 - netrw
 - relativenumber
 - Calculator
 - Spell checking
 - Sudo Save
 - Jumps
 - Registers
 - Macros
 - Macros over a collection of files
 - Key maps
 - Normalise line endings
 - Plugins Im loving of as 2023
 - Resources
 
Help
Vim has brilliant built-in help. Its only one :help away, :h operator or :h motion.
:h cmdnormal mode cmd help:h i_cmdinsert mode cmd help:h v_cmdvisual mode cmd help:h c_cmdcommand line cmd help
Basics
:enewnew 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)
 
Motions
Learning motions 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.
:sphorizontal split:vsvertical splitctrl+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).
Tabs
<c-T>break window out into its own tabgtgoto next tab<c-pgdown>goto next tab<c-pgup>goto previous tab:tabnewcreates a new tab
netrw
Vim’s built-in edit command, will present you with a nice file system explorer, for example :e . to present the current working directory.
:Exfull window explorer:Sexside explorer
netrw keys
Navigate
-go up dir<cr>enter dir or open file
Act
cdmake this dir the currentdmake dirDdelete%make fileRrenamemccopy marks to targetmeput marks on arg listmmmove marked files to targetmxshell cmd to marksmzcompress marks
View
<c-l>refreshghtoggle hiddenicycle between thin, long, wide viewsItoggle bannerstoggle sort moderreverse sort orderqfdisplay file info<c-tab>collapse/expand explorer windowacycle between normal, hiding, showing
Select
mbmark dirmfmark filemuunmark marksmrmark using regexmFunmark filesmtset cd as markfile targetmpprint marks
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.
]sjump to next error[sjump to previous errorz=suggest corrections for current wordzgadd word to dictionaryzwremove word from dictionaryzugundozgorzwfor 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:jumpsshow 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"0the 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 aor"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 2023
While core Neovim 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 what kind of text editing jobs one mostly does.
There are lots of package managers out there, if you’re on Neovim, Packer.nvim is excellent.
lsp-zero
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.
lsp-zero is a one stop LSP shop for neovim:
bundles all the “boilerplate” to have nvim-cmp (a completion engine) and the LSP client working together nicely, with the help of mason.nvim, it can let you install language servers from inside neovim.
TODO: keybindings
nvim-dap
rust
A Debug Adapter Protocol client implementation for Neovim
For rust debugging:
rustup component add rust-analyzer- Download codelldb
 - Unpack the vsix (just a gzip)
 - Setup 
rust-tools.nvim 
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 addavoid 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 --paginateor:Git -p.:Git blameuses a temporary buffer with maps for additional triage. Press enter on a line to view the commit where the line changed, org?to see other available maps. Omit the filename argument and the currently edited file will be blamed in a vertical, scroll-bound split.:Git mergetooland:Git difftoolload their changesets into the quickfix list.- Called with no arguments, 
:Gitopens a summary window with dirty files and unpushed and unpulled commits. Pressg?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:Geditargument to diff against older versions of the file.:Greadis a variant ofgit checkout -- filenamethat operates on the buffer rather than the file itself. This means you can useuto undo it and you never get any warnings about the file changing outside Vim.:Gwritewrites to both the work tree and index versions of a file, making it likegit addwhen called from a work tree file and likegit checkoutwhen called from the index or a blob in history.:Ggrepis:grepforgit grep.:Glgrepis:lgrepfor the same.:GMovedoes agit mvon the current file and changes the buffer name to match.:GRenamedoes the same with a destination filename relative to the current file’s directory.:GDeletedoes agit rmon the current file and simultaneously deletes the buffer.:GRemovedoes 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 quotesv$S"surround visual selection with double quotesvipS<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.
gcccomment current linegc<motion>comment motion based selection e.g.gcapfor paragraph selection
Resources
- Smash into Vim the awesome PeepCode screen cast that helped me break through the learning curve back in the 2000’s
 - Vim Cheat Sheet good quick reference
 - tjdevries nvim kickstart