Modes
Vim currently supports 7 basic modes.
- Normal mode.
- Visual mode (v / V).
- Select mode.
- Insert mode (i).
- Command-line mode (:). Serves as a prefix for many commands.
- Ex mode.
- Terminal-job mode.
Esc returns the editor to normal mode. This will also cancel a partial, unwanted command.
Refer to :help vim-modes
for details, including information on additional
advanced editor modes, which aren’t covered here.
Saving and exiting
Closing out of vim is often a frustrating step for new users.
:w
: Write (save) changes to disk.:q
: Quit (exit), as long as there are no unsaved changes.:wq
: Write changes and quit.:q!
: Quit without saving changes.:x
/ ZZ: Quit, saving changes.:qall!
/:qa!
: Force quit, even with multiple buffers open.
Text editing basics
Note that vim uses different naming conventions.
Normal | Vim |
---|---|
cut | delete |
copy | yank |
paste | put |
Insert
These commands will enter insert mode.
- i: Insert before cursor.
- I: Insert before line (i.e. to beginning of line).
Use Esc to exit back to normal mode.
Append
- a: Append after cursor.
- A: Append after line (i.e. to end of line).
- o: Append (open) a new line after current line.
- O: Append (open) a new line before current line.
Replace
- r: Replace one character.
- R: Replace many characters. Good for columns of text.
- cc: Change (replace) entire line.
- cw: Change (replace) to the end of the word.
- C / c$: Change (replace) from cursor to end of line.
- cit: Change text inside html tag.
- ci': Change text inside single quotes.
- ci{: Change text inside curly brackets.
Delete (cut)
Almost all deletion commands are performed by typing d followed by a motion.
- dd /
:d
: Delete a line. - 2dd: Delete 2 lines.
- dw: Delete current word.
- D / d$: Delete from cursor to end of line.
- x: Delete character to the right of (under) cursor.
- X: Delete character to the left of (before) cursor.
- s: Delete character and substitute text.
- S: Delete line and substitute text (same as cc).
- di': Delete text inside single quotes.
Yank (copy)
- yy: Yank current line.
- 2yy: Yank 2 lines.
- yw: Yank current word.
- Y / y$: Yank from cursor to end of line.
Put (paste)
- p: Put the clipboard after cursor.
- P: Put the clipboard before cursor.
Undo/redo
- u: Undo the last command.
- U: Undo all changes to line.
- Ctrl-r: Redo the last command.
Also refer to visual mode, which is extremely useful for text selection.
Movement/navigation
Characters
Vim uses the home row for navigation. The arrow keys also work, but these are faster to type because you don’t have to lift your hand.
- h: Move cursor left.
- j: Move cursor down.
- k: Move cursor up.
- l: Move cursor right.
Prefix a cursor movement command with a number to repeat it. For example, 4j moves down 4 lines.
Words
- w: Move to next word.
- W: Move to next blank delimited word.
- e: Move to the end of the word.
- E: Move to the end of blank delimited word.
- b: Move to the beginning of the word.
- B: Move to the beginning of blank delimted word.
Sentences
- (: Move a sentence back.
- ): Move a sentence forward.
- {: Move a paragraph back.
- }: Move a paragraph forward.
Lines
- 0: Move to the begining of the line.
- ^: Move to the first non-blank character of the line.
- $: Move to the end of the line.
- gg: Move to first line (beginning).
- G: Move to last line (end).
- 2G /
:2
: Move to line 2. - 2k: Move up 2 lines.
- 2j: Move down 2 lines.
- '': Go to the last place you were.
Scrolling (screen)
See :help scroll
for details.
- H: Move to top (head) of screen.
- M: Move to middle of screen.
- L: Move to bottom (last) of screen.
- %: Move to associated
()
,{}
,[]
block. - Ctrl-f: Scroll a full page down (forwards).
- Ctrl-d: Scroll a half page down.
- Ctrl-b: Scroll a full page up (backwards).
- Ctrl-u: Scroll a half page up.
Visual mode
Selecting a visual mode type
- v: Enter visual mode.
- V: Enter linewise visual mode.
- Ctrl-v: Enter visual block mode.
Marking text
- o: Move to other end of marked area.
- O: Move to other corner of block.
- aw: Mark a word.
- ab: A block with
()
. - aB: A block with
{}
. - ib: Inner block with
()
. - iB: Inner block with
{}
. - ma: Mark a line in a file with marker a.
- 'a: After moving around, go back to line of marker a.
:marks
: View all the marks.
Commands that work on marked text
- y: Yank marked text.
- d: Delete marked text.
- >: Shift text right (increase indent).
- <: Shift text left (decrease indent).
- ==: Fix indentation of current line.
- gg=G / (v)=: Fix indentation of entire file.
- =G: Reindent the current cursor till end of buffer.
- ~: Toggle between upper and lower case.
-
gq</kbd> Hard wrap text at line width defined by `textwidth` variable. Our vim configuration uses 80 characters.
Ranges
A range is either a single address or a pair of addresses separated by ,
or ;
.
Here are some examples using :d
as the short form of :delete
.
:d
: Delete current line.:.d
: Delete current line.:1d
: Delete first line.:$d
: Delete last line.:1,$d
: Delete all lines.:%d
: Delete all lines (syntactic sugar for1,$
).:.,5d
/:,5d
: Current line to line 5.:,+3d
: Delete current line and the next 3 lines.:1,+3d
: Delete first line to current line + 3.:,-3d
: Delete current line and the last 3 lines. Vim will prompt you, since this is a reversed range.:/^foo/,$delete
: Delete from the next line that starts with “foo” to the end.:/^foo/+1,$delete
: Delete from the line after the line that starts with “foo” to the end.:3,'xdelete
: Lines 3 to the line marked by markx
.
Note that instead of ,
, ;
can be used as a separator.
The difference is that in the case of from,to
, the to is relative to the current line, but when using from;to
, the to is relative to the address of from!
Assuming you’re on line 5, :1,+1d
would delete lines 1 to 6, whereas :1;+1d
would only delete lines 1 and 2.
Stacking range patterns
The /
address can be preceded with another address.
This allows you to stack patterns:
:/foo//bar//quux/d
This would delete the first line containing “quux” after the first line containing “bar” after the first line containing “foo” after the current line.
Search and replace inside a file
Find
/pattern
Enter: Search forward for string.
Useful search prefixes:
- /: Search forward.
- ?: Search backward.
- \*: Search forward for current word under the cursor.
- #: Search backward for current word under cursor.
Once interactive after pressing Enter:
- n: Search for next match.
- N: Search for previous match.
- &: Repeat last
:s
command.
Quick search
- f/: Move forward to first
/
character. - t/: Move forward right before the first
/
character. - %: Find matching brace, parenthesis, etc.
Replace
Substitution is accomplished with the :s
command.
It is commonly used in combination with ranges or the :g
command.
Vim uses a syntax similar to sed:
:s/<pattern>/<replacement>/<flags>
Optional flags
g
: Globally replace all occurrences.c
: Confirm replacements.
Examples
:s/foo/bar/g
: Change each “foo” to “bar” in the current line.:%s/foo/bar/g
: Change each “foo” to “bar” in all the lines.
Code folding
- za: Toggle the current fold. Will open if closed, and vice versa.
- zo: Open current folded code chunk.
- zc: Close current folded code chunk.
- zr: Reduce (open) all folds in the current buffer.
- zm: More folding (close) in the current buffer.
- zA: Toggle all in cursor.
- zO: Open all in cursor.
- zC: Close all in cursor.
- zR: Reduce (open) all folds in the document.
- zM: More folding (close) in the entire document.
File and window management
:w file
: Write file.:r file
: Read file in after line.:n
: Go to next file.:p
: Go to previous file.:e file
: Edit file.!!program
: Replace line with output from program.
Buffer management
Vim supports multiple files, tabs, and window splitting. I recommend using this instead of tmux whenever possible because it’s easier to manage the clipboard.
:ls
: List open buffers.:b
name/number: Switch to specific open buffer.
Multiple files
Vim supports opening multiple files directly from the shell. Use the ‘-O’ flag to split vertically or ‘-o’ to split horizontally.
vim -O file1 file2
Alternatively, you can manage files inside vim.
:e filename
: Edit a file in a new buffer.:bn
/:bnext
: Go to the next buffer.:bp
/:bprev
: Go to the previous buffer.:bd
: Delete a buffer (close a file).:sp filename
: Open a file in a new buffer and split window.:vsp filename
: Open a file in a new buffer and vertically split window.- Ctrl-w s: Split window horizontally.
- Ctrl-w v: Split window vertically.
- Ctrl-w w: Switch windows.
- Ctrl-w q: Quit a window.
- Ctrl-w r: Reverse (flip) the windows.
To focus (zoom) the active split window, use Ctrl-w | (for a vertical split) or \_ (for a horizontal split). Exit from the focus mode with Ctrl-w =.
Tabs
:tabnew filename
: Open a file in a new tab.:tabmove 2
: Move current tab to the 2nd position (indexed from 0).:tabc
;:tabclose
: Close the current tab and all its windows.:tabo
;:tabonly
: Close all tabs except for the current one.- gt;
:tabn
;:tabnext
: Move to the next tab. - gT;
:tabp
;:tabprev
: Move to the previous tab. - 2gt: Move to tab number 2.
- Ctrl-wt: Move the current split window into its own tab.
Explore
:Explore
: Explore file directory.:Explore!
: Explore file directory with vertical splitting.:bd
: Exit explore mode.:Sexplore
: Split-screen explorer.:Hexplore
: Horizontal split-screen explorer.:Vexplore
: Vertical split-screen explorer.:Texplore
: Tabbed full-screen explorer.:gt
: Switch between tabs.:tabn
: Next tab.:tabb
: Back (previous) tab.
Terminal
The built-in terminal was introduced in Vim 8.1.
:term
/:terminal
: Open terminal, using a horizontal split.:vert term
/:vertical terminal
: Open terminal, using a vertical split.- Ctrl-D: Kill hanging shell session.
Copy and paste source code
- Yank (copy) lines as normal.
- Switch to terminal window using Ctrl-w.
- Paste copied text using Ctrl-w "" (two quotes).
Navigation
While on the terminal in vim, you have to switch to “Terminal-Normal” mode, with Ctrl-w Shift-N (note case). Now you can use the usual vim commands to move around, cut, copy and paste. Once finished, use either i or a to switch back to the prompt.
Miscellaneous
- ;: Repeat last command.
- .: Repeat last text-changing command.
- J: Join line below to the current one.
- xp: Transpose two letters (delete and paste).
:%sort u
: Sort lines, removing duplicates (keep unique).:!CMD
: Run an external shell command (e.g.:!ls ~
).
Line numbers
:set number
: Enable line numbers.:set nonumber
: Disable line numbers.
Useful help commands
:help myvimrc
:help local-options
:help setlocal
:help map-local
Useful local options
:setlocal wrap
:setlocal nowrap
:setlocal wrap!
:setlocal number
:setlocal nonumber
:setlocal number!
Customization
Vim supports customization through a .vimrc
configuration file, and plugins in
a .vim
directory.
When using a graphical Vim client, such as MacVim, you can also customize
the appearance with a .gvimrc
file.
Note that Vim 8+ now contains a
native third-party package manager.
Leader key
Vim calls the prefix key the leader. Vim also has a second leader key called local leader. This is meant to be a prefix for mappings that only take effect for certain types of files, like Python files or HTML files.
You can be specific about when you want mappings to apply by using
nmap
, vmap
, and imap
.
These tell Vim to only use the mapping in normal, visual,
or insert mode respectively.
Each of the *map
commands has a *noremap
counterpart that ignores
other mappings: noremap
, nnoremap
, vnoremap
, and inoremap
.
Always use these non-recursive variants when defining custom mappings.
Here are some keys not used in normal mode that may be suitable for remapping:
- -
- Backspace
- Enter (aka CR; carriage return)
- Space
- H
- L
Conditionals
Version specific conditionals (e.g. Vim 8.2+):
if v:version >= 802
set background=dark
else
set background=light
endif
Use finish
inside if
/else
conditional to early return.
Colors
:colorscheme
Space Tab: List installed color schemes.
Plugins
NERDTree
NERDTree is a file browser for Vim.
- Ctrl-N: Open NerdTREE file browser.
- s: Open file in a new vertical split.
- i: Open file in a new horizontal split.
- m a: Create a new file (child node). Simply enter the file name and hit Enter.
Nvim-R
Nvim-R is an excellent R IDE for REPL inside Vim. Conceptually, it works similarly to ESS for Emacs. Refer to the official Nvim-R.txt documentation file for additional information and configuration options.
Note: The <LocalLeader>
key is \
by default.
To use the plugin, open an R or R Markdown file in Vim, and then type <LocalLeader>rf
.
This will spawn a new R console buffer.
Depending on the size of the terminal window, this will be either
horizontal (narrow window) or vertical (wide window).
Now you will be able to use the plugin key bindings to send commands to R.
Inside a graphical Vim client, such as MacVim, an R menu option will appear.
R Menu Command
----------------------------------------------------------
Start/Close
. Start R (default) \rf
. Start R (custom) \rc
--------------------------------------------------------
. Close R (no save) \rq
. Stop R :RStop
Send
. File \aa
. File (echo) \ae
. File (open .Rout) \ao
--------------------------------------------------------
. Block (cur) \bb
. Block (cur, echo) \be
. Block (cur, down) \bd
. Block (cur, echo and down) \ba
--------------------------------------------------------
. Chunk (cur) \cc
. Chunk (cur, echo) \ce
. Chunk (cur, down) \cd
. Chunk (cur, echo and down) \ca
. Chunk (from first to here) \ch
--------------------------------------------------------
. Function (cur) \ff
. Function (cur, echo) \fe
. Function (cur and down) \fd
. Function (cur, echo and down) \fa
--------------------------------------------------------
. Selection \ss
. Selection (echo) \se
. Selection (and down) \sd
. Selection (echo and down) \sa
. Selection (evaluate and insert output in new tab) \so
--------------------------------------------------------
. Paragraph \pp
. Paragraph (echo) \pe
. Paragraph (and down) \pd
. Paragraph (echo and down) \pa
--------------------------------------------------------
. Line \l
. Line (and down) \d
. Line (and new one) \q
. Left part of line (cur) \r<Left>
. Right part of line (cur) \r<Right>
. Line (evaluate and insert the output as comment) \o
. All lines above the current one \su
Command
. List space \rl
. Clear console \rr
. Remove objects and clear console \rm
--------------------------------------------------------
. Print (cur) \rp
. Names (cur) \rn
. Structure (cur) \rt
. View data.frame (cur) in new tab \rv
. View data.frame (cur) in horizontal split \vs
. View data.frame (cur) in vertical split \vv
. View head(data.frame) (cur) in horizontal split \vh
. Run dput(cur) and show output in new tab \td
. Run print(cur) and show output in new tab \tp
--------------------------------------------------------
. Arguments (cur) \ra
. Example (cur) \re
. Help (cur) \rh
--------------------------------------------------------
. Summary (cur) \rs
. Plot (cur) \rg
. Plot and summary (cur) \rb
--------------------------------------------------------
. Set working directory (cur file path) \rd
--------------------------------------------------------
. Sweave (cur file) \sw
. Sweave and PDF (cur file) \sp
. Sweave, BibTeX and PDF (cur file) (Linux/Unix) \sb
--------------------------------------------------------
. Knit (cur file) \kn
. Knit, BibTeX and PDF (cur file) (Linux/Unix) \kb
. Knit and PDF (cur file) \kp
. Knit and Beamer PDF (cur file) \kl
. Knit and HTML (cur file, verbose) \kh
. Knit and ODT (cur file) \ko
. Knit and Word Document (cur file) \kw
. Markdown render (cur file) \kr
. Spin (cur file) (only .R) \ks
--------------------------------------------------------
. Open attachment of reference (Rmd) \oa
. Open PDF (cur file) \op
. Search forward (SyncTeX) \gp
. Go to LaTeX (SyncTeX) \gt
Edit
. Complete object name CTRL-X CTRL-O
--------------------------------------------------------
. Indent (line) ==
. Indent (selected lines) =
. Indent (whole buffer) gg=G
--------------------------------------------------------
. Toggle comment (line, sel) \xx
. Comment (line, sel) \xc
. Uncomment (line, sel) \xu
. Add/Align right comment (line, sel) \;
--------------------------------------------------------
. Go (next R chunk) \gn
. Go (previous R chunk) \gN
Object Browser
. Open/Close \ro
. Expand (all lists) \r=
. Collapse (all lists) \r-
. Toggle (cur) Enter
fzf.vim
Fuzzy file matching is supported in Vim with fzf.vim. This is an incredibly powerful feature that enables quick searching across files directly in Vim.
:FZF :Files Fuzzy match against files. :Rg Fuzzy ma :Ag :GFiles Git files (git ls-files)
git ls-files
Bang-versions of the commands (e.g. :FZF!
or :Files!
) opens fzf in fullscreen.
:FZF! open fuzzy file search full screen
:Files
: Runs $FZF_DEFAULT_COMMAND if defined (e.g. ripgrep rg
). This will include a split file preview viewer.
:Rg
: Run a ripgrep search in fuzzy file viewer, with a preview window.
:Ag
: Run a silver searcher (Ag) search in fuzzy file viewer, with a preview window