SlideShare uma empresa Scribd logo
1 de 67
Vim – Tips and Tricks
          1

   Logan Palanisamy
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.
Agenda
                          3

 vim Basics
 Intermediate Concepts
 Coffee Break
 Advanced Concepts
 Q&A
Three modes
                        4

 Normal/Command mode
 Insert mode
 Command Line/EX mode
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
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
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
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
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
Basic Formats
                                       10

Format                                      Example
operator [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
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|
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
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
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
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
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
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
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)
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]
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
Tools to learn Regular Expressions

 http://www.weitz.de/regex-coach/
 http://www.regexbuddy.com/
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.
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
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
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
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
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
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
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
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
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
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
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/
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.
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
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
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
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
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
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
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
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
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
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
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
Sorting lines
                         46

Command         Result




:help sorting
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
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
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
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
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.
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
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
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
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
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
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
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)
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.
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
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
References
                            62

 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/vima
  day/archive.html
 http://twiki.corp.yahoo.com/view/GDAdserver/Vi
  mClinic
 http://twiki.corp.yahoo.com/view/Jumpcut/VimTips
 http://vimdoc.sourceforge.net/htmldoc/
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/
References – Contd.
                          64

 http://icc.skku.ac.kr/~joonsub/Solaris/Unix_Pow
    er_Tools/ch30_01.htm
   http://www.eng.hawaii.edu/Tutor/vi.html
   http://www.w3reference.com/vi.html
   http://directory.google.com/Top/Computers/Soft
    ware/Editors/Vi/
   http://seerofsouls.com/wiki/How-
    Tos/AdvancedViUsage (Window spliting, folding,
    etc)
References – Contd.
                          65

 http://www.thegeekstuff.com/2009/04/vi-vim-
    editor-search-and-replace-examples/#comments
   http://thomer.com//vi/vi.html
   http://www.vmunix.com/~gabor/vi.html
   http://www.lagmonster.org/docs/vi2.html - Cheat
    sheet
   http://www.vimregex.com/
   http://tnerual.eriogerg.free.fr/vimqrc.pdf
Q&A
                           66

 devel-vim@yahoo-inc.com
 http://tech.groups.yahoo.com/group/vim/
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 –

Mais conteúdo relacionado

Mais procurados

Ddl &amp; dml commands
Ddl &amp; dml commandsDdl &amp; dml commands
Ddl &amp; dml commandsAnjaliJain167
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?Nikita Popov
 
Linux basic commands with examples
Linux basic commands with examplesLinux basic commands with examples
Linux basic commands with examplesabclearnn
 
Curso de RESTful WebServices em Java com JAX-RS (Java EE 7)
Curso de RESTful WebServices em Java com JAX-RS (Java EE 7)Curso de RESTful WebServices em Java com JAX-RS (Java EE 7)
Curso de RESTful WebServices em Java com JAX-RS (Java EE 7)Helder da Rocha
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to RubyRanjith Siji
 
Tm09 modelo er_extendido
Tm09 modelo er_extendidoTm09 modelo er_extendido
Tm09 modelo er_extendidoJulio Pari
 
JCL BEYOND DFSORT
JCL BEYOND DFSORTJCL BEYOND DFSORT
JCL BEYOND DFSORTNirmal Pati
 
10 SQL - Funções de agregação
10 SQL - Funções de agregação10 SQL - Funções de agregação
10 SQL - Funções de agregaçãoCentro Paula Souza
 
Unix And Shell Scripting
Unix And Shell ScriptingUnix And Shell Scripting
Unix And Shell ScriptingJaibeer Malik
 
Html 5-tables-forms-frames (1)
Html 5-tables-forms-frames (1)Html 5-tables-forms-frames (1)
Html 5-tables-forms-frames (1)club23
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple InheritanceBhavyaJain137
 
PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array. PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array. wahidullah mudaser
 
Regular Expression (Regex) Fundamentals
Regular Expression (Regex) FundamentalsRegular Expression (Regex) Fundamentals
Regular Expression (Regex) FundamentalsMesut Günes
 
Java orientação a objetos (variaveis de instancia e metodos)
Java   orientação a objetos (variaveis de instancia e metodos)Java   orientação a objetos (variaveis de instancia e metodos)
Java orientação a objetos (variaveis de instancia e metodos)Armando Daniel
 
Php server variables
Php server variablesPhp server variables
Php server variablesJIGAR MAKHIJA
 

Mais procurados (20)

Ddl &amp; dml commands
Ddl &amp; dml commandsDdl &amp; dml commands
Ddl &amp; dml commands
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Linux basic commands with examples
Linux basic commands with examplesLinux basic commands with examples
Linux basic commands with examples
 
Curso de RESTful WebServices em Java com JAX-RS (Java EE 7)
Curso de RESTful WebServices em Java com JAX-RS (Java EE 7)Curso de RESTful WebServices em Java com JAX-RS (Java EE 7)
Curso de RESTful WebServices em Java com JAX-RS (Java EE 7)
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
HTML (Web) basics for a beginner
HTML (Web) basics for a beginnerHTML (Web) basics for a beginner
HTML (Web) basics for a beginner
 
Tm09 modelo er_extendido
Tm09 modelo er_extendidoTm09 modelo er_extendido
Tm09 modelo er_extendido
 
JCL BEYOND DFSORT
JCL BEYOND DFSORTJCL BEYOND DFSORT
JCL BEYOND DFSORT
 
10 SQL - Funções de agregação
10 SQL - Funções de agregação10 SQL - Funções de agregação
10 SQL - Funções de agregação
 
Unix And Shell Scripting
Unix And Shell ScriptingUnix And Shell Scripting
Unix And Shell Scripting
 
Html 5-tables-forms-frames (1)
Html 5-tables-forms-frames (1)Html 5-tables-forms-frames (1)
Html 5-tables-forms-frames (1)
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple Inheritance
 
PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array. PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array.
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Basic Input and Output
Basic Input and OutputBasic Input and Output
Basic Input and Output
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Regular Expression (Regex) Fundamentals
Regular Expression (Regex) FundamentalsRegular Expression (Regex) Fundamentals
Regular Expression (Regex) Fundamentals
 
Java orientação a objetos (variaveis de instancia e metodos)
Java   orientação a objetos (variaveis de instancia e metodos)Java   orientação a objetos (variaveis de instancia e metodos)
Java orientação a objetos (variaveis de instancia e metodos)
 
Php server variables
Php server variablesPhp server variables
Php server variables
 

Destaque

Introduction to Vim, the text editor
Introduction to Vim, the text editorIntroduction to Vim, the text editor
Introduction to Vim, the text editorVysakh Sreenivasan
 
How to become a practical Vim user
How to become a practical Vim userHow to become a practical Vim user
How to become a practical Vim userKana Natsuno
 
Vim, the Way of the Keyboard
Vim, the Way of the KeyboardVim, the Way of the Keyboard
Vim, the Way of the KeyboardFederico Galassi
 
Introduction to Vim
Introduction to VimIntroduction to Vim
Introduction to VimBrandon Liu
 
Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)Peter Kofler
 
FLTK Summer Course - Part I - First Impact - Exercises
FLTK Summer Course - Part I - First Impact - ExercisesFLTK Summer Course - Part I - First Impact - Exercises
FLTK Summer Course - Part I - First Impact - ExercisesMichel Alves
 
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...Alessandro Molina
 
Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2Anil Sagar
 
FLTK Summer Course - Part VII - Seventh Impact
FLTK Summer Course - Part VII  - Seventh ImpactFLTK Summer Course - Part VII  - Seventh Impact
FLTK Summer Course - Part VII - Seventh ImpactMichel Alves
 
FLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second ImpactFLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second ImpactMichel Alves
 
Using Git on the Command Line
Using Git on the Command LineUsing Git on the Command Line
Using Git on the Command LineBrian Richards
 
Git hooks For PHP Developers
Git hooks For PHP DevelopersGit hooks For PHP Developers
Git hooks For PHP DevelopersUmut IŞIK
 
Introduction to Git Commands and Concepts
Introduction to Git Commands and ConceptsIntroduction to Git Commands and Concepts
Introduction to Git Commands and ConceptsCarl Brown
 
Creating Custom Drupal Modules
Creating Custom Drupal ModulesCreating Custom Drupal Modules
Creating Custom Drupal Modulestanoshimi
 
FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises Michel Alves
 
"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development process"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development processPolished Geek LLC
 
Servicios web con Python
Servicios web con PythonServicios web con Python
Servicios web con PythonManuel Pérez
 

Destaque (20)

Introduction to Vim, the text editor
Introduction to Vim, the text editorIntroduction to Vim, the text editor
Introduction to Vim, the text editor
 
How to become a practical Vim user
How to become a practical Vim userHow to become a practical Vim user
How to become a practical Vim user
 
Vim survival guide
Vim survival guideVim survival guide
Vim survival guide
 
Vim, the Way of the Keyboard
Vim, the Way of the KeyboardVim, the Way of the Keyboard
Vim, the Way of the Keyboard
 
Power poin perswnt
Power poin perswntPower poin perswnt
Power poin perswnt
 
Introduction to Vim
Introduction to VimIntroduction to Vim
Introduction to Vim
 
Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)
 
FLTK Summer Course - Part I - First Impact - Exercises
FLTK Summer Course - Part I - First Impact - ExercisesFLTK Summer Course - Part I - First Impact - Exercises
FLTK Summer Course - Part I - First Impact - Exercises
 
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
 
Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2
 
FLTK Summer Course - Part VII - Seventh Impact
FLTK Summer Course - Part VII  - Seventh ImpactFLTK Summer Course - Part VII  - Seventh Impact
FLTK Summer Course - Part VII - Seventh Impact
 
Advanced Git
Advanced GitAdvanced Git
Advanced Git
 
FLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second ImpactFLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second Impact
 
Using Git on the Command Line
Using Git on the Command LineUsing Git on the Command Line
Using Git on the Command Line
 
Git hooks For PHP Developers
Git hooks For PHP DevelopersGit hooks For PHP Developers
Git hooks For PHP Developers
 
Introduction to Git Commands and Concepts
Introduction to Git Commands and ConceptsIntroduction to Git Commands and Concepts
Introduction to Git Commands and Concepts
 
Creating Custom Drupal Modules
Creating Custom Drupal ModulesCreating Custom Drupal Modules
Creating Custom Drupal Modules
 
FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises
 
"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development process"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development process
 
Servicios web con Python
Servicios web con PythonServicios web con Python
Servicios web con Python
 

Semelhante a vim - Tips and_tricks

Beginning with vi text editor
Beginning with vi text editorBeginning with vi text editor
Beginning with vi text editorJose Pla
 
Vi Editor Cheat Sheet
Vi Editor Cheat SheetVi Editor Cheat Sheet
Vi Editor Cheat SheetLoiane Groner
 
Vi Cheat Sheet v 1 00
Vi Cheat Sheet v 1 00Vi Cheat Sheet v 1 00
Vi Cheat Sheet v 1 00Nicole Cordes
 
VIM for (PHP) Programmers
VIM for (PHP) ProgrammersVIM for (PHP) Programmers
VIM for (PHP) ProgrammersZendCon
 
101 3.8.2 vim reference card
101 3.8.2 vim reference card101 3.8.2 vim reference card
101 3.8.2 vim reference cardAcácio Oliveira
 
Rubizza #1 | Special Lecture. Vim
Rubizza #1 | Special Lecture. Vim Rubizza #1 | Special Lecture. Vim
Rubizza #1 | Special Lecture. Vim Rubizza
 
Using VI Editor in Red Hat by Rohit Kumar
Using VI Editor in Red Hat by Rohit KumarUsing VI Editor in Red Hat by Rohit Kumar
Using VI Editor in Red Hat by Rohit KumarRohit Kumar
 
Vi reference
Vi referenceVi reference
Vi referenceaireddy
 
Regular expressions in oracle
Regular expressions in oracleRegular expressions in oracle
Regular expressions in oracleLogan Palanisamy
 

Semelhante a vim - Tips and_tricks (20)

vim-cheatsheet.pdf
vim-cheatsheet.pdfvim-cheatsheet.pdf
vim-cheatsheet.pdf
 
Beginning with vi text editor
Beginning with vi text editorBeginning with vi text editor
Beginning with vi text editor
 
Vi Editor Cheat Sheet
Vi Editor Cheat SheetVi Editor Cheat Sheet
Vi Editor Cheat Sheet
 
Vim Cheat Sheet.pdf
Vim Cheat Sheet.pdfVim Cheat Sheet.pdf
Vim Cheat Sheet.pdf
 
Vi Cheat Sheet v 1 00
Vi Cheat Sheet v 1 00Vi Cheat Sheet v 1 00
Vi Cheat Sheet v 1 00
 
VIM for (PHP) Programmers
VIM for (PHP) ProgrammersVIM for (PHP) Programmers
VIM for (PHP) Programmers
 
101 3.8.2 vim reference card
101 3.8.2 vim reference card101 3.8.2 vim reference card
101 3.8.2 vim reference card
 
3.8.b vim reference card
3.8.b vim reference card3.8.b vim reference card
3.8.b vim reference card
 
Rubizza #1 | Special Lecture. Vim
Rubizza #1 | Special Lecture. Vim Rubizza #1 | Special Lecture. Vim
Rubizza #1 | Special Lecture. Vim
 
Using vi editor
Using vi editorUsing vi editor
Using vi editor
 
Using VI Editor in Red Hat by Rohit Kumar
Using VI Editor in Red Hat by Rohit KumarUsing VI Editor in Red Hat by Rohit Kumar
Using VI Editor in Red Hat by Rohit Kumar
 
Vim For Php
Vim For PhpVim For Php
Vim For Php
 
VIM for Programmers
VIM for ProgrammersVIM for Programmers
VIM for Programmers
 
Vi cheat sheet
Vi cheat sheetVi cheat sheet
Vi cheat sheet
 
Vi cheat sheet
Vi cheat sheetVi cheat sheet
Vi cheat sheet
 
Vi reference
Vi referenceVi reference
Vi reference
 
Vi reference
Vi referenceVi reference
Vi reference
 
Sed tips and_tricks
Sed tips and_tricksSed tips and_tricks
Sed tips and_tricks
 
Regular expressions in oracle
Regular expressions in oracleRegular expressions in oracle
Regular expressions in oracle
 
Awk essentials
Awk essentialsAwk essentials
Awk essentials
 

Último

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Último (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

vim - Tips and_tricks

  • 1. Vim – Tips and Tricks 1 Logan Palanisamy
  • 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.
  • 3. Agenda 3  vim Basics  Intermediate Concepts  Coffee Break  Advanced Concepts  Q&A
  • 4. Three modes 4  Normal/Command mode  Insert mode  Command Line/EX mode
  • 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
  • 10. Basic Formats 10 Format Example operator [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
  • 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
  • 46. Sorting lines 46 Command Result :help sorting
  • 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
  • 62. References 62  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/vima day/archive.html  http://twiki.corp.yahoo.com/view/GDAdserver/Vi mClinic  http://twiki.corp.yahoo.com/view/Jumpcut/VimTips  http://vimdoc.sourceforge.net/htmldoc/
  • 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/
  • 64. References – Contd. 64  http://icc.skku.ac.kr/~joonsub/Solaris/Unix_Pow er_Tools/ch30_01.htm  http://www.eng.hawaii.edu/Tutor/vi.html  http://www.w3reference.com/vi.html  http://directory.google.com/Top/Computers/Soft ware/Editors/Vi/  http://seerofsouls.com/wiki/How- Tos/AdvancedViUsage (Window spliting, folding, etc)
  • 65. References – Contd. 65  http://www.thegeekstuff.com/2009/04/vi-vim- editor-search-and-replace-examples/#comments  http://thomer.com//vi/vi.html  http://www.vmunix.com/~gabor/vi.html  http://www.lagmonster.org/docs/vi2.html - Cheat sheet  http://www.vimregex.com/  http://tnerual.eriogerg.free.fr/vimqrc.pdf
  • 66. Q&A 66  devel-vim@yahoo-inc.com  http://tech.groups.yahoo.com/group/vim/
  • 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 –