spacer

Linux vi and vim editor: Tutorial and advanced features

Related YoLinux Tutorials:

°Software development tools

°Text Editors

°Emacs and C/C++

°C++ Info, links

°MS/Visual C++ Practices

°C++ Memory corruption and leaks

°C++ String Class

°C++ STL vector, list

°Posix Threads

°Fork and Exec

°GDK Threads

°Clearcase Commands

°YoLinux Tutorials Index




Free Information Technology Magazines and Document Downloads
spacer


Free Information Technology Software and Development Magazine Subscriptions and Document Downloads


Vim Intro:

This "vi" tutorial is intended for those who wish to master and advance their skills beyond the basic features of the basic editor. It covers buffers, "vi" command line instructions, interfacing with UNIX commands, and ctags. The vim editor is an enhanced version of vi. The improvements are clearly noticed in the handling of tags.

The advantage of learning vi and learning it well is that one will find vi on all Unix based systems and it does not consume an inordinate amount of system resources. Vi works great over slow network ppp modem connections and on systems of limited resources. One can completely utilize vi without departing a single finger from the keyboard. (No hand to mouse and return to keyboard latency)

NOTE: Microsoft PC Notepad users who do not wish to use "vi" should use "gedit" (GNOME edit) or "gnp" (GNOME Note Pad) on Linux. This is very similar in operation to the Microsoft Windows editor, "Notepad". (Other Unix systems GUI editors: "dtpad", which can be found in /usr/dt/bin/dtpad for AIX, vuepad on HP/UX, or xedit on all Unix systems.)

See our list of Linux GUI editors


Vim Installation:

Red Hat / CentOS / Fedora:

  • rpm -ivh vim-common-...rpm vim-minimal-...rpm vim-enhanced-...rpm vim-X11-...rpm
  • yum install vim-common vim-minimal vim-enhanced vim-X11
Ubuntu / Debian:
  • apt-get install vim vim-common vim-gnome vim-gui-common vim-runtime
Compiling Vim from source:
  • Download vim source from vim.org
  • tar xzf vim-7.0.tar.gz
  • cd vim70
  • ./configure --prefix=/opt --enable-cscope
  • make
  • make install
Basic "vi" features

One edits a file in vi by issuing the command: vi file-to-edit.txt

The vi editor has three modes, command mode, insert mode and command line mode.

  1. Command mode: letters or sequence of letters interactively command vi. Commands are case sensitive. The ESC key can end a command.
  2. Insert mode: Text is inserted. The ESC key ends insert mode and returns you to command mode. One can enter insert mode with the "i" (insert), "a" (insert after), "A" (insert at end of line), "o" (open new line after current line) or "O" (Open line above current line) commands.
  3. Command line mode: One enters this mode by typing ":" which puts the command line entry at the foot of the screen.

Partial list of interactive commands:

Cursor movement:
Keystrokes Action
h/j/k/l Move cursor left/down/up/right
spacebar Move cursor right one space
-/+ Move cursor down/up in first column
ctrl-d Scroll down one half of a page
ctrl-u Scroll up one half of a page
ctrl-f Scroll forward one page
ctrl-b Scroll back one page
M (shift-m) Move cursor to middle of page
H (shift-h) Move cursor to top of page
L (shift-l) Move cursor to bottom of page
W
w
5w
Move cursor a word at a time
Move cursor ahead 5 words
B
b
5b
Move cursor back a word at a time
Move cursor back a word at a time
Move cursor back 5 words
e
5e
Move cursor to end of word
Move cursor ahead to the end of the 5th word
0 (zero) Move cursor to beginning of line
$ Move cursor to end of line
) Move cursor to beginning of next sentence
( Move cursor to beginning of current sentence
G Move cursor to end of file
% Move cursor to the matching bracket.
Place cursor on {}[]() and type "%".
Use the matchit or xmledit plug-in to extend this capability to XML/XHTML tags.
'. Move cursor to previously modified line.
'a Move cursor to line mark "a" generated by marking with keystroke "ma"
'A Move cursor to line mark "a" (global between buffers) generated by marking with keystroke "mA"
]' Move cursor to next lower case mark.
[' Move cursor to previous lower case mark.

Editing commands:

Keystrokes Action
i Insert at cursor
a Append after cursor
A Append at end of line
ESC Terminate insert mode
u Undo last change
U Undo all changes to entire line
o Open a new line
dd
3dd
Delete line
Delete 3 lines.
D Delete contents of line after cursor
C Delete contents of line after cursor and insert new text. Press esc key to end insertion.
dw
4dw
Delete word
Delete 4 words
cw Change word
x Delete character at cursor
r Replace character
R Overwrite characters from cursor onward
s Substitute one character under cursor continue to insert
S Substitute entire line and begin to insert at beginning of line
~ Change case of individual character
ctrl-a
ctrl-x
Increment number under the cursor.
Decrement number under the cursor.
/search_string{CR} Search for search_string
?search_string{CR} Search backwards (up in file) for search_string
/\<search_string\>{CR} Search for search_word
Ex: /\<s\>
Search for variable "s" but ignore declaration "string" or words containing "s". This will find "string s;", "s = fn(x);", "x = fn(s);", etc
n Find next occurrence of search_word
N Find previous occurrence of search_word
. repeat last command action.

Terminate session:

  • Use command: ZZ
    Save changes and quit.
  • Use command line: ":wq"
    Save (write) changes and quit.
  • Use command line: ":w"
    Save (write) changes without quitting.
  • Use command line: ":q!"
    Ignore changes and quit. No changes from last write will be saved.
  • Use command line: ":qa"
    Quit all files opened.

Vi/Vim modes:

Vi/Vim modes are set using the "set" command and its many options.

:set all - display all mode settings of your editing session.
:set termcap - display terminal settings of your editing session.

:set ic - Change default to ignore case for text searches
Default is changed from noignorecase to ignorecase. (ic is a short form otherwise type set ignorecase)

Common options to set:
Full "set" Command Short form Description
:set autoindent
:set noautoindent
:set ai
:set noai
{CR} returns to indent of previous line.
Turn on autoindent: :set ai
Turn off autoindent: :set noai
Set indent set shift
Intelligent auto-indent: set smartindent
Toggle autoindent on/off when pasting text (press F2 key to toggle mode after one is in "insert" mode): set pastetoggle=<F2>
:set autowrite
:set noautowrite
:set aw
:set noaw
This tells vim to automatically write the file when switching to edit another file. See tags
:set backspace=indent,eol,start
:set backspace
:set bs=indent,eol,start
:set bs
Allow backspacing over an indent, line break (end of line) or start of an insert
:set backup=on
:set backup=off
:set bk=on
:set bk=off
Create backup file of file changes while editing.
To automatically remove the backup file after the file being edited is written, use the option :set writebackup=on/off
File backup mode settings: :set backupcopy=yes/no/auto
:set cryptmethod=zip
set cryptmethod=blowfish
  Set file encryption for file save of buffer contents.
  • zip: pkzip
  • blowfish: strong encryption
This is set upon reading a file if encrypted.
Vim 7.3+
:set errorbells
:set noerrorbells
:set eb
:set noeb
Silence error beep
:set flash
:set noflash
:set fl
:set nofl
Screen flashes upon error (for deaf people or when noerrorbells is set)
:set tabstop=8 :set ts Tab key displays 8 spaces
:set ignorecase
:set noignorecase
:set ic
:set noic
Case sensitive searches
:set number
:set nonumber
:set nu
:set nonu
Display line numbers
:set showmatch
:set noshowmatch
no abbreviations Cursor shows matching ")" and "}"
:set showmode
:set noshowmode
no abbreviations Editor mode is displayed on bottom of screen
:set showmatch
:set noshowmatch
no abbreviations Cursor shows matching ")" and "}"
:set syntax on
:set syntax off
no abbreviations Set syntax highlighting and color highlighting for a file type (eg XML, HTML, C++, Java, etc). Also cursor shows matching ")" and "}"
Also can set syntax highlighting explicitly: :set syntax=html
Syntax definition files: /usr/share/vim/vim73/syntax/
:set taglength :set tl Default=0. Set significant characters
:set closepunct='".,;)]}
% key shows matching symbol.
Also see showmatch
:set linelimit=1048560
Maximum file size to edit
:set wrapscan
:set nowrapscan
:set ws
:set nows
Breaks line if too long
:set wrapmargin=0
:set nowrapmargin
:set wm
:set nowm
Define right margin for line wrapping.
:set list
:set nolist

Display all Tabs and Ends of lines (Dislays these hidden characters).
:set bg=dark
:set bg=light

VIM: choose color scheme for "dark" or "light" console background.
See full list of set options

Advanced "vi" features

Interactive Commands:

  • Marking a line:
    Any line can be "Book Marked" for a quick cursor return.
    • Type the letter "m" and any other letter to identify the line.
    • This "marked" line can be referenced by the keystroke sequence "'" and the identifying letter.
      Example: "mt" will mark a line by the identifier "t".
      "'t" will return the cursor to this line at any time.
      A block of text may be referred to by its marked lines. i.e.'t,'b
  • vi line buffers:
    To capture lines into the buffer:
    • Single line: "yy" - yanks a single line (defined by current cursor position) into the buffer
    • Multiple lines: "y't" - yanks from current cursor position to the line marked "t"
    • Multiple lines: "3yy" - yank 3 lines. Current line and two lines below it.
    Copy from buffer to editing session:
    • "p" - place contents of buffer after current line defined by current cursor position.
  • vim: Shift a block of code left or right:
    • Enter into visual mode by typing the letter "v" at the top (or bottom) of the block of text to be shifted.
    • Move the cursor to the bottom (or top) of the block of text using "j", "k" or the arrow keys.
      Tip: Select from the first collumn of the top line and the last character of the line on the bottom line.
      Zero ("0") will move the cursor to the first character of a line and "$" will move the cursor to the last character of the line.
    • Type >> to shift the block to the right.
      Type << to shift the block to the left.
    Note: The number of characters shifted is controlled by the "shift width" setting. i.e. 4: ":set sw=4"
    This can be placed in your $HOME/.vimrc file.

Command Line:

  • command options:
    The vi command line interface is available by typing ":". Terminate with a carriage return.
    Example commands:
    • :help topic
      If the exact name is unknown, TAB completion will cycle through the various options given the first few letters. Ctrl-d will print the complete list of possibilites.
  • Executing Unix commands in vi:
    Any UNIX command can be executed from the vi command line by typing an "!" before the UNIX command.
    Examples:
    • ":!pwd" - shows your current working directory.
    • ":r !date" - reads the results from the date command into a new line following the cursor.
    • ":r !ls -1" - Place after the cursor, the current directory listing displayed as a single column.
  • Line numbers:
    Lines may be referenced by their line numbers. The last line in the file can be referenced by the "$" sign.
    The entire file may be referenced by the block "1,$" or "%"
    The current line is referred to as "."
    A block of text may be referred to by its marked lines. i.e. 5,38 or 't,'b
  • Find/Replace:
    Example:
    • :%s/fff/rrrrr/ - For all lines in a file, find string "fff" and replace with string "rrrrr" for the first instance on a line.
    • :%s/fff/rrrrr/g - For all lines in a file, find string "fff" and replace with string "rrrrr" for each instance on a line.
    • :%s/fff/rrrrr/gc - For all lines in a file, find string "fff" and replace with string "rrrrr" for each instance on a line. Ask for confirmation
    • :%s/fff/rrrrr/gi - For all lines in a file, find string "fff" and replace with string "rrrrr" for each instance on a line. Case insensitive.
    • :'a,'bs/fff/rrrrr/gi - For all lines between line marked "a" (ma) and line marked "b" (mb), find string "fff" and replace with string "rrrrr" for each instance on a line. Case insensitive.
    • :5,20s/fff/rrrrr/gc - For all lines between line 2 and line 20, find string "fff" and replace with string "rrrrr" for each instance on a line. Confirm each change with y/n.
    • :%s/*$/ - For all lines in a file, delete blank spaces at end of line.
    • :%s/\(.*\):\(.*\)/\2:\1/g - For all lines in a file, move last field delimited by ":" to the first field. Swap fields if only two.
    • :%s#<[^>]\+>##g - Find and remove all HTML tags but keep the text contents.
    • :%s/^\(.*\)\n\1$/\1/ - Find and remove all duplicate lines
    For more info type:
    • :help substitute
    • :help pattern
    • :help gdefault
    • :help cmdline-ranges
  • Sorting:
    Example:
    • Mark a block of text at the top line and bottom line of the block of text. i.e. "mt" and "mb" on two separate lines. This text block is then referenced as "'t,'b.
    • :'t,'b !sort

  • Moving columns, manipulating fields and awk:
    :'t,. !awk '{print $3 " " $2 " " $1}' - This will reverse the order of the columns in the block of text. The block of text is defined here as from the line marked with the keystroke "bt" and the current line ("."). This text block is referenced as "'t,."
                  aaa bbb ccc              ccc bbb aaa
                  xxx yyy zzz   becomes->  zzz yyy xxx
                  111 222 333              333 222 111
    
  • Source Code Formatting: C++/Java
    • Use vim visual text selection to mark the lines to format (beautify):
      • eg. Whole file:
        • Go to first line in file: shift-v
        • Go to last line in file: shift-g
        • Select the key equals: =
      This will align all braces and indentations. For the equivalent in emacs see the YoLinux emacs tutorial.
  • Text Formatting:
    • Mark a block of text at the top line and bottom line of the block. i.e. "mt" and "mb" on two separate lines.
    • Example: ":'t,'b !nroff"
    • You can insert nroff commands i.e.:
      .ce 3 Center the next three lines
      .fi Fill text - left and right justify (default)
      .nf No Fill
      .ls 2 Double line spacing
      .sp Single line space
      .sv 1.0i Vertical space at top of page space
      .ns Turn off spacing mode
      .rs Restore spacing mode
      .ll 6.0i Line length = 6 inches
      .in 1.0i Indent one inch
      .ti 1.0i Temporarily one time only indent one inch
      .pl 8.0i Page length = 8 inches
      .bp Page break
      Example:
      .fi
      .pl 2i
      .in 1.0i
      .ll 6.0i
      .ce
      Title to be centered
      .sp
      The following text bla bla bla bla bla bla bla bla bla bla 
      bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla 
      bla bla bla bla bla bla bla bla bla bla bla bla bla bla 
      bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla 
      bla bla bla bla bla
      

      Becomes:

                               Title to be centered
      
                The following text bla bla bla bla bla bla bla bla
                bla  bla  bla  bla bla bla bla bla bla bla bla bla
                bla bla bla bla bla bla bla bla bla  bla  bla  bla
                bla  bla  bla  bla bla bla bla bla bla bla bla bla
                bla bla bla bla bla bla bla bla bla  bla  bla  bla
                bla bla bla bla
      
      
      
  • Spell Checking:
    • Mark a block of text by marking the top line and bottom line of the block. i.e. "mt" and "mb" on two separate lines.
    • :'t,'b !spell will cause the block to be replaced with misspelled words.
    • Press "u" to undo.
    • Proceed to correct words misspelled.
  • Macros:
    :map letter commands_strung_together
    :map - lists current key mappings
    Example - :map g n cwNEW_WORD{ctrl-v}{esc}i{ctrl-v}{CR}
    This example would find the next search occurrence, change the word and insert a line feed after the word. The macro is invoked by typing the letter "g".
    • Control/Escape/Carriage control characters must be prefixed with ctrl-V.
    • Choose a letter which is not used or important. (i.e. a poor choice would be "i" as this is used for insert)
  • Double spacing:
    • :%s/$/{ctrl-V}{CR}/g
      This command applies an extra carriage return at the end of all lines
  • Strip blanks at end of line:
    • :%s/{TAB}*$//
  • Delete all lines beginning with or matching a pattern:
    • :1,$ /^#/d
      Delete all (first to last line: 1,$ or g) comments lines in file. Delete all lines beginning (^) with "#" (specify text pattern).
    • :g/#/d
      Delete all lines (g) containing comments (comments follow "#") in file. Delete all lines containing "#".
    • :g!/^#/d
      Delete all lines except (g! or v) comment lines beginning (^) with "#".
  • Strip DOS ctrl-M's:
    • :1,$ s/{ctrl-V}{ctrl-M}//

    Note: In order to enter a control character, one muust first enter ctrl-v. This is true throughout vi. For example, if searching for a control character (i.e. ctrl-m): /ctrl-v ctrl-M If generating a macro and you need to enter esc without exiting the vi command line the esc must be prefixed with a ctrl-v: ctrl-v esc.
  • Editing multiple files:
    • vi file1 file2 file3
    • :n Edit next file (file2)
    • :n Edit next file (file3)
    • :rew Rewind to the first file (file1)
  • Line folding:

    Many times one may encounter a file with folded lines or may wish to fold lines. The following image is of a file with folded lines where each "+" represents a set of lines not viewed but a marker line prefixed with a "+" is shown stating how many lines have been folded and out of view. Folding helps manage large files which are more easily managed when text lines are grouped into "folds".

    Example: vim /usr/share/vim/vim63/plugin/netrw.vim

    spacer

    Keystrokes:

    Keystroke Description
    zR Unfold all folded lines in file.
    za Open/close (toggle) a folded group of lines.
    zA Open a closed fold or close an open fold recursively.
    zc Close a folded group of lines.
    zC Close all folded lines recursively.
    zd Delete a folded line.
    zD Delete all folded lines recursively.
    zE Eliminate all folded lines in file.
    zF Create "N" folded lines.
  • Hyper-Linking to include files:
    • Place cursor over the file name (i.e. #include "fileABC.h")
    • Enter the letter combination: gf
      (go to file)
    This will load file fileABC.h into vim. Use the following entry in your ~/.vimrc file to define file paths. Change path to something appropriate if necessary.
    "Recursively set the path of the project.
    set path=$PWD/**
    
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.