Skip to content

Instantly share code, notes, and snippets.

@rochacbruno
Last active September 4, 2025 19:56
Show Gist options
  • Save rochacbruno/ead5a4db7cfcd8ab4f18856b7f8b7391 to your computer and use it in GitHub Desktop.
Save rochacbruno/ead5a4db7cfcd8ab4f18856b7f8b7391 to your computer and use it in GitHub Desktop.
Useful vim tips

Vim Tips & Tricks - Modern Reference Guide

A comprehensive collection of Vim power-user techniques

adapted from zzapper

Table of Contents


Search Techniques

Basic Search Positioning

Pattern Description
/joe/e Cursor at end of match
3/joe/e+1 Find 3rd joe, cursor at end + 1
/joe/s-2 Cursor at start of match - 2
/joe/+3 Find joe, move cursor 3 lines down

Advanced Search Patterns

Pattern Description
/^joe.*fred.*bill/ Find joe AND fred AND bill (joe at line start)
/^[A-J]/ Lines beginning with A-J
/begin\_.*end Search over multiple lines
/fred\_s*joe/ Any whitespace including newline
/fred|joe Search for fred OR joe
/.*fred\&.*joe Search for fred AND joe in any order
/\<fred\>/ Exact word match (not alfred/frederick)
/\<\d\d\d\d\> Exactly 4 digits
/\<\d\{4}\> Same as above
/\([^0-9]|^\)%.*% Absence of digit or line start

Multi-line & Empty Line Searches

/^\n\{3}                    " Find 3 empty lines
/^str.*\nstr                " Find 2 successive lines starting with str
/\(^str.*\n\)\{2}           " Same as above
/<!--\_p\{-}-->             " Multi-line comments
/bugs\(\_.\)*bunny          " bugs followed by bunny anywhere

Visual Search & Special Patterns

:vmap // y/<C-R>"<CR>       " Search for visually highlighted text
:vmap <silent> // y/<C-R>=escape(@", '\\/.*$^~[]')<CR><CR>  " With special chars

Zero-width Assertions

Pattern Description
/<\zs[^>]*\ze> Search tag contents, ignoring chevrons
/<\@<=[^>]*>\@= Same using lookaround
/<\@<=\_[^>]*>\@= Tags across multiple lines

Special Search Techniques

/\%>20l\%<30lgoat           " Search between lines 20 and 30
/^.\{-}home.\{-}\zshome/e   " Match only 2nd occurrence in line
?http://www.vim.org/        " Search backwards (no escaping needed!)
/\c\v([^aeiou]&\a){4}       " 4 consecutive consonants

Substitution & Replace

Basic Substitutions

Command Description
:%s/fred/joe/igc General substitute
:%s//joe/igc Substitute last search
:%s/~/sue/igc Substitute last replacement
:%s/\r//g Delete DOS returns ^M
:%s/\r/\r/g Turn DOS ^M into real returns

Cleaning & Formatting

:%s= *$==                   " Delete end of line blanks
:%s= \+$==                  " Same thing
:%s#\s*\r\?$##              " Clean trailing spaces AND DOS returns
:%s/^\n\{3}//               " Delete blocks of 3 empty lines
:%s/^\n\+/\r/               " Compress empty lines
:%s#<[^>]\+>##g             " Delete HTML tags (non-greedy)
:%s#<\_.\{-1,}>##g          " Delete multi-line HTML tags

Advanced Substitutions

:'a,'bg/fred/s/dick/joe/igc " Substitute in range with global
:%s= [^ ]\+$=&&=            " Duplicate end column
:%s#example#& = &#gic       " Duplicate matched string
:%s#.*\(tbl_\w\+\).*#\1#    " Extract tbl_* strings
:s/\(.*\):\(.*\)/\2 : \1/   " Reverse fields separated by :
:%s/^\(.*\)\n\1$/\1/        " Delete duplicate lines
:%s/^\(.*\)\(\n\1\)\+$/\1/  " Delete multiple duplicates

Using Registers in Substitutions

:s/fred/<c-r>a/g            " Sub with register a contents
:s/fred/\=@a/g              " Better alternative

Column Operations

:%s:\(\(\w\+\s\+\)\{2}\)str1:\1str2:     " Sub in column 3
:%s:\(\w\+\)\(.*\s\+\)\(\w\+\)$:\3\2\1:  " Swap first & last column
:%s/^\(.\{30\}\)xx/\1yy/                 " Sub at column 30

Incrementing/Decrementing Numbers

:%s/\d\+/\=(submatch(0)-3)/              " Decrement by 3
:g/loc\|function/s/\d/\=submatch(0)+6/   " Increment by 6 on certain lines
:%s#txtdev\zs\d#\=submatch(0)+1#g        " Increment after txtdev
:let i=10 | 'a,'bg/Abc/s/yy/\=i/ |let i=i+1  " Sequential numbering

Global Commands

Basic Global Operations

Command Description
:g/gladiolli/# Display with line numbers
:g/fred.*joe.*dick/ Display lines with all three
:g/\<fred\>/ Display lines with exact fred
:g/^\s*$/d Delete blank lines
:g!/^dd/d or :v/^dd/d Delete lines NOT containing string

Range-based Global Commands

:g/joe/,/fred/d             " Delete from joe to fred (powerful!)
:g/fred/,/joe/j             " Join lines between patterns
:g/-------/.-10,.d          " Delete string & 10 previous lines
:g/{/ ,/}/- s/\n\+/\r/g     " Delete empty lines between braces

File Manipulation with Global

:g/^/put_                   " Double space file
:g/^/m0                     " Reverse file
:'a,'bg/^/m'b               " Reverse section a to b
:g/^/t.                     " Duplicate every line
:g/fred/t$                  " Copy lines with fred to EOF
:g/stage/t'a                " Copy to marker a

Advanced Global Operations

:g/^/ if line('.')%2|s/^/zz /     " Operate on every other line
:'a,'bg/somestr/co/otherstr/      " Copy matching lines after pattern
:g/fred/y A                       " Append all fred lines to register a
:g/^MARK$/r tmp.txt | -d          " Replace MARK with file contents
:g/<pattern>/z#.5                 " Display with context

Creating Files from Content

:g/^/exe ".w ".line(".").".txt"   " Create file for each line

Essential Commands

Word & Pattern Navigation

Key Description
* / # Find word under cursor forward/backward
g* / g# Find partial word under cursor
% Match brackets {}
. Repeat last modification
@: Repeat last : command
@@ Repeat last macro

Completion in Insert Mode

Key Description
<C-N> / <C-P> Word completion
<C-X><C-L> Line completion
<C-X><C-F> File path completion
<C-X><C-O> Omni completion

Pulling Content to Command Line

Key Description
/<C-R><C-W> Pull word under cursor
/<C-R><C-A> Pull WORD under cursor
<C-R>% Insert filename
<C-R>/ Insert last search
<C-R>= Insert expression result

Visual Mode

Visual Mode Types

Command Description
v Character-wise visual
V Line-wise visual
<C-V> Block-wise visual
gv Reselect last visual area
o / O Move to other end of selection

Visual Operations

V}J                         " Join visual block
V}gJ                        " Join without spaces
`[v`]                       " Highlight last insert
:%s/\%Vold/new/g            " Substitute in visual area

Visual Block Editing

08l<c-v>10j2ld              " Delete columns 8-9 of 10 lines
<C-V> motion y              " Yank block
<C-V> motion P              " Paste block

Text Objects in Visual Mode

Object Description Example
daW Delete contiguous non-whitespace
di< Delete inside < > yi< yank, ci< change
da< Delete around < >
dat / dit Delete around/inside tag pair
diB / daB Delete inside/around {} block
das Delete a sentence

Registers & Macros

Register Operations

Register Purpose
"a to "z Named registers
"A to "Z Append to named registers
"0 Last yank
"1 to "9 Delete history
"+ System clipboard
"* Selection clipboard
". Last inserted text
": Last command
"/ Last search pattern
"_ Black hole register

Recording Macros

qq                          " Start recording to q
q                           " Stop recording
@q                          " Execute macro q
@@                          " Repeat last macro
100@q                       " Execute 100 times
qQ@qq                       " Make recursive macro

Editing Macros

"qp                         " Display macro q
"qdd                        " Store edited macro back
:reg q                      " View register q
:let @a='                   " Edit macro directly

Using Registers

"ayy                        " Yank line to register a
"Ayy                        " Append to register a
"5p                         " Paste from delete register 5
"_dd                        " Delete without affecting registers
:let @*=@a                  " Copy register a to clipboard
:let @*=@%                  " Copy filename to clipboard

Navigation & Marks

Jump Navigation

Command Description
'. Jump to last modification line
`. Jump to exact spot of last modification
g; / g, Navigate change list
<C-O> / <C-I> Navigate jump list
:changes List changes
:jumps List jumps

Marks

ma                          " Set mark a
'a                          " Jump to line of mark a
`a                          " Jump to exact position of mark a
mA                          " Set global mark A
:marks                      " List all marks
:delmarks a-z               " Delete marks

Text Manipulation

Case Changes

Command Description
guu / gUU Lowercase/uppercase line
g~~ Toggle case line
vEU / vE~ Upper case / toggle word
ggguG Lowercase entire file

Formatting

gq}                         " Format paragraph
gqap                        " Format around paragraph
ggVGgq                      " Reformat entire file
:s/.\{,69\};\s*\|.\{,69\}\s\+/&\r/g  " Break lines at 70 chars

Advanced Manipulations

<C-A> / <C-X>               " Increment/decrement number
<C-R>=5*5                   " Insert calculation result (25)
:put=range(1,10)            " Insert numbers 1-10
:%s/\<\(on\|off\)\>/\=strpart("offon", 3 * ("off" == submatch(0)), 3)/g  " Swap words

Multiple Files & Buffers

Buffer Navigation

Command Description
:bn / :bp Next/previous buffer
:b3 Go to buffer 3
:b main Go to buffer with "main" in name
:ls / :buffers List buffers
:bd Delete buffer
:sav filename Save as new name
<C-^> Toggle between buffers

Working with Multiple Files

:args *.php                 " Load PHP files
:argdo %s/old/new/ge | update  " Replace in all files
:bufdo %s/foo/bar/e         " Operate on all buffers
:wn / :wp                   " Save and go to next/prev
:sball                      " Split all buffers

Windows & Splits

Split Operations

Command Description
:split / :vsplit Horizontal/vertical split
<C-W>w Cycle through windows
<C-W>hjkl Navigate windows
<C-W>HJKL Move windows
<C-W>= Equalize sizes
<C-W>_ / <C-W>| Maximize height/width

Quick Split Navigation

map <C-J> <C-W>j<C-W>_
map <C-K> <C-W>k<C-W>_

Command Line & External Commands

External Command Integration

:r!ls -R                    " Read command output
:20,25 !rot13               " Filter lines through command
!!date                      " Replace line with date
:%!sort -u                  " Sort unique
:'a,'b!sort -u              " Sort range

Command Line Tricks

vim -o file1 file2          " Open horizontal split
vim -O file1 file2          " Open vertical split
vim -p file1 file2          " Open in tabs
vim -c "/main" joe.c        " Open and search
vim -c "argdo %s/ABC/DEF/ge | update" *.c  " Batch edit

Advanced Techniques

Folding

zf}                         " Fold paragraph
zo / zc                     " Open/close fold
zR / zM                     " Open/close all folds
zf1G                        " Fold to beginning
zfG                         " Fold to end

Diff Mode

vim -d file1 file2          " Start in diff mode
dp                          " Put difference to other file
do                          " Get difference from other file
:diffthis                   " Enable diff for window

Sessions

:mksession                  " Save session (Session.vim)
:mksession MySession.vim    " Named session
vim -S                      " Restore session
vim -S MySession.vim        " Restore named session

Incrementing Techniques

" Create numbered list from 23 to 64
o23<ESC>qqYp<C-A>q40@q

" Advanced incrementing function
let g:I=0
function! INC(increment)
  let g:I = g:I + a:increment
  return g:I
endfunction

Time Travel

:earlier 10m                " Go back 10 minutes
:later 5m                   " Go forward 5 minutes

Modelines

" vim:noai:ts=2:sw=4:readonly:
" vim:ft=html:               " Force HTML syntax

Help System

Getting Help

Command Description
:h quickref Quick reference sheet
:h tips Vim tips
:h visual<C-D><tab> List visual help topics
:h ctrl<C-D> List control key help
:helpg pattern Grep help files
:h CTRL-R Help for Ctrl-R in normal mode
:h i_CTRL-R Help for Ctrl-R in insert mode
:h /\r Help for \r in regexp

Debugging Settings

:verbose set history?       " Show where option was set
:scriptnames                " List loaded scripts
:function                   " List functions

Essential Settings (.vimrc)

set nocompatible            " Use Vim defaults
set incsearch               " Jump to search as you type
set ignorecase smartcase    " Smart case searching
set wildignore=*.o,*.obj,*.bak,*.exe
set shiftwidth=4 tabstop=4
set hidden                  " Change buffer without saving
set number relativenumber   " Hybrid line numbers
set undofile                " Persistent undo

Useful Mappings

" Save and quit shortcuts
nnoremap <leader>w :w<CR>
nnoremap <leader>q :q<CR>

" Visual indenting (keeps selection)
vnoremap < <gv
vnoremap > >gv

" Search for visually selected text
vmap // y/<C-R>"<CR>

" Pull word under cursor into substitute
nmap <leader>z :%s#\<<c-r>=expand("<cword>")<cr>\>#

Remember: The power of Vim lies in combining these commands. Practice and muscle memory will make you incredibly efficient!

Modern Vim Tips & Tricks Guide

A comprehensive collection of Vim 9 tips for power users

Table of Contents

Essential Settings

Must-Have vimrc Settings

set nocompatible          " Use Vim defaults (not Vi)
set number relativenumber " Hybrid line numbers
set expandtab             " Use spaces instead of tabs
set tabstop=4 shiftwidth=4
set incsearch hlsearch    " Incremental and highlighted search
set ignorecase smartcase  " Smart case searching
set wildmenu wildmode=longest:full,full
set undofile              " Persistent undo
set backup                " Keep backup files

Navigation & Movement

Basic Movement Commands

Command Description Example
w / W Next word / WORD 3w - forward 3 words
b / B Previous word / WORD 2b - back 2 words
e / E End of word / WORD ge - end of previous word
0 / ^ / $ Start / First char / End of line -
gg / G Start / End of file 50G - go to line 50
{ / } Previous / Next paragraph -
( / ) Previous / Next sentence -

Advanced Navigation

Command Description Example
% Jump to matching bracket Works with (), [], {}
* / # Search word under cursor forward/backward -
gd / gD Go to local/global declaration Great for code
[[ / ]] Previous/next section or function -
[{ / ]} Jump to start/end of code block -
gi Return to last insert position -
g; / g, Navigate change list -
<C-o> / <C-i> Navigate jump list backward/forward -

Text Manipulation

Essential Operations

Command Description Example
ciw Change inner word ci" - change inside quotes
daw Delete a word (with space) da{ - delete around braces
yip Yank inner paragraph yi( - yank inside parens
gU / gu Uppercase / lowercase gUiw - uppercase word
~ Toggle case g~$ - toggle to end of line
J Join lines 3J - join 3 lines
gq Format text gqap - format paragraph
<C-a> / <C-x> Increment/decrement number Works in visual mode too

Text Objects

Object Meaning Example Use
iw / aw inner/a word diw - delete inner word
is / as inner/a sentence cas - change a sentence
ip / ap inner/a paragraph vip - select inner paragraph
it / at inner/a tag (HTML/XML) dit - delete inner tag
i" / a" inner/around quotes ci" - change inside quotes
i( / a( inner/around parentheses da( - delete around parens
i{ / a{ inner/around braces vi{ - select inner block

Search & Replace

Search Patterns

Pattern Description Example
/\<word\> Exact word match /\<the\> - matches "the" not "there"
/\v Very magic mode /\v(\w+)\s+\1 - find duplicate words
/\zs / /\ze Set match start/end /foo\zsbar - match bar in foobar
/\%23l Search in specific line /\%23lfoo - find foo in line 23
/\%V Search in visual selection -

Substitution Examples

:%s/old/new/g           " Replace all in file
:s/old/new/g            " Replace all in line
:%s/\<word\>/new/gc     " Replace whole word with confirmation
:%s/\v(\w+) (\w+)/\2 \1/g  " Swap two words
:g/pattern/d            " Delete all lines matching pattern
:v/pattern/d            " Delete all lines NOT matching pattern
:g/^$/d                 " Delete empty lines
:%s/\s\+$//e            " Remove trailing whitespace

Registers & Macros

Register Operations

Register Purpose Example
"a to "z Named registers "ayy - yank line to register a
"A to "Z Append to registers "Ayy - append line to register a
"0 Last yank "0p - paste last yank
"1 to "9 Delete history "2p - paste 2nd last delete
"+ System clipboard "+yy - copy line to clipboard
"* Selection clipboard "*p - paste from selection
". Last inserted text ".p - paste last insertion
": Last command @: - repeat last command
"/ Last search pattern -

Macro Tips

qa           " Start recording macro in register a
q            " Stop recording
@a           " Execute macro a
@@           " Repeat last macro
100@a        " Execute macro a 100 times
:reg a       " View contents of register a
:let @a='    " Edit macro a directly

Windows & Buffers

Window Management

Command Description
<C-w>s / :split Horizontal split
<C-w>v / :vsplit Vertical split
<C-w>w Cycle through windows
<C-w>h/j/k/l Navigate to window
<C-w>H/J/K/L Move window
<C-w>= Equalize window sizes
<C-w>_ / ` `
<C-w>+ / <C-w>- Increase/decrease height
<C-w>> / <C-w>< Increase/decrease width

Buffer Operations

Command Description
:ls / :buffers List all buffers
:b <name/number> Switch to buffer
:bn / :bp Next/previous buffer
:bd Delete buffer
:bufdo <cmd> Execute command in all buffers
:tab ball Open all buffers in tabs
<C-^> Toggle between buffers

Marks & Jumps

Mark Commands

Command Description Example
ma Set mark a 'a - jump to mark a
mA Set global mark A 'A - jump to mark A (any file)
'' Jump back to line before jump -
'. Jump to last change -
'^ Jump to last insert -
:marks List all marks -
:delmarks a-z Delete marks -

Visual Mode

Visual Mode Types

Mode Command Description
Character v Select by character
Line V Select by line
Block <C-v> Select rectangular block

Visual Mode Operations

Command Description
o / O Move to other end of selection
gv Reselect last visual selection
I / A Insert/append in block mode
r Replace selection with character
:normal Execute normal command on selection
:'<,'>sort Sort selected lines
:'<,'>!command Filter through external command

Command-Line Tips

Useful Ex Commands

:earlier 10m       " Go back 10 minutes in time
:later 5m          " Go forward 5 minutes
:changes           " List changes
:jumps             " List jumps
:oldfiles          " List recently edited files
:browse oldfiles   " Browse and open recent files
:scriptnames       " List loaded scripts
:verbose set option?  " Find where option was set
:checktime         " Check if file changed externally

Command-Line Shortcuts

Shortcut Description
<C-r>" Insert default register
<C-r>/ Insert last search
<C-r>= Insert expression result
<C-r>% Insert current filename
<C-f> Edit command in command-line window
q: Open command history
q/ Open search history

File Operations

File Management

:e **/*pattern<Tab>    " Fuzzy file finding
:find filename         " Find and open file in path
:r !command            " Insert command output
:w !sudo tee %         " Save with sudo
:DiffOrig              " Compare with last saved
:saveas newname        " Save with new name
:file newname          " Rename current buffer

Argument List

:args **/*.py          " Load Python files into arglist
:argdo %s/old/new/ge | update  " Replace in all files
:first/:last           " Navigate arglist
:argument 3            " Jump to 3rd file

Programming Features

Code Navigation

Command Description
[m / ]m Previous/next method start
[M / ]M Previous/next method end
% Jump between matching pairs
gf Go to file under cursor
<C-]> Jump to tag definition
<C-t> Jump back from tag
K Look up word in documentation

Folding

set foldmethod=indent   " Fold based on indentation
set foldmethod=syntax   " Fold based on syntax
set foldmethod=marker   " Fold based on markers
za                      " Toggle fold
zR                      " Open all folds
zM                      " Close all folds
zo/zc                   " Open/close fold
zj/zk                   " Next/previous fold

Completion

Command Description
<C-x><C-l> Line completion
<C-x><C-f> File path completion
<C-x><C-o> Omni completion
<C-x><C-n> Keyword completion
<C-x><C-]> Tag completion
<C-x><C-v> Vim command completion
<C-n> / <C-p> Next/previous match

Advanced Tricks

Global Commands

:g/pattern/command     " Execute command on matching lines
:g!/pattern/command    " Execute on non-matching lines
:g/TODO/t$             " Copy all TODO lines to end
:g/^/m0                " Reverse file
:g/pattern/normal @q   " Run macro on matching lines

Expression Register

"=5*5<CR>p             " Calculate and paste result
<C-r>=expand('%')<CR>  " Insert filename in insert mode
:put =range(1,10)      " Insert numbers 1-10

Quick Tips

:set paste             " Paste mode (no auto-indent)
:retab                 " Fix tabs/spaces
:set list              " Show invisible characters
ggVG=                  " Reindent entire file
:%!python -m json.tool " Format JSON
:w !diff % -           " Compare unsaved changes
:for i in range(1,10) | put =i | endfor  " Generate sequence

Recording Tips

" Convert CSV to table
qa0f,r|j0q            " Record: replace comma with pipe
999@a                 " Apply to many lines

" Number lines
:let i=1 | g/^/s/^/\=i.' '/ | let i=i+1

" Remove duplicate lines
:sort u

" Align equals signs
:'<,'>!column -t -s = -o =

Pro Tip: Map frequently used commands in your .vimrc for maximum efficiency!

" Example mappings
nnoremap <leader>w :w<CR>
nnoremap <leader>q :q<CR>
nnoremap <leader>s :%s//g<Left><Left>
vnoremap < <gv
vnoremap > >gv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment