Vim
last updated 2026-11
Vim is a modal editor - the same key does different things depending on the mode you're in. most of the time you're in normal mode, and only drop into the others for a moment. Esc always takes you back to normal mode (press it twice if unsure)
- normal - moving around and editing with commands (
dddeletes a line,yycopies it,ppastes,uundoes). it's the mode Vim starts in, and where you return from all the others with Esc - insert - typing text, like in any other editor. enter it from normal mode with
i(before the cursor),a(after it),I/A(start/end of the line), oro/O(on a new line below/above) - visual - selecting text, then acting on it with a command (
d,y,>,gq, …). enter it from normal mode withv(by characters),V(whole lines) or Ctrl-v (a rectangular block) - command-line - typing an Ex command at the bottom of the screen (
:wsaves,:qquits,:wqboth,:q!quits without saving) or a search (/patternforward,?patternbackward). enter it from normal mode with:,/or?, run the command with Enter, or cancel with Esc - replace - typing over existing text instead of inserting. enter it from normal mode with
R(orrto replace just one character), or press Insert while in insert mode
new to Vim? run vimtutor - a 30-minute hands-on lesson that comes with Vim, and the best way to start. after that, :help (or :h) with any command or setting - :h gq, :h textwidth - explains it, Ctrl-] follows a link in the help and Ctrl-o goes back
every key is a command
there are no menus - in normal mode every letter is a command, and they combine. most take a count in front (6dd deletes 6 lines, 3w moves 3 words), and the operators (d delete, y copy, c change, > indent, gq reformat) take any motion after them (dw deletes to the end of the word, d$ to the end of the line, dG to the end of the file). once that clicks, you don't learn commands one by one, you just compose them
normal mode:
h j k l - left, down, up, right (arrow keys work too)
w b e - next word, previous word, end of word
0 ^ $ - start of line, first non-blank character, end of line
gg G - first line, last line
40G - go to line 40 (or :40)
Ctrl-f Ctrl-b - page down, page up
% - jump to the matching bracket
x - delete the character under the cursor
dd 6dd - delete (cut) the line, or 6 lines
dw d$ dG - delete to the end of the word, line, file
yy 6yy - copy (yank) the line, or 6 lines
p P - paste after / before the cursor (whole lines go below / above)
cw cc - change the word / whole line (delete it and go to insert mode)
u Ctrl-r - undo, redo
. - repeat the last change
>> << - indent, unindent the line
J - join the next line to this one
* # - search forward / backward for the word under the cursor
n N - next / previous match of the last search
ZZ - save and quit
visual mode:
v V Ctrl-v - start selecting characters, lines, a rectangular block
o - jump to the other end of the selection
iw ip i( i" - select inner word, paragraph, inside brackets, inside quotes
aw ap a( a" - same, including the surrounding space, brackets or quotes
d y c - delete (cut), copy, change the selection
> < - indent, unindent the selected lines
gq - reformat the selection to 'textwidth'
~ u U - toggle case, lowercase, uppercase
: - run a command on the selected lines (Vim fills in :'<,'>)
I A - in block mode, insert / append text on every line, finish with Esc
gv - (from normal mode) select the last selection again
y, d and p use Vim's own registers, not the system clipboard - so text copied in Vim doesn't paste into the browser and vice versa. put "+ in front to use the clipboard ("+yy copies the line, "+p pastes), or add set clipboard=unnamedplus to ~/.vimrc to make it the default. this needs Vim built with clipboard support - check with vim --version | grep clipboard (+clipboard, not -clipboard), on Ubuntu it's the vim-gtk3 package. :reg shows what's in all the registers
chaining the commands
reformat a paragraph of plain text - with textwidth set (e.g. :set tw=80) Vim breaks lines while you type, but after editing inside a paragraph its lines are ragged. put the cursor anywhere in it and press
vipgq
vip selects the paragraph (visual, inner paragraph), and gq reformats it. or skip the selection and give the motion straight to the operator - gqip does the same
a few more:
dap - delete the paragraph, including the blank line after it
ci" - replace the text inside the quotes (deletes it and goes to insert mode)
yiw - copy the word under the cursor, from anywhere in it
ddp - swap the line with the one below (cut it, paste it below the next)
xp - swap two characters (fixes typos like "teh")
gg=G - re-indent the whole file (go to the top, = indents up to the end)
ggVG - select the whole file
d/foo - delete from the cursor up to the next "foo" (finish with Enter)
>ip - indent the paragraph
macros
when a change is more than one command, record it once and replay it - e.g. to turn a list of lines into quoted, comma-separated items, put the cursor on the first line and record I"<Esc>A",<Esc>j (quote the start and end, go to the next line), then repeat it for the rest:
qa - start recording into register a (any letter works)
q - stop recording
@a - replay it
@@ - replay the last macro again
10@a - replay it 10 times (it stops early when a command fails, e.g. j on the last line)
:'<,'>norm @a - replay it on every selected line
starting Vim
vim file.txt - open a file (a new one is created on the first :w)
vim a.txt b.txt - open several files, each in its own buffer (only the first one is shown)
vim -p *.py - open each file in its own tab
vim -o a b ; vim -O a b - open the files in split windows, one above the other / side by side
vim +40 file - open the file at line 40
vim + file - open it at the last line
vim +/pattern file - open it at the first match of the pattern
vim -R file - open it read-only (same as `view file`)
vim -d a b - show the differences between two files side by side (same as `vimdiff a b`)
command | vim - - edit the output of a command
working with multiple files
every open file is a buffer. a window shows one buffer, and a tab holds one or more windows - so you can have many files open while seeing just one of them
:e file - open another file in the current window (Tab completes the name)
:ls - list the buffers, with their numbers
:bn :bp - next / previous buffer
:bf :bl - first / last buffer
:b 3 ; :b name - buffer 3, or the one whose name contains "name"
Ctrl-^ - switch to the previous buffer, and back again
:bd - close the buffer
:tabe file - open the file in a new tab (:tabe alone opens an empty one)
gt gT 3gt - next / previous tab, tab number 3
:tabc - close the tab
:sp file ; :vs file - split the window, one above the other / side by side
Ctrl-w w - go to the next window (Ctrl-w h/j/k/l - to the one in that direction)
Ctrl-w q - close the window
:wa :qa :wqa - save all / quit all / save all and quit
Vim won't switch away from a buffer with unsaved changes - either save it first, or add set hidden to ~/.vimrc and it keeps the changes in the background (:qa still warns about them before quitting). Neovim has it on by default
search and replace
searching is done from normal mode, and the pattern is a regular expression (in Vim's own flavour - e.g. groups are \(…\), unless you start the pattern with \v):
/pattern - search forward (finish with Enter)
?pattern - search backward
n N - next / previous match, in the direction of the last search
* # - search forward / backward for the word under the cursor
/foo\c - ignore case for this search (\C to match case)
:set ic scs - ignore case, unless the pattern has a capital letter (ignorecase + smartcase)
:set hls - highlight all matches (hlsearch), :noh hides them until the next search
replacing is the :s command - :s/old/new/flags, on the lines given in front of it:
:s/old/new/ - replace the first match on the current line
:s/old/new/g - all matches on the current line
:%s/old/new/g - all matches in the file (% = all lines)
:%s/old/new/gc - same, but ask before each one (y/n, a = all, q = quit)
:10,20s/a/b/g - only on lines 10 to 20
:'<,'>s/a/b/g - only on the selected lines (press : in visual mode, Vim fills in the range)
:%s//new/g - an empty pattern reuses the last search - find it with / first, then replace
:%s/\v(\w+) (\w+)/\2 \1/ - groups and \1, \2 (here with \v) - swaps the first two words on every line
:%s/x/&&/g - & is the whole match - doubles every "x"
:g/pattern/cmd runs a command on every line that matches (:g! or :v on every line that doesn't) - most often d to delete them:
:g/^\s*$/d - delete all empty lines
:g/^\s*\/\//d - delete all // comment lines (C++, JS, …)
:v/pattern/d - keep only the lines that match
configuration and key mappings
Vim reads ~/.vimrc on start (Neovim reads ~/.config/nvim/init.vim). it's just a list of the same commands you'd type after : (without the colon), " starts a comment. open it with :e $MYVIMRC, and after a change reload it with :source $MYVIMRC - anything from it can also be typed as a : command to try it out first
a few settings worth having:
syntax on " syntax highlighting
filetype plugin indent on " indentation rules per file type
set number " line numbers
set expandtab tabstop=4 shiftwidth=4 " Tab inserts 4 spaces, > indents by 4
set ignorecase smartcase " case-insensitive search, unless the pattern has a capital
set hlsearch incsearch " highlight matches, and show them already while typing
set textwidth=80 " break lines at 80 characters while typing
let mapleader = "," " the <Leader> key in mappings (default is \) - set it before them
the main power of Vim is that all of its commands are just keystrokes - so a mapping can bind a key to any sequence of them, in any mode. there's one command per mode:
nmap - normal mode
imap - insert mode
vmap - visual mode (xmap = visual only, vmap also covers select mode)
cmap - command-line mode
map - normal, visual and operator-pending mode at once
use the noremap form (nnoremap, inoremap, xnoremap, cnoremap) unless you need otherwise - with plain nmap, the keys on the right side are mapped again if they have mappings of their own, which easily ends in loops or surprises. :nmap (:imap, …) without arguments lists the current mappings, :verbose nmap x also says where x was mapped
special keys are written in <…> - <Esc>, <CR> (Enter), <Tab>, <Space>, <BS>, <F5>, <C-x> for Ctrl-x, <Leader> for the key set by mapleader
some examples, by mode:
" insert mode: Ctrl-v and r reformats the current paragraph - leave insert mode,
" select the paragraph, reformat it, and go back to insert mode
" (<Esc>gwipa instead keeps the cursor where it was - gw is gq that doesn't move it)
inoremap <C-v>r <Esc>vipgqi
" insert mode: typing č inserts its HTML entity instead
inoremap č č
" normal mode: j and k move by screen lines in wrapped text, not by file lines
nnoremap j gj
nnoremap k gk
" normal mode: ,<Space> hides the search highlight, ,n toggles line numbers
nnoremap <Leader><Space> :nohlsearch<CR>
nnoremap <Leader>n :set number!<CR>
" visual mode: keep the selection after indenting, so > can be pressed repeatedly
xnoremap > >gv
xnoremap < <gv
" visual mode: ,s sorts the selected lines
xnoremap <Leader>s :sort<CR>
" command-line mode: typing w!! saves the file via sudo, when you forgot to open it as root
cnoremap w!! w !sudo tee % >/dev/null
Vim for Python
Vim highlights and indents Python on its own. for checking code as you type, formatting, completion and jumping to definitions, the usual setup is ALE - it runs linters and fixers in the background and talks to language servers - with ruff (linter and formatter) and pyright (types, completion, go to definition). plugins are installed with vim-plug, and the tools themselves separately, e.g. pipx install ruff pyright
~/.vimrc - Python setup
" vim-plug - install it once with:
" curl -fLo ~/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
" then add plugins between begin and end, and run :PlugInstall
let g:ale_completion_enabled = 1 " must be set before ALE loads
let g:ale_fix_on_save = 1 " run the fixers (formatting, import sorting) on every :w
call plug#begin()
Plug 'dense-analysis/ale' " linting, fixing, completion, go to definition
Plug 'Vimjas/vim-python-pep8-indent' " PEP 8 indentation of continuation lines
Plug 'vim-test/vim-test' " run the test under the cursor, the file, or all (pytest)
call plug#end()
augroup python_setup
autocmd!
autocmd FileType python let b:ale_linters = ['ruff', 'pyright']
\ | let b:ale_fixers = ['ruff', 'ruff_format']
augroup END
" ALE - the same keys work for any language it has a language server for
nnoremap gd :ALEGoToDefinition<CR>
nnoremap gr :ALEFindReferences<CR>
nnoremap K :ALEHover<CR>
nnoremap <Leader>r :ALERename<CR>
nnoremap ]e :ALENext<CR>
nnoremap [e :ALEPrevious<CR>
" vim-test - picks pytest up on its own
nnoremap <Leader>t :TestNearest<CR>
nnoremap <Leader>T :TestFile<CR>
Vim for JS/TS
recent Vim highlights and indents JavaScript and TypeScript on its own (JSX/TSX included, though it gets confused by more complex JSX). the rest is the same ALE setup as for Python, with eslint, prettier and tsserver - ALE picks them up from the project's node_modules, so they only need to be in the project's package.json (tsserver comes with typescript)
~/.vimrc - JS/TS setup
" vim-plug, ALE and vim-test with their options and keys as in the Python setup above
" (vim-test picks jest, vitest, … up on its own), plus this between plug#begin() and plug#end():
Plug 'MaxMEllon/vim-jsx-pretty' " better highlighting and indentation of JSX/TSX
augroup js_setup
autocmd!
autocmd FileType javascript,javascriptreact,typescript,typescriptreact
\ let b:ale_linters = ['eslint', 'tsserver']
\ | let b:ale_fixers = ['prettier', 'eslint']
augroup END
Vim for Lisp
for Common Lisp, Vlime gives Vim what SLIME gives Emacs (see Emacs and SLIME) - a REPL connected to a running SBCL, sending forms to it, compiling, completion, the debugger, the inspector and docs lookup. it runs a Swank server in SBCL, and needs Quicklisp to install its dependencies on the first start. editing the parentheses is up to paredit (keeps them balanced, moves whole forms), and rainbow colours each nesting level differently
~/.vimrc - Common Lisp setup
" Quicklisp, once: curl -O https://beta.quicklisp.org/quicklisp.lisp && sbcl --load quicklisp.lisp
" then in the SBCL prompt: (quicklisp-quickstart:install) and (ql:add-to-init-file)
call plug#begin()
Plug 'vlime/vlime', {'rtp': 'vim/'} " REPL integration with SBCL (the plugin lives in vim/)
Plug 'kovisoft/paredit' " balanced parentheses, moving whole s-expressions
Plug 'luochen1990/rainbow' " a different colour for every nesting level
call plug#end()
let g:rainbow_active = 1
let maplocalleader = "\\" " Vlime's keys start with <LocalLeader> - \ by default
" in a .lisp file:
" \rr start SBCL with the Vlime server and connect to it (\cc connects to one already running)
" \ss send the s-expression under the cursor to the REPL (\st the whole top-level form)
" \of compile the file, \l load it
" \dda show the documentation of the symbol under the cursor
" \i interaction mode - Enter sends the form under the cursor
" :help vlime-tutor walks through the rest
Claude in Vim
Claude Code is a command-line tool, so the simplest way is to run it in Vim's own terminal - :vert term claude opens it in a split next to the code (needs Vim built with +terminal). it edits the files directly - :checktime (or :e) reloads the buffers it changed, and set autoread in ~/.vimrc makes Vim reload unchanged buffers on its own. in Claude Code's prompt, /vim switches on Vim-style editing too
the vim-claude-code plugin (a small community project, not Anthropic's) wraps that up:
- Ctrl-\ opens and hides Claude in a split, and the session keeps running in the background
:Claude explain,:Claude fix,:Claude test,:Claude refactorwork on the visual selection, or on the function under the cursor- edits Claude proposes open as a diff to accept or reject (needs
python3), and buffers reload on their own after changes :Claude commitand:Claude reviewwrite a commit message from the staged diff, or review it:Claude doctorchecks the setup
Plug 'rishi-opensource/vim-claude-code'
see also my tips on working with Claude
working with encrypted files
Vim's own encryption
Vim can encrypt a file itself - on save it asks for a key, and next time it asks for it on open. the file is only readable with Vim then
vim -x file - open the file and set a key for it (asks for it twice)
:X - set a key for the current file, takes effect on the next :w
:set key= - remove the key, the next :w saves the file unencrypted
:set cm? - show the encryption method in use
the method is set with cryptmethod (cm) - put set cm=blowfish2 in ~/.vimrc, the older zip and blowfish methods are broken. Vim built with libsodium (:echo has('sodium') gives 1) has the stronger xchacha20v2 too. Neovim dropped this encryption altogether
gpg with vim-gnupg
for anything that matters, a gpg encrypted file is the safer bet - and it can be opened by anything else too. the vim-gnupg plugin makes Vim decrypt *.gpg, *.pgp and *.asc files on open and encrypt them back on save, and turns off the swap and undo files and viminfo for them, so the plain text doesn't leak to the disk
install it as a Vim package:
git clone https://github.com/jamessan/vim-gnupg ~/.vim/pack/plugins/start/vim-gnupg
by default it encrypts new files for gpg keys (it asks for the recipients). to use just a passphrase (symmetric encryption, same as gpg -c), add to ~/.vimrc:
let g:GPGPreferSymmetric = 1
then vim notes.txt.gpg asks for a passphrase and creates or opens the file. files already encrypted with gpg -c open the same way, and stay symmetric