Vim Intro:: Linux GUI Editors
Vim Intro:: Linux GUI Editors
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.)
Vim Installation:
Ubuntu / Debian:
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.
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-h) Move cursor to middle of page
H Move cursor to top of page
L Move cursor to bottom of page
W
Move cursor a word at a time
w
Move cursor ahead 5 words
5w
B Move cursor back a word at a time
b Move cursor back a word at a time
5b Move cursor back 5 words
e Move cursor to end of word
5e 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 "%".
2
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"
Move cursor to line mark "a" (global between buffers) generated by marking
'A
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 Delete line
3dd Delete 3 lines.
D Delete contents of line after cursor
Delete contents of line after cursor and insert new text. Press esc
C
key to end insertion.
dw Delete word
4dw 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 Increment number under the cursor.
ctrl-x Decrement number under the cursor.
/search_string{CR} Search for search_string
?search_string{CR} Search backwards (up in file) for search_string
3
/\<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.
Interactive Commands:
Marking a line:
o Type the letter "m" and any other letter to identify the line.
o 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:
o Single line: "yy" - yanks a single line (defined by current cursor position) into the
buffer
o Multiple lines: "y't" - yanks from current cursor position to the line marked "t"
4
o Multiple lines: "3yy" - yank 3 lines. Current line and two lines below it.
o "p" - place contents of buffer after current line defined by current cursor position.
vim: Shift a block of code left or right:
o Enter into visual mode by typing the letter "v" at the top (or bottom) of the block
of text to be shifted.
o 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.
o 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:
o :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.
o :set all - display all settings of your session.
o :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)
o Common options to set:
5
people or when noerrorbells is set)
tabstop=8 ts Tab key displays 8 spaces
ignorecase/noignorecase ic/noic Case sensitive searches
number/nonumber nu/nonu Display line numbers
showmatch/noshowmatch no
Cursor shows matching ")" and "}"
abbreviations
showmode/noshowmode no Editor mode is displayed on bottom
abbreviations 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.
Any UNIX command can be executed from the vi command line by typing an "!" before
the UNIX command.
Examples:
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
6
Find/Replace:
Example:
o :%s/fff/rrrrr/ - For all lines in a file, find string "fff" and replace with string
"rrrrr" for the first instance on a line.
o :%s/fff/rrrrr/g - For all lines in a file, find string "fff" and replace with string
"rrrrr" for each instance on a line.
o :%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
o :%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.
o :'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.
o :%s/*$/ - For all lines in a file, delete blank spaces at end of line.
o :%s/\(.*\):\(.*\)/\2:\1/g - For all lines in a file, move last field delimited by ":" to
the first field. Swap fields if only two.
o :help substitute
o :help pattern
o :help gdefault
o :help cmdline-ranges
Sorting:
Example:
o 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.
o :'t,'b !sort
:'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
7
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:
o Mark a block of text at the top line and bottom line of the block. i.e. "mt" and
"mb" on two separate lines.
o Example: ":'t,'b !nroff"
o You can insert nroff commands i.e.:
o 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
8
o 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:
o 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.
o :'t,'b !spell will cause the block to be replaced with misspelled words.
o Press "u" to undo.
o Proceed to correct words misspelled.
Macros:
9
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.
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".
Keystrokes:
Keystroke Description
10
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.
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.
:1,$ s/<HTML>/<html>/g
:1,$ s/<\/HTML>/<\/html>/g
:1,$ s/<HEAD>/<head>/g
:1,$ s/<\/HEAD>/<\/head>/g
:1,$ s/<TITLE>/<title>/g
:1,$ s/<\/TITLE>/<\/title>/g
:1,$ s/<BODY/<body/g
:1,$ s/<\/BODY/<\/body/g
:1,$ s/<UL>/<ul>/g
:1,$ s/<\/UL>/<\/ul>/g
...
..
.
:1,$ s/<A HREF/<a href/g
:1,$ s/<A NAME/<a name/g
:1,$ s/<\/A>/<\/a>/g
:1,$ s/<P>/<p>/g
:1,$ s/<B>/<b>/g
:1,$ s/<\/B>/<\/b>/g
:1,$ s/<I>/<i>/g
:1,$ s/<\/I>/<\/i>/g
:wq
11
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 affected. If it does, vim will error due to conflicts with the vim swap file.
Tagging:
Unix command line: vi -t subroutine_name This will find the correct file to
edit.
OR
Vi command line: :tag subroutine_name This will jump from your current file
to the file containing the subroutine. (short form :ta subroutine_name )
OR
By cursor position: ctrl-] Place cursor on the first character of the subroutine
name and press ctrl-] This will jump to the file containing the subroutine.
Note: The key combination ctrl-] is also the default telnet connection interrupt.
To avoid this problem when using telnet block this telnet escape key by
specifying NULL or a new escape key:
o telnet -E file-name
o telnet -e "" file-name
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)
12
Vim supports tag name completion. Start the typing the tag
:tag start-of-tag-name_TAB name and then type the TAB key and name completion will
complete the tag name for you.
:tag /search-string Jump to a tag name found by a search.
ctrl-] The vim editor will jump into the tag to follow it to a new
position in the file or to a new file.
ctrl-t The vim editor will allow the user to jump back a level.
(or :pop)
:tselect <function-name> 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.
:tnext When multiple answers are available you can go to the next
answer.
:set ignorecase
(or :set ic) The ignore case directive affects tagging.
:tags Show tag stack (history)
:4pop 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)
:tnext
Jump to next matching tag.
(Also short form :tn and jump two :2tnext)
:tprevious Jump to previous matching tag.
(Also short form :tp and jump two :2tp)
:tfirst Jump to first matching tag.
(Also short form :tf, :trewind, :tr)
:tlast Jump to last matching tag.
(Also short form :tl)
:set Using multiple tag files (one in each directory).
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:
13
vim/tag search
ctags framework
There are more than one version of ctags out there. The original Unix version, the GNU version
and the version that comes with vim. This discussion is about the one that comes with vim.
(default with Red Hat)
The ctags program which is written by the VIM team is called " Exuberant Ctags" and supports
the most features in VIM.
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.
14
map S G:w!^M:r!spell %^M
colorscheme desert
"Specify that a dark terminal background is being used.
set bg=dark
Notes:
Cscope was developed to cross reference C source code. It now can be used with C++ and Java
and can interface with vim.
Using Cscope to cross reference souce code will create a database and allow you to traverse the
source to find calls to a function, occurances of a function, variable, macros, class or object and
their respective declarations. Cscope offers more complete navigation than ctags as it has more
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.
The Cscope database (cscope.out) is generated the first time it is invoked. Subsequent use will
update the database based on file changes.
The database can be generated manually using the command i.e.: cscope -b *.cpp *.h or
cscope -b -R .
15
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:
Results of the Cscope query will be displayed at the bottom of the vim screen.
Argument Description
16
-R Scan subdirectories recursively
-b Build the cross-reference only.
-C Ignore letter case when searching.
-fFileName Specify Cscope database file name instead of default "cscope.out".
-Iinclude- Look in "include-directories" for any #include files whose names do
directories not begin with "/".
Scan specified files listed in "Files". File names are separated by
-iFiles
linefeed. Cscope uses the default file name "cscope.files".
Kernel mode ignores /usr/include.
-k
Typical: cscope -b -q -k
-q create inverted index database for quick search for large projects.
-sDirectoryName Use specified directory for source code. Ignored if specified by "-i".
-u Unconditionally build a new cross-reference file..
-v Verbose mode.
file1 file2 ... List files to cross reference on the command line.
Environment
Description
Variable
CSCOPE_EDITOR Editor to use: /usr/bin/vim
EDITOR Default: /usr/bin/vim
INCLUDEDIRS Colon-separated list of directories to search for #include files.
Colon-separated list of directories to search for additional source
SOURCEDIRS
files.
Colon-separated list of directories to search. If not set, cscope
VPATH
searches only in the current directory.
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.
17
Also see:
Vim plugins:
Vim comes with some default plugins which can be found in:
User added plugins are added to the user's local directory: ~/.vim/plugin/ or
~/.vimrc/plugin/
Command Description
:Explore List files in your current directory
:Explore directory- List files in specified directory
name
:Vexplore Split with a new vertical window and then list files in your current
directory
:Sexplore Split with a new horizontal window and then list files in your
current directory
18
The new window buffer created by ":Vexplore" and ":Sexplore" can be closed with ":bd" (buffer
delete).
CScope: cscope_maps.vim
See cscope and vim description and use in this tutorial above.
This plugin allows you to open multiple text files and accessed by their tabs displayed at the top
of the frame.
Keystroke Description
:bn New buffer
:bd Buffer delete
:b3 Go to buffer number 3
ctrl-w followed by New buffer. Puts curson in upper tabbed portion of window. Navigate
"k" with arrow keys or "h"/"l".
:qa Quit vim out of all buffers
tab The "tab" key jumps between tabbed buffers.
The new window buffer tab created can be closed with ":bd" (buffer delete).
Links:
19
Usefull for C/C++ programmers to switch between the source ".cpp" and commensurate ".hpp"
or ".h" file and vice versa.
Command Description
switches to the header file corresponding to the current file being edited (or
:A
vise 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:
Plug-in Installation:
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:
20
#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite <vivek@nixcraft.com>
#
# Latest version can be found at http://www.nixcraft.com/
#
# Q1.Script to sum to nos
#
if [ $# -ne 2 ]
then
echo "Usage - $0 x y"
echo " Where x and y are two nos for which I will print sum"
exit 1
fi
echo "Sum of $1 and $2 is `expr $1 + $2`"
#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#
21