vim - tips and_tricks

67

Click here to load reader

Upload: logan-palanisamy

Post on 16-Apr-2017

1.570 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: vim - Tips and_tricks

Vim – Tips and Tricks1

Logan Palanisamy

Page 2: vim - Tips and_tricks

Meeting Basics2

Put your phones/pagers on vibrate/muteMessenger: Change the status to offline or in-

meetingRemote attendees: Mute yourself (*6). Ask

questions via Adobe Connect.

Page 3: vim - Tips and_tricks

Agenda3

vim BasicsIntermediate ConceptsCoffee BreakAdvanced ConceptsQ & A

Page 4: vim - Tips and_tricks

Three modes4

Normal/Command modeInsert modeCommand Line/EX mode

Page 5: vim - Tips and_tricks

Transitioning between modes5

From To CommandCommand mode Insert mode i, I, a, A, o, OInsert mode Command mode ESCCommand mode Command Line mode :Command Line mode Command mode Press vi or Enter

Page 6: vim - Tips and_tricks

Navigational commands6

Keys Movementh, j, k, l Move left, down, up, right+, - Move to first character of one line below or abovew, b, e Forward by word, backward by word, end of wordW, 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 screen5|, n|, Move to the 5th column, nth column on a line0, ^, $ Move to beginning, first non-white character; end of

line20G, n G Go to the 20th line, nth line. G takes to the end of file.

gg takes to the file line10%, 55% Go to the 10% of the file, 55% of the file

Page 7: vim - Tips and_tricks

Normal/Command mode keys7

Key Functioni, I insert, insert at the beginningx, X delete a character, delete the left charactera, A append, append at the endr, R replace; replace until Escapeds, S substitute; substitute at the beginning of the lineo, O add a line below or above current linec <object> change the objectd <object> delete the objecty <object> yank the objectu, ctrl R, . undo, cancel undo, redo~, J, ctrl A, ctrl X

toggle case, Join lines, Increment/Decrement a number

p, P paste, Paste before

Page 8: vim - Tips and_tricks

Markers8

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

Page 9: vim - Tips and_tricks

Special markers9

'' (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

Page 10: vim - Tips and_tricks

Basic Formats10

Format Exampleoperator [number] object cw, c2w[number] operator object cw, 2cw, 2c$ [number] operator [number] object 2d3w (deletes 6 words)[number] operator motion/where/scope

d), 2d), d/pat, d10G, yG, cH, >L

[number] operator 5u, 2p, 8x, 9D, 3yy, 4i, 11o, 4. (redo), 7a, 3r, 8j, 8J, 3ctrlA

Page 11: vim - Tips and_tricks

The powerful combination11

What Change

Delete

Copy Lower/Uppercase

Toggle case

One word cw dw yw guw, gUw g~wTwo words (with and without punctuation)

c2w, 2cW

2dw, 2dW

2yw, 2yW

2guw, 2gUW 2g~w, 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~0To top of screen cH dH yH guH, gUH g~HNext line c+ d+ y+ gu+, gU+ g~+Column 8 of current line

c8| d8| y8| gu8|, gU8| g~8|

Page 12: vim - Tips and_tricks

The powerful combination ...12

What Change

Delete

Copy Lower/Uppercase

Toggle 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~18GUp to marker x c`x d`x y`x gu`x, gU`x g~`x

Page 13: vim - Tips and_tricks

Searching13

/pat1, ?pat1 search forward, backwardn repeats the search in same direction, N

reverses the direction of search5n, 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

Page 14: vim - Tips and_tricks

Searching with offset14

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

Page 15: vim - Tips and_tricks

Regular Expressions15

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

Page 16: vim - Tips and_tricks

Extended Regular Expressions16

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

Page 17: vim - Tips and_tricks

Greedy/Lazy match17

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

Page 18: vim - Tips and_tricks

POSIX Character Classes18

POSIX Description[:alnum:] Alphanumeric characters

[:alpha:] Alphabetic characters

[:ascii:] ASCII characters

[:blank:] Space and tab

[:cntrl:] Control characters[:digit:] [:xdigit:] Digits, Hexadecimal digits

[: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)

Page 19: vim - Tips and_tricks

Perl Character Classes19

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]

Page 20: vim - Tips and_tricks

Regular Expressions – Examples20

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\{1,3}

Very basic IP address format

[0-9]{2,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}

IP address format with \v switch which escapes 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-z]*)\?\s\+[A-Z][a-z]*

First name, optional Middle Initial/name, and Last name

Page 21: vim - Tips and_tricks

Tools to learn Regular Expressions

http://www.weitz.de/regex-coach/http://www.regexbuddy.com/

Page 22: vim - Tips and_tricks

Visual Mode22

Command Resultv character modeV line mode^V (ctrl + V) block/vertical mode

o expand/shrink from the other end'< < is the starting marker'> > is the ending markerv<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.

Page 23: vim - Tips and_tricks

Command Line/EX mode23

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

Page 24: vim - Tips and_tricks

Address Ranges24

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 ($):%, :1,$

All lines in the file

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

Page 25: vim - Tips and_tricks

Address Ranges with relative addressing25

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

Page 26: vim - Tips and_tricks

Substitution26

[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

Page 27: vim - Tips and_tricks

Substitution - Examples27

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/g

Substitute this with that on ALL ranges of lines that start with pat1 and end with pat2

:/pat1/,/pat2/g/pat3/s/this/that/g

Substitute this with that on lines that contain pat3 between the FIRST range of lines that start with pat1 and end with pat2

Page 28: vim - Tips and_tricks

Substitution – Examples contd28

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

Page 29: vim - Tips and_tricks

Substitution – Examples contd29

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/:%s/$/^M/:%s/$/\r/

Add a blank line after each line. ^M stands for ctrl v + ctrl M\r introduces a carriage return http://unix.t-a-y-l-o-r.com/VMswitch.html has more examples

Page 30: vim - Tips and_tricks

Substitution with Grouping and Back Referencing30

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 sideSame group can be referenced any number of

times

Page 31: vim - Tips and_tricks

Grouping and Back Referencing. Examples31

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 \1/

Group 1 contains everything between "This .. nested". Group 2 contains just the characters between "This" and "nested".

/\(.\)\(.\)\(.\)\3\2\1 Search for six character palindromes/\v(.)(.)(.)\3\2\1 Same as above with \v switch:%s/\(.\)\(.\)\(.\)\3\2\1/\1\2\3\1\2\3/g

Convert six char palindrome strings to repetitive strings

:%s/\v(.)(.)(.)\3\2\1/\1\2\3\1\2\3/g

same as above with \v switch

:%s/^\s*\(.*[^ ]\)\s*$/\1/ Trim the leading and trailing blanks

Page 32: vim - Tips and_tricks

Advanced Substitution32

Command ExplanationReplace a string that is preceded and succeeded by specific strings( with \zs, \ze and without them)

:s/\(.\{-}\zsabc\ze\)\{2}/DEF/

Replace the 2nd occurrence of abc with DEF

:s/\(.\{-}\zsabc\ze\)\{2}/DEF/g

Replace every 2nd occurrence

Replace n to mth occurrenceReplace nth to end

Page 33: vim - Tips and_tricks

Joining lines33

Command ResultJ, 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

Merge multiple blank lines into one blank line:g/^$/,/./- j

:%s/^\n\{2,\}/\r/

Page 34: vim - Tips and_tricks

Moving Lines34

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.

Page 35: vim - Tips and_tricks

Copying Lines35

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

Page 36: vim - Tips and_tricks

Indenting Lines36

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

Page 37: vim - Tips and_tricks

Formatting lines37

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

Page 38: vim - Tips and_tricks

Deleting lines38

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 below:g/pat1/-1,+1 d

Page 39: vim - Tips and_tricks

Yanking lines39

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

Page 40: vim - Tips and_tricks

Registers40

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

Page 41: vim - Tips and_tricks

Deleting or yanking into registers41

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

Page 42: vim - Tips and_tricks

Pasting Lines42

Command Resultp, P paste below, above current line from the

default register5p 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 delete5"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

Page 43: vim - Tips and_tricks

Pasting Lines – contd. 43

Command Result:put :normal p

Put the contents of the default buffer at current line

:1,5 normal p:1,5 put

The "normal" keyword lets Normal Mode 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

Page 44: vim - Tips and_tricks

Writing selectively44

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! >>err.txt

same as :'a,'b!grep ^Error > err.txt

Page 45: vim - Tips and_tricks

undo-tree: Flashing back and forth45

Command Resultg- Go to older text stateg+ 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

Page 46: vim - Tips and_tricks

Sorting lines46

Command Result

:help sorting

Page 47: vim - Tips and_tricks

Operating on multiple files47

Command Resultvim *.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 | update

Operate command on all the files

:help args

Page 48: vim - Tips and_tricks

Window spliting48

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, ctrll-wb,ctrl-w[hjkl]

Moving between windows, move to top window, move to bottom window, move to left, down, up, right window

: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 windowsvim –o file1 file2 Creating windows when launching vimvim –O file1 file2 Same as above, but veritical windows:help window to learn so much more about the windows feature

Page 49: vim - Tips and_tricks

Tabbed Editing49

Command Resultvim –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

Page 50: vim - Tips and_tricks

Folding50

Command Resultzf/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 30zo, zO Open fold, open fold repetitively

zc, zC Close fold, close fold repetitivelyzj, zk move down, up to start, end of next foldzd, zD delete fold at cursor, delete recursively[z, ]z Move cursor to start/end of open foldzA (toggle) while standing on the fold line:help folding to learn all about folding

Page 51: vim - Tips and_tricks

Inserting a file or output of a command51

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.

Page 52: vim - Tips and_tricks

Invoking shell commands52

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

Page 53: vim - Tips and_tricks

Mapping keys53

shortcut for long and frequently commands:map shows all the mapped keys:map F2 :g/pat1/,/pat2/s/this/that/gPressing F2 types the mapped command:unmap F2 unmaps the key

Page 54: vim - Tips and_tricks

Recording and Replaying with macros54

qa to recordq to end the recording@a to replay. “a” is the name of the macro and can be any

alphabet from a-zqA appends to macro aN@a plays the macro a N times.:register a shows what is in macro a

Page 55: vim - Tips and_tricks

Recording and replaying a vim session55

Command Resultvim -w mods.txt file1 Record in mods.txt the modifications done to

file1vim –s mods.txt file2 Replay the modifications from the script file

mods.txt to file2.:source !mods.txt Same as above above

Page 56: vim - Tips and_tricks

Batch mode56

Invoke the same set of commands on multiple filescat 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

Page 57: vim - Tips and_tricks

Typing fast with abbreviations57

Command Result:ab usa United States of America

Abbreviations. Expands usa to "United ..America" as you type

:unab usa unabbreviates usa:ab List all the abbreviations in use

Page 58: vim - Tips and_tricks

Random stuff58

Command Result:1,10 g/pat1/co $ | s/pat2/pat3/g

Concatenate multiple commands on matched lines 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 arrow>, :CTRL + F

Recall or search vim command history (~/.viminfo file stores this info)

:history, :help :historyvimtutor 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)

Page 59: vim - Tips and_tricks

Customizing vim with .vimrc and EXINIT59

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.

Page 60: vim - Tips and_tricks

Customizing vim with .vimrc and EXINIT60

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 allvim -u NONE file1 : The –u option starts vim

without initialization files

Page 61: vim - Tips and_tricks

help within vim61

:help or Press F1:help substitute:help pattern:help gdefault:help cmdline-ranges:helpgrep pat1 to search the help file for pat1

Page 62: vim - Tips and_tricks

References62

http://twiki.corp.yahoo.com/view/Platform/UsingVim

http://dist.corp.yahoo.com/by-package/vim_syntax_yicf/

http://ydoc.engineering.corp.sp1.yahoo.com/vimaday/archive.html

http://twiki.corp.yahoo.com/view/GDAdserver/VimClinic

http://twiki.corp.yahoo.com/view/Jumpcut/VimTipshttp://vimdoc.sourceforge.net/htmldoc/

Page 63: vim - Tips and_tricks

References – Contd.63

Learning the vi and Vim Editors (7th edition) by Arnold Robbins, Elbert Hannah, and Linda Lamb

Regular Expression Recipies by Nathan Goodhttp://www.rayninfo.co.uk/vimtips.htmlhttp://www.networkcomputing.com/unixworld/

tutorial/009/009.html - this is very good.

http://hydra.nac.uci.edu/indiv/gdh/vi/http://www.thegeekstuff.com/2010/04/vim-

editor-tutorial/

Page 64: vim - Tips and_tricks

References – Contd. 64

http://icc.skku.ac.kr/~joonsub/Solaris/Unix_Power_Tools/ch30_01.htm

http://www.eng.hawaii.edu/Tutor/vi.htmlhttp://www.w3reference.com/vi.htmlhttp://directory.google.com/Top/Computers/

Software/Editors/Vi/

http://seerofsouls.com/wiki/How-Tos/AdvancedViUsage (Window spliting, folding, etc)

Page 65: vim - Tips and_tricks

References – Contd.65

http://www.thegeekstuff.com/2009/04/vi-vim-editor-search-and-replace-examples/#comments

http://thomer.com//vi/vi.htmlhttp://www.vmunix.com/~gabor/vi.htmlhttp://www.lagmonster.org/docs/vi2.html -

Cheat sheethttp://www.vimregex.com/http://tnerual.eriogerg.free.fr/vimqrc.pdf

Page 66: vim - Tips and_tricks

Q & A66

[email protected]://tech.groups.yahoo.com/group/vim/

Page 67: vim - Tips and_tricks

Unanswered questions67

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 –