You are on page 1of 33

Table

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

Vim help and resources


gvimtutor shell command. Opens a tutor file and has various lessons to get started with Vim

vimtutor if gvim is not available

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

For complete list of modes, see :h vim-modes-intro and :h mode-switching

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+w delete the current word

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

Ctrl+d unindent current line

Pressing Esc key changes the mode back to Normal mode

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:

Changing to Insert 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

A to place the cursor at end of line


o open new line below the current line and change to Insert mode
O to open new line above the current line and change to Insert mode
s delete character under the cursor and change to Insert mode
S deletes entire line and change to Insert mode

Changing to Command Line mode

: changes the mode to Command Line mode, awaiting further commands


/ change to Command Line mode for searching in forward direction
? to start searching in backward direction

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

v start visual selection

V visually select current line

Ctrl+v visually select column(s)

Pressing Esc key changes the mode back to Normal mode

Command Line mode


After : or / or ? is pressed in Normal mode, the prompt appears in last line of Vim window
This mode is used to perform file operations like save, quit, search, replace, shell commands, etc.
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

Identifying current mode in gvim


In Insert mode, the cursor is a blinking | cursor, also -- INSERT -- can be seen on left hand side of the
Command Line
In Normal mode, the cursor is a blinking rectangular block cursor, something like this █
In Visual modes, the Command Line shows -- VISUAL -- or -- VISUAL LINE -- according to visual command
used
In Command Line mode, the cursor is of course on the Command Line

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

d↑ can also be used


D delete from current character to end of line
x delete only the current character under cursor
5x delete character under cursor and 4 characters to its right - total 5 characters
cc delete current line and change to Insert mode

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

Y also copies current line

y$ copy from current character to end of line

2yy copy current line and the line below it - total 2 lines
yj and y↓ can also be used

10yy copy current line and 9 lines below it - total 10 lines


yk copy current line and the line above it
y↑ can also be used

Paste
The paste command p is used after cut or copy operations

p paste the copied content one time

If copied text was line(s) paste below the current line


If the copied text was less than a line, paste the content to right of the cursor
P paste the copied content one time

If copied text was line(s) paste above the current line


If the copied text was less than a line, paste the content to left of the cursor
3p paste the copied content three times

Undo
u undo last edit
press u again for further undos
U undo changes on current line

press U again to redo changes

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)

rj replace the charcter under cursor with j

ry replace the character under cursor with y

3ra replace character under cursor and 2 characters to the right with aaa

To replace mutliple characters with different characters, use uppercase R

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

Open new line


o open new line below the current line and change to Insert mode

O open new line above the current line and change to Insert mode

Indenting
>> indent current line

3>> indent current line and two lines below


<< unindent current line
5<< unindent current line and four lines below

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

Moving within current line


0 move to beginning of current line - column number 1
^ move to beginning of first non-blank character of current line, useful for indented lines

$ move to end of current line

g_ move to last non-blank character of current line

3| move to 3rd column character

Moving within long lines(spread over multiple screen lines)

g0 to move to beginning of current screen line

g$ to move to end of current screen line

gm to move to middle of current screen line


g^ to move to first non-blank character of current screen line

See :h left-right-motions for more info

Word and Character based move


Difference between word and WORD (definitions quoted from :h word )

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.

Word based move

w move to start of next word (192.1.168.43 requires multiple w movements)


W move to start of next WORD (192.1.168.43 requires one W movement)
b move to beginning of current word if cursor is not at start of word or beginning of previous 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

Character based move

f( move forward in the current line to next occurrence of character (


fb move forward in the current line to next occurrence of character b
3f" move forward to third occurrence of character " in current line
t; move forward in the current line to character just before ;

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

Text Objects based move


( move backward a sentence
) move forward a sentence

{ move backward a paragraph

} move forward a paragraph

:h object-motions for more info

Moving within current file


gg move to first non-blank character of first line of file
G move to first non-blank character of last line of file

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

% move to matching pair of brackets like () {} [] (Nesting is taken care)


To add a new matching pair like <>, add set matchpairs+=<:> to your vimrc file
It is also possible to match a pair of keywords like HTML tags, if-else, etc with % Check :h matchit-install
for more info

Scrolling
Ctrl+d scroll half page down
Ctrl+u scroll half page up
Ctrl+f scroll one page forward

Ctrl+b scroll one page backward


Ctrl+Mouse Scroll scroll one page forward or backward

Marking frequently used locations


ma mark location in the file with variable a (use any of the 26 alphabets)
`a move from anywhere in the file to exact location marked by a
'a will move to first non-blank character of the line marked by a
:marks will show existing marks

d`a delete upto character marked by a


marks can be paired with any command that accept movements like d,c,y

Jumping back and forth


This is helpful if you are moving around while editing a large file or moving between different buffers

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

g, go to newer change location

:h jump-motions for more info

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

Multiple copy-paste using " registers


One can use lowercase alphabets a-z to save content for future use. And append content to those registers by using
corresponding uppercase alphabets A-Z at later stage

"ayy copy current line to "a register


"ap paste content from "a register
"Ayj append current line and line below it to "a register ( "a has total 3 lines now)

"cyiw copy word under cursor to "c register

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

"0 yanked text is stored in this register


Useful for this sequence: yanking content, deleting something and then pasting yanked content using "0p
"1 to "9 deleted contents are stored in these registers and get shifted with each new deletion. "1 has the
most recently deleted content
"2p paste content deleted before the last deletion

"+ this register stores system clipboard contents


gg"+yG copy entire file contents to clipboard
"+p paste content from clipboard
"* this register stores visually selected text
contents of this register can be pasted using middle mouse button click or "*p

Further reading

how to use Vim registers


Using registers on Command Line mode

12
Normal Mode

Advanced Vim registers

Combining editing commands with movement commands


dG delete from current line to end of file
dgg delete from current line to beginning of file

d`a delete from current character upto location marked by a

d% delete upto matching pairs () {} []

ce delete till end of word and change to Insert mode

yl copy character under cursor


d) delete upto end of sentence in forward direction

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

over multiple lines


ya} copy all characters within {} including the {}. Works even if matching braces are spread over multiple lines

For more info :h text-objects

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

for more info and related commands, see :h CTRL-G


J join current and next line with one space character in between
gJ join current and next line without any character in between

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

gu followed by motion command to change case of those characters to lowercase

example: gue , gu$ , guiw etc


gU followed by motion command to change case of those characters to UPPERCASE

example: gUe , gU$ , gUiw etc


= followed by motion command to indent code

example: =} , gg=G etc

14
Command Line mode

Command Line Mode


Saving changes
Exit Vim
Combining Save and Quit
Editing buffers
Search
Search and Replace
Editing lines filtered by pattern
Shell Commands
Miscellaneous

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

Combining Save and Quit


:wq save changes and quit
:wq! save changes even if file is read-only and quit

Editing buffers
Multiple files can be opened in Vim within same tab and/or different tab

Buffers

:e refreshes the current buffer

15
Command Line mode

:e filename open file for editing

:e# switch back to previous buffer


Ctrl+6 can also be used

:e#1 open first buffer

:e#2 open second buffer and so on


:bn open buffer next

:bp open buffer previous

Splitting

:split filename open file for editing in new horizontal split screen, Vim adds a highlighted horizontal bar with

filename for each file thus opened


use :sp filename for short
:vsplit filename open file for editing in new vertical split screen

use :vs filename for short


If filename is not given, the current one is used

Multiple tabs

:tabe filename open file for editing in new tab instead of adding to buffers
:h :tabe for more info and different options

:tabn to go to next tab


gt and Ctrl+Page Down can also be used
2gt to move to second tab, the number specified is absolute, not relative

:tabp to go to previous tab


gT and Ctrl+Page Up can also be used

:tabr to go to first tab (r for rewind)


:tabl to go to last tab (l for last)
:tabm 0 move current tab to beginning

:tabm 2 move current tab to 3rd position from left


:tabm move current tab to end

Making changes to all buffers

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

displaying normal messages and ! skips error messages as well


It is not an efficient way to open buffers just to search and replace a pattern across multiple files, use tools like
sed,awk,perl instead
:h :bufdo , :h :windo and :h :silent for more info
how to change multiple files
Effectively work with multiple files
When to use Buffers and when to use Tabs

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

By default, cursor is placed at starting character of match

/searchpattern/s+2 places cursor 2 characters after start of match


/searchpattern/s-2 places cursor 2 characters before start of match

/searchpattern/e places cursor at end of match

/searchpattern/e+4 places cursor 4 characters after end of match


/searchpattern/e-4 places cursor 4 characters before end of match

/searchpattern/+3 places cursor 3 lines below match

/searchpattern/-3 places cursor 3 line above match

Highlight settings

:set hlsearch highlights the matched pattern

:set nohlsearch do not highlight matched pattern


:set hlsearch! toggle highlight setting
:noh clear highlighted patterns, doesn't affect highlight settings

Search and Replace


General syntax is :range s/searchpattern/replacestring/flags
s is short-form for substitute
Space between range and s is optional and may be used for clarity

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

i flag ignores case sensitivity for searchpattern


:3,6 s/call/jump/g replace all occurrences of call to jump on lines 3 to 6

g flag changes default behavior to search and replace all occurrences

:1,$ s/call/jump/g replace all occurrences of call to jump in entire file


$ points to last line of file
:% s/call/jump/g replace all occurrences of call to jump in entire file
% is short-cut for the range 1,$
More on substitute and Regular Expressions is covered in a later chapter. :h :substitute and :h range for
more info

Editing lines filtered by pattern


The g command, short for global allows to edit lines that are first filtered based on a searchpattern

:g/call/d delete all lines containing the word call

: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

:%! sort sort all lines of file

:3,8! sort sort only lines 3 to 8 of file

:r! date insert output of date command below current line

:r report.log insert contents of file report.log below current line


Note that ! is not used as we are reading a file, not using external shell command
:.!grep '^Help ' % replace current line with all line starting with Help in current file
:sh open a shell session within Vim, use exit command to return to editing
Working with external commands
:h :! , :h :sh and :h :r for more info

Miscellaneous
:set number prefix line numbers (it is a visual guideline, won't modify text)
:set nonumber remove line number prefix

:set number! toggle number setting


:set relativenumber prefix line numbers relative to current line

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

Visual mode is used to edit text by selecting them first


Selection can either be done using mouse or using visual commands

Selection
v start visual selection, use any movement command to complete selection

ve, vip, v) etc


V visually select current line

Vgg, ggVG etc


Ctrl+v visually select column(s)
Ctrl+v3j2l to select a 4x3 block, etc

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

gJ join selected lines without any character in between


:h visual-operators for more info

Indenting
> indent the visually selected lines

3> indent the visually selected lines three times


< unindent the visually selected lines
= indent code, taking care of nesting too. Example below

19
Visual Mode

for(;;)
{
for(;;)
{
statements
}
statements
}

vip= to indent the code

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

Flags for Search and Replace


g replace all occurrences within line

c ask for confirmation before each replacement


i ignore case for searchpattern

I don't ignore case for searchpattern

Flags can be combined

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)

For more info, :h :s_flags

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

. match any single character, excluding new line


/c.t match 'cat' or 'cot' or 'c2t' or 'c^t' but not 'cant'

For more info, :h pattern-atoms

Pattern Qualifiers
* greedy match preceding character 0 or more times
/abc* match 'ab' or 'abc' or 'abccc' or 'abcccccc' etc

21
Regular Expressions

\+ greedy match preceding character 1 or more times

/abc\+ match 'abc' or 'abccc' but not 'ab'


\? match preceding character 0 or 1 times ( \= can also be used)

/abc\? match 'ab' or 'abc' but not 'abcc'

\{-} non-greedy match preceding character 0 or more times


Consider this line of text 'This is a sample text'
/h.\{-}s will match: 'his'

/h.*s will match: 'his is a s'


Read more on non-greedy matching
\{min,max} greedy match preceding character min to max times (including min and max)

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

\{number} match exactly with specified number


/c\{5} match exactly 'ccccc'

For more info, :h pattern-overview

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]

\A matches other than alphabet [^a-zA-Z]


\l matches lowercase alphabets [a-z]

\L matches other than lowercase alphabets [^a-z]


\u matches uppercase alphabets [A-Z]
\U matches other than uppercase alphabets [^A-Z]
\d matches digit character [0-9]

\D matches other than digit [^0-9]


\x matches hexademical character [0-9a-fA-F]
\X matches other than hexademical [^0-9a-fA-F]
\w matches any alphanumeric character or underscore [a-zA-Z0-9_]
\W match other than alphanumeric character or underscore [^a-zA-Z0-9_]

\s matches white-space characters space and tab


\S matches other than white-space characters
\t used in replacestring to insert a Tab character
\r used in replacestring to insert a newline character

For more info, :h /character-classes

Multiple and Saving Patterns

22
Regular Expressions

\| allows to specify two or more patterns to be matched

/min\|max match 'min' or 'max'


\(pattern\) allows to group matched patterns and use special variables \1 , \2 , etc to represent them in

same searchpattern and/or replacestring when using substitute command


/hand\(y\|ful\) match 'handy' or 'handful'
/\(\a\)\1 match repeated alphabets

Word Boundary
\<pattern Bind the searchpattern to necessarily be starting characters of a word
/\<his matches 'his' and 'history' but not 'this'

pattern\> Bind the searchpattern to necessarily be ending characters of a word

/his\> matches 'his' and 'this' but not 'history'


\<pattern\> Bind the searchpattern to exactly match whole word

/\<his\> matches 'his' and not 'this' or 'history'

Search Pattern modifiers


\v helps to avoid \ for pattern qualifiers, grouping pattern, etc

/\vc{5} match exactly 'ccccc'


/\vabc+ match 'abc' or 'abccc' but not 'ab'
/\vabc? match 'ab' or 'abc' but not 'abcc'

/\v<his> match whole word 'his', not 'this' or 'history'


/\vmin|max match 'min' or 'max'

/\vhand(y|ful) match 'handy' or 'handful'


/\v(\a)\1 match repeated alphabets
s/\v(\d+) (\d+)/\2 \1/ swap two numbers separated by space
\V no need to use \ when trying to match special characters

/V^.*$ match the exact sequence ^.*$


\c case insensitive search

/\cthis matches 'this', 'This', 'thiS', etc


\C case sensitive search

/\Cthis match exactly 'this', not 'This', 'thiS', etc


\%V only inside visually selected area

s/\%Vcat/dog/g replace 'cat' with 'dog' only in visually selected region

For more info

:h /magic
Magicness in Vim regex
Excellent examples and other Vim settings on case sensitivity

23
Regular Expressions

Changing Case using Search and Replace


These are used in the replacestring section

\u uppercases the next character

\U UPPERCASES the following characters

\l and \L are equivalent for lowercase

use \e and \E to end further case changes

Example:

:% s/\v(\a+)/\u\1/g will Capitalize all the words in current file (i.e only first character of word is capitalized)

:% s/\v(\a+)/\U\1/g will change to all letters to UPPERCASE in current file


:% s/\v(\w)_(\a+)/\1\u\2/g change variable_name to camelCase

for ex: 'min_max' will change to 'minMax', 'array_sum' will change to 'arraySum' and so on
Changing case with regular expressions

Delimiters in Search and Replace


One can also use other characters like #^$ instead of /

:% s#/project/adder/#/verilog/project/high_speed_adder/#g this avoids mess of having to use \/ for every /


character

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

Need for Macro


The repeat command can only repeat the last change. It also gets overwritten with every editing command. The q
command allows user to record any sequence of editing commands to effectively create a user defined command,
which can then be applied on other text across files. It can also be prefixed with a number to repeat the command.
Powerful indeed!

Steps

Press q to start recording session


Use any alphabet to store the recording, say a
Use the various editing commands in combination with movement commands to accomplish the sequence of
editing required
Press q again to stop recording
Use @a (the alphabet typed in step 2) to execute the recorded command elsewhere
5@a execute 5 times

@@ execute last recorded macro

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

followed by pressing Esc key


Note-1: It looks like ^[ but is a single character
Note-2: if you are using gvim and Ctrl+v is mapped to something else, Ctrl+q can be used instead
q stop recording
Now, in Normal mode, wherever you press @w , it will clear text until end of word and insert the characters
Hello
To use the last recorded macro, @@ can be used without having to remember which register was used to save
the recording

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

"wp will paste contents of w register, which is ceHello<Esc>

Note that in Vim, it will look like ceHello^[


change it to ce'Hello!'<Esc>
then visually text the sequence and press "wy to replace the contents of w register to this new sequence
this can be achieved in non-visual mode as well by placing cursor at start of sequence and then "wy followed
by appropriate movement to copy till end of sequence
now @w will clear text until end of word and insert the characters 'Hello!'
to use this recording in a portable manner, add let @w = "ce'Hello!'<Esc>" to ~/.vimrc
Note again that you need to type the <Esc> key using Ctrl+v followed by Esc key in Insert mode

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>

How about changing starting word of multiple lines bunched together?

^ce'Hello!'<Esc>j we need to first end the recording by going to next line


5@w whatever count of lines to modify

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";

# some other code here

if($word eq reverse($word))
print "$word is a palindrome\n";

o{<Esc>jo}<Esc> record the sequence for one statement in a register say p


:g/\<if(/ normal @p execute the macro for all occurences
When dealing with multiple lines, recording macro with q might be cleaner than using :s

26
Recording Macro

if($a > 4)
{
print "$a is greater than 4\n";
}

# some other code here

if($word eq reverse($word))
{
print "$word is a palindrome\n";
}

Example 3
Suppose we need to convert these lines in markdown text

# <a name="intro-guide"></a>Intro Guide


# <a name="basic-steps"></a>Basic steps
# <a name="advanced-usage"></a>Advanced Usage
# <a name="further-reading"></a>Further Reading

to table of contents, like this

* [Intro Guide](#intro-guide)
* [Basic steps](#basic-steps)
* [Advanced Usage](#advanced-usage)
* [Further Reading](#further-reading)

$T>d$0r*la[<Esc>pa]<Esc>lcf"(#<Esc>f"C)<Esc>j say this is saved in b register


$ move to end of line
T> move to character after last occurence of '>' in the line
d$ delete upto end of line

0 move to first column of line


r* replace '#' with '*'
l move cursor one character right
a[<Esc> append '[' and change to Normal mode
p paste the earlier deleted content

a]<Esc> append ']' and change to Normal mode


lcf"(#<Esc> move cursor one character right, clear text upto next double quote, insert '(#' and change to
Normal mode
f"C)<Esc>j move cursor to next double quote, clear text till end of line, insert ')', change to Normal mode and
move cursor one line down
4@b on first line, as they are bunched together
or vip: normal @b
Note: again, this is a demonstration and s/\v.*"(.*)".*\>(.*)/* [\2](#\1)/ is perhaps better option

Further Reading

27
Recording Macro

A Gentle Introduction to Macros


Advanced vim macros
macro Q&A on vi stackexchange

28
Customizing Vim

Customizing the editor


General Settings
Text and Indent Settings
Mappings
Search Settings
Custom Mappings
Abbreviations
autocmd
Matchit
Guioptions
Further Reading

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

Based on Vim version 7.4


Some mappings are suitable only for gvim

General Settings
set history=100 increase default history from 20 to 100

set nobackup don’t create backup files


Vim backup files
set noswapfile don’t create swap files
Disabling swap files
colorscheme murphy a dark colored theme
set showcmd show partial Normal mode command on Command Line and character/line/block-selection for Visual
mode
set wildmode=longest,list,full bash like Tab completion
first tab hit will complete as much as possible
second tab hit will provide a list
third and subsequent tabs will cycle through
How to set persistent Undo

Text and Indent Settings


set textwidth=0 no. of characters in a line after which Vim will automatically create new line
filetype plugin indent on Vim installation comes with lot of defaults
:echo $VIMRUNTIME gives your installation directory. One of them is indent directory which has indent styles
for 100+ different file types
Using this setting directs Vim to apply based on file extensions like .pl for Perl , .c for C , .v for

29
Customizing Vim

verilog , etc

set autoindent copy indent on starting a new line


useful for files not affected by filetype plugin indent on
See also :h smartindent
set shiftwidth=4 defines how many characters to use when using indentation commands like >>
set tabstop=4 defines how many characters Tab key is made of

set expandtab change Tab key to be made up of Space characters instead of single Tab character

set cursorline highlight the cursor line


Show vertical bar at particular column as visual guide for required textwidth

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

nnoremap Normal mode non-recursive mapping


vnoremap Visual mode non-recursive mapping

inoremap Insert mode non-recursive mapping


inoreabbrev Insert mode non-recursive abbreviation

:h :map-commands for more info

Search Settings
set incsearch the cursor would move to matching pattern as you type
set hlsearch highlight searchpattern

vnoremap * y/<C-R>"<CR> press * to search visually selected text in forward direction


vnoremap # y?<C-R>"<CR> press # to search visually selected text in backward direction
nnoremap / /\v automatically add very magic mode modifier for forward direction search
nnoremap ? ?\v automatically add very magic mode modifier for backward direction search

nnoremap <silent> <Space> :noh<CR><Space> Press Space to clear highlighted searches


<silent> modifier executes the command without displaying on Command Line
Note that command also retains default behavior of Space key

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

nnoremap #4 ggdG Press F4 to delete entire contents of file


nnoremap #5 gg"+yG Press F5 to copy entire contents of file to system clipboard
nnoremap Y y$ change Y to behave similar to D and C
Check out use of Leaders for even more mapping tricks

30
Customizing Vim

Insert mode

inoremap <F2> <Esc>:w<CR>a Press F2 to save file in Insert mode as well


Note the mapping sequence - it requires going to Normal mode first. Hence the a command to get back to
Insert mode
inoremap <F2> <C-o>:w<CR> alternate way, Ctrl+o allows to execute a command and return back to insert

mode automatically
inoremap <C-e> <Esc>ea Ctrl+e to move to end of word

inoremap <C-b> <C-o>b Ctrl+b to move to beginning of word

inoremap <C-a> <C-o>A Ctrl+a to move to end of line

inoremap <C-s> <C-o>I Ctrl+s to move to start of line


Can't use Ctrl+i remapping as it affects Tab as well
inoremap <C-v> <C-o>"+p Ctrl+v to paste from clipboard in insert mode

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

just saves the additional Ctrl+x, see also :h i_CTRL-x


See also :h ins-special-special

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

inoreabbrev p #!/usr/bin/perl<CR>use strict;<CR>use warnings;<CR> In Insert mode, type p followed by Enter

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

inoreabbrev teh the Automatically correct typo 'teh' to 'the'


inoreabbrev @a always @()<CR>begin<CR>end<Esc>2k$ This one works best with @a followed by Esc key in Insert
mode. This inserts an empty always block (used in Verilog) and places the cursor at end of first line. After which
use i command to type inside the parenthesis

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

:h :autocmd and :h autocmd-groups

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

:echo $VIMRUNTIME get path of installation directory


mkdir -p ~/.vim/plugin create required directories from terminal or within Vim if you prefer
cp /usr/share/vim/vim74/macros/matchit.vim ~/.vim/plugin/ replace /usr/share/vim/vim74 with output of echo

if it is different in your case


:h matchit-install for more info

Guioptions
set guioptions-=m no menu bar
set guioptions-=T no tool bar

See also :h guioptions

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

building vimrc from scratch


adding custom keywords to match on %
using gf to open file in new tab or splits
open file under cursor with gf based on current file extension
Vim history
Indenting all the files in folder

33

You might also like