Vim tips and tricks document discusses various Vim commands for navigation, editing, searching, and substitution. It covers the three main Vim modes (normal, insert, command line), navigating text, searching with regular expressions, visual mode, and ex commands. The document provides examples for common operations like changing, deleting, copying text as well as regular expression patterns for names, emails, and more.
2. Meeting Basics
2
Put your phones/pagers on vibrate/mute
Messenger: Change the status to offline or in-
meeting
Remote attendees: Mute yourself (*6). Ask questions
via Adobe Connect.
5. Transitioning between modes
5
From To Command
Command mode Insert mode i, I, a, A, o, O
Insert mode Command mode ESC
Command mode Command Line mode :
Command Line mode Command mode Press vi or Enter
6. Navigational commands
6
Keys Movement
h, j, k, l Move left, down, up, right
+, - Move to first character of one line below or above
w, b, e Forward by word, backward by word, end of word
W, B,E Same as above ignoring punctuation
(,), {, }, [[, ]], [{, Move to sentence, paragraph, section, block (curly brace)
]}
H, M, L Move to home/top, middle and last/bottom of the screen
^F, ^B Scroll forward, backward one screen
^D, ^U Scroll Down/forward, Up/backward half screen
5|, n|, Move to the 5th column, nth column on a line
0, ^, $ Move to beginning, first non-white character; end of line
20G, n G Go to the 20th line, nth line. G takes to the end of file. gg takes
to the file line
10%, 55% Go to the 10% of the file, 55% of the file
7. Normal/Command mode keys
7
Key Function
i, I insert, insert at the beginning
x, X delete a character, delete the left character
a, A append, append at the end
r, R replace; replace until Escaped
s, S substitute; substitute at the beginning of the line
o, O add a line below or above current line
c <object> change the object
d <object> delete the object
y <object> yank the object
u, ctrl R, . undo, cancel undo, redo
~, J, ctrl A, ctrl X toggle case, Join lines, Increment/Decrement a number
p, P paste, Paste before
8. Markers
8
Remember the line and column
mx marks the current position (x can be any
of 52 characters a-z, A-Z)
Upper case markers work across files
„x (apostrophe) moves the cursor to first
character of line marked by x
`x (back quote) moves the cursor to
character marked by x
9. Special markers
9
'' (two apostrophes with no space in between) returns to
beginning of the line of the previous mark or context
`` (two back quotes with no space in between) returns to
the previous mark or context
'' <pause> '', and `` <pause> `` toggle between current and
previous locations
Numerical markers ('0, '1, ..'9) point to previous sessions. `.
takes you to the location of last change
:[range]mark a, :/pat1/mark a
:marks
11. The powerful combination
11
What Change Delete Copy Lower/Upper Toggle
case case
One word cw dw yw guw, gUw g~w
Two words (with and c2w, 2dw, 2yw, 2guw, 2gUW 2g~w,
without punctuation) 2cW 2dW 2yW 2g~W
One line cc dd yy guu, gUU g~~
To end of line c$, C d$, D y$, Y gu$, gu$ g~$
To beginning of line c0 d0 y0 gu0, gU0 g~0
To top of screen cH dH yH guH, gUH g~H
Next line c+ d+ y+ gu+, gU+ g~+
Column 8 of current line c8| d8| y8| gu8|, gU8| g~8|
12. The powerful combination ...
12
What Change Delete Copy Lower/Upper Toggle
case case
Previous paragraph c{ d{ y{ gu{, gU{ g~{
Third sentence following c3) d3) y3) gu3), gU3) g~3)
Up to pattern c/pat d?pat y/pat gu/pat, gU/pat g~/pat
Up to line 18 c18G d18G y18G gu18G, gU18G g~18G
Up to marker x c`x d`x y`x gu`x, gU`x g~`x
13. Searching
13
/pat1, ?pat1 search forward, backward
n repeats the search in same direction, N reverses
the direction of search
5n, 5N to go to the 5th match.
5/pat1, 5?pat1 will go to the 5th match of pat1
*, # search the current word forward/backward
/, ? followed by up or down arrow keys bring the
old searches
:set nowrapscan incsearch hlsearch ignorecase
14. Searching with offset
14
Command Result
/pat/+n Go to the first column of n lines below
/pat/-n Go to the first column of n lines above
/pat/e+n n characters to the right from end of pat
/pat/e-n n characters to the left from end of pat
/pat/s+n n characters to the right from start of pat
/pat/s-n n characters to the left from start of pat
; ; is a special kind offset
/pat1/;/pat2/ Search for pat2 after searching for pat1
/pat1/+1;/pat2/ Search for pat2 from the next line after pat1
?pat1?;/pat2/ Search backwards for pat1 and then pat2 forward
:help pattern-searches to learn more about searching
15. Regular Expressions
15
Meta character Meaning
. Matches any single character except newline
* Matches zero or more of the character preceding it
e.g.: bugs*, table.*
^ Denotes the beginning of the line. ^A denotes lines starting
with A
$ Denotes the end of the line. :$ denotes lines ending with :
Escape character (., *, [, , etc)
[] matches one or more characters within the brackets. e.g.
[aeiou], [a-z], [a-zA-Z], [0-9], [:alpha:], [a-z?,!]
[^] negation - matches any characters other than the ones inside
brackets. eg. ^[^13579] denotes all lines not starting with odd
numbers, [^02468]$ denotes all lines not ending with even
numbers
<, > Matches characters at the beginning or end of words
16. Extended Regular Expressions
16
Meta character Meaning
| alternation. e.g.: ho(use|me), the(y|m), (they|them)
+ one or more occurrences of previous character.
? zero or one occurrences of previous character.
{n} exactly n repetitions of the previous char or group
{n,} n or more repetitions of the previous char or group
{,m} zero to m repetitions of the previous char or group
{n, m} n to m repetitions of previous char or group
{-n, m} same as above, but in lazy/conservative/non-greedy
mode (*?, ??, +? in Perl)
(....) Used for grouping
:help regex to learn more about regular expressions
17. Greedy/Lazy match
17
Search Meaning
/b.*b Greedy match: aaabccbaaaabacbaaabxyz123baaaa
/b.{-}b Lazy match: aaabccbaaaabacbaaabxyz123baaaa
/b[^b]*b Same as above using negation.
/b[a-z]*b Greedy match: aaabccbaaaabacbaaabxyz123baaaa
/b[a-z]{-}b Lazy match: aaabccbaaaabacbaaabxyz123baaaa
/b[^a-z]*b Where using negation to do lazy match doesn't work
18. POSIX Character Classes
18
POSIX Description
[:alnum:] Alphanumeric characters
[:alpha:] Alphabetic characters
[:ascii:] ASCII characters
[:blank:] Space and tab
[:cntrl:] Control characters
[:digit:] Digits, Hexadecimal digits
[:xdigit:]
[:graph:] Visible characters (i.e. anything except spaces, control characters, etc.)
[:lower:] Lowercase letters
[:print:] Visible characters and spaces (i.e. anything except control characters)
[:punct:] Punctuation and symbols.
[:space:] All whitespace characters, including line breaks
[:upper:] Uppercase letters
[:word:] Word characters (letters, numbers and underscores)
19. Perl Character Classes
19
Perl POSIX Description
d [[:digit:]] [0-9]
D [^[:digit:]] [^0-9]
w [[:alnum:]_] [0-9a-zA-Z_]
W [^[:alnum:]_] [^0-9a-zA-Z_]
s [[:space:]]
S [^[:space:]]
a [:alpha:] Alphabetic character [a-zA-Z]
A [^[:alpha:]] Non-Alphabetic character [^a-zA-Z]
l [[:lower:]] Lower case letters [a-z]
L [^[:lower:]] Non-Lower case letters [^a-z]
u [[:upper:]] Upper case letters [A-Z]
U [^[:upper:]] Non-Upper case letters [^A-Z]
20. Regular Expressions – Examples
20
Example Meaning
[0-9]{10,} 10 or more digits. Curly braces have to escaped
[0-9]{3}-[0-9]{2}-[0-9]{4} Social Security number
([0-9]{3})[1-9]{3}-[0-9]{4} Phone number (xxx)yyy-zzzz
d{2,3}.d{1,3}.d{1,3}.d{ Very basic IP address format
1,3}
[0-9]{2,3}.[0-9]{1,3}.[0- IP address format with v switch which escapes
9]{1,3}.[0-9]{1,3} all special characters
(d{4}[ -]?){3}d{4} Credit Card (four occurrences of four digits
followed optionally by a space or dash)
http://www.vimregex.com/
[A-Z][a-z]+(s+[A-Z][a- First name, optional Middle Initial/name, and
z]*)?s+[A-Z][a-z]* Last name
21. Tools to learn Regular Expressions
http://www.weitz.de/regex-coach/
http://www.regexbuddy.com/
22. Visual Mode
22
Command Result
v character mode
V line mode
^V (ctrl + V) block/vertical mode
o expand/shrink from the other end
'< < is the starting marker
'> > is the ending marker
v<move command> v12g, v%, v/pat
va{, va(, va[, va< marks the characters between matching {, (, [, <
va", va' marks the characters between matching ", ' (but the
quotes have to be on the same line)
vi{, vi(, vi[, vi<, vi", vi' Same as its va counterpart above, but doesn't
include the enclosing marks.
23. Command Line/EX mode
23
:[range of lines][g/pattern/] action [count]
:[range of lines][v/pattern/] action [count]
action is one of the following:
co – copy, d – delete, j – join, l – list,
m – move, p – print, pu – put, r – read,
s – substitute, t – copy, w – write, y – yank,
> - shift right, < - shift left, # - number the lines
! – invoke a shell command
24. Address Ranges
24
Range Remarks
:1,10 Lines between 1 and 10
:1, . Beginning of the file to current line (.)
:.,$ Current line (.) to the end of the file ($)
:%, All lines in the file
:1,$
:'a, 'b lines between markers a and b
:'a-1, 'b+2 One line above line marked by a and 2 lines below the
line marked by 2
:/pat1/,/pat2/-1 Lines between pat1 and one above pat2
:?pattern1?, /pattern2/-1 Same as above but pat1 is searched backwards
:-3,+3 Three lines above and below current line
:1,10g/pattern/ Lines between 1 and 10 that contain the pattern
:1,10v/pattern/ Lines between 1 and 10 that don't contain the pattern
25. Address Ranges with relative addressing
25
Range Remarks
:10;+5 Treats line 10 as current line (relative addressing)
:/pat1/;+5 Lines between pat1 and five lines below it. Short cut
for :/pat1/, /pat1/+5
:g/pat1/;+5 same as above, but for the whole file.
:v/pat1/;+5 Lines that are mutually exclusive of the above
26. Substitution
26
[address][g/pat1/]s/pat2/pat3/[options] [count]
[address][v/pat1/]s/pat2/pat3/[options] [count]
Options: g – global, c – confirm, e – ignore error, i – ignore
case, I (capital i) - dont ignore case, n – count the number
of occurrences without substitution
: or ; or any other character could be also be used as the
delimiter. Useful when / is part of the search or
replacement string.
:set ic, set noic
27. Substitution - Examples
27
Example Explanation
:s/this/that/ Substitute the first occurrence of this with that on
the current line
:s/this/that/gi Substitute all occurrences of this with that on the
current line, ignoring the case
:%s/this/that/g Same as above on the entire file
:1,100s/this/that/g Same as above on lines between 1 and 100
:g/pat1/s/this/that/g Substitute all occurrences of this with that on ALL
lines containing "pat1"
:1,100g/pat1/s/this/that/g Same as above, but for lines between 1 and 100
:g/pat1/,/pat2/s/this/that/ Substitute this with that on ALL ranges of lines that
g start with pat1 and end with pat2
:/pat1/,/pat2/g/pat3/s/this Substitute this with that on lines that contain pat3
/that/g between the FIRST range of lines that start with
pat1 and end with pat2
28. Substitution – Examples contd
28
Example Explanation
:s/this/that/g 3 Substitute ALL occurrences of this with that on the
current line and two following lines
:g/pat1/s/this/that/g 3 Substitute this with that on lines containing pat1
and two lines following that
:1,100g/pat1/s/this/that/g 3 Same as above but for lines between 1 and 100
:%s:/dir1/dir2:/dir4/dir5:g On the entire file (%), replace /dir1/dir2 with
/dir4/dir5. : is used as the delimiter and / is part of
the string
:%s/(his|her)/their/ Replace either his or her with their
:%s/<(hey|hi)>/hai/gi Replace FULL words "hey" or "hi" with "hai". They
or This won't be replaced
:%s/v<(hey|hi)>/hai/gi Same as above with the v flag to avoid escaping
29. Substitution – Examples contd
29
Example Explanation
:g/pat1/-4 s/this/that/4 Replace this with that on the line containing pat1
and three lines above it
:v/pat1/s/this/that/g Replace this with that on lines that DON'T containt
pat1
:%s/ */&&/g & on the right-hand side stands for the entire search string. This
example doubles the space between words
:%s/this/& and that/ Replace this with "this and that"
:1,10s/[a-z]/U&/g Convert lower to upper case on lines 1 to 10
:1,10s/[[:upper:]]/L&/g Convert upper to lower case on lines 1 to 10
:%s/<./u&/g Capitalize the first letter of every word. Called "Title Case"
:%s/.*/&^M/ Add a blank line after each line.
:%s/$/^M/ ^M stands for ctrl v + ctrl M
:%s/$/r/ r introduces a carriage return
http://unix.t-a-y-l-o-r.com/VMswitch.html has
more examples
30. Substitution with Grouping and Back
Referencing
30
Parts of strings in the Search/Left-hand side can be
grouped and referenced in the Replacement/Right-
hand side
Up to nine groups possible (1, 2, ..9)
Groups can be nested or referenced back on the
Search side
Same group can be referenced any number of times
31. Grouping and Back Referencing. Examples
31
Command Explanation
:%s/^(.*):(.*)/2, 1/ Swap two fields delimited with :. "column
A:column B" becomes "column B:column A"
:1,$s/([^,]*), (.*)/2 1/ Convert "Lname, Fname" to "Fname Lname"
:1,$s/v([^,]*), (.*)/2 1/ Same as above with v switch
:%s/^(This (.*) nested)/2 Group 1 contains everything between "This ..
1/ nested". Group 2 contains just the characters
between "This" and "nested".
/(.)(.)(.)321 Search for six character palindromes
/v(.)(.)(.)321 Same as above with v switch
:%s/(.)(.)(.)321/123 Convert six char palindrome strings to
123/g repetitive strings
:%s/v(.)(.)(.)321/123123/ same as above with v switch
g
:%s/^s*(.*[^ ])s*$/1/ Trim the leading and trailing blanks
32. Advanced Substitution
32
Command Explanation
Replace a string that is preceded and
succeeded by specific strings( with zs, ze and
without them)
:s/(.{-}zsabcze){2}/DEF/ Replace the 2nd occurrence of abc with DEF
:s/(.{-}zsabcze){2}/DEF/g Replace every 2nd occurrence
Replace n to mth occurrence
Replace nth to end
33. Joining lines
33
Command Result
J, 5J, 81J Join the next line, next 5 lines, next 81 lines
:1, 10j Join lines 1,10
:/pat1/, /pat2/j Join lines between lines containing pat1 and pat2
:g/pat1/-1, /pat2/+2j Repetitively join lines between one line above pat1,
and two lines below pat2
:1,100g/pat1/-1,/pat2/+2j Same as above, but for lines between 1 and 100
:g/./j Join adjacent lines
:g/pat1/j 3 Join the lines containing pat1 with two lines below
:v/./,/./- j
:g/^$/,/./- j Merge multiple blank lines into one blank line
:%s/^n{2,}/r/
34. Moving Lines
34
Command Result
:1, 10m $ Move lines between 1 and 10 to the end
of the file
:'a, 'bm /pat1 Move lines between 'a and 'b to the line
containing pat1
:/pat1/, /pat2/ m /pat3 Move lines between pat1 and pat2 to the
line after pat3
:/pat1/-1, /pat2/+2 m /pat3 Same as above but the range includes one
line above pat1 and two lines below pat2.
pat3 can also have offset
:g/pat1/-1, /pat2/+2 m $ Same as above, but do it repetitively for
the whole file
:1,100g/pat1/-1,/pat2/+2 m $ Same as above, but for lines between 1
and 100
:g/./m0 Reverse the file by moving ALL the
lines to the top one by one.
35. Copying Lines
35
Command Result
:1, 10co $ Copy lines between 1 and 10 to the end of the file
:/pat1/, /pat2/ co /pat3 Copy lines between pat1 and pat2 to the line after pat3
:/pat1/-1, /pat2/+2 co /pat3 Same as above but the range includes one line above
pat1 and two lines below pat2. pat3 can also have offset
:g/pat1/, /pat2/ co 0 Copy lines between pat1 and pat2 to the beginning of the
file, and do it repetitively for the whole file
:1,100g/pat1/,/pat2/ co 0 Same as above, but for lines between 1 and 100
:g/pat1/co `a Copy all lines matching pat1 to line marked by a
:v/pat1/co `a Copy all lines not matching pat1 to line marked by a
:%co $ Copy the whole file
:%t 0 Same as above, but the top half reversed
:g/./t . Duplicate the lines
36. Indenting Lines
36
Command Result
:1, 10> Shift right the lines between 1 and 10 by one indent
width (8 characters)
:.,+10 >> Shift the next 10 lines by 2 indent widths
:.,/pat1/ -1 > Shift right from current line to the line above containing pat1
:/pat1/, /pat2/ < Shift Left lines between pat1 and pat2
:g/pat1/, /pat2/ < Same as above, but repetitively for the whole file
:1,100g/pat1/,/pat2/ < Same as above, but for lines between 1 and 100
:/pat1/;+10 >>> Shift right the lines between pat1 and 10 lines below it by 3
indent widths. Note the relative addressing
:g/pat1/;+10 >>> Same as above, but repetitively for the whole file
<m, >m shift left, right to m where m could be /pat, marker,
line number, end of file, 50%, etc
n<<, n>> shift n lines left, right
37. Formatting lines
37
Command Result
:1, 5 right Right justify lines 1 to 15
:.,$ center Center the lines between current and end of file
:'a,'b left Left justify the lines between markers a and b
:5,/pat1/ right right justify lines between 5 and the line containg pat1
:/pat1/,/pat2/ right Right justify lines between pat1 and pat2
:g/pat1/,/pat2/ right same as above but repetitively for the whole file
:1,100g/pat1/,/pat2/ right same as above but for lines between 1 and 100
:'a,'bg/pat1/,/pat2/ right same as above but for lines between 'a and 'b
:help formatting
38. Deleting lines
38
Command Result
:'a-1, 'b+1 d Delete the lines between one line above 'a and one line below 'b
:-10,+10d Delete 10 lines above and below current line
:?pat1?, /pat2/ d Delete lines between pat1 and pat2
:g/pat1/, /pat2/ d Repetitively delete lines between pat1 and pat2
:1,100g/pat1/,/pat2/ d Same as above, but for lines between 1 and 100
:/pat1/;+10 d Delete lines between pat1 and 10 lines below. Note the
use of relative addressing with ";"
:/pat1/ d 11 Same as above using the count option
:g/pat1/d delete ALL lines containing pat1
:g/pat1/d 3 delete ALL lines containing pat1 and two lines below
:g/pat1/s/^(.*n){3 Same as above. n is the newline character.
}//
:g/pat1/-1 d 3 delete ALL lines containing pat1 and one line above and
:g/pat1/-1,+1 d below
39. Yanking lines
39
Command Result
:., +10y Yank the current and the next 10 lines
:'a,'by Yank the lines between makers a and b
:'a,$y Yank the lines between marker a and the end of file
:/pat1/+1, /pat2/-1 y Yank lines between pat1 and pat2, but not excluding
the lines containing the pattern
:/pat1/;+10 y Yank lines between pat1 and 10 lines below. Note
the use of relative addressing with ";"
:/pat1/ y 11 Same as above using the count option
40. Registers
40
Registers are buffers that hold deleted or yanked
lines
a-z are explicit registers. registers 0-9 contain the
lines of the last 10 deletes
%, #, /, -, . are special registers that respectively
hold current file name, previous file name, search
string, deleted string, location of last change
:register (:display) shows the registers available
41. Deleting or yanking into registers
41
Command Result
"ayy Yank the current line into register a
"b4dd Delete 4 lines into register b
:register b Show the contents of register b
:/pat1/, /pat2/ y a Yank lines between pat1 and pat2 into register a
:/pat1/, /pat2/y B Yank lines between pat1 and pat2 and "append" to register b.
Upper case makes it appendable
:/pat1/ y c 11 Yank the line containing pat1 and 10 lines below it into register c
:/pat1/;+10 d E delete pat1 and 10 lines below it and APPEND to register e.
Note the use of ";".
:g/pat1/d f delete all lines containing pat1, and store just the last
occurrence in register f
:g/pat1/d F same as above, but store ALL deleted lines in buffer f by
keep appending all the deletions
42. Pasting Lines
42
Command Result
p, P paste below, above current line from the default
register
5p paste below the current line the contents of the
default register five times
"ap Paste below the current line from register a (" is
double quote)
5"ap Same as above, but contents pasted five times
"2p Paste from the second most delete
"9p Paste from the 9th most delete
5"3p Paste 5 times what was deleted 3 deletes ago
":p Paste the most recent EX command
"/p Paste the most recent search pattern
"%p Paste the current file name
43. Pasting Lines – contd.
43
Command Result
:put Put the contents of the default buffer at current line
:normal p
:1,5 normal p The "normal" keyword lets Normal Mode
:1,5 put commands to be executed in EX mode. Put the
contents of default buffer between lines 1 and 5
:/pat1/put a Put the contents of register a below the line
containing pat1
:g/pat1/put a Same as above but for all occurrences of pat1
:v/pat1/put a Put the contents of register a below the lines not
containing pat1
:g/./put b Put the contents of register b after every line
:?pat1?,/pat2/g/./put b Same as above but for lines between pat1 and pat2
44. Writing selectively
44
Command Result
:w Save the current file
:w myfile Save to myfile
:w! myfile Overwrite if myfile exists
:'a,'bw myfile Save lines between markers a and b to myfile
:/pat1/+1,/pat2/-1 w myfile Save lines between pat1 and pat2 to myfile,
excluding the lines containing the pattern
:.,$w >> myfile Append to myfile lines between current line and
end of file
:g/pat1/,/pat2/w! >> myfile append all lines between pat1 and pat2 for all such
ranges
:g/pat1/,/pat2/w! myfile Only the last range between pat1 and pat2 will be
saved
:'a,'bg/^Error/ . w! same as :'a,'b!grep ^Error > err.txt
>>err.txt
45. undo-tree: Flashing back and forth
45
Command Result
g- Go to older text state
g+ Go to newer text state
:earlier {count} Go to older text state {count} times
:earlier {N}s Go to older text state about {N} seconds before
:earlier {N}m Go to older text state about {N} minutes before
:earlier {N}h Go to older text state about {N} hours before
:later {count} Go to newer text state {count} times
:later {N}s Go to newer text state about {N} seconds after
:later {N}m Go to newer text state about {N} minutes after
:later {N}h Go to newer text state about {N} hours after
:ea, :lat :ea is shortcut for :earlier, so is :lat for :later
:help undo-tree
47. Operating on multiple files
47
Command Result
vim *.txt open vim with multiple files
:args, :buffers show the list of all files with their positions
:n, :next go to the next file
:n! go to the next file without saving current
:wn, :wN write and go to the next/previous file
:N, :prev go to the previous file
:3n, :3N go to the third file down/up from the current file
:rew, :first, go to the very first file
:last go to the last file
:qa, :wa quit all, write all
:argdo %s/pat1/pat2/ge | Operate command on all the files
update
:help args
48. Window spliting
48
Command Result
:split, vsplit Spliting windows horizontally, vertically
:close, :only close current window; close all but the current window
:new, :vnew Open a new horizontal/veritcalwindow with empty buffer
:ctrl-w, ctrl-wt, Moving between windows, move to top window, move to
ctrll-wb,ctrl- bottom window, move to left, down, up, right window
w[hjkl]
:all :vertical all opens a window for each file
:wa, :qa Write all changed windows, quit from all windows
:resize -5 reduce the size of the current window by 5 lines
:buffers lists all the files
:windo %s/x/y/g Execute the substitute command on all windows
vim –o file1 file2 Creating windows when launching vim
vim –O file1 file2 Same as above, but veritical windows
:help window to learn so much more about the windows feature
49. Tabbed Editing
49
Command Result
vim –p f1 f2 ... Opens f1, f2 etc in different tab pages
:tabn, gt goes to the next tab
:tabN, gT goes to the previous tab
:tabn 5, 5gt goes to the 5th tab
:tabfirst, :tabrewind goes to the first tab
:tablast goes to the last tab
:tabs Lists all the tabs and files they contain
:tabnew Opens a new tab with empty window
:tabc, tabc 5 Closes current window, or 5th window
:tabonly Close all other tabs
:tabdo %s/x/y/ge Execute the substitute command on all tabs
:help tabedit Lists all these commands and more
50. Folding
50
Command Result
zf/pat1, zf10G Fold upto the next line containing /pat1, fold
current line to line 10 (Basically fold lines from
current to movement)
:10,30fo Fold lines 10 to 30
zo, zO Open fold, open fold repetitively
zc, zC Close fold, close fold repetitively
zj, zk move down, up to start, end of next fold
zd, zD delete fold at cursor, delete recursively
[z, ]z Move cursor to start/end of open fold
zA (toggle) while standing on the fold line
:help folding to learn all about folding
51. Inserting a file or output of a command
51
Command Result
:r myfile Insert the contents of myfile below current line
:$r myfile Insert the contents of myfile at the end of the file
:0r myfile Insert the contents of my file at the top of the file
:'ar myfile Insert the contents of myfile below line marked by a
:/pat1/r myfile Insert myfile below line containing pat1
:g/pat1/r myfile Same as above repetitively for all lines containing
pat1
:$r % Append the contents of the current file at the end of
the file
:r !date Insert the output of "date" below current line
!<command> could be used wherever myfile is used
in the above commands.
52. Invoking shell commands
52
Command Result
:1,10!sort Replace lines 1 and 10 with its sorted output
:1,10w !sort Same as above, but doesn't replace the lines. Space
needed after "w"
:1,10!grep /pat1 Replace lines 1 and 10 with lines containing pat1.
equivalent to :1,10v/pat1/d
:‟a,‟b!awk „{print $2, $3}‟ Replace lines marked by a and b with fields 2 and 3
10!!sort automatically expands to :.,.+9!sort
53. Mapping keys
53
shortcut for long and frequently commands
:map shows all the mapped keys
:map F2 :g/pat1/,/pat2/s/this/that/g
Pressing F2 types the mapped command
:unmap F2 unmaps the key
54. Recording and Replaying with macros
54
qa to record
q to end the recording
@a to replay.
“a” is the name of the macro and can be any
alphabet from a-z
qA appends to macro a
N@a plays the macro a N times.
:register a shows what is in macro a
55. Recording and replaying a vim session
55
Command Result
vim -w mods.txt file1 Record in mods.txt the modifications done to file1
vim –s mods.txt file2 Replay the modifications from the script file mods.txt
to file2.
:source !mods.txt Same as above above
56. Batch mode
56
Invoke the same set of commands on multiple files
cat vimcmd
:1,10d,
:%s/this/that/g
:wq
vim –e myfiles*.txt < vimcmd
: CTRL + F will bring the old commands back. Save
it as "vimcmd"
:argdo, :windo, :tabdo are other possibilities
57. Typing fast with abbreviations
57
Command Result
:ab usa United States of Abbreviations. Expands usa to "United ..America"
America as you type
:unab usa unabbreviates usa
:ab List all the abbreviations in use
58. Random stuff
58
Command Result
:1,10 g/pat1/co $ | Concatenate multiple commands on matched lines
s/pat2/pat3/g with "|". Copy lines containing pat1 in lines between
1, 10 to the end of the files and substitute pat2 with
pat3.
:g/pat1/normal $3bD Delete the last three words on lines with pat1
vim <directory> All files in a directory can be edited
:h quickref Lists useful shortcuts
:<uparrow>, :<down Recall or search vim command history (~/.viminfo
arrow>, :CTRL + F file stores this info)
:history, :help :history
vimtutor Starts vim with a special help file.
vimdiff f1.txt f2.txt Shows the difference in two vertical windows
:set revins Insert from right to left (reverse insert)
59. Customizing vim with .vimrc and EXINIT
59
If a .vimrc file exists in the current directory, vim
reads it when beginning a session.
If no .vimrc file exists in the current directory, vim
checks the home directory for a .vimrc file. If such a
file exists, vim reads it when beginning a session.
60. Customizing vim with .vimrc and EXINIT
60
If no .vimrc file is found, vim uses its defaults.
Values set in the EXINIT environmental variable
override any values set in a .vimrc file
.vimrc contains a series of "set" commands. e.g.:
set nonu, set ic
:set all
vim -u NONE file1 : The –u option starts vim
without initialization files
61. help within vim
61
:help or Press F1
:help substitute
:help pattern
:help gdefault
:help cmdline-ranges
:helpgrep pat1 to search the help file for pat1
63. References – Contd.
63
Learning the vi and Vim Editors (7th edition) by
Arnold Robbins, Elbert Hannah, and Linda Lamb
Regular Expression Recipies by Nathan Good
http://www.rayninfo.co.uk/vimtips.html
http://www.networkcomputing.com/unixworld/tu
torial/009/009.html - this is very good.
http://hydra.nac.uci.edu/indiv/gdh/vi/
http://www.thegeekstuff.com/2010/04/vim-
editor-tutorial/
67. Unanswered questions
67
How to substitute the nth occurrence, from start or end, of a string (e.g. sed
„s/pat1/pat2/3‟)?
How to substitute the nth to last of a string (e.g. sed „s/pat1/pat2/3g‟)?
How to substitute the mth to nth occurrences of a string?
How to delete lines outside of a given range (e.g. delete all lines except 55 to
100) in one go? 1,55d, 101,$d is a two step process. :55,100!d doesn‟t work
How to identify palindrome of any length?
How to have repetition (n occurences of a character in the replacement string
e.g :%s/;/-{80}/ eighty occurrences of –