vim Cheatsheet
Basic Tips and Tricks⚑
Navigation⚑
i
- insert mode. Next keys typed are inserted into the file.<Esc>
- Escape from insert mode so you can navigate and use edit commands1G
- Go to line 1gg
- Go to top of fileG
- Got to bottom of file (Shift + g)S
- Places you at insert mode at the right indentation (Shift + s)%
- Jump to the matching bracket/brace (Shift + 5)
Working with files⚑
:w
- Save file:wq!
- Save and write file:q
- Quit file with no changes:q!
- Quit without saving
Editing text⚑
=G
- Fix indentation in the whole file (Equal, Shift + G)x
- Delete char at current positiona
- Append after current positionA
- Append after end of lineo
- Insert new line belowO
- Insert new line abovedw
- Delete word (and copy it to clipboard)1dd
- Delete current line (and copy it to clipboard)1yy
- Yank current line (aka copy to clipboard)1p
- Paste clipboardguu
- Lowercase line1gUU
- Uppercase line1~
- Invert case (upper->lower; lower->upper) of current characterga
- Display hex, ascii value of character under cursorg8
- Display hex value of utf-8 character under cursor
Search⚑
- set hlsearch highlight all matching patterns
:noh
(short for :nohlsearch) will clear the current highlighted patterns/foo
- Search for the next occurance of "foo"-
?foo
- Search for the previous occurance of "foo" -
:%s/foo/bar/g
- Search file for all occurances offoo
and replace withbar
globally :%s/^M//g
= Remove CRLF ^M line chars (Ctrl+V to get the ^ and then Ctrl+M to insert the M)
Deleting empty lines⚑
-
Delete all empty lines:
:g/^$/d :v/./d
-
Delete all lines that are empty or that contain only whitespace characters (spaces, tabs):
Explanation::g/^\s*$/d :v/\S/d
v
operates on lines that do not match,\S
matches anything that is not a whitespace, andd
deletes the flagged lines (all lines that have no characters, or that have only whitespace characters). -
Condense multiple blank lines into a single blank line.
Explanation: Delete all trailing whitespace from each line, then replace three or more consecutive line endings with two line endings.:%s/\s\+$//e :%s/\n\{3,}/\r\r/e
e
flag means that no error is displayed if the pattern is not found. In the second command,\n
in the search pattern finds newline, while\r
in the replacement inserts a newline.
Shell escapes⚑
(More of a security tip, but seems fitting here)
:set shell=/bin/sh
:shell
Or alternatively:
:!/bin/sh
.vimrc⚑
$ cat ~/.vimrc
set autoindent
set expandtab
set tabstop=2
set shiftwidth=2
set ignorecase
set visualbell
set mouse=a
set hlsearch
set number
syntax on