Skip to content

Vim Shortcuts

From vimtutor

To move the cursor, press the h,j,k,l keys as indicated.

^ k Hint: The h key is at the left and moves left. < h l > The l key is at the right and moves right. j The j key looks like a down arrow. v

DescriptionShortcut
Enter insert mode, from normal modei (insert before cursor), a (append after cursor)
Leave insert mode, activate normal modeEsc or Ctrl + c or Ctrl + [ (US Keyboard)
Leave insert mode, activate normal mode for 1 commandCtrl + o
Quit and SaveZ Z , :wq
Quit and do not saveZ Q , :q!
DescriptionShortcut
File Explorer, open:Explore or :edit .
File Explorer, new tab in current directory:Te
File Explorer, open file selected in new tabt
File Explorer, open file selected in splits
File Explorer, Delete fileD
File Explorer, Rename fileR
File Explorer, Make directoryd

Command Mode, aka Ex Mode - Frequently Used

Section titled “Command Mode, aka Ex Mode - Frequently Used”
DescriptionShortcut
Save (write):w
Save all open buffers:wa
Source, current file:source %
Quit:q
Save only if there are changes and quit:x
Save, write buffer even if no changes and quit:wq
See working directory:pwd
Change directory to current open file/buffer:cd %:p:h
Change directory to specific directory:cd <directory>
Change directory to current working directory (cwd):lcd
Quit without saving:q!
DescriptionShortcut
Search: command historyC-f
Search: set case insensitive:set ic
Search: set case sensitive:set noic
Search: highlight:set hls
File, Open, Edit <file>:e <file> or :edit <file
File, Save as:f
File, set file encodingset fileencoding=utf8
Show list of commands / autocomplete: <…> Ctrl + D or tab
Autocomplete, chose choicesTab
Autocomplete, accept choice, keep in command modeCtrl + y
Line numbers: absolute as in file / deactivate:set nu :set nonu
Line numbers: relative to point / deactivate:set rnu :setnornu
Line numbers: hybrid of above / deactivate:set:nu rnu :set nonu nornu
Earlier, go back in time of file, 2 number of times:earlier 2
Earlier, go back in time of file, {N} minutes before:earlier {N}m
Make, run make by default or makeprg defined command:make
Messages, Vim logs View:messages
Lines, copy given line range, see :h cmdline-ranges:copy or :t
Lines, move given line range:norm
Normal mode commands execution:move or :m
Key mappings, depends on mode, see :h map-overview:map
Settings, Tab stop or number of spaces for a tab:set tabstop 2
Digraphs, show call digraph codes:diagraphs

For :make, output will go to quickfix list for easy fixes on items

Search for patterns with :grep, :lgrep, :vimgrep, :lvimgrep

Section titled “Search for patterns with :grep, :lgrep, :vimgrep, :lvimgrep”
DescriptionShortcut
Grep, with external application:grep
Grep, see results in quickfix list:cw or :copen
Grep, with external application, local window:lgrep
Grep, see results quickfix list, local window:lw or :lopen
Grep, on all files with pattern:grep my-pattern *
Grep, include hidden dotfiles:grep my-pattern ./.*

Usage:

:vim[grep][!] {pattern}[g][j] {file} …

  • ‘g’ option specifies that all matches for a search will be returned instead of just one per line
  • ‘j’ option specifies that Vim will not jump to the first match automatically.

Supports with Vim’s edit-compile-edit cycle to edit code, compile for errors and fix them.

DescriptionShortcut
Quickfix, Open:copen
Quickfix, Close:cclose
Next item:cnext
Previous item:cprev

For c, think of it as compilation

  • Copy previous 2 lines and current line: :-2,t
  • Move line down: :m+1, move line up 2 :m-2
  • Append \ to all lines in buffer: :%norm A\\
  • In Python, comment all lines with the word print: :g/print/norm I#
  • Find all lines with the pattern beg.*tab (e.g. \begin{tabular}) and go to line before and append \ to line: g/beg.*tab/norm kA\\
    • Find all the lines matching the pattern beg.*tab (a way for me to match \begin{tabular} without having to type the whole thing).
    • For each of those lines, go to the preceding line.
    • Append \ to that line.
  1. Global :g examples - act on range, pattern and Ex execute command

    Source: Power of g - Vim Tips

    DescriptionShortcut
    Global, act on range, pattern and execute command:[range]g/pattern/cmd
    Global, Display context (5 lines) for all occurrences of a pattern:g/pattern/z#.5
    Global, Delete all lines matching a pattern:g/pattern/d
    Global, Delete all lines not matching a pattern:g!/pattern/d or :g!/pattern/d
    Global, Delete all blank lines:g/^$`/d
    Global, Copy all lines matching pattern to end of file:g/pattern/t`$
    Global, Copy all lines matching a pattern to register ‘a’qaq:g/pattern/y A
    Global, Fast Delete (do not copy) all lines matching a pattern:g/pattern/d _

    See more with

    • :help ex-cmd-index provides a list of Ex commands.
    • :help 10.4 is the section of the user manual discussing the :global command.
    • :help multi-repeat talks about both the :g and :v commands.
  2. Using do commands to search and replace

    Source: Search and replace in multiple files - Vim Tips Wiki

    • :argdo: (all files in argument list)
    • :bufdo (all buffers)
    • :tabdo (all tabs)
    • :windo (all windows in current tab)
    • :cdo (all files/items listed in quickfix list)

    Search and replace words in files in a directory using :vimgrep or :grep oldpattern *, then C-q to add all items to quickfix list, :cdo s/oldpattern/new/g on entries to make changes

    Vim command mode:

    Terminal window
    # Search and replace in all open buffers from :ls
    :bufdo %s/pattern/replace/ge | update
    # Explanation
    # bufdo Apply the following commands to all buffers.
    # %s Search and replace all lines in the buffer.
    # pattern Search pattern.
    # replace Replacement text.
    # g Change all occurrences in each line (global).
    # e No error if the pattern is not found.
    # | Separator between commands.
    # update Save (write file only if changes were made).
    # Suppose all *.cpp and *.h files in the current directory need to be changed (not subdirectories)
    # use the argument list (arglist):
    :arg *.cpp All *.cpp files in current directory.
    :argadd *.h And all *.h files.
    :arg Optional: Display the current arglist.
    :argdo %s/pattern/replace/ge | update Search and replace in all files in arglist.
    # Search and replace, change, with all files
    :arg **/*.cpp All *.cpp files in and below current directory.
    :argadd **/*.h And all *.h files.
    ... As above, use :arg to list files, or :argdo to change.
    # Replace current word
    :arg **/*.cpp All *.cpp files in and below current directory.
    :argadd **/*.h And all *.h files.
    ... As above, use :arg to list files, or :argdo to change.
    # Replace items in quickfix list
    :cdo s/variable_old_name/variable_new_name/g
    # Replace items in quickfix list with prompt
    :cdo s/variable_old_name/variable_new_name/gc
DescriptionShortcut
Show file location and statusCtrl + g
Retrieve and place in buffer:r <file or external command>
Spell check:set spell
DescriptionShortcut
Execute shell command:!<command>
  1. External Command Examples

    Terminal window
    # Execute shell command to list directory, then press enter to return to vim
    !ls
    # Get command output of {cmd} and place in buffer
    :r !{cmd}
    # Place date in buffer
    :r !date
    # Get file and place in buffer
    :r {file}
    # Replace current line with output of shell
    # Example use: decoding strings, formatting text like json, using . for the current line
    :.!{cmd}
    # Replace entire buffer with command output, using % for entire
    :%!{cmd}
    # Replace a selection with the output of a shell command
    # Example use: sorting, complex text changes
    :'<,'>!{cmd}
    #### Sort entire buffer
    :% !sort
    # Send current buffer as input to a command
    :w !{cmd}
    ## Practical Examples
    ### Backup a file
    :!cp % %.bak
    ### Insert External Data
    #### Date
    :r !date
    ### Buffer as command input
    #### Create files listed in the buffer
    :w !xargs touch
    #### Decode base64 string on current line and replace the line in buffer
    :.!base64 -d
    #### Format current line json
    :.!jq .
    #### Sort selection
    :'<,'>!sort
    #### Sort case insensitive
    :'<,'>!sort i
    1. Key binding

      Execute current line and output the result to the command line. Execute in bash and see result in Vim

      vim.keymap.set(“n”, “<leader>ex”, “:.w !bash -e<cr>”, opts)

      Execute file and see results in Vim

      vim.keymap.set(“n”, “<leader>eX”, ”:%w !bash -e<cr>”, opts)

      6 Practical External Command Tricks: Level Up Your Neo(vim) Skills

Terminal window
# Copy current file name to system clipboard register @+
:let @+ = expand('%')
# expand('%') gets the current file name
# Pipe visual selection to shell command
:'<,'>w !psql $DATABASE_URL > sql.out
# Use case is running an SQL statement in vim, piping to a database connection
# and getting the output in a file

This first table per DevOps Bootcamp - Operating Systems and Linux Basics - DevOps Bootcamp - Operating Systems and Linux Basics

Other table per vimtutor command

DescriptionShortcut
Delete 10 linesd10, d
Delete all lines:%d
Delete character at pointx
Delete linedd
Enter Insert mode, append text at end of character at pointa
Enter Insert mode, Append text at end of line, insert modeA
Enter Insert mode, at beginning of lineI
Enter Insert mode, at new line below / above current oneo, O
Go to, beginning of filegg
Go to, end of fileG
Go to, file, url at point (open with system app)gf , gx
Go to, last insert modegi
Go to, last selected textgv
Go to line 12, Go to line 10012G, 100G or :100
Jump history back (o for out), forward (i for in)C-o, C-i
Jump to beginning of line (bol)0 / Home / ^ (soft)
Jump to end of line (eol)$ / End
Repeat last command, repeat macro (like command, inserts, combos).
Replace all occurrences of stringold with new, new can be blank:%s/stringold/new
Replace in region stringold with new, new can be blank:’<,‘>s/stringold/new/g
Search: command historyq: (like C-f in command mode)
Undou

Editing, Selection (Marking), Text viewing and editing

Section titled “Editing, Selection (Marking), Text viewing and editing”
DescriptionShortcut
Case of character at point, toggle~
Case of inner tag selection, toggleg~it
Case of word, toggleg~w
Copy 1 to 10 lines of file:1,10y
Copy (yank) entire file:%y or gg v G, or :1,$y
Copy (yank) entire lineyy
Copy (yank inside) content inside quotations “yi”
Copy (yank) selectiony
Copy (yank) wordyw
Fold, closezc
Fold, openzo
Format, auto format= =
Format, auto format file= g
Join linesJ
Put (paste deleted or copied text)p
RedoCtrl + r
Select, Start select - visual selectionv
Select, visual and selected areav i <choose selection options>
Select, visual and text inside selected symbol, like bracketv i ], v i ’, v i “
Select, visual block mode (rectangle mark, multiple cursor select)C-v
Select, visual line modeV
  • p can be combined with dd to delete and then paste the deleted line.

Source: :h registers, https://www.brianstorti.com/vim-registers/

DescriptionShortcut
Registers mini-mode (insert mode)C-r
Registers mini-mode (insert mode), paste (system clipboard)+
Registers mini-mode (insert mode) paste from register ‘a’C-r a
Register - access register at char ‘r‘“r
Register - yank text to register ‘r‘“ry
Register - paste text from register ‘r‘“rp
Registers - List, last 0-9 registers are last yanked (copied) text:reg
Registers - List:reg a b c
  1. 4 read only Registers

    DescriptionShortcut
    Register: Last inserted text”.
    Register: Current file path”%
    Register: Last executed command”:
    Register: Alternative file, like last edited file”#
  2. Expression and Search Registers

    DescriptionShortcut
    Register: Expressions”=
    Register: Search”/
    1. Example use

      • ”. to write same text twice
      • ”% enter current file name in commands
      • ”: to re run the last command like :w
      • ”# is the file used with Ctrl + ^
      • #= used with results of expression, like in insert mode, do Ctrl+r = and do 2+2 <enter>, then 4 is printed. Or do Ctrl+r = and in the command do system('ls') <enter> and the output of the ls command is pasted in the buffer
      • ”/ to reuse the last searched word for another search and search and replace
  3. Moving by Words (“web and WEB”) and Lines, Go to words, line positions

    DescriptionShortcut
    Move one word forward / after whitespacew / W
    Move one word backward / after whitespaceb / B
    Move to end of word / after whitespacee / E
    Move to word after next whitespaceW
    Move to end of line$
    Move to beginning of line0
    Move to first non blank character^
    • Specifically, a capital W will move to just after the next whitespace character, where a lowercase w will use other forms of punctuation to delimit a word.
    1. Listing 9. Example Method Call and usage of web and WEB

      Source: Chapter 3: Getting Around - LazyVim for Ambitious Developers

      myObj.methodName("foo", "bar", "baz")
      -----ww---------w-w--w--ww--w--ww--w---->
      ------------------------W------W-------->
      DescriptionShortcut
      Replace character at pointr + <character to replace>
      Replace mode (like Insert mode, delete replaced characters)R

      v visual selection can be combined with commands d for delete, y for copy, c for change

  4. Open lines

    DescriptionShortcut
    Open line below cursor, insert modeo
    Open line above cursorO
  5. Files

    DescriptionShortcut
    Save selected lines to file FILENAME:w FILENAME
  6. Combination Commands

    DescriptionShortcut
    Replace content between symbolsdi + <symbol> like di”
    Cut content between symbolsci + <symbol> like ci(
    Swap lines up and down (delete line, paste it)ddp
    Delete entire document - G from first line, gg from last linedG or dgg
    Auto indent entire documentgg=G
  1. Movement

    DescriptionShortcut
    Jump # of times using hjkl cursor10j / #j
    Page UpCtrl + b
    Page DownCtrl + f
    Half page upCtrl + u
    Half page downCtrl + d
    Move cursor top, middle, bottom of screen(Shift) H, M, L
    z mini mode: Move screen and leave cursor, top, bottom, middlezt, zb, zz
    Search word at point*
    Begin/End of sentence( / )
    Begin/End of paragraph{ / }
    Find mode, character, move to next matchf <char>
    Find mode, move to next match of pattern;
    Find mode (til / until), character, move to before itt <char>
    Navigation Previous, method start[m
    Navigation Previous, method end[M
    Navigation Previous, ( or { or <[( or [{ or [<
    Navigation Next )])
    Navigation Previous, Spelling error[s
    Navigation Next, Spelling error]s
  2. Search and Replace

    DescriptionShortcut
    Search text in file forwards/ + <phrase> + Enter
    Search next / previousn / N
    Search text in file backwards? + <phrase> + Enter
    Find matching bracket%
    Change text in bracketsci[ or ci] or ci{
    Search x and Replace with y in entire file:%s/x/y/g
    1. Search and Replace Command Mode

      • To substitute new for the first old in a line type :s/old/new
      • To substitute new for all ‘old’s on a line type :s/old/new/g
      • To substitute phrases between two line #‘s type :#,#s/old/new/g
      • To substitute all occurrences in the file type :%s/old/new/g
      • To ask for confirmation each time add ‘c’ :%s/old/new/gc

      Search and replace also takes regex like \d for digits, see :help pattern-search

  3. Tags

    DescriptionShortcut
    Find tagC-]
    Find ambiguous tagg C-]
    Jump back in tag jump stackC-t

Using d delete operator and a motion that the operator will operate on

DescriptionShortcut
Delete word with first character at pointdw
Delete to end of lined$
Delete to end of current wordde
  1. Delete with Counts

    DescriptionShortcut
    Delete 2 words from pointd2w / d#w
    Delete 2 / # of lines2dd / #dd
  2. Change Operator

    Delete and make changes

    DescriptionShortcut
    Delete to end of word and insert modece
    Delete line and insert modecc
    Delete line to end from point and insertc$
DescriptionShortcut
Move cursor 2 / # words forward2w / #w
Move cursor 2 / # words backward2b / #b
Move curse to end of 3 / # forward3e / #e
DescriptionShortcut
Record macro to register like aqa
Record macro to register, then quitq<register><commands>q
Stop macro during recordingq
Run macro@
Run macro at register w 6 times6@w
Run last macro@@

Source: :h recording, https://www.redhat.com/sysadmin/use-vim-macros and https://www.brianstorti.com/vim-registers/

  • To record a macro and save it to a register, type the key q followed by a letter from a to z that represents the register to save the macro, followed by all commands you want to record, and then type the key q again to stop the recording.
  • Example to store macro in register a, go down and delete line and then stop macro recording: qajddq
  1. Macros are just text and can be edited, examples

    • Add a semicolon to end of the w macro :let @W=‘i;’
      • W in uppercase means append value to the register
    • Edit the register :let @w ‘<Ctrl-r w> and change what you want and close the quotes
    • Copy ivim is awesome into the clipboard register ”+ and execute @”+
  2. Sample Key Combinations

    Delete lines containing a string in a file

    :g/<yourstring>/d

    • :g Prepare to execute a command globally (on all lines that match a certain pattern).
    • /<yourstring> Start specifying the pattern to match <yourstring>. Replace this with the string you want to delete lines based on.
    • / End specifying the pattern to match.
    • d The command to execute on all lines that match the pattern. In this case, delete those lines.

Source: Using Marks - Vim Tips Wiki

DescriptionShortcut
Mark place in filem <lower case letter>
Mark place in file to access in any filem <upper case letter>
Marks, normal mode, go to mark` <mark letter>
Marks, list marks:marks
DescriptionShortcut
Delete word at pointC-w
Delete character at pointC-h
Run normal mode command, then run commandC-o
Digraph, insertC-k
Digraph, insert alphaC-k a*
Digraph, insert other Greek lettersC-k <US keyboard letter>*

From vim :h digraph

Diagraphs are used to enter characters that normally cannot be entered by an ordinary keyboard. These are mostly printable non-ASCII characters.

DescriptionShortcut
Completion, (autocomplete)C-n or C-p
Completion, omni completionC-x C-o
Completion, complete lineC-x C-l
Completion, keyword (anything from file)C-x C-n
Completion, filenamesC-x C-f
Completion, tagsC-x C-]
Completion, definitionC-x C-d
Completion, dictionaryC-x C-k
Completion, dictionary, spellingC-x s
Completion, anything with ‘complete’ optionC-n
Completion, accept suggestionC-y

See :h completeinfomode

From :h windows-intro:

A buffer is the in-memory text of a file. A window is a viewport on a buffer. A tab page is a collection of windows.

DescriptionShortcut
Move to next windowCtrl + w w
Move window to new tabCtrl + w T
Resize, Balance windowsCtrl + w =
Resize, Maximize heightCtrl + w _
Resize, Maximize widthCtrl + w
Switch to windows by directionCtrl + w, hjkl
Split frame, horizontal (top, down)C-w, s or :sp
Split frame, vertical (left, right)C-w, v or :vsp
Split frame, open file in new window:sp <file>
Close split frameC-w c
Close window:q
Zoom in / Zoom outCtrl + Shift + - / Ctrl + Shift + =
Max height_

See :h wincmd for more commands

DescriptionShortcut
List buffersls
Switch buffers:bnext :bprevious :bp
Switch buffers by number or (partial) name:b <number or name or partial unique name>
Switch buffers - see also Navigation previous, next[b , ]b
Buffer ForwardCtrl + i
Buffer BackCtrl + o , Ctrl + ^
Buffer back to last buffer, alternate buffersCtrl + ^ (Ctrl + Shift + 6, sometimes Ctrl + 6)
Refresh buffer:e
Close buffer:bd

Tabs in Vim are like layouts or workspaces and not like tabs in newer IDEs. They preserve the window layout.

DescriptionShortcut
Edit/Open in new tab:tabe example.txt
Open current buffer in new tab:tabnew %
Close tab:tabc (close)
Close all other tabs except current:tabo (only)
Next tabgt
Prior tabgT
Numbered tabnnngt
list all tabs:tabs
DescriptionShortcut
Help:help or :h
Help keyF1
Help on command:help <command>
Help on a key in normal mode:help <key>
Help on a key in insert mode:help i_<key>
Help on a key in command mode:help c_<key>
Help, search for a word:helpgrep <word>
Help, go to documentation/link at pointK
Documentation at pointK
Documentation at point, enter docs bufferK K or K Ctrl + w, Ctrl + w
Documentation at point, exit docs bufferq
DescriptionShortcut
Open terminal:term
Exit to Normal modeCtrl-\ Ctrl-N
  • Tip on switching to terminal on Unix/Linux:
    • Ctrl + z to have vim go into background and bring up terminal
    • fg to resume vim
DescriptionShortcut
Suspend vim, go back to terminalC-z
Suspend vim, from terminal return to vimType fg in terminal + enter
Save a session to filemksession session.vim
Load a session from filesource session.vim