Professional Documents
Culture Documents
Vim Reference
Vim Reference
of Contents
About 1.1
Introduction 1.2
Normal Mode 1.3
Command Line mode 1.4
Visual Mode 1.5
Regular Expressions 1.6
Recording Macro 1.7
Customizing Vim 1.8
1
About
Vim Reference
Vim reference guide for beginner to intermediate users
Vim curated resources for more complete resources list, including tutorials for beginners
For more Linux resources, visit scripting course
Chapters
Introduction
Normal mode
Command Line mode
Visual mode
Regular Expressions
Recording Macro
Customizing vim
ebook
Read as ebook on gitbook
Download ebook for offline reading - link
License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License
2
Introduction
Introduction
Ice Breaker
Vim help and resources
Opening Vim
Modes of Operation
Insert mode
Normal mode
Visual mode
Command Line mode
Identifying current mode in gvim
Vim is a text editor, powerful one at that. It has evolved from vi to vim (Vi Improved) and gvim (Vim with GUI)
Vim is not a full fledged writing software like LibreOffice Writer or MS Word. It is a text editor, mainly used for
writing programs
Notepad in Windows is an example for text editor. There are no formatting options like bold, heading, page
numbers etc
If you have written C program within IDE, you might have noticed that keywords are colored (syntax highlighting),
automatic code indentation, etc. Vim provides all of that and more
Vim has programmable abilities on editing tasks. One can also execute shell commands right within Vim and
incorporate their outputs. Text can be modified, sorted, regular expressions be applied for complicated search and
replace. Record a series of editing commands and execute on other portions of text in same file or another file. To sum
it up - for most editing tasks, no need to write a program, they can be managed within Vim
Now, one might wonder, what is all this need for complicated editing features? Why does a text editor require
programming capablities? Why is there even a requirement to learn using a text editor? All one needs from editor is
writing text with keyboard, use Backspace or Delete key, have some GUI button for opening and saving, preferrably a
search and replace feature, etc.
A simple and short answer is: to reduce repititive manual task and the time taken to type a computer code. Faster
editing probably makes sense. Reduce typing time? seems absurd. But when you are in the middle of coding a large
program, thinking about complicated logic, it helps to have minimal typing distraction
Ice Breaker
Open a terminal and try these steps:
gvim first_vim.txt opens the file first_vim.txt for editing (use vim if gvim is not available)
Press i key (yes, the lowercase alphabet i, not any special key)
Start typing, say 'Hello Vim'
Press Esc key
Press : key
Type wq
Press Enter key
cat first_vim.txt sanity check to see what you typed is saved or not
3
Introduction
Phew, what a complicated procedure to write a simple line of text, isn't it? This is the most challenging and confusing
part for a newbie to Vim. Don't proceed any further if you haven't got a hang of this, take help of youtube videos if you
must. Master this basic procedure and you are ready for awesomeness of Vim
Material presented here is based on gvim , which has a few subtle differences from vim - see this stackoverflow
thread for details
For built-in help, use Help menu in gvim, or type :help in Normal mode ( :h is short for :help )
:h usr_toc.txt table of contents for Vim User Manual - 'Task oriented explanations, from simple to complex.
Reads from start to end like a book.'
:h reference_toc table of contents for Reference Manual - 'Precise description of how everything in Vim
works.'
also see :h help-summary and guideline to use help
best introduction to Vi and its core editing concepts explained as a language
this stackoverflow thread also has numerous tips and tricks to use Vim
About, Download, Documentation, etc - https://github.com/vim/vim
Vim 8.0 is in works
Vim curated resources
Opening Vim
gvim new document when filename is not specified
gvim script.sh opens script.sh, blank document if script.sh doesn't exist
gvim report.log power.log area.log open specified files, but only report.log is in the current buffer. Use :n
(short for :next ) to go to next buffer for editing
gvim -p report.log power.log area.log open specified files in separate tabs
gvim -o report.log power.log area.log open specified files as horizontal splits
gvim -O report.log power.log area.log open specified files as vertical splits
gvim -R script.sh opens script.sh in Readonly mode, changes can still be made and saved despite warning
messages shown (for example, by using :w! )
gvim -M script.sh opens script.sh in stricter Readonly mode, Vim won't allow any changes to be made unless
:set modifiable is used and file can't be saved until :set write is used
gvim +/while script.sh open script.sh and place the cursor under first occurrence of while
gvim +25 script.sh open script.sh with cursor on 25th line
gvim -c 'normal =G' script.pl open script.pl and execute the normal mode command =G
gvim -c ':%s/search/replace/g' script.pl open script.pl and execute the given Command Line mode command
gvim -h for complete list of options
Modes of Operation
4
Introduction
Vim is best described as a modal editor. Here, we'll mainly see four modes
Insert mode
Normal mode
Visual mode
Command Line mode
Insert mode
This is the mode where required text is typed. Usual editing options available are Delete, Backspace and Arrow keys.
Some smart editing short-cuts:
Ctrl+p auto complete word based on matching words in backward direction, if more than one word matches, they
are displayed as drop-down list
Ctrl+n auto complete word based on matching words in forward direction
Ctrl+x Ctrl+l auto complete line, if more than one line matches, they are displayed as drop-down list
Ctrl+t indent current line
Normal mode
This is the default mode when Vim is opened. This mode is used to run commands for editing operations like copy,
delete, paste, recording, moving around file, etc. It is also referred to as Command mode
Below commands are commonly used to change modes from Normal mode:
i insert, pressing i (lowercase) key changes the mode to Insert mode, places cursor to the left
a append, pressing a (lowercase) key changes the mode to Insert mode, places cursor to the right
I to place the cursor left of first non-blank character of line (helpful for indented lines)
gI to place the cursor at first column of line
gi to place the cursor at same position where it was left last time in Insert mode
5
Introduction
Visual mode
Visual mode is used to edit text by selecting them first
Selection can either be done using mouse or using visual commands
Press Esc key to ignore whatever is typed and return to Normal mode
6
Normal Mode
Normal mode
Cut
Copy
Paste
Undo
Redo
Replace characters
Repeat
Open new line
Indenting
Arrow Movements
Moving within current line
Word and Character based move
Text Objects based move
Moving within current file
Scrolling
Marking frequently used locations
Jumping back and forth
Numbers
Multiple copy-paste using " registers
Special registers
Combining editing commands with movement commands
Context editing
Miscellaneous
Remember to be in Normal mode, if not press Esc key. Press Esc again if needed
Cut
There are various ways to delete text, which can then be pasted elsewhere using paste command
Select text (using mouse or visual commands), press d to delete the text
dd delete current line
2dd delete current line and the line below it - total 2 lines
dj or d↓ can also be used ( j and ↓ both function as down arrow key)
10dd delete current line and 9 lines below it - total 10 lines
dk delete current line and the line above it
4cc delete current line and 3 lines below it and change to Insert mode - total 4 lines
C delete from current character to end of line and change to Insert mode
7
Normal Mode
s delete only the character under cursor and change to Insert mode
5s delete character under cursor and 4 characters to its right and change to Insert mode - total 5 characters
S delete current line and change to Insert mode (same as cc )
Copy
There are various ways to copy text using the yank command y
Select text to copy (using mouse or visual commands), press y to copy the text
yy copy current line
2yy copy current line and the line below it - total 2 lines
yj and y↓ can also be used
Paste
The paste command p is used after cut or copy operations
Undo
u undo last edit
press u again for further undos
U undo changes on current line
Redo
Ctrl+r to redo a change undone by u
8
Normal Mode
Replace characters
Often, we just need to change one character (ex: changing i to j)
3ra replace character under cursor and 2 characters to the right with aaa
Rlion Esc replace character under cursor and 3 characters to right with lion. Esc key marks the completion of
R command
The advantage of r and R commands is that one remains in Normal mode, without the need to switch to Insert
mode and back
Repeat
. the dot command repeats the last change
If the last command was deleting two lines and dot key is pressed, two more lines will get deleted
If last command was to select five characters and delete them, dot key will select five characters and delete
If the last change was clearing till end of word and inserting some text, dot key will repeat that change
O open new line above the current line and change to Insert mode
Indenting
>> indent current line
Arrow Movements
The four arrow keys can be used in Vim to move around as in any other text editor. Vim also maps them to four
characters in Normal mode (faster typing compared to arrow keys)
h left ←
j down ↓
k up ↑
l right →
9
Normal Mode
word A word consists of a sequence of letters, digits and underscores, or a sequence of other non-blank
characters, separated with white space (spaces, tabs, ). This can be changed with the 'iskeyword' option. An
empty line is also considered to be a word.
WORD A WORD consists of a sequence of non-blank characters, separated with white space. An empty line is
also considered to be a WORD.
B move to beginning of current WORD if cursor is not at start of WORD or beginning of previous WORD
e move to end of current word if cursor is not already at end of word or end of next word
E move to end of current WORD if cursor is not already at end of WORD or end of next WORD
3w move 3 words forward, similarly number can be prefixed for W,b,B,e,E
3tx move forward to character just before third occurrence of character x in current line
Fa move backward in the current line to character a
Ta move backward in the current line to character just after a
; repeat previous f,F,t,T movement in forward direction
, repeat previous f,F,t,T movement in backward direction
10
Normal Mode
5G move to first non-blank character of fifth line of file, similarly 10G for tenth line and so on
:5 move to first non-blank character of fifth line of file, similarly :10 for tenth line and so on
Scrolling
Ctrl+d scroll half page down
Ctrl+u scroll half page up
Ctrl+f scroll one page forward
Ctrl+o navigate to previous location in jump list (can remember it by thinking o as old)
11
Normal Mode
Ctrl+i navigate to next location in jump list (remember by noting that i and o are next to each other in most
keyboards)
g; go to previous change location
Related
gi to place the cursor at same position where it was left last time in Insert mode
Numbers
Ctrl+a increment a number (decimal/octal/hex will be automatically recognized - octal is a number prefixed by
0 and hex by 0x )
Ctrl+x decrement a number
Special registers
Vim has special purpose registers with pre-defined behavior
" all yanked/deleted text is stored in this register. p command can also be invoked as ""p
Further reading
12
Normal Mode
Context editing
We have seen movement using w,%,f etc. They require precise positioning to be effective. Vim provides a way to
modify commands that accepts movement like y,c,d to recognize context. These are i and a text object
selections - easy way to remember their subtle differences is to think of i as inner and a as around
diw delete a word regardless of where the cursor is on that word. Equivalent to using de when cursor is on first
character of the word
diW delete a WORD regardless of where the cursor is on that word
daw delete a word regardless of where the cursor is on that word and a space character to left/right of the word
depending on its position as part of sentence
dis delete a sentence regardless of where the cursor is on that sentence
yas copy a sentence regardless of where the cursor is on that sentence and a space left/right
cip delete a paragraph regardless of where the cursor is on that paragraph and change to Insert mode
di" delete all characters within pair of double quotes, regardless of where cursor is within quotes
da' delete all characters within pair of single quotes as well as the quotes
ci( delete all characters within () and change to Insert mode. Works even if matching parenthesis are spread
Miscellaneous
gf open the file pointed by file path under the cursor
:h gf and :h 'suffixesadd' for more info
* searches the word under the cursor in forward direction - matches only the whole word
shift+left mouse click can also be used in gvim
g* searches the word under the cursor in forward direction - matches as part of another word also
# searches the word under the cursor in backward direction - matches only the whole word
g# searches the word under the cursor in backward direction - matches as part of another word also
Ctrl+g display file information like name, number of lines, etc at bottom of screen
13
Normal Mode
3J join current and next two lines with space in between the lines
~ invert the case of character under cursor, i.e lowercase becomes UPPERCASE and vice versa
g~ followed by motion command to invert case of those characters
14
Command Line mode
Any operation is completed by pressing Enter key after which the mode changes back to Normal mode
Press Esc key to ignore whatever is typed and return to Normal mode
Saving changes
:w save changes
:w filename provide a filename if it is a new file or if you want to save to another file
:w! save changes even if file is read-only, provided user has appropriate permissions
:wa save changes made to all the files opened
Exit Vim
:q quit the current file (if other tabs are open, they will remain) - if unsaved changes are there, you will get an
error message
:qa quit all
:q! quit and ignore unsaved changes
Editing buffers
Multiple files can be opened in Vim within same tab and/or different tab
Buffers
15
Command Line mode
Splitting
:split filename open file for editing in new horizontal split screen, Vim adds a highlighted horizontal bar with
Multiple tabs
:tabe filename open file for editing in new tab instead of adding to buffers
:h :tabe for more info and different options
If multiple buffers are open and you want to apply common editing across all of them, use bufdo command
:silent! bufdo %s/searchpattern/replacestring/g | update substitute across all buffers, silent skips
Search
/searchpattern search the given pattern in forward direction
Use n command to move to next match and N for previous match
?searchpattern search the given pattern in backward direction
16
Command Line mode
n command goes to next match in backward direction and N moves to next match in forward direction
Press Esc key to ignore typed pattern search and return to Normal mode
Highlight settings
:. s/a/b/ replace first occurrence of character a with character b on current line only
:2 s/apple/Mango/i replace first occurrence of word apple with word Mango only on second line
:1,5 g/call/d delete lines containing the word call only from first five lines
:v/jump/d delete all lines NOT containing the word jump
:g/cat/ s/animal/mammal/g replace 'animal' with 'mammal' only on lines containing the searchpattern 'cat'
:.,+20 g/^#/ normal >> indent from current line to next 20 lines that start with # character
17
Command Line mode
For more info, see :h :g Also, check out :h :t and :h :m to copy/move the filtered lines using :g and :h ex-
cmd-index for complete list of commands to use with :g
Shell Commands
One can also use shell commands within Vim
:!ls execute shell command and display output, doesn't change contents of file
:.! date replace current line with output of date command
Miscellaneous
:set number prefix line numbers (it is a visual guideline, won't modify text)
:set nonumber remove line number prefix
current line is 0, 1 for lines above and below, 2 for two lines above and below and so on
useful visual guide for commands like 11yy, 6>>, 9j etc
:set norelativenumber remove relative line number prefix
:set relativenumber! toggle relative number setting
18
Visual Mode
Visual Mode
Selection
Editing
Indenting
Changing Case
Further Reading
Selection
v start visual selection, use any movement command to complete selection
Editing
d delete the selected text
c clear the selected text and change to Insert mode
for visually selected column, after c type any text and press Esc key. The typed text will be repeated across
all lines
I after selecting with Ctrl+v , press I , type text and press Esc key to replicate text across all lines to left of
the selected column
A after selecting with Ctrl+v , press A , type text and press Esc key to replicate text across all lines to right of
the selected column
ra replace every character of the selected text with a
: perform Command Line mode editing commands like g,s,!,normal on selected text
J join selected lines with space character in between
Indenting
> indent the visually selected lines
19
Visual Mode
for(;;)
{
for(;;)
{
statements
}
statements
}
for(;;)
{
for(;;)
{
statements
}
statements
}
Changing Case
~ invert the case of visually selected text, i.e lowercase becomes uppercase and vice versa
U change visually selected text to UPPERCASE
u change visually selected text to lowercase
Further Reading
For more info on Visual mode, :h visual-mode
Visual mode tutorial
Visual mode examples
20
Regular Expressions
Regular Expressions
Flags for Search and Replace
Pattern atom
Pattern Qualifiers
Character Classes
Multiple and Saving Patterns
Word Boundary
Search Pattern modifiers
Changing Case using Search and Replace
Delimiters in Search and Replace
Further Reading
s/cat/Dog/gi replace every occurrence of cat (ignoring case, so it matches Cat, cAt, etc) with Dog (note that i
doesn't affect the replacement string Dog)
Pattern atom
^ start matching from beginning of a line
/^This match This only at beginning of line
$ match pattern should terminate at end of a line
/)$ match ) only at end of line
/^$ match empty line
Pattern Qualifiers
* greedy match preceding character 0 or more times
/abc* match 'ab' or 'abc' or 'abccc' or 'abcccccc' etc
21
Regular Expressions
min or max can be left unspecified as they default to 0 and infinity respectively
greedy match, tries to match as much as possible
\{-min,max} non-greedy match, tries to match as less as possible
Character Classes
[abcde] match any of 'a' or 'b' or 'c' or 'd' or 'e' ONE time
use [a-e] as shortform
[^abcde] match any character other than 'a' or 'b' or 'c' or 'd' or 'e'
use [^a-e] as shortform
[aeiou] match vowel character
[^aeiou] match consonant character
\a matches alphabet character, short-cut for [a-zA-Z]
22
Regular Expressions
Word Boundary
\<pattern Bind the searchpattern to necessarily be starting characters of a word
/\<his matches 'his' and 'history' but not 'this'
:h /magic
Magicness in Vim regex
Excellent examples and other Vim settings on case sensitivity
23
Regular Expressions
Example:
:% s/\v(\a+)/\u\1/g will Capitalize all the words in current file (i.e only first character of word is capitalized)
for ex: 'min_max' will change to 'minMax', 'array_sum' will change to 'arraySum' and so on
Changing case with regular expressions
Further Reading
:h regular-expression
vimregex
What does this regex mean?
24
Recording Macro
Recording Macro
Need for Macro
Example 1
Example 2
Example 3
Further Reading
Steps
Example 1
qwceHello<Esc>q
q start recording
save recording to w register
ce change till end of word
Hello literally type these characters
<Esc> denotes pressing Esc key, one can type it in Insert or Command Line mode by pressing Ctrl+v
25
Recording Macro
What if you made a mistake and you wanted 'Hello!' instead of Hello ? Instead of meticulously recording the
sequence again, we can take advantage of the fact that we are using registers to record and play the macro
Now, suppose, you wanted to change only the starting word of a line, irrespective of where the current position of cursor
is
^ce'Hello!'<Esc>
Hmm, all this is fine, but how to change only those lines in the file whose starting word is Hi to 'Hello!' And they
are not bunched next to each other
:g/^Hi/ normal @w use the :g command to filter the lines and then execute the Normal mode command @w
Note: This particular editing can easily be done using :% s/^Hi/'Hello!'/ This example was used to only show
how to use the q macro recording
Example 2
Suppose, we forgot braces in Perl for single statement control structures
if($a > 4)
print "$a is greater than 4\n";
if($word eq reverse($word))
print "$word is a palindrome\n";
26
Recording Macro
if($a > 4)
{
print "$a is greater than 4\n";
}
if($word eq reverse($word))
{
print "$word is a palindrome\n";
}
Example 3
Suppose we need to convert these lines in markdown text
* [Intro Guide](#intro-guide)
* [Basic steps](#basic-steps)
* [Advanced Usage](#advanced-usage)
* [Further Reading](#further-reading)
Further Reading
27
Recording Macro
28
Customizing Vim
Different programming languages require different syntax, indentation, etc. The company you work for might have its
own text format and guidelines. You might want to create a short-cut for frequently used commands or create your own
command
~/.vimrc put your custom settings in this file, see this sample vimrc file for example
General Settings
set history=100 increase default history from 20 to 100
29
Customizing Vim
verilog , etc
set expandtab change Tab key to be made up of Space characters instead of single Tab character
Mappings
Mappings allow to create new commands or redefine existing ones. Mappings can be defined for specific mode.
Examples given here are restricted to specific mode and non-recursive
Search Settings
set incsearch the cursor would move to matching pattern as you type
set hlsearch highlight searchpattern
Custom Mappings
Normal mode
nnoremap #2 :w<CR> Press F2 function key to save file. Pressing Esc key gets quite natural after writing text in
Insert mode. Instead of multiple key presses to save using Command Line, F2 is easier
nnoremap #3 :wq<CR> Press F3 to save the file and quit
30
Customizing Vim
Insert mode
mode automatically
inoremap <C-e> <Esc>ea Ctrl+e to move to end of word
Ctrl+q can be used instead of Ctrl+v to insert characters like Enter key (may not work with vim)
See also How to make vim paste from (and copy to) system's clipboard?
inoremap <C-l> <C-x><C-l> Ctrl+l to autocomplete matching lines
Abbreviations
From typo correction to short-cuts to save typing, abbreviations are quite useful. Abbreviations get expanded only when
they stand apart as a word by itself and not part of another word. For example, if the letter p is abbreviated, it is
activated in variety of ways like pressing Esc, Space, Enter, Punctuations, etc not when it is part of words like pen, up,
etc
key - this will automatically add the Perl interpreter path and two statements
inoreabbrev py #!/usr/bin/python3 In Insert mode, use py for Python interpreter path
autocmd
Execute commands based on events
31
Customizing Vim
augroup plpy
autocmd!
" automatically add Perl path using previously set inoreabbrev for p
autocmd BufNewFile *.pl :normal ip
" automatically add Python path
autocmd BufNewFile *.py :normal ipy
" Prevent comment character leaking to next line
autocmd FileType * setlocal formatoptions-=r formatoptions-=o
augroup END
Further Reading
autocmd tutorial
augroup tutorial
Matchit
set matchpairs+=<:> adds <> to % matchpairs
To match keywords like HTML tags, if-else pairs, etc with % , one can install matchit.vim plugin. It is not enabled by
default as it is not backwards compatible
Guioptions
set guioptions-=m no menu bar
set guioptions-=T no tool bar
Further Reading
Excellent book on Vimscript and customizing Vim
Vim plugins
Useful .vimrc tips
~/.vimrc from various users:
vim-sensible
sane defaults
minimal for new users
generate vimrc
32
Customizing Vim
33