VI Editor
VI Editor
search
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
Search
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
Action
converted by Web2PDFConvert.com
spacebar
Ads by Google
Move cursor right one space Move cursor down/up in first column Scroll down one half of a page Scroll up one half of a page Scroll forward one page Scroll back one page Move cursor to middle of page Move cursor to top of page Move cursor to bottom of page Move cursor a word at a time Move cursor ahead 5 words Move cursor back a word at a time Move cursor back a word at a time Move cursor back 5 words Move cursor to end of word Move cursor ahead to the end of the 5th word 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 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. Move cursor to line mark "a" generated by marking with keystroke "ma" 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.
DLite Press New $22.15 D-Link DI-624 Wireless Cable/DSL Rou... D-Link
Privacy Information
and Development
Magazine Subscriptions and Document Downloads
e 5e 0 (zero) $ ) ( G %
Action
/search_string{CR} ?search_string{CR}
/\<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 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.
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. :set all - display all settings of your session.
converted by Web2PDFConvert.com
Short form
ai/noai aw/noaw eb/noeb fl/nofl
Description
{CR} returns to indent of previous line See tags Silence error beep Screen flashes upon error (for deaf people or when noerrorbells is set) Tab key displays 8 spaces Case sensitive searches Display line numbers
ts ic/noic nu/nonu no Cursor shows matching ")" and "}" abbreviations showmode/noshowmode no Editor mode is displayed on abbreviations bottom of screen taglength Default=0. Set significant tl characters closepunct='".,;)]} % key shows matching symbol. Also see showmatch linelimit=1048560 Maximum file size to edit wrapscan/nowrapscan ws/nows Breaks line if too long wrapmargin=0/nowrapmargin Define right margin for line wm/nowm wrapping. list/nolist Display all Tabs/Ends of lines. bg=dark VIM: choose color scheme for bg=light "dark" or "light" console background.
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. :%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. For more info type:
converted by Web2PDFConvert.com
:'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 xxx yyy zzz 111 222 333 ccc bbb aaa becomes-> zzz yyy xxx 333 222 111
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 .fi .nf .ls 2 .sp .sv 1.0i .ns .rs .ll 6.0i .in 1.0i .ti 1.0i .pl 8.0i .bp 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
Center the next three lines Fill text - left and right justify (default) No Fill Double line spacing Single line space Vertical space at top of page space Turn off spacing mode Restore spacing mode Line length = 6 inches Indent one inch Temporarily one time only indent one inch Page length = 8 inches Page break
Becomes:
converted by Web2PDFConvert.com
Title to be centered The bla bla bla bla bla 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
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)
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 "#".
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
converted by Web2PDFConvert.com
Keystrokes:
Keystroke
zR za zA zc zC zd zD zE zF
Description
Unfold all folded lines in file. Open/close (toggle) a folded group of lines. Open a closed fold or close an open fold recursively. Close a folded group of lines. Close all folded lines recursively. Delete a folded line. Delete all folded lines recursively. Eliminate all folded lines in file. Create "N" folded lines.
s/<A HREF/<a href/g s/<A NAME/<a name/g s/<\/A>/<\/a>/g s/<P>/<p>/g s/<B>/<b>/g s/<\/B>/<\/b>/g s/<I>/<i>/g s/<\/I>/<\/i>/g
Execute: vi -e file-name.html < ViCommands-HtmlUpdate.txt [Potential Pitfall]: This must be performed while vim has none of the files open which are to be
converted by Web2PDFConvert.com
affected. If it does, vim will error due to conflicts with the vim swap file.
Tagging:
This functionality allows one to jump between files to locate subroutines.
In all cases you will be entered into the correct file and the cursor will be positioned at the subroutine desired. If it is not working properly look at the "tags" file created by ctags. Also the tag name (first column) may be abbreviated for convenience. One may shorten the significant characters using :set
taglength=number
Tag Notes: A project may have a tags file which can be added and referred to by: :set tags=tags\
/ad/src/project1.tags
A "\" must separate the file names. :set autowrite will automatically save changes when jumping from file to file, otherwise you need to use the :w command.
vim tagging notes: (These specific tag features not available in vi) Tag Command
:tag start-of-tag-name_TAB :tag /search-string ctrl-] ctrl-t :tselect <function-name>
Description
Vim supports tag name completion. Start the typing the tag name and then type the TAB key and name completion will complete the tag name for you. Jump to a tag name found by a search. The vim editor will jump into the tag to follow it to a new position in the file or to a new file. The vim editor will allow the user to jump back a level. (or :pop) When multiple entries exist in the tags file, such as a function declaration in a header file and a function definition (the function itself), the operator can choose by issuing this command. The user will be presented with all the references to the function and the user will be prompted to enter the number associated with the appropriate one. When multiple answers are available you can go to the next answer. The ignore case directive affects tagging. Show tag stack (history) Jump to a particular position in the tag stack (history). (jump to the 4th from bottom of tag stack (history). The command ":pop" will move by default "1" backwards in the stack (history).) or
:4tag
(jump to the 4th from top of tag stack) Jump to next matching tag. (Also short form :tn and jump two :2tnext) Jump to previous matching tag. (Also short form :tp and jump two :2tp) Jump to first matching tag. (Also short form :tf, :trewind, :tr)
converted by Web2PDFConvert.com
:tlast
Jump to last matching tag. (Also short form :tl) Using multiple tag files (one in each directory). :set tags=./tags,./subdir/tags Allows one to specify all tags files in directory tree: set
tags=src/**/tags
Use Makefile to generate tags files as well as compile in each directory. Links: Vim docs - ctags vim/tag search ctags framework
ctags version 5.0.1: ctags --lang=c++ --c-types=+Ccdefgmnpstuvx *.cpp ../inc/*.h To generate a tags file for all files in all subdirectories: ctags -R . The ctags program which is written by the VIM team is called " Exuberant Ctags" and supports the most features in VIM. Man page: ctags - Generate tag files for source code
Defaults file:
VIM: $HOME/.exrc
~/.vimrc ~/.gvimrc ~/.vim/ (directory of vim config files.)
VI: $HOME/.exrc
Example:
set autoindent set wrapmargin=0 map g hjlhjlhjlhlhjl " " S = save current vi buffer contents and run spell on it, " putting list of misspelled words at the end of the vi buffer. map S G:w!^M:r!spell %^M colorscheme desert "Specify that a dark terminal background is being used. set bg=dark
Notes: Look in /usr/share/vim/vim61/colors/ for available colorschemes. (I also like "colorscheme desert") Alternate use of autoindent: set ai sw=3
complete cross referencing. Vim must be compiled with Cscope support. Red Hat Enterprise Linux 5 (or CentOS 5), includes vim 7.0 with cscope support. Earlier versions of Red Hat or Fedora RPM does not support Cscope and thus must be compiled.
Invoke Cscope from within vim from the vim command line. Type the following: :cscope find search-type search-string The short form of the command is ":cs f" where the "search-type" is:
Description
Find all references to a symbol Find global definition Find calls of this function Find functions that the specified function calls Find specified text string Open file Find files that "#include" the specified file
Results of the Cscope query will be displayed at the bottom of the vim screen. To jump to a result type the results number (+ enter) Use tags commands to return after a jump to a result: ctrl-t To return to same spot as departure, use ctrl-o To use "tags" navigation to search for words under the cursor (ctrl-\ or ctrl-]) instead of using the vim command line ":cscope" (and "ctrl-spaceBar" instead of ":scscope"), use the vim plugin, cscope_maps.vim [cache] When using this plugin, overlapping ctags navigation will not be available. This should not be a problem since cscope plugin navigation is the same but with superior indexing and cross referenceing. Place this plugin in your directory "$HOME/.vim/plugin" Plugin required for vim 5 and 6. This feature is compiled in with vim 7.0 on Red Hat Enterprise Linux 5 and CentOS 5 and newer Linux OS's. Attempts to use the plugin when not required will result in the following error:
E568: duplicate cscope database not added
Cycle through results: Next result: :tnext Previous result: :tprevious Create a split screen for Cscope results: :scscope find search-type search-string (Short form: :scs f search-type search-string) Use command line argument ":cscope -R": Scan subdirectories recursively Use Cscope ncurses based GUI without vim: cscope ctrl-d: Exit Cscope GUI
Description
Scan subdirectories recursively Build the cross-reference only. Ignore letter case when searching. Specify Cscope database file name instead of default "cscope.out". Look in "include-directories" for any #include files whose names do not begin with "/". Scan specified files listed in "Files". File names are separated by linefeed.
converted by Web2PDFConvert.com
directories
-iFiles
-iFiles -k
-q Use specified directory for source code. Ignored if specified by "-i". sDirectoryName -u Unconditionally build a new cross-reference file.. -v Verbose mode. List files to cross reference on the command line. file1 file2 ...
Cscope uses the default file name "cscope.files". Kernel mode ignores /usr/include. Typical: cscope -b -q -k create inverted index database for quick search for large projects.
Description
Editor to use: /usr/bin/vim Default: /usr/bin/vim Colon-separated list of directories to search for #include files. Colon-separated list of directories to search for additional source files. Colon-separated list of directories to search. If not set, cscope searches only in the current directory.
Generates cscope.files of ".cpp" and ".hpp" source files for a C++ project. Note that this generates CScope files in the current working directory. The CScope files are only usefull if you begin the vim session in the same directory. Thus if you have a heirarchy of directories, perform this in the top directory and reference the files to be edited on the command line with the relative path from the same directory in which the CScope files were generated. Also see: cscope man page cscope home page Using cscope with Linux kernel source code
Vim plugins:
Vim default plugins:
Vim comes with some default plugins which can be found in: Red Hat / CentOS / Fedora: RHEL4/5: /usr/share/vim/vim70/autoload/ Fedora 3:/usr/share/vim/vim63/plugin/ Ubuntu / Debian: Ubuntu 6.06: /usr/share/vim/vim64/plugin/
Command
:Explore
Description
List files in your current directory
converted by Web2PDFConvert.com
:Explore directory-
List files in specified directory Split with a new vertical window and then list files in your current directory Split with a new horizontal window and then list files in your current directory
name
:Vexplore :Sexplore
The new window buffer created by ":Vexplore" and ":Sexplore" can be closed with ":bd" (buffer delete).
Keystroke
:bn :bd :b3 ctrl-w followed by "k" :qa tab
Description
New buffer Buffer delete Go to buffer number 3 New buffer. Puts curson in upper tabbed portion of window. Navigate with arrow keys or "h"/"l". Quit vim out of all buffers The "tab" key jumps between tabbed buffers.
This vim directive will allow undo history to remain when switching buffers. The new window buffer tab created can be closed with ":bd" (buffer delete). Links: minibufexpl plugin home page
Command
Description
switches to the header file corresponding to the current file being edited (or vise :A versa) :AS splits and switches :AV vertical splits and switches :AT new tab and switches :AN cycles through matches :IH switches to file under cursor :IHS splits and switches :IHV vertical splits and switches :IHT new tab and switches :IHN cycles through matches If you are editing fileX.c and you enter ":A" in vim, you will be switched to the file fileX.h Links:
converted by Web2PDFConvert.com
Plug-in Installation:
Example of installation of a.vim and minibufexpl.vim plug-ins:
mkdir -p ~/.vim/plugin cd ~/.vim/plugin wget -O a.vim http://www.vim.org/scripts/download_script.php?src_id=7218 wget -O minibufexpl.vim http://www.vim.org/scripts/download_script.php? src_id=3640
Note that the URL of the plug-in can be found from the home page of the plug-in.
Vim tip:
Using a mousewheel with vim in an xterm. Place in file $HOME/.Xdefaults
XTerm*VT100.Translations: #override \n\ : string("0x9b") string("[64~") \n\ : string("0x9b") string("[65~")
Links:
The vim home page Interview with Bill Joy and the history of VI Vi/Ex Editor tutorial Fast vi tutorial Troubleshooters.com: VI and VIM Vim as an XML/XHTML editor
Books:
"The Ultimate Guide to VI and EX Text Editors" Hewlet Packard Corporation ISBN #0-8053-4460-8, Addison-Wesley Pub Co., Benjamin/Cummings Publishing Company
"Learning the vi and vim Editors (7th edition) by Arnold Robbins, Elbert Hannah, Linda Lamb ISBN #059652983X, O'Reilly
"Vi iMproved (VIM) by Steve Oualline ISBN #0735710015, Sams (1st edition)
YoLinux.com Home Page YoLinux Tutorial Index | Terms Privacy Policy | Advertise with us | Feedback Form | Unauthorized copying or redistribution prohibited.
3
3,980
14
A free browser that lets you do more of what you like on the web
www.google.com /chrom e
converted by Web2PDFConvert.com