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
DescriptionShortcut
Save (write):w
Save all open buffers:wa
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
Edit <file>:e <file> or :edit <file
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

:copy, :move, :norm examples

  • 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.

This first table per DevOps Bootcamp Series with Nana Janashia (DevOps Bootcamp with Nana)

Other table per vimtutor command

DescriptionShortcut
Delete character at pointx
Delete linedd
Delete 10 linesd10, d
Delete all lines:%d
Undou
Enter Insert mode, at beginning of lineI
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 new line below / above current oneo, O
Go to line 12, Go to line 10012G, 100G or :100
Jump to beginning of line (bol)0 / Home / ^ (soft)
Jump to end of line (eol)$ / End
Jump history back, forwardC-o, C-i
Go to, beginning of filegg
Go to, last selected textgv
Go to file, url at point (open with system app)gf , gx
Go to, end of fileG
Go to, last insert modegi
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
Repeat last command, repeat macro (like command, inserts, combos).
Search: command historyq: (like C-f in command mode)
DescriptionShortcut
RedoCtrl + r
Select, Start select - visual selectionv
Select, visual and selected areav i <choose selection options>
Select, visual and text inside selected symbolv i ], v i ’, v i “
Select, visual line modeV
Select, visual block mode (rectangle mark)C-v
Copy (yank) selectiony
Copy (yank) wordyw
Copy (yank inside) content inside quotations “yi”
Copy (yank) entire lineyy
Copy (yank) entire file:%y or gg v G, or :1,$y
Copy 1 to 10 lines of file:1,10y
Put (paste deleted or copied text)p
Case of character at point, toggle~
Case of word, toggleg~w
Case of inner tag selection, toggleg~it
Join linesJ
Format, auto format= =
  • 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

    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
    • 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
      1. Using do commands

        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 listed in quickfix list)

        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.
  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

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.

  • q<register><commands>q

  • Execute macro: @

  • Repeat last macro: @@

  • Example to store macro in register a, go down and delete line: 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
Fold, openzo
Fold, closezc
DescriptionShortcut
Delete word at pointC-w
Delete character at pointC-h
Run normal mode command, then run commandC-o
DescriptionShortcut
Completion, (autocomplete)C-n or C-p
Completion, anything from fileC-x C-n
Completion, on filenamesC-x C-f
Completion, on tagsC-x C-]
Completion, anything with ‘complete’ optionC-n
DescriptionShortcut
Show file location and statusCtrl + g
Retrieve and place in bufferr <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

DescriptionShortcut
Move to next windowCtrl + w Ctrl + w
Switch to windows by directionCtrl + w, hjkl
Split frame, horiztonal (top, down)C-w, s
Split frame, vertical (left, right)C-w, v
Close split frameC-w c
Close window:q
Zoom in / Zoom outCtrl + Shift + - / Ctrl + Shift + =
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
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>
Documentation at pointK
Documentation at point, enter docs bufferCtrl + w, Ctrl + w
DescriptionShortcut
Open terminal:term
Exit to Normal modeCtrl-\ Ctrl-N
Bring up/Hide open terminalC-/
  • 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