Vim is the most commonly used editor for traditional C/C++ developers working on Solaris/Linux platform till date. This is aimed at making a quick introduction to Vim editor, its configuration and a number of commands to fully unleash it's editing power.
Dadar West Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Vim Vi Improved
1. VIM – Vi Improved!VIM – Vi Improved!
Configuring and using VIM editor
By
Tusharadri Sarkar
July 13, 2009
IBM
July 13, 2009 1Tusharadri Sarkar
2. A Brief History of VimA Brief History of Vim
Vim is an improvement over the popular Vi editor
The Vi editor was developed by Bill Joy in 1976
“ed” was the original UNIX text editor
Bill 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 platform
GUI feature was added in 1996, gVim appeared
July 13, 2009 2Tusharadri Sarkar
3. 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 system
Support for extended regular expressions
Support for scripting languages (native: vimscript +
others: Perl, Ruby, Python, TCL etc.)
Support for plug-ins and a GUI (gVim) version
Limited IDE features and mouse interaction (for
both GUI and CLI versions)
July 13, 2009 3Tusharadri Sarkar
4. Features of VimFeatures of Vim
Editing capability of compressed or archived files
(.gzip, .bzip2, .zip and .tar files)
Editing capability of files over network protocols like
SSH, FTP and HTTP
Session state prevention
Spell checking
Splitting of windows (both horizontal & vertical)
Support for Unicode + other languages
Trans-session command
Syntax highlighting
Visual mode
July 13, 2009 4Tusharadri Sarkar
5. 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 keys
Automatic Keyword Completion
Character, line and block wise editing: The Visual
mode
Use multiple clipboards/buffers: No right clicks!!
Use macros: Record and replay multiple macros
Powerful command line editing
Customize Vim as you like it: Too many vim
options
July 13, 2009 5Tusharadri Sarkar
7. Configuring VimConfiguring Vim
Make 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
8. 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
9. :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
10. Each option has a short form
Using short form is convenient while
enabling/disabling any option for current session
:set number == se nu enables line number
To 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
12. 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 Text
Replacing Text
3. Execution Mode (Last Line Mode)
Saving
Exiting
Pattern matching and substitutions
Visual Mode (Only in Vim, mainly covers 2 & 3)
July 13, 2009 12Tusharadri Sarkar
13. 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
14. Vim: NavigationVim: Navigation
Keystroke 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
15. Vim: NavigationVim: Navigation
Keystroke 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
16. Vim: NavigationVim: Navigation
Keystroke 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
17. Vim: Inserting/Editing TextVim: Inserting/Editing Text
Keystroke 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
18. Vim: Inserting/Editing TextVim: Inserting/Editing Text
Keystroke Action
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
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
19. Vim: Inserting/Editing TextVim: Inserting/Editing Text
Keystroke 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 / Fc
Search 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
20. Vim: Inserting/Editing TextVim: Inserting/Editing Text
Keystroke 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
21. 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
22. Advanced editing: Multiple FilesAdvanced editing: Multiple Files
Command Function
:e abc Stop editing current file and edit file abc
:e! abc
Same 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
:n
Edit 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
:rew
Rewind 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
23. Advanced editing: Multiple WindowsAdvanced editing: Multiple Windows
This 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
24. 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!cmd
Insert 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
25. Pattern SubstitutionsPattern Substitutions
General 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
26. 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
27. 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
29. Some useful features of VimSome useful features of Vim
Vimdiff
Ctags
Cscope
July 13, 2009 29Tusharadri Sarkar
30. Vimdiff: Find the differencesVimdiff: Find the differences
To start vim in diff mode: vimdiff f1 f2 [f3 [f4]] or
Alternatively 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
31. Vimdiff: Find the differencesVimdiff: Find the differences
When 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
32. Vimdiff: Find the differencesVimdiff: Find the differences
Force 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
33. Vimdiff: Find the differencesVimdiff: Find the differences
Highlight 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
34. Vimdiff: Find the differencesVimdiff: Find the differences
Diff 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
35. 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
36. Ctags with VimCtags with Vim
Other 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 tag
Jump 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
37. Cscope with VimCscope with Vim
Cscope: Developed to cross-reference C code
It can also be used to with C++ and Java
Using cscope to cross reference source code
will create a database
Traverse 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
38. Cscope with VimCscope with Vim
To 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_stringsearch_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
39. 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
40. 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
41. 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
42. 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
43. gVim on CygwingVim on Cygwin
Location of gVim in cygwin: /usr/bin/gvim.exe
Also you can find vim here: /usr/bin/vim.exe
In 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
44. Configure your XTerminal: tipsConfigure your XTerminal: tips
You can launch multiple XTerminal from one
XTerminal using command: xterm
Change 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