VIM – Vi Improved!VIM – Vi Improved!
Configuring and using VIM editorBy
Tusharadri SarkarJuly 13, 2009
IBM
July 13, 2009 1Tusharadri Sarkar
A Brief History of VimA Brief History of VimVim is an improvement over the popular Vi editorThe Vi editor was developed by Bill Joy in 1976 “ed” was the original UNIX text editorBill Joy modified “ed” and named it “ex”He developed Vi as a “Visual interface” to “ex”Bram Moolenaar developed Vim in November,1991
for the Amiga Computer, added many additional features
In 1992 it was ported to UNIX platformGUI feature was added in 1996, gVim appeared
July 13, 2009 2Tusharadri Sarkar
Features of VimFeatures of Vim
Vim has almost full compatibility with vi + extra features and enhancements like:
Completion, comparison and merging of files: vimdiff
An integrated help systemSupport for extended regular expressionsSupport for scripting languages (native: vimscript +
others: Perl, Ruby, Python, TCL etc.)Support for plug-ins and a GUI (gVim) versionLimited IDE features and mouse interaction (for
both GUI and CLI versions)
July 13, 2009 3Tusharadri Sarkar
Features of VimFeatures of VimEditing capability of compressed or archived files
(.gzip, .bzip2, .zip and .tar files) Editing capability of files over network protocols like
SSH, FTP and HTTPSession state preventionSpell checkingSplitting of windows (both horizontal & vertical)Support for Unicode + other languagesTrans-session commandSyntax highlightingVisual mode
July 13, 2009 4Tusharadri Sarkar
Why use Vim?Why use Vim?
You never need not use the mouse or arrow keys!!Powerful navigation capability with minimal use of
Ctrl/Meta keysAutomatic Keyword CompletionCharacter, line and block wise editing: The Visual
modeUse multiple clipboards/buffers: No right clicks!!Use macros: Record and replay multiple macrosPowerful command line editingCustomize Vim as you like it: Too many vim
optionsJuly 13, 2009 5Tusharadri Sarkar
Configuring VimConfiguring Vim
How to configure Vim
&
Set Vim as the default editor
July 13, 2009 6Tusharadri Sarkar
Configuring VimConfiguring VimMake aliases of the vim path in the .bashrc file of
your login directory as follows: ◦alias vi=‘/usr/local/bin/vim –X’◦alias vim=‘/usr/local/bin/vim –X’* Note: The actual path may vary from system to system. This is
the most common path.
Create the .vimrc file in the login directory with your preferred Vim options
Invoke the bash shell once and you will set vim as your default editor
July 13, 2009 7Tusharadri Sarkar
Configuring VimConfiguring Vim
Options for the .vimrc file: Most frequently used are
:set nocompatible " use vim defaults:set ls=2 " always show status line (last 2):set tabstop=4 " numbers of spaces of tab char:set shiftwidth=4 " numbers of spaces to auto indent:set scrolloff=3 " keep 3 lines when scrolling:set showcmd " display incomplete commands:set hlsearch " highlight searches:set incsearch " do incremental searching:set ruler " show the cursor position
July 13, 2009 8Tusharadri Sarkar
:set visualbell t_vb= " turn off error beep/flash:set number " show line numbers:set ignorecase " ignore case when searching:set viminfo='20,<50,s10,h:set autoindent " always set auto indenting on:set smartindent " smart indent:set expandtab " tabs are converted to spaces:set sm " show matching braces:syntax on " syntax highlighting
July 13, 2009 9Tusharadri Sarkar
Configuring VimConfiguring Vim
Each option has a short formUsing short form is convenient while
enabling/disabling any option for current session :set number == se nu enables line numberTo disable any option, just prefix ‘no’ before it :se nonu disables line number If you have GUI support (gVim), you can also set
the color scheme, font style, window height/width and background and foreground colors
July 13, 2009 10Tusharadri Sarkar
Configuring VimConfiguring Vim
Using VimUsing Vim
Navigation
Smart Editing
Command Execution
And more…
July 13, 2009 11Tusharadri Sarkar
Modes of VimModes of Vim
There are 3 modes with distinct sets of functionalities:
1. Command Mode (For Navigation)2. Input Mode (Everything shows up on screen)
Entering TextReplacing Text
3. Execution Mode (Last Line Mode)SavingExitingPattern matching and substitutions
Visual Mode (Only in Vim, mainly covers 2 & 3)
July 13, 2009 12Tusharadri Sarkar
Switching between modes of VimSwitching between modes of Vim
Input Mode ex Mode
Command Mode
SHELL
I, i, A, a, O, o, R, r, S, s
[Esc]
[Enter]
:
vi/vim: x, : q,
ZZ
July 13, 2009 13Tusharadri Sarkar
Vim: NavigationVim: NavigationKeystroke Function
h Move cursor left *
l/spacebar Move cursor right *
k/Ctrl+p Move cursor up *
J/Ctrl+n Move cursor down *
Crtl+f Scroll forward one page
Ctrl+b Scroll back one page
Ctrl+d Scroll down one half of a page
Ctrl+u Scroll up one half of a 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/w Move cursor forward a word at a time*July 13, 2009 14Tusharadri Sarkar
Vim: NavigationVim: NavigationKeystroke Function
B/b Move cursor to bottom of page *
E/e Move cursor to end of 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 {}[]()
‘. (Apostrophe dot) Move cursor to previously modified line
‘a (Apostrophe a)Move cursor to line mark "a" generated by marking "ma"
July 13, 2009 15Tusharadri Sarkar
Vim: NavigationVim: NavigationKeystroke Function
‘A (Apostrophe A)Move cursor to line mark "a" (global between buffers) generated by marking with keystroke "mA"
gg Move to the beginning of the file
]’ Move cursor to next lower case mark
[‘ Move cursor to previous lower case mark
+/- Move cursor down/up in first column
^ Move to the first character of first word
Functions marked with * also support motions; e.g. # 10w will take the cursor 10 words forward. 40G will take you to the 40th line from
beginning
July 13, 2009 16Tusharadri Sarkar
Vim: Inserting/Editing TextVim: Inserting/Editing TextKeystroke Action
i Insert at cursor *
a Append after cursor
A Append at end of line
u Undo last change
U Undo all changes to entire line
o Open a new line below cursor
O Open a new line above cursor
~ (Tilde) Change case of individual character
D Delete contents of line after cursor
C Delete contents of line after cursor and insert new text
Ctrl+a Increment number under the cursor
Ctrl+x Decrement number under the cursor
July 13, 2009 17Tusharadri Sarkar
Vim: Inserting/Editing TextVim: Inserting/Editing TextKeystroke Action
x Delete character at cursor *
r Replace character *
R Overwrite characters from cursor onward
sSubstitute one character under cursor continue to insert *
SSubstitute entire line and begin to insert at beginning of the line
dw Delete word *
cw Change word
d0 (d+Zero) Delete to beginning of the line
dd Delete line *
d$ Delete to the end of a line *
xp Transpose two characters
July 13, 2009 18Tusharadri Sarkar
Vim: Inserting/Editing TextVim: Inserting/Editing TextKeystroke Action
P Put deleted/cut text above cursor
p Put deleted/cut text below cursor
/string{CR} /string{CR}
?string{CR} Search backwards (up in file) for string
n Find next occurrence of search string downward
N Find previous occurrences of search string upwards
/\<string\>{CR}
Search for word string; e.g. # /\<s\>Search for variable "s" but ignore declaration "string" or words containing "s". This will find "string s;", "s = fn(x);", "x = fn(s);"
fc / FcSearch forward and backward for character c in current line
; / , (semi/coma)Repeat forward and backward search for char in same line
July 13, 2009 19Tusharadri Sarkar
Vim: Inserting/Editing TextVim: Inserting/Editing TextKeystroke Action
xp Transpose two characters
Amazing . (dot) Repeat the last action in command mode
d Delete a region (Vim only; Supported in V mode)
yy Copy current line *
yw Copy word *
y Copy region (Vim only, V mode)
c Change text of region (Vim only, V mode)
!tr ‘[a-z]’ ‘[A-Z]’ Convert region to uppercase (Vim only, V mode)
!tr ‘[A-Z]’ ‘[a-z]’ Convert region to lowercase (Vim only, V mode)
Ctrl+r Redo last undo (Vim only)
The same rule of motion applies here also with actions marked *
July 13, 2009 20Tusharadri Sarkar
Advance editingAdvance editing: : Buffers, Marks & Buffers, Marks & MacrosMacros
Command Function
“Bdd Delete current line to buffer B *
“Bp Restore content from buffer B *
“Byy Copy current line to buffer B *
ma Set mark ‘a’ to a line
‘’ (2 apostrophes)
Toggle between current and previous marked positions
Ctrl+o / Ctrl+I Same as above but not marked places
q register Start recording a macro
q Stop recording current macro
@register Play the macro i.e. write down the register content
Remember: macro only records the keystrokes entered
July 13, 2009 21Tusharadri Sarkar
Advanced editing: Multiple FilesAdvanced editing: Multiple Files
Command Function
:e abc Stop editing current file and edit file abc
:e! abcSame as above but discarding all the changes in current file
:e! Load latest saved version of the current file
Crtl+^ Return to the most recently edited file
:nEdit the next file (When vim is opened with multiple files)
:set autowrite(: se aw)
Automatically save the current file before switching to the next file
:rewRewind files list to start editing first file(When vim is opened with multiple files)
:r abc Insert contents of file abc below current line
July 13, 2009 22Tusharadri Sarkar
Advanced editing: Multiple WindowsAdvanced editing: Multiple WindowsThis is a Vim only featureThis is a Vim only feature
Command Function
:sp Split current window horizontally in two
:vsp Split current window vertically into two
vim –O [n | files…]
Opens n windows, files split vertically
:new Open a new blank window
:on Make current window the only window
:q Quit current window
:qa Quit all windows
:xa Save and quit all windows
[Ctrl+w]+/- Increase/decrease window size
[Ctrl+w] [Ctrl+w] Toggle between windows
July 13, 2009 23Tusharadri Sarkar
Advance editing: Abbreviation & Advance editing: Abbreviation & Interface to SHELLInterface to SHELL
Command Action
:ab blr Bangalore Abbreviate Bangalore to blr
:unab blr Kill the above abbreviation
:ab List of all abbreviations
:!cmd Run any UNIX command cmd
:!% Execute the current file as a Shell/Perl Script
:r!cmdInsert output of UNIX command cmd below current line
:sh Escape to the UNIX shell
Ctrl+z Suspend editor (use fg to return to vim)
:!cc% Compile currently edited C file
:!javac% Compile currently edited Java file
July 13, 2009 24Tusharadri Sarkar
Pattern SubstitutionsPattern SubstitutionsGeneral format of substitution:[.|$|%]s/s1/s1[switches] or :n1,n2s/s1/s2/[switches]
[switches] are: g|c|i|I meaning global/confirmation/ignore-case/no-ignore-case
Some interesting examples of pattern substitutions
Command Function
:1,$s/#//g Globally remove #
:3,10s/^/#/ Insert # at the beginning of line 3 to 10
:$s/$/;/ Insert a ; at the end of last line
:%s/abc/xyz/gc Globally replace abc by xyz interactively
:1,$s/include/<&>/g Globally replace include by <include>
July 13, 2009 25Tusharadri Sarkar
Starting, Saving & QuittingStarting, Saving & Quitting
Command Function
vim +100 abc Open file abc at line no. 100
vim +/pat abc Open file abc at the first occurrence of pattern pat
vim + abc Open file abc at end
vim f1 f2 f3 …First open file f1, then switch to f2 using :n, then switch to f3 using :n and so on…
vim –r abc Recover buffer from swap file
vim –R abc Open file in read-only mode
July 13, 2009 26Tusharadri Sarkar
Starting, Saving & QuittingStarting, Saving & Quitting
Command Function
:w Save file remaining in editing mode
:w abc Save current file content by file name abc
:w! abc Same as above but overwriting existing file abc
:n1,n2w abc Write line n1 to n2 to file abc
:n1,n2w >> abc Append lines n1 to n2 to file abc
:.w abc Write the current line to file abc
:$w abc Write the last line to file abc
:x / :wq/ZZ Save file and quit editing mode
:q! / :qa Quit editing mode discarding all the changes
:q Quit as above when no changes are made
July 13, 2009 27Tusharadri Sarkar
Vim: Graphical Cheat Sheet!Vim: Graphical Cheat Sheet!
July 13, 2009 28Tusharadri Sarkar
Some useful features of VimSome useful features of Vim
VimdiffCtags
Cscope
July 13, 2009 29Tusharadri Sarkar
Vimdiff: Find the differencesVimdiff: Find the differencesTo start vim in diff mode: vimdiff f1 f2 [f3 [f4]] orAlternatively you can use: vim –d f1 f2 [f3 [f4]]Vim enables the following options while using diff:◦ diff on◦ scrollbind on◦ scrollopt includes “hor”◦ wrap off◦ foldmethod “diff”◦ foldcolumn 2
Vim sets them as local to the window when using diff mode. Otherwise they are set to global values while editing other files.
July 13, 2009 30Tusharadri Sarkar
Vimdiff: Find the differencesVimdiff: Find the differencesWhen already in editing mode, diff mode can be
invoked in 3 ways◦ :diffsplit <filename>◦ :diffthis ◦ :diffpatch <patchfile>
To ensure these commands use a vertical split, use option :vert◦ :vert diffpatch /tmp/diff◦ :vert diffsplit main.c
July 13, 2009 31Tusharadri Sarkar
Vimdiff: Find the differencesVimdiff: Find the differencesForce the difference to be updated :diffupdate
To jump between the differences◦ [c :Jump backward to the previous start of a
change◦ ]c : Jump forward to the previous start of a
change
July 13, 2009 32Tusharadri Sarkar
Vimdiff: Find the differencesVimdiff: Find the differencesHighlight the differences with the following groups:◦hl-DiffAdd Added/inserted lines◦hl-DiffChange Changed text◦hl-DiffText Changed text inside a changed
line◦hl-DiffDelete Deleted lines
July 13, 2009 33Tusharadri Sarkar
Vimdiff: Find the differencesVimdiff: Find the differencesDiff Copying: Two commands to copy test from
one buffer to another:◦ [range] diffg[et] [buffspace]: Modify current buffer
to undo differences with another buffer within range
◦ [range] diffpu[t] [buffspace]: Modify another buffer to undo differences with the current buffer within range
◦do: Same as ‘diffg[et]’ without argument or range◦dp: Same as ‘diffpu[t]’ without argument or range
July 13, 2009 34Tusharadri Sarkar
Ctags with VimCtags with Vim
Ctags helps to jump to the references under cursor
Add tags to a particular sets of file or entire directory: ctags –R <path>; It will create a tags file
Alternatively you can use: ctags *.h *.c to create tags
Most frequently used commands for ctags: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/pop The vim editor will allow the user to
jump back a level
July 13, 2009 35Tusharadri Sarkar
Ctags with VimCtags with VimOther ctags options to be used with Vim:
Command Action
:tag start-of-tag-name_TAB
Vim supports tag name completion; completes the tag name for you
:tag /search-string Jump to a tag name found by a search
:tselect <function-name>
If multiple entries exist in the tags file, the operator can choose by issuing this command.
:tnext Jump to the next matching tag
:tags Show tag stack (history)
:n pop/n tagJump to a particular position in the tag stack (history)
:tprevious Jump to the previous matching tag
:tfirst / :tlast Jump to first/last matching tag
:set tags=./tags1,./tag2 Add multiple tags files
July 13, 2009 36Tusharadri Sarkar
Cscope with VimCscope with VimCscope: Developed to cross-reference C codeIt can also be used to with C++ and JavaUsing cscope to cross reference source code
will create a databaseTraverse the source to find calls to a function,
occurrences of a function, variable, macros, class or object and their respective declarations
cscope offers more complete navigation than ctags
To use cscope, vim must be compiled with cscope support
July 13, 2009 37Tusharadri Sarkar
Cscope with VimCscope with VimTo generate the cscope database use the command:
cscope –b *.cpp/(or .cc/.c) *.h or cscope –b –R Invoke cscope from vim:cscope find search_type serach_string
search_type Description
symbol (s) Find all references to a symbol
global (g) Find global definition
calls (c) Find calls of this function
called (d) Find functions that the specified function calls
text (t) Find specified text string
file (f) Open file
include (i) Find files that "#include" the specified file
July 13, 2009 38Tusharadri Sarkar
Cscope with VimCscope with Vim List of cscope environment variables
You can manually generate a cscope file with a shell script
#!/bin/bash find ./ -name "*.[ch]pp" -print > cscope.files
cscope -b -q -k
Variables Description
CSCOPE_EDOTOR Editor to use: /usr/bin/vim
EDITOR Default: /usr/bin/vim
INCLUDEDIRS List of directories separated by :
SOURCEDIRS List of search directories separated by :
VPATH Same as above. If not set cscope will search in the current directory only
July 13, 2009 39Tusharadri Sarkar
Some more additional featuresSome more additional features
Sorting: 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. Now :'t,'b !sort
Moving columns, manipulating fields with awk:
't,. !awk '{print $3 " " $2 " " $1}' - This will reverse the
order of the columns in the block of text
July 13, 2009 40Tusharadri Sarkar
Some more additional featuresSome more additional features
Source code formatting in C++/Java: Use visual mode. Goto first line (Shift+v) then goto last line
(Shift+g) and then select ‘=‘
Text formatting: Use bookmark as above i.e. “mt” and “mb”. Now apply
the command # “:’t,’b !nroff
Spell checking: Same as above. Command # :’t,’b !spell You can undo the
changes by pressing u
July 13, 2009 41Tusharadri Sarkar
Configuring gVim of CygwinConfiguring gVim of Cygwin
Use the Xtreminal of Cygwin
Run Vim in GUI mode (gVim)
Customize Cygwin XTerminal
July 13, 2009 42Tusharadri Sarkar
gVim on CygwingVim on CygwinLocation of gVim in cygwin: /usr/bin/gvim.exeAlso you can find vim here: /usr/bin/vim.exeIn the login directory, create suitable aliases in
.bashrc ◦ alias gv=‘/usr/bin/gvim.exe’
Create a .gvimrc file in the same directory with your preferred options set
Launch the Xserver by command: startx from cygwin window. This will open the XTreminal
Launch the gVim from Xterm using your alias
July 13, 2009 43Tusharadri Sarkar
Configure your XTerminal: tipsConfigure your XTerminal: tipsYou can launch multiple XTerminal from one
XTerminal using command: xtermChange the default display setting of your
XTerminal:$ xterm -ls -bg <background> -fg <foreground> -title <Title> -fn '*<fontsize>*‘
$ xterm –ls –bg blue –fg azure –title <TITLE> –fn ‘*16*’
You can directly open the XTerminal using a set of options:$ rxvt -fn '*-courier-*-r-*-16-*' -sl 9999 -bg Black -fg Cyan -e /bin/bash –login
Best way would be to create one or more aliases of this in .bashrc file
July 13, 2009 44Tusharadri Sarkar
References:References:
• http://www.yolinux.com/TUTORIALS/LinuxTutorialAdvanced_vi.html
• http://vimdoc.sourceforge.net/htmldoc/intro.html• http://www.vim.org/• http://www.viemu.com/vi-vim-cheat-sheet.gif
July 13, 2009 45Tusharadri Sarkar
THANK YOU !!THANK YOU !!
And Happy Vimming…
July 13, 2009 46Tusharadri Sarkar