vim / vi editor tutorial

Upload: andrew-florit

Post on 30-May-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 Vim / Vi Editor Tutorial

    1/9

    VIM tutorialby Andrew Florit

    Table of ContentsIntroduction................................................................................................................................................1Vim states...................................................................................................................................................1Starting Vim...............................................................................................................................................2Opening files..............................................................................................................................................3Cursor movement.......................................................................................................................................3Visual commands.......................................................................................................................................3

    Copying text in visual mode..................................................................................................................4Insert commands........................................................................................................................................4Deleting text...............................................................................................................................................5Copying text...............................................................................................................................................5

    Pasting text.................................................................................................................................................5Find/Replace..............................................................................................................................................6Macros........................................................................................................................................................6Closing Vim/saving text/undoing changes................................................................................................7Managing splitted windows.......................................................................................................................7Programming..............................................................................................................................................7Miscellaneous commands..........................................................................................................................8Customizing Vim.......................................................................................................................................8

    IntroductionThis document provides a tutorial and quick reference for the Vim editor available on all Linux/Unixsystems and also on Windows. It deals with the commands and features I deem most useful and easy toremember and use, including Visual editing on multiple files.

    Vim commands may appear cumbersome and overwhelming at first, the more so if you are used tomodern IDEs, but once learned they become very handy and you will never forget them.

    As regards notation: ESC denotes the escape key at the top-left corner of your keyboard Ctrl+V (and similar sequences) denote keeping the Ctrl key pressed while you type the V key

    (no Shift key involved)

    some commands start with the colon character ':'. (These commands belong to the ed editorwhich underlies vi, and are available in Command mode)

    Vim statesVim operation is based on States (stateful editor). Vim states include Command, Insert and Visualmodes. The meaning of a keystroke depends on the state Vim is currently in.

    1 / 9 Version 1.5 06/23/2010

  • 8/9/2019 Vim / Vi Editor Tutorial

    2/9

    Vim starts out in Command mode, which allows you to manage files, navigate the document(s) and tocarry out find/replace operations. You can return to Command mode at any time by typing ESC .

    Typing an Insert command causes Vim to switch to Insert mode. Insert commands include: i, I, o, O, a,A. While in Insert mode all characters you type are entered at the current cursor position. When you aredone inserting characters you can return to Command mode by typing ESC.

    Typing a Visual command sets Vim in Visual mode. Visual commands include v, V and Ctrl+V. Whilein Visual mode, text is highlighted while you move the current character position. Typing an ESCreturns Vim to Command mode.

    Typing a cursor movement command leaves Vim in Command mode.

    This cycle is described in the following picture:

    Starting Vimvim filename filename2 ... start Vim and edit filename, filename2, The loaded files are

    displayed one at a time. Use :n (:N) to go to the 'next' ('previous')loaded file.

    vim filepattern start Vim and edit all files matching filepattern (e.g. *.php).Use :n (:N) to go to the 'next' ('previous') loaded file

    Vim starts out in Command mode.

    2 / 9 Version 1.5 06/23/2010

  • 8/9/2019 Vim / Vi Editor Tutorial

    3/9

    Opening filesIn Command mode:

    :split filename splits the current window horizontally and loads filename into thenew window (see managing splitted windows below)

    :vsplit filename splits the current window vertically and loads filename into the newwindow (see managing splitted windows below)

    :r filename insert the contents of filename below the current line

    :e filename stop editing the 'current file' and start editing filename

    Cursor movementIn Command mode:

    h, j, k, l move the cursor one character left, down, up, right

    w move the cursor to the beginning of next word

    e move the cursor to the end of the next word

    ^ move the cursor to the beginning of the current line

    $ move the cursor to the end of the current line

    + move to the beginning of next line

    - move to the beginning of previous line

    Ctrl+F Move the cursor forward by a screenful of text

    Ctrl+B Move the cursor backward by a screenful of text

    G Move the cursor to the end of the file

    numG Move the cursor to line number num. (For instance, 10G moves toline 10.) To display/hide line numbers use the following commands::set number / :set nonumber

    gg Move the cursor to the beginning of the file (like 1G)

    H Move the cursor to the top of the screen.

    Ctrl+W Ctrl+W jumps to the next window (cyclically)

    Visual commands

    Typing a Visual command sets Vim in Visual mode. Visual commands include v, V and Ctrl+V. Whilein Visual mode text is highlighted while you move the current character position. Typing ESC returnsVim to Command mode.

    In Command mode:

    v enter Characterwise selection mode.

    V enter Linewise selection mode. Whole lines are always selected.

    3 / 9 Version 1.5 06/23/2010

  • 8/9/2019 Vim / Vi Editor Tutorial

    4/9

    Ctrl+V enter Blockwise selection mode.

    d delete the currently highlighted text and save it to the clipboard.

    y copy the currently highlighted text to the clipboard

    P, p insert the text currently in the clipboard at the current cursorposition.

    If the saved text had been selected linewise, inserts the saved linesabove or below the current line.If the saved text had been selected character- or block-wise, insertsthe saved text before or after the current character

    ESC return to Command mode

    Copying/moving text in visual mode1. position the cursor at the first character in the text you want to copy/move

    2. enter one of the Visual commands (v, V, Ctrl+V) according as you want to copy a range ofcharacters, a range of lines, or a block of text

    3. move the cursor by characters (h, l) or lines (j, k). VIM highlights the text involved

    4. use the y command to copy the highlighted text to the clipboard (the selected text remains in thefile but the highlight disappears) or

    5. use the d command to cut the highlighted text to the clipboard (the selected text disappears, butit is saved into the clipbuard)

    6. you are now back in Command mode

    7. to insert the saved text, position the cursor in any currently open document and type P or p toinsert the saved text from the clipboard as described above.

    Insert commandsThese command cause Vim to switch to Insert mode. While in Insert mode the text you type is insertedinto the document at the current cursor position. To terminate Insert mode and return to Commandmode type ESC

    In Command mode:

    i Insert text to the left of the current character.

    I Insert text at the beginning of the current line.

    a Insert text to the right of the current character (append.)

    A Insert text at the end of the current line (append.)

    o Open a new empty line under the current one and insert text there.

    O Open a new empty line above the current one and insert text there.

    cw change word (delete the current word and go to Insert mode)

    4 / 9 Version 1.5 06/23/2010

  • 8/9/2019 Vim / Vi Editor Tutorial

    5/9

    c$ delete from the cursor position to end of current line and go toInsert mode there

    :r filename includes filename after the current line

    ESC return to Command mode

    Deleting textIn Command mode:

    nx delete character at cursor (repeat n times, eg: 3x)

    nX delete character before cursor (repeat n times)

    dw delete current word

    D delete from cursor position to end of current line

    ndd delete current line (repeat n times, e.g. 3dd deletes three linesstarting from the current one)

    d in Visual mode, deletes the currently highlighetd text and stores itin the clipboard

    :l1,l2d delete lines in the range l1 to l2

    :.,$d deletes all lines from the current line through the end of the file

    n is number of times the command will be repeated. Default: 1 deleted text is saved to the clipboard delete can be undone by the u command

    Copying texty in Visual mode: copy the highlighted text to the clipboard

    nY in Command mode: copy n lines starting from the current line tothe clipboard

    :l1:l2y in Command mode: copy lines in the range from l1 to l2 to theclipboard

    :l1,l2w! filename in Command mode: writes lines in the range l1 to l2 from thecurrent file to filename

    Pasting textIn Command mode:

    p insert copied/deleted text after the character or line

    P insert copied/deleted text before the current character or line

    5 / 9 Version 1.5 06/23/2010

  • 8/9/2019 Vim / Vi Editor Tutorial

    6/9

    :r filename inserts the contents of filename after the current line

    Find/ReplaceFind operations are case-sensitive by default, but Vim can be caused to carry out case insensitivesearches (see Miscellaneous commands at the end of this document.)

    In Command mode:

    * Read the string under the cursor and go to the next place itappears.

    # Same as above, except it moves the cursor to the previousoccurence.

    /text Starting from the cursor, find the next occurence of the string. Tore-execute your last search, type n (for next occurence).

    ?text Same as /, but searches in the opposite direction. To re-executeyour last search, type N

    :l1,l2s/oldstring/newstring/g replace oldstring with newstring in the range of lines from l1 tol2 (g means replace multiple occurrences on the same line, if youomit g only the first occurrence is replaced)

    :1,$/oldstring/newstring/g the same on the whole file (1 = first line, $ = last line)

    oldstring above can be a Regular Expression (RE). In a RE the following special characters can appear:

    . matches any single character

    .* matches any string

    ^ matches the beginning of line$ matches the end of line

    [xyz] matches any one of the characters x, y, z

    [a-z] matches any single character in the range a to z

    \c matches any special character c (for instance, to match a / specify it as \/)

    In Visual mode:

    :' characters yourself, Vimautomatically inserts them after you type the colon :, meaningthat the following command will be executed over thehighlighted text.

    6 / 9 Version 1.5 06/23/2010

  • 8/9/2019 Vim / Vi Editor Tutorial

    7/9

    MacrosIn Command mode:

    qregister Start macro recording into the named 'register'. For instance, qastarts recording and puts the macro into register a.

    q End recording.

    @register Replay the macro stored in the named register. For instance, @areplays the macro in register a.

    Closing Vim/saving text/undoing changesIn Command mode:

    :wq save and close the current file

    :w! [filename] save the current file (optionally rename as filename)

    :l1,l2w! filename write the lines in the range l1 to l2 to filename

    :q! close the current file without saving changes

    u undo the last change (repeat the u command to undo multiplechanges)

    Note:1. the ! causes filename to be overwritten if it already exists (optional)

    Managing splitted windowsIn Command mode:

    Ctrl+W Ctrl+W jumps to the next window (cyclically)

    Ctrl+W+ Increases the size of the current split by one line

    Ctrl+W- (Minus sign) Decreases the size of the current split by one line.

    Ctrl+W_ (Underscore) Maximize the current split (that is, make it take up as much room aspossible.)

    Ctrl+W= Makes all splitted windows equal

    ProgrammingIn Command mode:

    ]p Just like p, but it automatically adjusts the indent level of the pastedcode to match that of the code you paste into.

    % Putting the cursor on a brace, bracket, or parenthesis and pressing% will send the cursor to the matching brace, bracket, or

    7 / 9 Version 1.5 06/23/2010

  • 8/9/2019 Vim / Vi Editor Tutorial

    8/9

    parentheses.

    > Indent the highlighted code

    < Unindent the highlighted code

    gd Go to the definition (or declaration) of the function or variableunder the cursor.

    Miscellaneous commandsIn Command mode:

    :set number display line numbers

    :set nonumber hide line numbers

    :set tabstop=n sets the tab positions at every n characters in the line

    :set ignorecase causes Vim to ignore the character case in find operations (default iscase sensitive find: set noignorecase)

    u undoes the last change. Can be repeated to undo a sequence ofchanges in reverse order.

    . (a dot) repeats the last command. To repeat a find operation use n orN instead.

    Customizing VimYou can control Vim's overall behaviour by putting some configuration commands into a .vimrc file inyour home directory. Some useful commands for editing source code are as follows:

    set tabstop=3set noexpandtab

    set shiftwidth=3

    set autoindent

    set smartindent

    set scrolloff=1

    tabstop=n set tab positions every n characters

    noexpandtab retains TAB characters in the file (set expandtab replaces TABcharacters with blanks)

    shiftwidth number of characters to indent when user types the '>' command ona block of lines

    autoindent, smartindent enables automatic indentation depending on syntax

    8 / 9 Version 1.5 06/23/2010

  • 8/9/2019 Vim / Vi Editor Tutorial

    9/9

    scrolloff retains one line of text from previous page of text when pagingthrough the document by Ctr+F or Ctrl+B

    9 / 9 Version 1.5 06/23/2010