# Vim Color Editor HOW-TO (Vi Improved with syntax color highlighting)

v18.8, 14 May 2003

This document is a guide to quickly setting up the Vim color editor on Linux or Unix systems. The information here will improve the productivity of programmers because the Vim editor supports syntax color highlighting and bold fonts, improving the "readability" of program code. A programmer's productivity improves 2 to 3 times with a color editor like Vim. The information in this document applies to all operating sytems where Vim works, such as Linux, Windows 95/NT, Apple Mac, IBM OSes, VMS, BeOS and all flavors of Unix like Solaris, HPUX, AIX, SCO, Sinix, BSD, Ultrix etc.. (it means almost all operating systems on this planet!)

1. Introduction
1.1. Before you Install
1.2. Install Vim on Redhat Linux
1.3. Install Vim on Debian GNU/Linux
1.4. Install Vim on Unixes
1.5. Install Vim on Microsoft Windows 95/NT
1.6. Install Vim on VMS
1.7. Install Vim on OS/2
1.8. Install Vim on Apple Macintosh
2. Install Vim on Microsoft Windows 95/NT
2.1. Install bash shell
2.2. Edit bash_profile
2.3. Setup Window colors
4. Setup gvim init files
4.1. Sample gvimrc file
4.2. Xdefaults parameters
5. Color Syntax init files
5.1. Auto source-in method
5.2. Manual method
6. VIM Usage
7. Remote Vi - MS Windows QVWM Manager
8. Vi companions
8.1. Directory Tree 'tags'
8.2. Ctags for ESQL
8.3. Ctags for JavaScript programs, Korn, Bourne shells
8.4. Debugger gdb
9. Online VIM help
10.1. Vi Resources and Tips
11. Vim Tutorial
11.1. Vim Hands-on Tutorial
11.2. Vi Tutorials on Internet
12. Vi Tutorial
12.1. Cursor Movement Commands
12.2. Repeat Counts
12.3. Deleting Text
12.4. Changing Text
12.5. Yanking (Copying) Text
12.6. Filtering text
12.7. Marking Lines and Characters
12.8. Naming Buffers
12.9. Substitutions
12.10. Miscellaneous "Colon Commands"
12.11. Setting Options
12.12. Key Mappings
12.13. Editing Multiple Files
12.14. Final Remarks
13. Vim Reference Card
13.1. Vi states
13.2. Shell Commands
13.3. Setting Options
13.4. Notations used
13.5. Interrupting, cancelling
13.6. File Manipulation
13.7. Movement
13.8. Line Positioning
13.9. Character positioning
13.10. Words, sentences, paragraphs
13.11. Marking and returning
13.12. Corrections during insert
13.14. Delete
13.15. Insert, change
13.16. Copy and Paste
13.17. Operators (use double to affect lines)
13.18. Search and replace
13.19. General
13.20. Line Editor Commands
13.21. Other commands
14. Build Your "WYSIWYG" HTML Editor With Vi & Netscape
14.1. Sample .vimhtmlrc File
14.2. WYSIWYG
14.3. Other 'WYSIWYG' uses
14.4. Source code for atchange
15. Emacs - Old Habits Die Hard !
16. Related URLs
17. Other Formats of this Document
17.1. Acrobat PDF format
17.2. Convert Linuxdoc to Docbook format
17.3. Convert to MS WinHelp format

# 1. Introduction

(The latest version of this document is at "http://milkyway.has.it" and mirror at "http://www.milkywaygalaxy.freeservers.com" . You may want to check there for changes).

Vim stands for 'Vi Improved'. Vi is the most popular and powerful editors in the Unix world. Vi is an abbreviation for " Vi sual" editor. One of the first editors was a line editor called 'ed' (and 'ex'). The Vi sual editor like Vi was a vast improvement over line editors like 'ed' (or 'ex'). The editors 'ed' and 'ex' are still available on Linux: see 'man ed' and 'man ex'.

A good editor improves programmer productivity. Vim supports color syntax highlighting of program code and also emphasises text using different fonts like normal, bold or italics. A color editor like Vim can improve the productivity of programmers by 2 to 3 times !! Programmers can read the code much more rapidly as the code syntax is colored and highlighted.

## 1.1. Before you Install

Before you install Vim, please refer to the OS specific release notes and information about compiling and usage of Vim at -

If you do not have the Vim package (RPM, DEB, tar, zip) then download the Vim source code by ftp from the official Vim site

## 1.2. Install Vim on Redhat Linux

To use Vim install the following RPM packages on Redhat Linux -
  rpm -i vim*.rpm OR do this - rpm -i vim-enhanced*.rpm rpm -i vim-X11*.rpm rpm -i vim-common*.rpm rpm -i vim-minimal*.rpm
You can see the list of files the vim rpm installs by -
  rpm -qa | grep ^vim | xargs rpm -ql | less or rpm -qa | grep ^vim | awk '{print "rpm -ql " $1 }' | /bin/sh | less and browse output using j,k, CTRL+f, CTRL+D, CTRL+B, CTRL+U or using arrow keys, page up/down keys. See 'man less'. Note that the RPM packages for Redhat Linux use a Motif interface. If you have installed the GTK libraries on your system, consider compiling Vim from the source code for a clean GUI interface. For information on compiling Vim from the source code, see "Install Vim on Unixes", below. ## 1.3. Install Vim on Debian GNU/Linux To install Vim on Debian Linux (GNU Linux), login as root and when connected to internet type -   apt-get install vim vim-rt It will download the latest version of vim, install it, configure it. The first package listed is vim, the standard editor, compiled with X11 support, vim-rt is the vim runtime, it holds all the syntax and help files. On Debian 3.0 (woody) and above, use 'apt-get install vim' instead. The vim-rt package is part of the main vim package. ## 1.4. Install Vim on Unixes For other flavors of unixes like Solaris, HPUX, AIX, Sinix, SCO download the source code file ( see Section 1.1 )   zcat vim.tar.gz | tar -xvf - cd vim-5.5/src ./configure --prefix=$HOME/local make make install
You can exclude prefix option if you want to install in default location in /usr/local. If the graphics version 'gvim' gives trouble then try with
  ./configure --prefix=$HOME/local --enable-gui=motif ## 1.5. Install Vim on Microsoft Windows 95/NT See Section 2 . ## 1.6. Install Vim on VMS ### 1.6.1. Download files You will need both the Unix and Extra archives to build vim.exe for VMS. For using Vim's full power you will need the runtime files as well. Get these files ( see Section 1.1 ) You can download precompiled executables from: "http://www.polarfox.com/vim" VMS vim authors are - ### 1.6.2. Compiling Unpack the Unix and Extra archives together into one directory. In the <.SRC> subdirectory you should find the make file OS_VMS.MMS. By editing this file you may choose between building the character, GUI and debug version. There are also additional options for Perl, Python and Tcl support. You will need either the DECSET mms utility or the freely available clone of it called mmk (VMS has no make utility in the standard distribution). You can download mmk from http://www.openvms.digital.com/freeware/MMK/ If you have MSS on your system, the command > mms /descrip=os_vms.mms will start building your own customised version of Vim. The equivalent command for mmk is: > mmk /descrip=os_vms.mms ### 1.6.3. Deploy Vim uses a special directory structure to hold the document and runtime files:   vim (or wherever) |- tmp |- vim55 |----- doc |----- syntax |- vim56 |----- doc |----- syntax vimrc (system rc files) gvimrc Use: > define/nolog device:[leading-path-here.vim] vim > define/nolog device:[leading-path-here.vim.vim56] vimruntime > define/nolog device:[leading-path-here.tmp] tmp to get vim.exe to find its document, filetype, and syntax files, and to specify a directory where temporary files will be located. Copy the "runtime" subdirectory of the vim distribution to vimruntime. Note: Logicals$VIMRUNTIME and $TMP are optional. Read more at :help runtime ### 1.6.4. Practical usage Usually you want to run just one version of Vim on your system, therefore it is enough to dedicate one directory for Vim. Copy all Vim runtime directory structure to the deployment position. Add the following lines to your LOGIN.COM (in SYS$LOGIN directory). Set up logical $VIM as:   >$ define VIM device:

Set up some symbols:

  > $! vi starts Vim in chr. mode. >$ vi*m :== mcr device:VIM.EXE > $!gvi starts Vim in GUI mode. >$ gv*im :== spawn/nowait mcr device:VIM.EXE -g

Create .vimrc and .gvimrc files in your home directory (SYS$LOGIN). The easiest way is just rename example files. You may leave the menu file (MENU.VIM) and files vimrc and gvimrc in the original$VIM directory. It will be default setup for all users, and for users is enough just to have their own additions or resetting in home directory in files .vimrc and .gvimrc. It should work without problems.

Note: Remember, system rc files (default for all users) do not have the leading "." So, system rc files are:

# 4. Setup gvim init files

To enable the syntax color highlighting you MUST copy the gvimrc file to your home directory. This will also put the "Syntax" Menu with gvim command. You can click on Syntax Menu and select appropriate languages like C++, Perl, Java, SQL, ESQL etc..
  cd $HOME cp /usr/doc/vim-common-5.3/gvimrc_example ~/.gvimrc Comment lines in .gvimrc begin with double-quotes ("). You can customize gvim by editing the file$HOME/.gvimrc and put the following lines -
  " This line is a comment .... one which begins with double-quotes " The best is the bold font, try all of these and pick one.... set guifont=8x13bold "set guifont=9x15bold "set guifont=7x14bold "set guifont=7x13bold " " Highly recommended to set tab keys to 4 spaces set tabstop=4 set shiftwidth=4 " " The opposite is 'set wrapscan' while searching for strings.... set nowrapscan " " The opposite is set noignorecase set ignorecase set autoindent " " You may want to turn off the beep sounds (if you want quite) with visual bell " set vb " Source in your custom filetypes as given below - " so $HOME/vim/myfiletypes.vim It is very strongly recommended that you set the tabstop to 4 and shiftwidth to 4. The tabstop is the number of spaces the TAB key will indent while editing with gvim. The shiftwidth is the number of spaces the lines will be shifted with "> > " or " < <" vi commands. Refer to Vi tutorials Section 11 for more details. To see the list of available fonts on Linux/Unix see the command xlsfonts . Type -   bash$ xlsfonts | less bash$xlsfonts | grep -i bold | grep x bash$ man xlsfonts

## 4.1. Sample gvimrc file

You can change the settings like color, bold/normal fonts in your $HOME/.gvimrc file. It is very strongly recommended that you set the background color to lightyellow or white with black foreground. Ergonomics says that best background color is lightyellow or white with black foreground. Hence change the variable 'guibg' in your$HOME/.gvimrc file as follows:
  highlight Normal guibg=lightyellow

The sample gvimrc from /usr/doc/vim-common-5.3/gvimrc_example is as follows:
  " Vim " An example for a gvimrc file. " The commands in this are executed when the GUI is started. " " To use it, copy it to " for Unix and OS/2: ~/.gvimrc " for Amiga: s:.gvimrc " for MS-DOS and Win32: $VIM\_gvimrc " Make external commands work through a pipe instead of a pseudo-tty "set noguipty " set the X11 font to use. See 'man xlsfonts' on unix/linux " set guifont=-misc-fixed-medium-r-normal--14-130-75-75-c-70-iso8859-1 set guifont=8x13bold "set guifont=9x15bold "set guifont=7x14bold "set guifont=7x13bold " " Highly recommended to set tab keys to 4 spaces set tabstop=4 set shiftwidth=4 " " The opposite is 'set wrapscan' while searching for strings.... set nowrapscan " " The opposite is set noignorecase set ignorecase " " You may want to turn off the beep sounds (if you want quite) with visual bell " set vb " Source in your custom filetypes as given below - " so$HOME/vim/myfiletypes.vim " Make command line two lines high set ch=2 " Make shift-insert work like in Xterm map map! " Only do this for Vim version 5.0 and later. if version >= 500 " I like highlighting strings inside C comments let c_comment_strings=1 " Switch on syntax highlighting. syntax on " Switch on search pattern highlighting. set hlsearch " For Win32 version, have "K" lookup the keyword in a help file "if has("win32") " let winhelpfile='windows.hlp' " map K :execute "!start winhlp32 -k " . winhelpfile "endif " Hide the mouse pointer while typing set mousehide " Set nice colors " background for normal text is light grey " Text below the last line is darker grey " Cursor is green " Constants are not underlined but have a slightly lighter background highlight Normal guibg=grey90 highlight Cursor guibg=Green guifg=NONE highlight NonText guibg=grey80 highlight Constant gui=NONE guibg=grey95 highlight Special gui=NONE guibg=grey95 endif
See also sample vimrc used for console mode vim command from /usr/doc/vim-common-5.3/vimrc_example.

## 4.2. Xdefaults parameters

You can set some of the Vim properties in Xdefaults file.

WARNING: Do not set Vim*geometry as it will break the gvim menu, use Vim.geometry instead .

Edit the $HOME/.Xdefaults file and add the following lines:   ! GVim great Colors. Vim*useSchemes: all Vim*sgiMode: true Vim*useEnhancedFSB: true Vim.foreground: Black !Vim.background: lightyellow2 Vim*background: white ! Do NOT use Vim*geometry , this will break the menus instead ! use Vim.geometry. Asterisk between Vim and geometry is not allowed. ! Vim.geometry: widthxheight Vim.geometry: 88x40 !Vim*font: -misc-fixed-medium-r-normal--20-200-75-75-c-100-iso8859-15-*5 Vim*menuBackground: yellow Vim*menuForeground: black In order for this change to take effect, type -   xrdb -merge$HOME/.Xdefaults man xrdb

You can also edit the ~/.gvimrc file to change the background colors
  gvim $HOME/.gvimrc The best background color is lightyellow or white, with black foreground. highlight Normal guibg=lightyellow # 5. Color Syntax init files ## 5.1. Auto source-in method This section below is obtained from gvim session by typing 'help syntax' -   bash$ gvim some_test :help syntax
Click on the menu Window=>Close_Others to close other Window. And then do CTRL+] on 'Syntax Loading Procedure' menu which will take you there. (Use CTRL+T to rewind and go back).

If a file type you want to use is not detected, then there are two ways to add it.

Method 1: You can modify the $VIMRUNTIME/filetype.vim file, but this is not recommended as it will be overwritten when you install a new version of Vim. Method 2: Create a file in$HOME/vim/myfiletypes.vim and put these lines in it -
  " " ************************************************************* " Filename : $HOME/vim/myfiletypes.vim " See the document by typing :help autocmd within vim session " see also the doc at /usr/share/vim/doc/autocmd.txt " This file will setup the autocommands for new filetypes " using the existing syntax-filetypes. " For example when you open foo.prc it will use syntax of plsql " Basically does :set filetype=prc inside vim " Add a line in$HOME/.gvimrc as below: " so $HOME/vim/myfiletypes.vim " " ************************************************************* augroup filetype au! au! BufRead,BufNewFile *.phc set filetype=php au! BufRead,BufNewFile *.mine set filetype=mine au! BufRead,BufNewFile *.xyz set filetype=drawing au! BufRead,BufNewFile *.prc set filetype=plsql augroup END Then add a line in your$HOME/.vimrc and $HOME/.gvimrc file to source in the file "myfiletypes.vim". ( CAUTION: You MUST put this in both vimrc and gvimrc files in order for this to work) Example:   so$HOME/vim/myfiletypes.vim

NOTE: Make sure that you set "so myfiletypes.vim" before switching on file type detection. This is must be before any ":filetype on" or ":syntax on" command.

See the documentation on autocommand at -

• :help autocmd (within a vim editing session)

Your file will then be sourced in after the default FileType autocommands have been installed. This allows you to overrule any of the defaults, by using ":au!" to remove any existing FileType autocommands for the same pattern. Only the autocommand to source the scripts.vim file is given later. This makes sure that your autocommands in "myfiletypes.vim" are used before checking the contents of the file.

## 5.2. Manual method

Instead of using "Syntax" menu you can also manually source in the syntax file. Edit the file with gvim and at : (colon) command give 'so' command. For example -
  gvim foo.pc :so $VIM/syntax/esqlc.vim The syntax source files are at /usr/share/vim/syntax/*.vim. Vim supports more than 120 different syntax files for different languages like C++, PERL, VHDL, JavaScript,...and so on!! Each syntax file supports one or more default file name extensions, for example, JavaScript syntax file supports the *.js extension. If you happen to use an extension that conflicts with another default syntax file (such as adding JavaScript to a *.html file) than you can source in the additional syntax file with the command :so$VIM/syntax/javascript.vim. To avoid all of this typing, you can create a soft link like -
  ln -s $VIM/syntax/javascript.vim js gvim foo.html (... this file contains javascript functions and HTML) :so js # 6. VIM Usage You can use Vim in two modes - one with GUI and other without GUI. To use GUI use command -   gvim foo.cpp To use non-gui mode give -   vim foo.cpp OR plain vanilla mode vi foo.cpp It is very strongly recommended that you always use gvim instead of vim, since GUI mode with colors will definitely improve your productivity. The vim also gives colors but cannot set the background colors and gvim can set the background and foreground colors. GUI mode gvim provides the following - • You can mark the text using the mouse to do cut, copy and paste. • You can use the Menu bar which has - File, Edit, Window, Tools, Synatx and Help buttons. • Also in near future in gvim - a second menu bar will display the list of files being edited, and you can switch files by clicking on the filenames, until then you can use vi commands - :e#, :e#1, :e#2, :e#3, :e#4, ....so on to select the files. # 7. Remote Vi - MS Windows QVWM Manager QVWM Window Manager is the best as it is very similar in appearance to Microsoft Windows. If you want to use Vi and Vim remotely from a MS Windows PC client, then you should use VNC + QVWM manager. Servers are generally located in remote Data Centers and to edit the files, you should first login to remote servers from MS Windows or Linux desktop PCs. After starting VNC server and QVWM manager on remote server, you should fire up vncviewer on your client desktop and edit remote files with gvim . To use graphical editor like gvim for remote operations, use the following techniques below: You can use the VNC to display remote machines on your local display. Compiling qvwm on Solaris : On Solaris you should install the following packages which you can get from "http://sun.freeware.com" - xpm, imlib, jpeg, libungif, giflib (giftran), libpng, tiff. And you can download the binary package for solaris from "http://www.qvwm.org" . Or you can download the qvwm source for solaris from "http://www.qvwm.org" and compile it using gcc. If mainsite is busy use the mirror sites listed there. Click on the link "The latest version of qvwm is [ftp/http]" to download the source code. Troubleshooting the compile: • You must install all the packages listed - xpm, imlib, jpeg, libungif, giflib, libpng, tiff. Otherwise src will not compile • Must edit the src/util.cc file and change snprintf to printf to compile the program to get rid of the compile errors. • You should put unsigned long before arg in usleep() usleep((unsigned long) 10000) • Still problems then see "http://www.milkywaygalaxy.freeservers.com/vnc" for compile instructions. For transferring files from Unix to MS Windows use the ftp clients like # 8. Vi companions Generally Vim is used in conjunction with other powerful tools like ctags and gdb . ctags is for very rapid navigation through millions of lines of "C/C++" code and gdb is for debugging the "C/C++" code. A brief introduction of these two indispensable commands will be given in this chapter. ctags is the most powerful command available for coding C, C++, Java, Perl, Korn/Bourne shell scripts or Fortran. Developers very extensively use ctags to navigate through thousands of functions within C/C++ programs. See 'man ctags' on Unix. It is very important that you learn how to use ctags to develop programs in C or C++, Java, etc.. Navigation is the single most important task while doing development of C or C++ code. Using ctags you can very quickly read the code by jumping from a calling line to the called function, drill down deeper into nested function calls, and unwind back all the way up to the top. You can go back and forth from function to function very quickly. Without NAVIGATION you will be completely lost! ctags is like the magnetic COMPASS needle for the programmers. Usage of ctags :   ctags *.cpp gvim -t foo_function gvim -t main This will edit the C++ program file which contains the function foo_function() and will automatically place the cursor on the first line of the function foo_function(). The second command takes you to the line with the main() function definition. Inside the Vim editor, you can jump to a function by typing : (colon) tag < function name > as below -   :tag sample_function This will place the cursor on first line of sample_function() If you want to jump into the function from a line in file which contains the function name, place the cursor just before the function name and press CTRL+] (press control key and left-square-bracket key simultaneously).   // example code switch(id_number) { Case 1: if ( foo_function( 22, "abcef") == 3 ) ^ | | | Place the cursor here (just before foo_function) and press CTRL+] This takes you to the function named "foo_function". To come back to this line press CTRL+t To go back to the calling line press CTRL+t (Control key and letter 't' together). Keep pressing CTRL+t to unwind and go to the first line where you started the navigation. That is you can keep pressing CTRL+] and then keep pressing CTRL+t to go back. You can repeat these as many times as you want to have complete navigation through all the functions of C or C++. ## 8.1. Directory Tree 'tags' To recursively process the tags file for the entire directory :  $ cd $HOME$ ctags -R
This will recurse the directory underneath and create a tag file all the files under the directory and beneath. But to use this tag file you must set the following in the vim session or modify .gvimrc file
  $vi ~/.gvimrc " Set the tag file search order set tags=./tags,tags,~/tags,/home/john/ccplus/tags Or in the Vim session you set the tags with colon command:  $ vi somefile.cpp :set tags=./tags,tags,~/tags,/home/john/ccplus/tags

## 8.2. Ctags for ESQL

Since ctags does not directly support the Embedded SQL/C (ESQL) language, the following shell script can be used to create tags for esql. ESQL/C is database SQL commands embedded inside the "C" programs. Oracle's ESQL/C is called Pro*C and Sybase, Informix have ESQL/C and PostgreSQL has product "ecpg".

Save this file as "sqltags.sh" and do chmod a+rx tags_gen.sh.

## 11.2. Vi Tutorials on Internet

There are many Vi Tutorials on internet. In Yahoo (Lycos, excite or Hotbot) enter "Vi Tutorial" in search field and search engine will return many pointers.

# 12. Vi Tutorial

In this tutorial, we describe some "advanced" vi concepts and commands, so you can appreciate the power of vi and so you decide how to build your knowledge of vi commands. Nearly all vi references list the available commands, but many don't bother to discuss how the commands interrelate; this topic is the main purpose of this tutorial.

## 12.1. Cursor Movement Commands

The vi cursor movement commands allow you to position the cursor in the file and/or on the screen efficiently, with a minimum number of keystrokes. There are oodles of cursor movement commands - don't try memorizing them all at once! Later, we'll see that much of the power of vi comes from mixing cursor movement commands with other commands to delete, change, yank (copy), and filter text.

Please edit a large text file (say, wknight ) so you can experiment with each command as it is described. Keep in mind these commands will only work in Command Mode, not Insert Mode; if you start getting your "commands" in your text, press the ESC key to return to Command Mode.

• cursor keys : As we've seen, cursor keys move by single character amounts left, down, up, and right. Movement above the top of the file, below the bottom, to the right of the end of a line, or left of the beginning is not allowed (no line wrapping).

• hjkl : When vi was written (around 1978), many terminals on UNIX systems did not have cursor keys! h, j, k, and l were chosen as commands to move left, down, up, and right, respectively. Try them! Most vi diehards prefer these to the cursor keys because

• (a) they are in the same place on all keyborads, and

• (b) they fit nicely under the fingers, unlike most cursor keys, which are arranged in a box or "T" or some other nonlinear shape.

Why h, j, k, and l? Well, in the ASCII character set, CTRL-H is backspace (moves left), CTRL-J is linefeed (moves down), and, of course, k and l are next to h and j, so you see, they're mnemonic.

• 0 : ("zero", not "oh") Move to the beginning of current line. (To try this and the next few commands, use the cursor keys or h j k l to move to an indented text line that contains few "e" characters. If you can't find an indented line in your file, create one by inserting a few space characters at the beginning of a line.)

• ^ : Move to first non-white character of current line. (For indented line, 0 and ^ are different.)

• $: Move to last character of current line. • tC : Move to (but not on) next character c in current line. (Press 0, then press te. This will move to the first e in the curent line.) • fC : Find (move on top of) next character c in current line. (Press fe, and the cursor will find - that is, move on top - the next e in the current line.) • TC : Move to (but not on) the previous character c in current line (Press$, then Te.)

• FC : Find (move on top of) the previous character c in current line. (Press Fe.)

• n| : Move to column n in current line. (Try 20 |. The digits 2 and 0 will not be displayed as you type them, but when you press | the cursor will move to column 20.) Try some experiments with t f T F | . When you do something illegal, vi will beep your terminal.

• w : Forward to beginning of next "small" word ( a "small" word consists of unbroken alphanumeric characters or punctuation characters, but not mixed alphanumeric and punctuation). Try tapping w a dozen times or so - note what happens at punctuation.

• W : Forward to beginning of next "big" word (alphanumeric and punctuation mixed). Try W a dozen times or so.

• b : Backward to beginning of "small" word.

• B : Backward to beginning of "big" word.

• e : Forward to end of "small" word.

• E : Forward to end of "big" word.

• + Return : Move to first non-white space character on next line. (+ and the Return key have the same effect.)

• - : Move to first non-white space character on previous line.

• ) : Move to the end of sentence. (A sentence ends either at a blank line or at a period or examination mark followed by two space characters or at the end of a line. A period or exclamation mark followed by one space character does not end a sentence; this is correct behaviour, according to traditional rules of how sentences should appear in typed documents, but often appears wrong to those who have never suffered through a formal typing class.)

• ( : Move to beginning of sentence.

• } : Move to end of paragraph. (Paragraphs are seperated with blank lines, by vi 's definition.)

• { : Move to beginning of paragraph.

• H : Move to home position (top line) on the screen

• M : Move to middle line on the screen.

• L : Move to last line on the screen.

• nG : Move to line n. If n is not given, move to the last line in the file. (Try 15G to move to line 15, for example. The CTRL-G command displays the name of the file, some status information, and the current line number. To move to the top of the file: 1G)

• CTRL-d : Scroll down half-screen (see note).

• CTRL-u : Scroll up half-screen (see note).

• CTRL-f : Move forward one-screen (see note).

• CTRL-b : Move backward one-screen (see note).

• Note : These four scrolling/paging commands cannot be used with the delete, change, yank, or filter commands.

• /reg_exp : Move to next occurrence of the regular expression reg_exp When you press /, the cursor drops to the lower left corner of the screen and waits for you to type in the regular expression. Press the Return key to finish; vi then searches forward for the next occurrence of the regular expression. For example, press /the followed by Return. This moves forward to the next occurrence of the, perhaps imbedded in the middle of some longer word (other, weather, etc.). If you just press / and then Return, vi searches for the next occurrence of whatever the last regular expression was that you searched for.

• n : Has the same effect as pressing / and then Return; i.e., searches for the next occurrence of whatever the last regular expression was that you searched for.

• ?reg_exp : Searches backward, rather than forward. If no reg_exp is given, it searches for the last regular expression that was entered. Both / and ? wrap around, so searching "below" the bottom or "above" the top of the file is legal.

• N : Same as pressing ? and then Return.

## 12.2. Repeat Counts

Many of the movement commands discussed above can be preceded with a repeat count; the movement is simply repeated the given number of times:

• 3w : Move forward three words

• 5k : Move up four characters

• 3fa : Find the third succeeding a in current line

• 6+ : Move down six lines

For some commands, the "repeat counts" has special meaning:

• 4H : Move to Line 4 on the screen (home plus 3)

• 8L : Move to the eigth line from the bottom of the screen

• 3$: Move to the end of the third line down For some commands (e.g., ^) the repeat count is ignored; for others (e.g., / and ? ) it is illegal ## 12.3. Deleting Text We've seen that dd deletes the current line. This can be used with a repeat count: 3dd deletes three lines, the current line, and the two following lines. The d command can be used as a "prefix" on most of the movement commands above to delete nearly arbitrary chunks of text. When used with d, the movement commands are called target specifiers. d can be given a repeat count. (As you try these experiments, remember to press u after each command to undo the deletion). • dw : Delete "small" word forward • d3w : Delete three "small" words forward • 3dw : Three times, delete "small" word forward • 3d3w : Three times, delete three "small" words forward (that is, delete nine "small" words forward) • d+ : Delete current line and next line down • d/the : Delete from current character up to but not including the next occurrence of the pattern the. • d$ : Delete to end of line

• d0 : Delete to beginning of line

• d30G : Delete from the curent line to and including Line 30

• dG : Delete from current line to and including last line

• d1G : Delete from current line to and including Line 1

To delete single characters, use x. x can be given a repeat count:

• 15x : Delete current and 14 following characters

x is actually just an abbreviation of d1; that is, delete one character right.

## 12.4. Changing Text

The c command is similar to d, except it toggles vi into Insert Mode, allowing the original (unwanted) text to be changed to something else.

For example, put the cursor on the beginning of a word (press w to get to the beginning of the next word). Then, press cw to change that word. On the screen, the last character in the word being changed will be replaced with a $symbol indicating the boundary of the change; type in a new word (you will overwrite the original word on the screen) and press the ESC key when done. Your input may be longer or shorter than the word being changed. Put the cursor at the beginning of a line containing at least three words, and try c3w to change three words. Try c$ to change to the end of the current line. In all cases where the change affects only the current line, the boundary of the change is indicated with $. When a change affects more than just the current line, vi deletes the original text from the screen and toggles into Insert Mode. For example, try c3+ to change the current and the next three lines; vi deletes the four original lines from the screen and toggles into Insert Mode in a new blank line. As usual, press the ESC key when you have finished entering your new text. Some other change commands: • cc : Change current line • 5cc : Change five lines (current and next four) • c/the : Change from current character up to but not including the next occurrence of the pattern the • c$ : Change to end of line

• c30G : Change from the current line to and including Line 30

• cG : Change from curernt line to and including last line

• c1G : Change from curernt line to and including Line 1

## 12.5. Yanking (Copying) Text

The y command yanks a copy of text into a buffer; the yanked text can then be put (or pasted) elsewhere in the file using p or P.

The simplest form of yank is yy to yank the current line; after yy, try p to put a copy of the yanked line after the cursor. Following yy, you can make as many copies of the yanked line as you want by moving up and down in the file and pressing p.

To copy multiple lines, try, for example, 5yy (yank the current and next four lines). p puts a copy of the yanked lines after the cursor; the sequence 5yyp "works" but it probably doesn't do what you would like. The P command is like p, but puts a copy of the yanked text ahead of the cursor; try the sequence 5yyP.

Other yank commands:

• y3w : Yank three words

## 12.7. Marking Lines and Characters

You can mark lines and characters to be used as targest for movement, deletion, change, yanking, and filtering using the command mc, where c is a lowercase letter.

For example, put the cursor in the middle of some word and press ma. This marks the character under the cursor as mark a.

Now, move the cursor off the marked character and to a different line ( use the cursor keys, CTRL-u, or whatever). To return to the marked line, press 'a (that is, single quote, then a). This moves to the first non-white space character on the line containing mark a.

Move off that line again. To return to the marked character, press a (that is, backquote, then a). This moves on top of the character marked with a.

Marking is usually used with deleting, changing, yanking or filtering. For example, move the cursor to a line other than the one containing mark a, and then press d'a (d, single quote, a). This deletes from the current line to and including the line marked with a.

Put the cursor in the middle of a different word and press mb to set mark b. Now, move the cursor away from that word (but only a few lines, so you can see what we're about to do more easily), and then press db (d, backquote, b). This deletes from the current CHARACTER to and including the CHARACTER marked with b.

As another example, to sort the output of who, mark the first line (ma), then move the cursor to the last line and press !'asort and the Return key.

If you jump to a mark and decide you want to jump back to whatever you jumped from, you can press '' (jump back to line) or  (jump back to character).

## 12.8. Naming Buffers

When you delete, change, or yank text, the original text is stored (until the next delete, change, or yank) in an unnamed buffer from which it can be put using p or P. Using the unnamed buffer, only the most recently deleted, changed or yanked text may be recovered.

If you wish to delete, change, or yank multiple sections of text and remember them all (up to a maximum of 26), you can give a buffer name ahead of the delete change or yank command. A buffer name has the form "c (double quote, lowercase c).

For example, press "ayy to yank the current line into buffer a, then move to a different line and press "byy to yank that line into buffer b. Now, move elsewhere in the file and press "ap and "bp to put copies of the text stored in buffers a and b.

Some other named buffer commands:

• "a6yy : Yank six lines (current and next five) into buffer a

• "bd1G : Delete from the curernt line to and including Line 1, storing the deleted lines in buffer b

• "cy'c : Yank from the current line to the line marked c into buffer c (marks and buffers are distinct, and may have the same name without confusing vi )

## 12.9. Substitutions

To substitute one chunk of text for another in lines throughout your file, use the :s command. Some substitute examples:

• :1,$s/the/THE/g From Line 1 to the last line (line$), substitute for the text THE; do this globally in each line where the occurrs

• :'a,.s/.*/ha ha/ From the line marked a to the current line (line .), substitute for everything on the line the text ha ha

## 12.10. Miscellaneous "Colon Commands"

All colon commands begin with a colon; when you press the colon, the cursor drops to the lower left corner of the screen, and a colon prompt is displayed waiting for you to finish your colon command.

Some important examples:

• :w Write the buffer contents to the file without quitting from vi

• :w abc Write the buffer contents to the file abc (creating abc if it doesn't exist, or overwriting current contents if it does exist) without quitting from vi

• :1,10w abc Write lines 1 through 10 to file abc

## 12.13. Editing Multiple Files

You can edit multiple files with vi by giving multiple file names as command line arguments:
  vi croc fatherw wknight
Three colon commands are used to move through the multiple files:

• :n Move to the next file in the argument list (you must save changes with :w or vi will print an error message)

• :N Move to the previous file in the argument list (you must save changes with :w or vi will print an error message)

• :rew Rewind and start over with the first file in the argument list

The :n, :N, and :rew commands are somewhat clumsy, but there are some important benefits: the contents of named buffers ("a, "b, "c, etc.) are remembered across files, so you can use :n and :rew with p and P to copy text back and forth between files. Also, the most recent search string for the / and ? commands remembered across files, so you can do repetitive searches in multiple files rather easily.

For example, try the following experiment: First get out of vi , then execute vi with croc and wknight as arguments:
  $vi croc wknight In croc, search for the /the < CR > Yank this line into buffer a: "ayy Now go to the next file (you've made no change to croc, so this will work): :n < CR > Search for the "next" line containing the, without retyping the search string: n Put a copy of buffer a after the current line in wknight: "ap Move down two lines, and yank the current line into buffer b: jj"byy Save the changes to wknight :w < CR > Now, rewind to croc :rew < CR > Search again, and put a copy of buffer b after the found line: n"bp Save the changes, and exit vi ZZ ## 12.14. Final Remarks This tutorial was intended to introduce some of the vi capabilities that you might overlook in your system's vi manual or that might not be mentioned in the manual (different systems have manuals of widely varying quality). You will not be a vi expert after reading this tutorial, but you will have a good appreciation of vi 's capabilities. Only time and effort can make a vi expert. But the efficiency and universality of vi make this effort pay off in the long run. You may have decided you hate vi . So be it! But be aware that vi remains the standard UNIX text editor - the one editor you can count on being available on every UNIX system you'll use - so even if you prefer to use something else day-to-day, you'd be well advised to know the bare minimum vi material covered in this tutorial. # 13. Vim Reference Card ## 13.1. Vi states Vi has 3 modes: 1. command mode - Normal and initial state; others return here (use ESC to abort a partially typed command) 2. input mode - entered by specific commands a i A I o O c C s S R and ended by ESC or abnormally with interrupt 3. line mode - i.e. waiting for input after a : , / , ? or a ! command (end with CR , abort with CTRL-c ). CTRL is the control key: CTRL-c means "control c" ## 13.2. Shell Commands 1. TERM= code Puts a code name for your terminal into the variable TERM 2. export TERM Conveys the value of TERM (the terminal code) to any UNIX system program that is terminal dependant. 3. tput init Initializes the terminal so that it will function properly with various UNIX system programs. 4. vi filename Accesses the vi screen editor so that you can edit a specified file. 5. vi file1 file2 file3 Enters three files into the vi buffer to be edited. Those files are file1, file2, and file3 . 6. view file Invoke vi editor on file in read-only mode 7. vi -R file Invoke vi editor on file in read-only mode 8. vi -r file Recover file and recent edits after system crash ## 13.3. Setting Options 1. :set option Activate option 2. :set option=value Assign value to option 3. :set no option Deactivate option 4. :set Display options set by user 5. :set all Display list of all current options, both default and those set by the user 6. :set option ? Display values of option ## 13.4. Notations used Notations: 1. CTRL-c CTRL is the control key: CTRL-c means "control c" 2. CR is Carriage return (ENTER key) ## 13.5. Interrupting, cancelling 1. ESC end insert or incomplete command 2. CTRL-? CTRL is the control key: CTRL-? means "control ?" delete or rubout interrupts 3. CTRL-l reprint/refresh screen if CTRL-? scrambles it ## 13.6. File Manipulation 1. ZZ Save the file and exit vi 2. :wq Save the file and exit vi 3. :w Write the current file 4. :w! Force write the current file, if file is read-only 5. :w name Write to file name 6. :q Exit from vi 7. :q! Force exit from vi (discarding changes) 8. :e name Edit file name 9. :e! reedit, discard changes 10. :e + name edit file name , starting at end 11. :e + n edit starting at line n 12. :e # edit alternate file 13. :n edit next file in arglist 14. :args list files in current filelist 15. :rew rewind current filelist and edit first file 16. :n args specify new arglist 17. :f show current file and line 18. CTRL-G synonym for :f , show current file and line 19. :ta tag to tag file entry tag 20. CTRL-] :ta, following word is tag ## 13.7. Movement 1. Arrows Move the cursor 2. CTRL-d Scroll half page down 3. CTRL-u Scroll half page up 4. CTRL-f Scroll a full page down 5. CTRL-b Scroll a full page up 6. :0 Move to start of file 7. :n Move to line number n 8. :$ Move to end of file

9. 0 Move to start of line

10. ^ Move to first non-blank character

11. $Move to end of line 12. CR Move to the start of next line 13. - Move to the start of previous line 14. % Find matching bracket 15. G goto line (last line default) 16. ]] next section/function 17. [[ previous section/function ## 13.8. Line Positioning 1. H Home window line 2. L Last window line 3. M Middle window line 4. + Next line, at first non-white 5. - Previous line, at first non-white 6. CR return, same as + 7. j next line, same column 8. k previous line, same column ## 13.9. Character positioning 1. 0 beginning of line 2.$ end of line

3. h forward

4. l backwards

5. SPACE same as l

6. fx find x forward

7. Fx find x backward

8. ; repeat last f F

9. , inverse of ;

10. | to specified column

11. % find matching { or }

## 13.10. Words, sentences, paragraphs

1. w Word forward

2. b Word backward

3. e End of word

4. ) To next sentence

5. ( Back sentence

6. } To next paragraph

7. { Back paragraph

8. W Blank delimited word

9. B Back W

10. E To end of W

## 13.11. Marking and returning

1.  (press twice the back-quote  key) Previous context

2. '' (press twice the single-quote  key) Previous context at first non-white in line

3. mx mark position with letter x

4. x (back quote key and letter x) goto mark x

5. 'x goto mark x at first non-white in line

## 13.12. Corrections during insert

1. CTRL-h Erase last character

2. CTRL-w Erase last word

3. erase Press DELETE key, same as CTRL-h

4. kill Your kill key, erase input this line

5. \ Escapes CTRL-h, DELETE and kill

6. ESC Ends insertion, back to command

7. CTRL-? Interrupt, terminates insert

8. CTRL-d Backtab over autoindent

9. CTRL-v Quote non-printing character

1. CTRL-l Clear and redraw

2. CTRL-r retype, eliminate @lines

3. z-CR redraw, current line at window top

4. z- redraw, current line at window bottom

5. z. redraw, current line at window center

6. /pat/z- pat line bottom

7. tn Use n line window

8. CTRL-e Scroll window down 1 line

9. CTRL-y Scroll window up 1 line

## 13.14. Delete

1. x Delete the character under the cursor

2. X Delete the charater before the cursor

3. D Delete to the end of line

4. d^ Delete back to start of line

5. dd Delete the current line

6. ndd Delete n lines starting with the current one

7. dnw Delete n words starting from cursor

## 13.15. Insert, change

1. i Enter input mode inserting before the cursor

2. I Enter input mode inserting before the first non-blank character

3. a Enter input mode inserting after the cursor

4. A Enter input mode inserting after the end of the line

5. o Open a new line below current line and enter input mode

6. O Open a new line above current line and enter input mode

7. r Replace the character under the cursor (does NOT enter input mode)

8. R Enter input mode replacing characters

9. C shift-c. Change rest of line

10. D shift-d. Delete rest of line

11. s Substitute chars

12. S Substitute lines

13. J Join lines

14. J Join lines

## 13.16. Copy and Paste

The "yank buffer" is filled by EVERY delete command, or explicitely by Y and yy .

1. Y Copy the current line to the yank buffer

2. n yy Copy n lines starting from the current to the yank buffer

3. p Paste the yank buffer after the cursor (or below the current line)

4. P Paste the yank buffer before the cursor (or above the current line)

5. " x p Put from buffer x

6. " x y Yank to buffer x

7. " x d Delete into buffer x

## 13.17. Operators (use double to affect lines)

1. d delete

2. c change

3. < left shift

4. > right shift

5. ! filter through command

6. = indent for LISP

7. y yank text to buffer

## 13.18. Search and replace

1. / text Search forward for text

2. ? text Search backward for text

3. n Repeat the last search in the same direction

4. N Repeat the last search in the reverse direction

5. / Repeat the last search forward

6. ? Repeat the last search backward

# 15. Emacs - Old Habits Die Hard !

If you were using Emacs before and now started using Vim & vi, then this mistake is commited very often and will be quite annoying to you.

You hit "control x" "control s" to save the file and Vim stops dead. How to rescue without killing the xwindow containing the vim process, and recovering. You will see that there is no response at the keyboard.

The explanation for this behaviour is : It is not the feature of vim but it is the feature of the xterm 'terminal'. The "control s" means stop feeding to terminal output, so you do not see any output. To get out of it do "control q" (to quit out of stop output). This happens only in vim/vi and not in gvim (graphical Vim).

Also in xterm, at the bash prompt type something and do "control s" and type something you will not see output. Now type "control q" you will see output.

# 16. Related URLs

Related VIM URLs are at -

# 17. Other Formats of this Document

This document is published in 14 different formats namely - DVI, Postscript, Latex, Adobe Acrobat PDF, LyX, GNU-info, HTML, RTF(Rich Text Format), Plain-text, Unix man pages, single HTML file, SGML (Linuxdoc format), SGML (Docbook format), MS WinHelp format.

This howto document is located at -

You can also find this document at the following mirrors sites -

The document is written using a tool called "SGML-Tools" which can be got from - "http://www.sgmltools.org" Compiling the source you will get the following commands like

• sgml2html xxxxhowto.sgml (to generate html file)

• sgml2html -split 0 xxxxhowto.sgml (to generate a single page html file)

• sgml2rtf xxxxhowto.sgml (to generate RTF file)

• sgml2latex xxxxhowto.sgml (to generate latex file)

## 17.1. Acrobat PDF format

PDF file can be generated from postscript file using either acrobat distill or Ghostscript . And postscript file is generated from DVI which in turn is generated from LaTex file. You can download distill software from "http://www.adobe.com" . Given below is a sample session:
  bash$man sgml2latex bash$ sgml2latex filename.sgml bash$man dvips bash$ dvips -o filename.ps filename.dvi bash$distill filename.ps bash$ man ghostscript bash$man ps2pdf bash$ ps2pdf input.ps output.pdf bash$acroread output.pdf & Or you can use Ghostscript command ps2pdf . ps2pdf is a work-alike for nearly all the functionality of Adobe's Acrobat Distiller product: it converts PostScript files to Portable Document Format (PDF) files. ps2pdf is implemented as a very small command script (batch file) that invokes Ghostscript, selecting a special "output device" called pdfwrite . In order to use ps2pdf, the pdfwrite device must be included in the makefile when Ghostscript was compiled; see the documentation on building Ghostscript for details. ## 17.2. Convert Linuxdoc to Docbook format This document is written in linuxdoc SGML format. The Docbook SGML format supercedes the linuxdoc format and has lot more features than linuxdoc. The linuxdoc is very simple and is easy to use. To convert linuxdoc SGML file to Docbook SGML use the program ld2db.sh and some perl scripts. The ld2db output is not 100% clean and you need to use the clean_ld2db.pl perl script. You may need to manually correct few lines in the document. The ld2db.sh is not 100% clean, you will get lots of errors when you run   bash$ ld2db.sh file-linuxdoc.sgml db.sgml bash$cleanup.pl db.sgml > db_clean.sgml bash$ gvim db_clean.sgml bash$docbook2html db.sgml And you may have to manually edit some of the minor errors after running the perl script. For e.g. you may need to put closing tag < /Para> for each < Listitem> ## 17.3. Convert to MS WinHelp format You can convert the SGML howto document to Microsoft Windows Help file, first convert the sgml to html using:   bash$ sgml2html xxxxhowto.sgml (to generate html file) bash\$ sgml2html -split 0 xxxxhowto.sgml (to generate a single page html file)
Then use the tool HtmlToHlp . You can also use sgml2rtf and then use the RTF files for generating winhelp files.

In order to view the document in dvi format, use the xdvi program. The xdvi program is located in tetex-xdvi*.rpm package in Redhat Linux which can be located through ControlPanel | Applications | Publishing | TeX menu buttons. To read dvi document give the command -
  xdvi -geometry 80x90 howto.dvi man xdvi 
And resize the window with mouse. To navigate use Arrow keys, Page Up, Page Down keys, also you can use 'f', 'd', 'u', 'c', 'l', 'r', 'p', 'n' letter keys to move up, down, center, next page, previous page etc. To turn off expert menu press 'x'.

You can read postscript file using the program 'gv' (ghostview) or 'ghostscript'. The ghostscript program is in ghostscript*.rpm package and gv program is in gv*.rpm package in Redhat Linux which can be located through ControlPanel | Applications | Graphics menu buttons. The gv program is much more user friendly than ghostscript. Also ghostscript and gv are available on other platforms like OS/2, Windows 95 and NT, you view this document even on those platforms.

To read postscript document give the command -
  gv howto.ps ghostscript howto.ps `

You can read HTML format document using Netscape Navigator, Microsoft Internet explorer, Redhat Baron Web browser or any of the 10 other web browsers.

You can read the latex, LyX output using LyX a X-Windows front end to latex.