Cheatsheets

Vim

Vim

Vim is a highly configurable text editor built to make creating and changing any kind of text very efficient. It is included as "vi" with most UNIX systems.

7 Categories 27 Sections 57 Examples
Editor Vim Text Editor Terminal Productivity Keyboard Shortcuts

Getting Started

Fundamental Vim concepts including modes, exiting, and opening files.

Modes

Vim operates in several modes. Understanding modes is key to using Vim effectively.

Entering Insert mode

These keys transition from Normal mode to Insert mode at various cursor positions.

Code
i " Insert before cursor
a " Insert after cursor
o " Open new line below and enter Insert mode
O " Open new line above and enter Insert mode
I " Insert at beginning of line
A " Insert at end of line
  • Press Esc at any time to return to Normal mode.
  • i and a are the most commonly used: i inserts before cursor, a inserts after.

Entering Visual mode

Visual mode lets you select text for operations like copy, delete, or indent.

Code
v " Character-wise Visual mode
V " Line-wise Visual mode
Ctrl-V " Block-wise Visual mode
  • Use V to select entire lines quickly.
  • Ctrl-V is powerful for column editing.

Entering Command-line mode

Command-line mode allows you to execute Ex commands, search, and filter text.

Code
: " Enter Command-line mode
/ " Enter search forward
? " Enter search backward
  • Press Esc or Ctrl-C to cancel and return to Normal mode.
  • Use Tab for command completion in Command-line mode.

Exiting

How to save files and exit Vim.

Save and quit

These commands write the buffer to disk and/or close Vim.

Code
:w " Save (write) the file
:q " Quit (fails if unsaved changes)
:wq " Save and quit
:x " Save and quit (only writes if changes exist)
ZZ " Save and quit (Normal mode shortcut)
  • :x and ZZ only write if the buffer has been modified, preserving file timestamps.
  • :wq always writes, even if no changes were made.

Quit without saving

Force-quit commands discard unsaved changes. Use with caution.

Code
:q! " Quit without saving (force quit)
ZQ " Quit without saving (Normal mode shortcut)
:qa! " Quit all windows without saving
  • The ! modifier forces the operation, bypassing safety checks.
  • :qa! is useful when you have multiple buffers/windows open.

Save all and quit

Multi-buffer save and quit commands for working with several files at once.

Code
:wa " Save all modified buffers
:wqa " Save all buffers and quit
:xa " Save all modified buffers and quit
  • :wa saves all buffers but keeps Vim open.
  • :wqa and :xa close Vim after saving everything.

Opening Files

Different ways to open files in Vim from the command line.

Basic file opening

Open files directly from the shell with optional line or pattern positioning.

Code
vim file.txt " Open a file
vim +42 file.txt " Open file at line 42
vim +/pattern file.txt " Open file at first match of pattern
  • The + flag accepts any Ex command to run after opening.
  • Use vim + file.txt to open at the last line.

Opening multiple files

Open multiple files in different layouts directly from the command line.

Code
vim file1.txt file2.txt " Open in buffers (:bn to switch)
vim -O file1.txt file2.txt " Open in vertical splits
vim -o file1.txt file2.txt " Open in horizontal splits
vim -p file1.txt file2.txt " Open in tabs
  • Use -O for side-by-side editing of related files.
  • Use -p for tab-based workflow.

Opening files from within Vim

Open additional files without leaving Vim using Ex commands.

Code
:e file.txt " Edit a file in current window
:sp file.txt " Open in horizontal split
:vsp file.txt " Open in vertical split
:tabe file.txt " Open in new tab
  • :e replaces the current buffer; use :bn to go back.
  • Tab-complete file paths with Tab in command mode.

Navigation

Moving efficiently through files and text in Vim.

Basic Movement

Fundamental cursor movement commands in Normal mode.

Character and line movement

The h/j/k/l keys replace arrow keys for efficient navigation without leaving the home row.

Code
h " Move left
j " Move down
k " Move up
l " Move right
0 " Jump to beginning of line
^ " Jump to first non-blank character
$ " Jump to end of line
  • Use 0 for absolute start, ^ for first non-whitespace character.
  • Prefix with a number for repeated movement (e.g., 5j moves down 5 lines).

Word movement

Word motions navigate by word boundaries. Lowercase variants treat punctuation as word boundaries; uppercase variants only use whitespace.

Code
w " Move forward to start of next word
b " Move backward to start of previous word
e " Move forward to end of current/next word
ge " Move backward to end of previous word
W " Move forward to start of next WORD (space-delimited)
B " Move backward to start of previous WORD
E " Move forward to end of next WORD
  • Use w/b for precise navigation around punctuation.
  • Use W/B for faster navigation across mixed text.

Document Movement

Commands for navigating through the entire document quickly.

Jumping to document positions

Jump directly to specific lines or screen positions.

Code
gg " Go to first line of document
G " Go to last line of document
:42 " Go to line 42
42G " Go to line 42 (Normal mode)
H " Move to top of screen (High)
M " Move to middle of screen (Middle)
L " Move to bottom of screen (Low)
  • gg and G are essential for quick top/bottom navigation.
  • H/M/L position the cursor on the visible screen area.

Scrolling

Scroll the viewport while maintaining or moving the cursor.

Code
Ctrl-D " Scroll down half a page
Ctrl-U " Scroll up half a page
Ctrl-F " Scroll down a full page (Forward)
Ctrl-B " Scroll up a full page (Backward)
Ctrl-E " Scroll down one line
Ctrl-Y " Scroll up one line
  • Ctrl-D and Ctrl-U are the most commonly used scroll commands.
  • Ctrl-E and Ctrl-Y scroll without moving the cursor line.

Search Movement

Finding text and navigating by search patterns and character jumps.

Pattern searching

Search for text patterns in the file. Vim supports regular expressions in search.

Code
/pattern " Search forward for pattern
?pattern " Search backward for pattern
n " Repeat search in same direction
N " Repeat search in opposite direction
* " Search forward for word under cursor
# " Search backward for word under cursor
  • Use :set hlsearch to highlight all matches.
  • Press :noh to clear search highlighting.

Character-level jumps

Jump to specific characters on the current line. Extremely useful for precise horizontal navigation.

Code
f{char} " Jump forward to next occurrence of {char}
F{char} " Jump backward to previous occurrence of {char}
t{char} " Jump forward to just before {char}
T{char} " Jump backward to just after {char}
; " Repeat last f/F/t/T in same direction
, " Repeat last f/F/t/T in opposite direction
  • f and t are among the most efficient ways to move within a line.
  • Combine with operators like d or c (e.g., dt) to delete/change up to a character).

Marks and Jumps

Setting bookmarks and navigating the jump list.

Setting and jumping to marks

Marks let you bookmark positions in a file and jump back to them.

Code
ma " Set mark 'a' at current position
'a " Jump to line of mark 'a'
`a " Jump to exact position of mark 'a'
:marks " List all marks
'' " Jump to position before last jump (line)
`` " Jump to position before last jump (exact)
  • Lowercase marks (a-z) are local to a buffer; uppercase marks (A-Z) are global across files.
  • Use ` (backtick) for exact column position, ' (single quote) for line start.

Jump list navigation

The jump list tracks your movement history. Use Ctrl-O/Ctrl-I to go back and forth.

Code
Ctrl-O " Jump to older position in jump list
Ctrl-I " Jump to newer position in jump list
:jumps " Show the jump list
  • Searches, marks, and line jumps are all recorded in the jump list.
  • Ctrl-O is one of the most useful navigation shortcuts in Vim.

Editing

Commands for inserting, copying, pasting, and transforming text.

Inserting Text

Various ways to enter Insert mode and begin typing.

Basic insert commands

Each command enters Insert mode at a different position relative to the cursor or line.

Code
i " Insert before cursor
I " Insert at beginning of line
a " Append after cursor
A " Append at end of line
o " Open new line below
O " Open new line above
  • A is especially useful for adding content to the end of a line.
  • o and O are preferred over pressing Enter manually.

Substitute and replace

These commands combine deletion with entering Insert or Replace mode.

Code
s " Delete character under cursor and enter Insert mode
S " Delete entire line and enter Insert mode
C " Delete from cursor to end of line and enter Insert mode
r " Replace single character (stays in Normal mode)
R " Enter Replace mode (overwrite characters)
  • s is equivalent to cl (change one character).
  • R is useful for fixed-width editing or overwriting text in place.

Clipboard Operations

Deleting, yanking (copying), and putting (pasting) text.

Delete and yank commands

Delete commands cut text into a register. Yank commands copy without deleting.

Code
x " Delete character under cursor
X " Delete character before cursor
dd " Delete (cut) entire line
D " Delete from cursor to end of line
yy " Yank (copy) entire line
Y " Yank entire line (same as yy)
d{motion} " Delete text covered by motion (e.g., dw, d$)
y{motion} " Yank text covered by motion (e.g., yw, y$)
  • Deleted text is stored in the unnamed register and can be pasted with p.
  • Use d$ or D to delete from cursor to end of line.

Put (paste) and system clipboard

Put commands paste text from registers. The + and * registers access the system clipboard.

Code
p " Put (paste) after cursor
P " Put (paste) before cursor
"+y " Yank to system clipboard
"+p " Paste from system clipboard
"*y " Yank to primary selection (X11)
"*p " Paste from primary selection (X11)
  • Vim must be compiled with +clipboard for system clipboard support.
  • On macOS, + and * registers behave the same.

Undo and Redo

Undoing and redoing changes in Vim.

Basic undo and redo

Vim maintains an undo tree that allows undoing and redoing changes.

Code
u " Undo last change
Ctrl-R " Redo last undone change
U " Undo all changes on current line
5u " Undo last 5 changes
  • Vim has unlimited undo by default (limited only by memory).
  • U (uppercase) undoes all changes on the current line since last entering it.

Undo branches and persistence

Vim tracks undo as a tree, not just a linear stack. Use time-based undo to revert by duration.

Code
:undolist " Show undo branches
g- " Go to older text state
g+ " Go to newer text state
:earlier 10m " Go to state 10 minutes ago
:later 5m " Go to state 5 minutes from undo point
:set undofile " Enable persistent undo across sessions
  • :earlier and :later accept time units like s, m, h.
  • Enable undofile in your vimrc for persistent undo history.

Find and Replace

Search and replace text using substitute commands.

Basic substitution

The substitute command is one of the most powerful editing tools in Vim.

Code
:s/old/new/ " Replace first 'old' on current line
:s/old/new/g " Replace all 'old' on current line
:%s/old/new/g " Replace all 'old' in entire file
:%s/old/new/gc " Replace all with confirmation
  • The g flag means global (all occurrences on a line).
  • The c flag prompts for confirmation at each match.

Advanced substitution

Advanced substitution with ranges, flags, and regex word boundaries.

Code
:5,20s/old/new/g " Replace in lines 5 through 20
:'<,'>s/old/new/g " Replace in visual selection
:%s/old/new/gi " Case-insensitive replace
:%s/\<word\>/new/g " Replace whole word only
:%s/pattern//gn " Count matches without replacing
  • Use \< and \> for word boundaries in Vim regex.
  • The n flag counts matches without performing replacement.

Operators and Text Objects

Combining operators with motions and text objects for powerful editing.

Operators

Operators perform actions on text defined by a motion or text object.

Common operators with motions

The operator + motion pattern is the foundation of Vim editing: {operator}{motion}.

Code
dw " Delete from cursor to next word
d$ " Delete from cursor to end of line
cw " Change word (delete and enter Insert mode)
c$ " Change from cursor to end of line
yip " Yank inner paragraph
>> " Indent current line right
<< " Indent current line left
== " Auto-indent current line
  • Double an operator to apply it to the whole line (dd, yy, cc, >>).
  • Operators can be prefixed with a count: 3dd deletes 3 lines.

Case and filter operators

Case operators change letter casing. The filter operator (!) pipes text through external commands.

Code
gUw " Uppercase from cursor to end of word
guw " Lowercase from cursor to end of word
g~~ " Toggle case of entire line
g~w " Toggle case of word
gUU " Uppercase entire line
guu " Lowercase entire line
!}sort " Filter paragraph through external sort command
  • g~ toggles case, gU uppercases, gu lowercases.
  • The ! operator is powerful for integrating external tools.

Text Objects

Text objects define regions of text for operators to act upon.

Word, sentence, and paragraph objects

i = inner (just the content), a = around (content plus surrounding whitespace/delimiters).

Code
ciw " Change inner word
caw " Change a word (including surrounding space)
dis " Delete inner sentence
dap " Delete a paragraph (including trailing blank line)
yip " Yank inner paragraph
  • ciw is one of the most commonly used text objects for replacing a word.
  • dap is useful for removing entire paragraphs cleanly.

Delimiter-based text objects

Delimiter text objects work with quotes, brackets, parentheses, and HTML/XML tags.

Code
ci" " Change inside double quotes
ca" " Change around double quotes (including quotes)
di( " Delete inside parentheses
da( " Delete around parentheses (including parens)
ci{ " Change inside curly braces
dit " Delete inside HTML/XML tags
cat " Change around tags (including the tags)
ci[ " Change inside square brackets
  • These work regardless of cursor position within the delimiters.
  • Equivalent pairs: ci( = ci), ci{ = ci}, ci[ = ci].

Repeating

Repeating commands and building efficient editing workflows.

Dot command and repetition

The dot command (.) is one of the most powerful features in Vim, repeating the last change.

Code
. " Repeat last change
; " Repeat last f/F/t/T search
, " Repeat last f/F/t/T in reverse
3dd " Delete 3 lines
5j " Move down 5 lines
2yy " Yank 2 lines
4>> " Indent 4 lines
  • Design your edits to be repeatable with dot (e.g., use ciw over individual character edits).
  • Number prefixes work with almost all commands.

Effective dot command usage

Combine search (n) with dot (.) for a powerful manual find-and-replace workflow.

Code
/word " Search for 'word'
ciwreplace " Change word to 'replace'
n " Jump to next occurrence
. " Repeat the change
n " Jump to next
. " Repeat again
  • This pattern gives you control over each replacement, unlike :%s.
  • Use n to skip an occurrence, . to replace it.

Visual Mode

Selecting and operating on text visually.

Visual Selection

Entering Visual mode and selecting text.

Visual mode types

Visual mode provides a way to select text before applying an operator.

Code
v " Enter character-wise Visual mode
V " Enter line-wise Visual mode
Ctrl-V " Enter block-wise Visual mode
gv " Reselect last visual selection
o " Move to other end of selection
O " Move to other corner of block selection
  • Use o to adjust the other end of the selection without starting over.
  • gv is extremely useful after an operation to reselect the same area.

Extending selections

Combine entering Visual mode with text objects or motions to select specific regions.

Code
viw " Select inner word
vip " Select inner paragraph
vi" " Select inside quotes
vi( " Select inside parentheses
vit " Select inside tags
V5j " Select current line and 5 lines below
  • In Visual mode, any motion extends the selection.
  • Text objects in Visual mode select the entire object.

Visual Operations

Operations you can perform on visually selected text.

Common visual operations

After making a visual selection, apply an operator to act on the selected text.

Code
d " Delete selection
x " Delete selection (same as d)
y " Yank (copy) selection
c " Change selection (delete and enter Insert)
> " Indent selection right
< " Indent selection left
= " Auto-indent selection
J " Join selected lines
  • These operations exit Visual mode after execution.
  • Use gv to reselect if you need to apply another operation.

Case and formatting operations

Visual mode allows case changes, formatting, and running Ex commands on selected lines.

Code
~ " Toggle case of selection
U " Uppercase selection
u " Lowercase selection
gq " Format/rewrap selected text
: " Enter command mode for selection (adds '<,'>)
  • Pressing : in Visual mode automatically adds the range '<,'>.
  • gq reformats text to the textwidth setting.

Visual Block

Block-wise visual selection for column editing.

Block selection and editing

Block Visual mode enables column-oriented editing across multiple lines simultaneously.

Code
Ctrl-V " Enter block visual mode
I{text}Esc " Insert text before block on all lines
A{text}Esc " Append text after block on all lines
r{char} " Replace all characters in block with {char}
c{text}Esc " Change block content on all lines
d " Delete the block
  • After pressing I or A, text appears on the first line only; it applies to all lines after pressing Esc.
  • Block mode is invaluable for editing tabular data or adding prefixes.

Practical block editing example

Practical examples of using block visual mode for commenting and uncommenting code.

Code
" Add comment prefix to lines 5-15:
5G " Go to line 5
Ctrl-V " Enter block visual
10j " Extend selection 10 lines down
I# Esc " Insert '# ' at start of each line
" Remove first 2 characters from lines:
Ctrl-V " Enter block visual
10j " Select 10 lines
ll " Extend 2 columns right
d " Delete the block
  • This technique works well for adding/removing comment characters.
  • Use $ in block selection to extend to end of each line regardless of length.

Windows and Tabs

Managing multiple views, windows, tabs, and buffers.

Split Windows

Splitting the Vim window for side-by-side editing.

Creating and navigating splits

Splits let you view and edit multiple files or different parts of the same file.

Code
:sp " Horizontal split (same file)
:sp file " Horizontal split with file
:vsp " Vertical split (same file)
:vsp file " Vertical split with file
Ctrl-W s " Horizontal split (same as :sp)
Ctrl-W v " Vertical split (same as :vsp)
Ctrl-W w " Cycle through windows
Ctrl-W h " Move to window left
Ctrl-W j " Move to window below
Ctrl-W k " Move to window above
Ctrl-W l " Move to window right
  • Ctrl-W is the window command prefix for all window operations.
  • Use Ctrl-W w to cycle quickly between two windows.

Resizing and closing windows

Resize and manage window layout. Prefix resize commands with a count for larger adjustments.

Code
Ctrl-W = " Equalize window sizes
Ctrl-W _ " Maximize current window height
Ctrl-W | " Maximize current window width
Ctrl-W + " Increase height by 1 line
Ctrl-W - " Decrease height by 1 line
Ctrl-W > " Increase width by 1 column
Ctrl-W < " Decrease width by 1 column
Ctrl-W q " Close current window
:only " Close all windows except current
  • Use 10 Ctrl-W + to increase height by 10 lines.
  • Ctrl-W = is useful after creating/closing splits to rebalance.

Tab Pages

Using tab pages for organizing multiple files.

Creating and managing tabs

Tabs in Vim are layouts that can each contain multiple windows/splits.

Code
:tabnew " Open a new empty tab
:tabe file " Open file in a new tab
:tabclose " Close current tab
:tabonly " Close all other tabs
:tabs " List all tabs
  • Vim tabs are different from tabs in other editors. Each tab can contain multiple windows.
  • Use :tabe with a file path to quickly open files in new tabs.

Navigating between tabs

Navigate between tabs using Normal mode shortcuts or Ex commands.

Code
gt " Go to next tab
gT " Go to previous tab
3gt " Go to tab 3
:tabfirst " Go to first tab
:tablast " Go to last tab
:tabmove 0 " Move current tab to first position
:tabmove " Move current tab to last position
  • gt and gT are the fastest way to switch tabs.
  • Tab numbers are 1-indexed in Vim.

Buffers

Managing buffers for efficient multi-file editing.

Listing and switching buffers

Buffers represent open files in memory. You can switch between them without closing any.

Code
:ls " List all buffers
:buffers " List all buffers (same as :ls)
:bn " Go to next buffer
:bp " Go to previous buffer
:b name " Switch to buffer by partial name
:b 3 " Switch to buffer number 3
:b# " Switch to alternate (last used) buffer
  • :b with partial name matching allows quick buffer switching.
  • Ctrl-^ or :b# toggles between the current and last buffer.

Buffer management

Manage buffer lifecycle and apply commands across multiple buffers.

Code
:bd " Delete (close) current buffer
:bd 3 " Delete buffer number 3
:bd file.txt " Delete buffer by name
:set hidden " Allow switching buffers without saving
:%bd " Delete all buffers
:bufdo cmd " Execute command in all buffers
  • set hidden in your vimrc allows switching buffers with unsaved changes.
  • :bufdo is powerful for batch operations (e.g., :bufdo %s/old/new/ge).

Advanced Features

Advanced Vim features for power users.

Macros

Recording and replaying sequences of commands.

Recording and playing macros

Macros record a sequence of keystrokes and replay them. They are stored in registers (a-z).

Code
qa " Start recording macro into register 'a'
q " Stop recording
@a " Play macro stored in register 'a'
@@ " Replay the last executed macro
5@a " Play macro 'a' five times
  • The bottom of the screen shows 'recording @a' while recording.
  • Macros can include any Normal mode commands, motions, and operators.

Practical macro example

A practical macro that wraps each line in quotes and adds a trailing comma.

Code
" Convert a list of words to quoted, comma-separated:
" apple -> 'apple',
" banana -> 'banana',
" cherry -> 'cherry',
qa " Start recording to register a
I'Esc " Insert quote at start
A',Esc " Append quote and comma at end
j0 " Move to start of next line
q " Stop recording
2@a " Apply to next 2 lines
  • End macros with j0 to position for the next line, making them repeatable.
  • Use a large count (e.g., 999@a) to apply a macro to all remaining lines.

Registers

Named storage areas for text, macros, and special values.

Using named registers

Named registers (a-z) let you store multiple pieces of text independently.

Code
"ay " Yank into register 'a'
"ap " Paste from register 'a'
"Ay " Append to register 'a' (uppercase)
:reg " View all register contents
:reg a " View contents of register 'a'
  • Uppercase register name (A-Z) appends to the register instead of overwriting.
  • Registers are shared between yank, delete, and macro operations.

Special registers

Special registers hold system clipboard, last search, last command, and other special values.

Code
"0p " Paste last yanked text (not deleted)
"+y " Yank to system clipboard
"+p " Paste from system clipboard
"_d " Delete to black hole register (truly delete)
"/ " Last search pattern register
": " Last command register
". " Last inserted text register
"% " Current filename register
  • "0 always holds the last yank, even after deleting (which goes to "1-"9).
  • "_ is the black hole register: text deleted into it is truly gone.

Folds

Folding and unfolding sections of code or text.

Managing folds

Folds hide sections of text, making large files easier to navigate.

Code
zo " Open fold under cursor
zO " Open fold under cursor recursively
zc " Close fold under cursor
zC " Close fold under cursor recursively
za " Toggle fold under cursor
zA " Toggle fold under cursor recursively
zM " Close all folds in document
zR " Open all folds in document
  • za is the most convenient for toggling individual folds.
  • zM and zR are useful for getting an overview or seeing all content.

Creating folds

Create folds manually or configure automatic folding by indent, syntax, or other methods.

Code
zf{motion} " Create a fold over motion
zf5j " Create fold over next 5 lines
:3,10fold " Create fold from line 3 to 10
zd " Delete fold under cursor
zE " Delete all folds in window
:set foldmethod=indent " Fold by indentation
:set foldmethod=syntax " Fold by syntax
:set foldmethod=manual " Manual fold creation
  • Manual folds require foldmethod=manual.
  • For code, foldmethod=syntax or foldmethod=indent are most useful.

Spell Checking

Built-in spell checking in Vim.

Spell check commands

Vim has built-in spell checking that highlights misspelled words and offers corrections.

Code
:set spell " Enable spell checking
:set nospell " Disable spell checking
:set spelllang=en_us " Set spell language
]s " Jump to next misspelled word
[s " Jump to previous misspelled word
z= " Show spelling suggestions
zg " Add word to spell file (good word)
zw " Mark word as incorrect (wrong word)
zug " Undo zg (remove from spell file)
  • Misspelled words are highlighted based on your colorscheme.
  • Use ]s and [s to quickly navigate between spelling errors.

Spell checking workflow

A typical workflow for spell-checking a document using Vim.

Code
:set spell " Turn on spell check
]s " Go to first error
z= " See suggestions, pick number
1z= " Accept first suggestion directly
]s " Go to next error
zg " Add technical term to dictionary
  • 1z= accepts the first suggestion without showing the menu.
  • Use zg liberally for technical terms and proper nouns.

Command-Line Tricks

Powerful Ex commands and external command integration.

External commands and filters

Vim integrates with the shell, letting you run commands and pipe text through filters.

Code
:!ls " Run external command
:!python % " Run current file with Python
:r !date " Insert output of date command
:r !curl -s URL " Insert content from URL
:.!tr a-z A-Z " Filter current line through tr
Ctrl-R Ctrl-W " Insert word under cursor in command line
  • % in Ex commands refers to the current filename.
  • :r inserts command output below the cursor.

Normal and global commands

:norm runs Normal mode commands on lines. :g (global) runs commands on matching lines.

Code
:norm A; " Append semicolon to current line
:%norm A; " Append semicolon to all lines
:g/pattern/d " Delete all lines matching pattern
:v/pattern/d " Delete all lines NOT matching pattern
:g/TODO/norm O " Add blank line above every TODO
:. " Repeat last Ex command
  • :g/pattern/command is incredibly powerful for batch line operations.
  • :v is the inverse of :g, matching lines that do NOT contain the pattern.

Options and Settings

Common Vim options for customizing your editing environment.

Display and search settings

Configure how Vim displays content and handles searching.

Code
:set number " Show line numbers
:set relativenumber " Show relative line numbers
:set cursorline " Highlight current line
:set hlsearch " Highlight search matches
:set incsearch " Show matches while typing
:set ignorecase " Case-insensitive search
:set smartcase " Case-sensitive if uppercase present
:set nowrap " Disable line wrapping
  • Combine ignorecase with smartcase for intelligent case matching.
  • Toggle any boolean option with :set option! (e.g., :set number!).

Indentation and tab settings

Configure how Vim handles indentation, tabs, and whitespace display.

Code
:set expandtab " Use spaces instead of tabs
:set tabstop=4 " Display width of tab character
:set shiftwidth=4 " Number of spaces for auto-indent
:set softtabstop=4 " Spaces per Tab keypress
:set autoindent " Copy indent from current line
:set smartindent " Smart auto-indenting for C-like code
:set list " Show invisible characters
:set listchars=tab:>-,trail:. " Define how to show invisibles
  • Always set all four tab-related options together for consistency.
  • Use :retab to convert existing tabs to spaces (or vice versa).

Redirection and Pipes

Piping text to and from external commands.

Filtering and piping

Vim can pipe buffer content to shell commands and read results back.

Code
:w !cmd " Pipe buffer content to external command
:r !cmd " Read command output into buffer
:%!sort " Sort all lines in the file
:%!sort -u " Sort and remove duplicates
:'<,'>!sort " Sort selected lines
:%!python -m json.tool " Format JSON
  • :w !cmd writes to stdin of cmd, not to a file named !cmd.
  • :%!cmd replaces the entire buffer with the command output.

Clipboard and advanced piping

Use external tools for clipboard operations and advanced text processing.

Code
:w !pbcopy " Copy buffer to macOS clipboard
:r !pbpaste " Paste from macOS clipboard
:w !xclip -sel clip " Copy to clipboard on Linux
:w !wl-copy " Copy to clipboard on Wayland
:%!column -t " Align text into columns
:%!awk '{print $2}' " Extract second field of every line
  • Choose the clipboard command based on your operating system.
  • Combine with visual selection for operating on specific regions.