Vamshi's notes on using Vi IMproved
#####################################
# Modified ; 10-03/2005, 5:50p
#####################################
Here are some of the vim commands which I find useful and use on a regular
basis. These are ordered based on how I discovered them (some I have
organized).
This document lists only advanced vim commands. So it will be really useful if
you know the basics of vi or vim, although its not required. Learning vim as an
extension of vi in general is not so helpful. Vim is far too big to learn
quickly and even to learn slowly. So the best way would be to learn it a bit at
a time and getting comfortable with it. Since you have gotten this far :), it is
very much possible. My 2 cents......
You can use the "Contents" section LINKS below to get around in this file.
##########################
# vim settings
##########################
":set mouse=a" to enable vim mouse support
######################
#***** Contents *****#
######################
* VIM7 - New Features
* Some_Useful_Shortcuts
* Pattern_Search_Commands
* Pattern_Search_and_replace_Commands
* Editing_Cleverly
* Getting Around Fast
* Formatting_Text
* Auto-indenting_commands
* A_useful_printing_option
* Inserting in the Standard Output
* Copying and Moving Text
* Substituting Text ....same as Patt....needs to be merged
* Selecting Text (Visual Mode)
* Comment Strings
* Folding_Lines
* Windowing
* Vimdiff_and_diff
* Ctags and Vim
* Make Compilations and Error Viewing
* Encryption
* Editing Remote Files
* Auto-Completion mode
* Using Macros
* Operating commands over several files, windows or buffers
* File characters info and status line settings
* Tabs and Spaces
* Use sessions to save state of work
* Register Contents : Useful insertions of work
* Helpfiles: local plugins
* Tracking and tracing your vim settings
* Numbering lines in a file
###########################
# VIM7 - New Features! #
###########################
Highlight Matched Pairs!
* On by default
':NoMatchParen' to turn off
':DoMatchParen' to turn on
Cursor line and more...
* You can turn on cursor line and cursor columns
':set cursorline'
':set cursorcolumn'
###########################
# Some_Useful_Shortcuts #
###########################
Accessing Command/Search history
* Pressing 'q:' or ':' gives the command history window (list of
previously executed commands in the current session)
* Pressing 'q/' or '/' gives the command history window (list of
previously executed commands in the current session)
* In both the above windows, you can scroll, search (use '/') and edit already typed commands/searches to make new ones.
* Close those windows by pressing
* ':q' closes window and places you back in the main window
* '' executes the command under the cursor and places you back in the main window.
It works both in insert and normal mode of the command/search window.
* '' closes the command/search window and allows you to go back to the command line.
* Insert Mode to Command Line (single operation) bypassing Normal Mode and back - While in Insert Mode press ''
and then use ':' or '/' to perform the respective operations.
* Insert Mode to Normal Mode (single operation) without using '' - While in Insert Mode press ''
and then use the Normal Mode key sequence (can do it only once, after which you are switched back to Insert Mode).
* Pressing Ctrl-p and Ctrl-n allows scrolling previous commands at the ':' prompt.
* 'ga' or ':as[cii]' on a single character will print its decimal/octal/hex values
* 'CTRL-D' lists all the complete option at the ':' prompt
* 'CTRL-L' completes if there is only one option available
* 'CTRL-L CTRL-D' does both the above
* We can remap the key to give bash-like behavior by typing
':cnoremap '
* Pressing '~' while on a character switches the character case.
Script Setting
---------------
':%s/^/\=line('.')."\t"/g' to insert line numbers in a file
Note: to highlight special keywords we can use the match option as
':hi ctermbg=red'
':mat //'
To clear these highlights do
':mat[ch]'
#############################
# Pattern_Search_Commands #
#############################
* We can use the '*' key to search for text under the cursor in the forward
direction. This searches only whole words. If you would like to search for
any pattern (not only whole words) then use 'g*'.
* We can use the '#' key to search for text under the cursor in the reverse
direction. If you would like to search for any pattern use 'g#'.
* 'q/' gives the search history window
* '/\|' search for multiple patterns using OR '\|'
* Show lines matching word under cursor '[I'
Some Regular expression used by Vi/Vim:
---------------------------------------
'^' matches the beginning of line
'$' matches the end of line
'.' matches a single character
'*' matches 0 or more ocurrences of the preceding character
'.*' represents multiple characters till the end of line
'\<' matches the beginning of a word
'\>' matches the end of a word
'[chars]' matches the chars in the enclosed set
'[^chars]' matches the chars not in the enclosed set
* Searching for whole words can be done by using '\<' and '\>' in your search
* '/begin.*middle.*end' searches a sentence which has begin, middle, end as
keywords
Useful Settings for Pattern Search
----------------------------------
":set ignorecase" turns ignore case on
"/\c" can be used to turn on ignore case temporarily for that
particular search (the "\c" can appear anywhere in the pattern)
#########################################
# Pattern_Search_and_replace_Commands #
#########################################
Note: We can comment (# )code from lines 12 to 31 in a perl program by using
the following command
:12,31 s/^/# /
If you want to comment the next 3 lines from the current cursor position
:.,+2 s/^/# /
To uncomment we can do the following
:.,+2 s/# //
We can use the visual commands 'v' or 'V' to get the lines which we want
to comment. To do this go into visual mode by using either 'v' or 'V' and
then press ':' and type away!!!
Some 'ex' commands that can be executed in Vi:
----------------------------------------------
'g' means Global or sometime search global
'p' means print
'%' => operate on the whole file; synonym or abbrev. of 1,$
'^' means the beginning of a line
'/$/' means end of line (ie the symbol '$')
'$' in a seach expression means the last line of file
's' mean Substitute
'c' means Confirm
* typing ':g//p' searches and prints all lines containing
at the bottom of the screen
* Typing ':g!//p' searches and prints all lines not containing the
at the bottom of the screen
* ':, g//p' searches and prints lines containing
from line number to line number
* ':g//s///g' does two operations at once. It
searches for '' in the whole file (ie globally search as indicated
by the first g) and then it changes to globally on that
line.
* ':%s///g' replaces with in the entire
file ('%') without any confirmation.
Other similar patterns:
& ':s///g' replace every occurrence of
with on the current line
& ':s//' replace only the first occurrence of
with on the current line
& ':s//~' repeats the previous replace on another line
& ':&' or ':s' repeats previous substitute or replace command on the
current line (works same as the above command)
& ':40,99 s///g' replace every occurrence of
to from line 40 to line 99
& ':%s///gc' replaces every occurrence of with
while asking for confirmation at each replacement. Answer 'y' to
make the replacement and /n for no replacement.
* ':s' unconditionally repeat previous string replace or ':sc' means repeat
previous string replace with confirm
* ':1,$ s/[ ]*$//' is useful to trim blank spaces at the end of every
line
* ':%s:/dir1/dir2/dir3/file:/dir1/dir4/dir5/file1:gc' Using a another
separator ":" is useful when doing file path search and replace. This way
you don't have to escape every "/" with "\/".
Visualizing invisible characters (white space and tab):
-------------------------------------------------------
Other extra info:
'$' indicates EOL
'^I' indicates tabspace
To visualize non-printing control characters hidden in a file, do
':set list'
':set nolist' #toggles back to normal mode
To visualize on a particular line, do
':l[ist]'
':l%' visualize control characters on all lines
######################
# Editing_Cleverly
######################
Deleting
'dd' deletes an entire lines of text
'D' deletes an entire line of text without erasing the line
'dw' delete from current cursor position to the end of word including
white space
'd%' deletes by parenthesis matching. very useful in code
'd)' delete from cursor to end of sentence
'"_d' delete (using register) without destroying default buffer contents
"'_d' delete word without destroying default buffer contents
Change
'cc' change current line
'C' change a line from current cursor position to the end of line
Swap
'xp' swap char under the cursor with the next char
'dwwP' swap words (only works if there is atleast another word after the
next word
'ddp' swap current line with the next line
Shift
'9>>' shift current line and next 8 lines to right shiftwidth spaces
'9<<' shift current line and next 8 lines to left shiftwidth spaces
Join
'J' join current and next line
'9J' join current and next 8 lines
':j!' retain leading white space when joining lines
':j! 9' retain leading white spaces when joining current and next 8 lines
#########################
# Getting Around Fast #
#########################
Moving by Screens
Other than the basic commands h, j, k, l to move left, up, down, right
respectively there are other commands which help you move really fast in vim.
'ctrl-f' scroll forward one screen
'ctrl-b' scroll backward one screen
'ctrl-d' scroll forward half screen
'ctrl-u' scroll backward half screen
Moving within a Screen
'H' Move to top of screen
'M' Move to middle of screen
'L' Move to end of screen
Repositioning the Screen
'z' Move current line to top of screen
'z.' Move current line to center of screen
'z-' Move current line to bottom of screen
#####################
# Formatting_Text #
#####################
Word Wrapping for viewing
Generally Vim wraps long lines breaking them at the last character to fit
on screen. But if you would like to view a file with long lines wrapped at
words then use the following commands. This only affects teh way the file is
displayed, not its contents.
':set lbr' or ':set linebreak' wraps long lines (view only)
':set nolbr' or ':set nolinebreak' turns off word wrapping
Spacing setting, permanently Word Wrapping (add EOL in the file) & Aligning
':gq' or 'gq'
'gqgq' or 'gqq' formats the current line
':gqap' - formats the current paragraph
":ce" centers a line
":le" left justifies a line
":ri" right justifies a line
CaSe FOrmaTting
"~" swaps the cAse of a single character
"g~~" toggles the case of an entire sentence
'guu' or 'Vu' makes an entire sentence lowercase
'gUU' or 'VU' makes an entire sentence UPPERCASE
'vE~' flip case word
'vEU' upper case word
'vEu' lower case word
'ggguG' lower case entire file
#############################
# Auto-indenting_commands #
#############################
'Code auto-indenting can be turned on by doing ':set ai''
Note: If the autoindent option is on, vim uses the indent of the first line
for the following lines
'=}a' or '=a}' re-indents the current {.....} block relative to how
the {, } have been indented
General key syntax '='
'==' indents the current line according to the above
'==' indents n lines
'1G=G' re-indents the whole file
'Vjjj=' visually marks 4 lines and re-indents them
Other keywords to be explored cindent, cinkeys, cinoptions,
cinoptions-values
'>>' indents the current line
'[Visual] =' indents the current visual block
Note: If you like to see vertical indenting just like in editors like ....., do
':set list'
':set listchars=tab:\|\ ' notice the last space
or
':set lcs=tab:\|\ ' notice the last space
##############################
# A_useful_printing_option #
##############################
To create a page break which is only recognized during printing - in
Insert mode press CTRL and L. '^L; will appear in your text. This will cause
the printer to start priting on a new page from that point.
6. Inserting in the Standard Output
-----------------------------------
Normally to read in a file we use ':r '.
To execute a command and insert its standard output below the cursor, do as
':r! {cmd}'
The command can be anything like sort, ls etc
7. Copying and Moving Text
--------------------------
"{a-zA-Z0-9.%#:-"} Use register {a-zA-Z0-9.%#:-"} for next delete, yank or put
(use uppercase character to append with delete and yank) ({.%#:} only work
with put).
:reg[isters] Display the contents of all numbered and named registers.
:reg[isters] {arg} Display the contents of the numbered and named registers
that are mentioned in {arg}.
:di[splay] [arg] Same as :registers.
["x]y{motion} Yank {motion} text [into register x].
["x]yy Yank [count] lines [into register x]
["x]Y yank [count] lines [into register x] (synonym for yy).
{Visual}["x]y Yank the highlighted text [into register x] (for {Visual} see
Selecting Text).
{Visual}["x]Y Yank the highlighted lines [into register x]
:[range]y[ank] [x] Yank [range] lines [into register x].
:[range]y[ank] [x] {count} Yank {count} lines, starting with last line number
in [range] (default: current line), [into register x].
["x]p Put the text [from register x] after the cursor [count] times.
["x]P Put the text [from register x] before the cursor [count] times.
["x]gp Just like "p", but leave the cursor just after the new text.
["x]gP Just like "P", but leave the cursor just after the new text.
:[line]pu[t] [x] Put the text [from register x] after [line] (default current
line).
:[line]pu[t]! [x] Put the text [from register x] before [line] (default
current line).
7. Substituting Text
---------------------
:[range]s[ubstitute]/{pattern}/{string}/[c][e][g][p][r][i][I] [count] For each
line in [range] replace a match of {pattern} with {string}.
:[range]s[ubstitute] [c][e][g][r][i][I] [count] :[range]&[c][e][g][r][i][I]
[count] Repeat last :substitute with same search pattern and substitute
string, but without the same flags. You may add extra flags
The arguments that you can use for the substitute commands:
[c] Confirm each substitution. Vim positions the cursor on the matching
string. You can type:
'y' to substitute this match
'n' to skip this match
to skip this match
'a' to substitute this and all remaining matches {not in Vi}
'q' to quit substituting {not in Vi}
CTRL-E to scroll the screen up {not in Vi}
CTRL-Y to scroll the screen down {not in Vi}.
[e] When the search pattern fails, do not issue an error message and, in
particular, continue in maps as if no error occurred.
[g] Replace all occurrences in the line. Without this argument,
replacement occurs only for the first occurrence in each line.
[i] Ignore case for the pattern.
[I] Don't ignore case for the pattern.
[p] Print the line containing the last substitute.
################################
# Selecting Text (Visual Mode) #
################################
To select text, enter visual mode with one of the commands below, and use
motion commands to highlight the text you are interested in. Then, use some
command on the text.
'v' start Visual mode per character.
'V' start Visual mode linewise.
'' exit Visual mode without making any changes
'gv' re-select the previous visual area
The operators that can be used are:
~ switch case
d delete
c change
y yank
> shift right
< shift left ! filter through external command = filter through 'equalprg' option command
gq format lines to 'textwidth' length
################################
# Comment Strings #
################################
Comment strings can be viewed by typing ':set comments'
###################
# Folding_Lines #
###################
Folding is a very nice feature when you are viewing large coding. By pressing
"zc" we can create a fold.
foldmethod
###############
# Windowing #
###############
Vim supports multiple windows.
Windowing
':sp[lit] ' or ':sf[ind] ' or 'ctrl-w ctrl-s' or
'ctrl-w s'
Used to split the window horizontally. Note that the command line way
of splitting has an extra option which makes it more
powerful. You can search for the file according the 'wildmode' option set.
':vs[plit] ' or 'ctrl-w ctrl-v' or 'ctrl-w v'
Used to split the window veritically. Command line options are more
powerful since they allow you to specify a file name.
':clo[se][!]' or 'ctrl-w ctrl-c' or 'ctrl-w c'
Closes the current window. The ! is used to forcebly close/hide a
buffer. In the case its get closed, the changes are lost
':q[uit][!]' or 'ctrl-w ctrl-q' or 'ctrl-w q'
Quits current window. If its the last window and ! is used, the
changes to the buffer are lost.
':on[ly]' or 'ctrl-w ctrl-o' or 'ctrl-w o'
Displays only the current window. Hides the rest if the hidden option
is set.
Navigating
######################
# Vimdiff_and_diff #
######################
To diff between two files
'vimdiff ' / 'vim -d '
This sets the following options in each of the files
'diff' on
'scrollbind' on
'scrollopt' includes "hor"
'wrap' off
'foldmethod' "diff"
'foldcolumn' 2
Navigating -
"[c" will go to the line of the next difference
"]c" will go to the line of the previous difference
Other Commands:
To start up diff mode against a file with another opened file in vim
':[vert{ical}] diffsplit '
If two files are already open and if you want to start the diff mode then
':diffthis'
in both the files. This sets all the above options for each of the files.
':diffpatch ' can be used to apply a patch to the current file and
open a buffer on the result. ':vert' can be prepended to this to get the buffer
in a vertical window.
':diffu{pdate}' can be used to force the differences to be updated
#################
# Ctags and Vim #
#################
Vim works with the 'ctags' function which makes it very easy to jump to
functions and variables.
'ctrl-]' can be used to jump to a function/variable definition
'ctrl-t' can be used to jump back
Before being able to use the above you need to generate a tags file using
'ctags '.
##################################
# Make Compilations and Error Viewing #
##################################
Vim can compile with ":make" using a makefile. In addition to this you can
browse the errors with the ":cn" and ":cp" options.
In this mode it becomes difficult to view more than single line error
messages. You can open up an error window by doing
":cope 8" where 8 is the number of lines show in the error window.
Now you scroll the errors using the ":c" commands which the errors are
being highlighted in the error window.
To close the error window, do ":ccl"
######################
# Encryption
######################
Missing data here.........
######################
# Editing Remote Files (A very useful feature for me!!!!)
######################
You can use scp, ftp, rcp, http to edit remote files. So when you write back
to a file it gets saved to the remote location
"vim scp://user@hostname/path/file"
This leads to a lot of other good stuff :).
"vimdiff file1 scp://user@hostname/path/file2"
(Compare files on remote systems)
######################
# Auto-Completion mode
######################
Auto-completion (CTRL-X) can be used in the 'insert' mode. Using
auto-completion, we can do (in combination with CTRL-X)
- Keyword Local Completion (CTRL-N/CTRL-P),
- Whole line completion (CTRL-L),
- File name completion (CTRL-F),
- Pattern path completion (CTRL-I),
- Definition completion (CTRL-D),
- Command line completion (CTRL-V)
###############
# Using Macros
###############
'qa' starts recording the macro 'a'
'q' stops recording the macro
'@a' repeat the macro number of times
One way to use this is to create a number list
insert 1
'qa'
'yy'
'p'
'CTRL-A' on the new line to convert the 1 to a 2
'q'
'20@a' and voila! You have number 1 to 22 pasted in your file
So typically the keysequence would be 'i, 1., [esc], qa, yy, p, [CTRL-A], q, 20@a'
############################################################
# Operating commands over several files, windows or buffers
############################################################
Three commands can be used to apply commands over multiple files
':argdo'
':windo'
':bufdo'
'argdo' applies a commands on all the files indicated by the 'args' command
':args *.[ch]'
':argdo %s///ge | update'
The 'e' option suppresses errors if is not found in a
particular file. And 'update' updates the file before moving on (otherwise
you get the file modified error).
############################################################
# File characters info and status line settings
############################################################
'Ctrl-g' or ':f[ile]' can be used to extract file information like file name, cursor
position (in terms of %, filename with path, file status and number of lines
in file ).
'g Ctrl-g' gives the number of lines, words and character in a file just like
the 'wc' command in UNIX
'{visual} g Ctrl-g' works for the selected region.
To more the status line more informative, do the following setting
'set statusline=[%n]\ %<%f\ %((%1*%M%*%R%Y)%)\ %=%-19(\LINE\ [%3l/%3L]\ COL\ [%02c%03V]%)\ ascii['%02b']\ %P '
##################
# Tabs and Spaces
##################
An endless argument in editors is whether to insert tabs or spaces while
writing code. In order to satisy people on both sides, vim can be set to do
exactly what people want. The 'expandtab' option when unset inserts tabs when
you press the key and when set inserts spaces.
':set expandtab' - for spaces
':set noexpandtab' - for tabs
For people trying to meet the people on the other side, we can do the
following steps to..
1) Convert tabs to spaces
-------------------------
':set expandtab'
':%retab!'
2) Convert spaces to tabs
-------------------------
'set noexpandtab'
':%retab!'
In order to visualize the above actions, it is useful to do ':set list'
which turns on invisible characters (spaces, tabs, end of line etc).
#####################################
# Use sessions to save state of work
#####################################
In vim, it is easy to create a session file which stores the views for all
windows and also the global settings, so that you can restore the state of
your work later on in the future. You can easily start editing at a previously
saved state/views by using the '-S' arguement as
'vim -S session.vim'
To create a session at some point, you can use the command
':mks[ession][!] '
This creates a vim script which can be used to restore state/views later.
If the file name is not given, it uses a default name "Session.vim". The '!'
can be used to overwrite an existing file.
#####################################
# Register Contents : Useful insertions of work
#####################################
You can insert some contents of the registers used by vim which are very useful.
'i_ctrl-r_%' inserts current file name
'i_ctrl-r_=' and insert an equation which will be evaluated and its result placed at the current cursor position
#####################################
# Helpfiles: local plugins
#####################################
Local plugin help files can be created and accessed as...
':helptags ~/.vim/doc' generates local tags file for local plugin help
':help local-additions' shows you the entries for the local help file
':help ' takes you to the local help
#####################################
# Tracking and tracing your vim settings
#####################################
Sometimes it becomes such that settings get overidden, settings you don't want
get set (mostly in default files and you don't even know it) or settings get
sourced twice. For such things, I figured out a couple of things that can help
you know what's going on. It drives me crazy when I don't know what's going
on!!!
The 'set' options can be traced as follows
':verbose set ' - this helps trace from which file this option has been set
We can figure out for a particular group what 'autocmd' has been set
':autocmd ' - this shows all that has been set for a particular group & filetype
#####################################
# Numbering lines in a file
#####################################
A neat filtering trick using the 'nl' linux/unix program.
':%! nl -ba' - this helps trace from which file this option has been set