Vi
Related Pages
This page is about the editor vim itself. The other related pages are
- Vimrc, which is dedicated to vim configuration settings and to the file ~/.vimrc.
External Links
General
- Official vim homepage
- Vim Tips Wiki
- Vim documentation: help
- Vim documentation: map
- My links on vim on del.icio.us
- List of all commands for each mode:
:help index
Other General
- Vi Lovers home page
- Good post explaining why vi is superior and defeating common misconception (with examples).
- Vi would not be vi without a bit of fun...
Cheat sheets
- Very good graphical keyboard cheatsheet
- Another compact & complete cheatsheet (as folded reference card).
- Real Short Vim Normal-Mode List of Commands (from Dr Chip's)
Guides & Cheat sheets
- New To Vim
- Quick Tips
- Avoiding the ESC key
- Vim map tutorial
- Dr Chip's Vim Page — A tremendous amount of Vim treasures from an expert user
- Efficient editing with vim
- C editing with VIM HOWTO
- Using vim as an IDE all in one
- Browsing programs with tags
- Using Bash completion with ctags and Vim
- Alternative tab navigation
- Seven habits of effective text editing (from author of Vim)
Vim in Windows/Cygwin
- Use cygwin shell
- Running the Win32 version of Vim from Cygwin
- cyg-wrapper.sh
- FAQ / 33.6 What are the recommended settings for using Vim with cygwin?
- Using Cygwin Bash as your Win32-Vim shell
- A patch to use Win32 clipboard under Cygwin ([1], [2])
Tips
- Use Ctrl-O instead of Esc in insert mode mappings
- How do I indent multiple lines quickly in vi?
- Replace a word with yanked text
Here we learn that Deleting, Changing and Yanking text copies the affected text to unnamed buffer ("").
But Yanking text also copies the text to buffer 0 ("0) - Search and replace the word under the cursor
- Find in files within Vim
About commands:grep
,:lgrep
,:vimgrep
,:lvimgrep
- Power of g
Examples on how to use the command:rg/pattern/cmd
- Keystroke Saving Substituting and Searching
- Quickly adding and deleting empty lines
- Very basic session persistence
Using mksession! and :au VimLeave...
Plugins (installed)
- snipMate : TextMate-style snippets for Vim
- a.vim : Alternate Files quickly (.c --> .h etc)
- AutoTag : Updates entries in a tags file automatically when saving
- surround.vim : Delete/change/add parentheses/quotes/XML-tags/much more with ease
- tComment : An extensible & universal comment plugin that also handles embedded filetypes
- mru.vim : Plugin to manage Most Recently Used (MRU) files
- Smart Tabs : Use tabs for indent, spaces for alignment
- See also Indent with tabs & align with spaces
- cpp.vim: General C++ Settings (no indentation for namespace...) (disabled highlight of leading tabs, line length overruns, unit test header test + nice
- diffchanges.vim : Show changes made to current buffer since the last save
- CScope
- See the tutorial here
- Cscope on Vim Wiki
- One can also use cscope and ctags together
- ClosePairs : Auto closes pairs of characters (simpler than AutoClose, and can also delete pair of braces at once with <BS>)
- minibufexpl.vim : Elegant buffer explorer - takes very little screen space
- 1st attempt: No real tab support. Seems to interfere with trinity plugin. Interesting key bindings inside though. To reassess...
- 2nd attempt: Don't care about tabs, the idea is to fully replace tabs with buffers since most plugins interface better with buffers. Disabled trinity plugin.
- Closing a buffer: Use d in minibufexpl window to close a buffer, or :bd[elete] seems to work most of the time.
- Some interesting links after a Google query:
- MiniBufExplorer questions (closing a buffer, making it invisible, etc.) (use d in minibufexpl, :set hidden to navigate to other buf even if current modified)
- Can we remap :q to :bd only when 2 or more buffer opened?
- Someone working on improving minibufexpl (v6.4)
- StackOverflow - An alternative to minibufexplorer (vim)?: see Vim BufStat, bufstat tips,
- StackOverflow - MiniBufExplorer and NERD_Tree closing buffers unexpected behavior: See tip165 - bclose + custom mapping below, :bd might just be good enough though...
- LustyExplorer : Dynamic filesystem and buffer explore
- LustyJuggler: Switch very quickly among your active buffers
{{{content}}}
AlterColour
function that computes new colour...)
" GRB: use fancy buffer closing that doesn't close the split
cnoremap <expr> bd (getcmdtype() == ':' ? 'Bclose' : 'bd')
Plugins (not yet installed)
- OmniCppComplete : C/C++ omni-completion with ctags database
- c.vim : C/C++ IDE -- Write and run programs. Insert statements, idioms, comments etc.
- winmanager : A windows style IDE for Vim 6.0 (Referenced in TagList plugin help)
- bufexplorer.zip : Buffer Explorer / Browser
- neocomplcache : Ultimate auto completion system for Vim
- FuzzyFinder : buffer/file/command/tag/etc explorer with fuzzy matching
- matchit.zip : extended % matching for HTML, LaTeX, and many other languages
- project.tar.gz : Organize/Navigate projects of files (like IDE/buffer explorer)
- AutoClose : Auto close pair of characters (Another version with same name than the one I tried below)
- See also dedicated tip entry: Automatically append closing characters
- SuperTab continued : Do all your insert-mode completion with Tab
Some videos that illustrates those plugins:
- Top Vim Plugins (YouTube), showing Surround, SnipMate, TComment, MRU, FuzzyFinder, NerdTree, MatchIt
Plugins (uninstalled)
- easytags.vim : Automated tag file generation and syntax highlighting of tags in Vim
- Replaced by AutoTag — syntax highlighting of tags is limited to c files; moreover AutoTag has a clever way to look for the tags file in project hierarchy.
- AutoClose : Inserts matching bracket, paren, brace or quote
Don't like it much because inserting the closing pair will jump out of nested pair, which is annoying when one try to simply insert a closing brace (but a solution is to use the Surrond plugin to surround some selected text with braces). - trinity.vim : Build the trinity of srcexpl, taglist, NERD_tree to be a good IDE
- Source Explorer (srcexpl.vim) : A Source code Explorer based on tags works like context window in Source Insight
- taglist.vim : Source code browser (supports C/C++, java, perl, python, tcl, sql, php, etc)
- The NERD tree : A tree explorer plugin for navigating the filesystem
{{{content}}}
{{{content}}}
{{{content}}}
Vimrc examples
- https://github.com/mitechie/pyvim (author of the screencast on LustyJuggler)
Invocation
vi -p file1.txt file2.txt # Open each file in a different tab
vi -t tagname # Open file and move cursor at specified tag (requires ctags)
view file.txt # View file in vim, with syntax highlighting... (read-only)
vimdiff file1.txt file2.txt # View differences in vim
The following is a description of the start up sequence as I understood by experience. It's certainly far from complete. For more information:
:version
:echo $HOME
:echo $VIM
:set runtimepath?
:help vimrc
:help gvimrc
:help runtimepath
- First, load the system config files:
- Second, load the user config files:
- Search for runtime files in path 'runtimepath'. Basically vim looks for directories in that path for further runtime files to execute (see
:help runtimepath
for more information)
File | description | OS | Location |
---|---|---|---|
vimrc | System config file for vim and gvim | Unix & Win | $VIM/vimrc |
gvimrc | System config file for gvim only | Unix & Win | $VIM/gvimrc |
File | description | OS | Location |
---|---|---|---|
vimrc | User config file for vim and gvim | Unix | $HOME/.vimrc |
Win | $HOME/_vimrc | ||
gvimrc | User config file for gvim only | Unix | $HOME/.vimrc |
Win | $HOME/_vimrc |
Windows
- Tab Edit with &Vim — The following registry setting add a context menu item in explorer to open a file in a new tab in a running instance of gvim (see [3]):
- Share config with Cygwin — To have win32 gvim and cygwin vim, use the same config files
- Simply define the env. var HOME to point to user home in cygwin:
- Create the file C:\Program Files\Vim\vimrc (system vimrc file for windows)
- Enable Ruby support — there is a bug in Vim7.3_46 that crashes vim when ruby is loaded. This is fixed in a later release [1]. Install:
REGEDIT4
[HKEY_CLASSES_ROOT\*\Shell\Tab Edit with &Vim\command]
@="\"C:\\Program Files\\vim\\vim71\\gvim.exe\" -p --remote-tab-silent \"%1\" \"%*\""
HOME=c:\cygwin\home\username
set runtimepath-=~/vimfiles
let tmp=&runtimepath
let &runtimepath="~/.vim,".tmp
Win32 gvim will read the standard configuration files .vimrc and .gvimrc (although this is not reported by :version
). It will also fetch the plugins from cygwin home directory.
Check also potential goodies Vi#Vim_in_Windows.2FCygwin above.
Managing Options
See :help options
for more details
"Show all options that differ from default
:set
"Show value of {option}
:set {option}?
"Set {option} to value
:set {option}={value}
"Add value to {option}
:set {option}+={value}
Scripting
Some basic stuff on Vim scripts:
# let is for variables
let myvar="Hello"
echo myvar
let myvar=call func(param1,param2)
# set is for vim options:
set runtimepath=~/.vim # set option
set runtimepath? # read option
# let <-> set
let myvar='batch'
let &filetype=myvar # &{option} returns option value in an expression
echo &filetype
if &filetype == 'java'
...
endif
# But these does not give the same:
set runtimepath? # No expansion
echo &runtimepath # Expansion occurs
# Another example, use variable to prepend a path to runtimepath:
set runtimepath-=~/vimfiles
let tmp=&runtimepath
let &runtimepath="~/.vim,".tmp
Simple C/C++ IDE using plugin TagList
Thanks to plugin TagList, it is possible to turn Vim into a simple yet efficient development IDE. The basic idea is to use the TagList window as a simple file explorer. We use a session file to add all files in the project to the TagList window. For C/C++ projects, we add our common settings/mapping defined in our cpp.vim.
Here an example session file project.vim:
" Project specific settings
set tags=./tags
TlistAddFiles src/*.cpp
TlistAddFiles src/*.h
" Source our custom cpp script
source ~/.vim/cpp.vim
" Session Persistence
au VimLeave * mksession!
set sessionoptions+=blank,buffers,curdir,folds,help,options,resize,tabpages,winpos,winsize
" Find in files
command! GREP :execute "grep -R <cword> ./src"|:cw
source Session.vim
Create the tag and cscope files:
ctags -R .
cscope -Rb
Then start the IDE session with:
gvim -S project.vim
Alternatively, one can use the filename Session.vim, and use the shorter command gvim -S
.
Use the mappings A-Up / A-Down to switch the current window to the next/previous file. These mappings simply move and center the cursor in the TagList window to the previous/next file, open the file and put the cursor to its last position.
To build the project (assuming you have a valid Makefile in the project directory), just issue the command
:make
To easily navigate between the compilation errors, open the quickfix window:
" Open the window when there are compilation errors:
:cw
" Or open it always:
:cope
Finally you can run the program directly from Vim with:
:!./bin/myprogram
"To repeat the last :!{cmd}, do:
:!!
Persistent session
Using :mksession
one can save the current session state for later:
" Save session in Session.vim
:mksession
" Save session in lastsession.vim
:mksession lastsession.vim
For ease add the following lines at the end of our project.vim:
set sessionoptions+=blank,buffers,curdir,folds,help,options,resize,tabpages,winpos,winsize
source ./Session.vim
Now start editing with:
gvim -S project.vim
And before quiting Vim, do:
" Overwrite! Session.vim and quit
:mksession!
:wqa
This can be done automatically (see [4]). Add to your configuration file either of these autocmd:
" Update the session file only if one already exists
au VimLeave * if v:this_session != "" | exe "mksession! " . v:this_session | endif
" Or always save the session file
au VimLeave * mksession!
Keyboard & Mouse Shortcuts
- ! If keys HJKLM have been remapped to MHJKL, shortcut below must be changed accordingly !
- Mouse shortcuts requires
:set mouse=a
. - Customer shortcuts are underlined
Define new shortcuts
- Note that not all combinations are possible (see [5] and
help :keycodes
)- S-b and S-B are the same
- C-b and C-b (both mean 0x02)
- A-b and A-B are different, but are represented by vim by setting the high bit (0x80), so A-b is same as 'â', and A-B is same as 'Â'
- Note that GUI Vim some Alt key shortcuts select the menu. To disable that:
set guioptions-=m
Custom Cheatsheets
Plugin Cheatsheet
:A |
Switch between header / source file |
{{ |
Insert & push closing brace down a new line |
^,s ^Spaces |
symbol: Find all references to token, split |
Leaderdcd |
DiffChangesDiffToggle |
:MRU |
Open MRU file list |
cs"' |
Change surrounding " to ' |
[[ or BS |
Previous file |
gcm |
Toggle comments motion |
^^ or ^6 (azerty) |
Edit alternate buffer (#) |
Cheatsheet
^W_ ^W| ^W= |
Max. h/w current window or tile |
MouseL |
Jump to tag |
^U |
Remove auto-range (:help omap-info )Insert register / object ( |
^Space |
Same as Esc, but easier (see [6]) |
n^O |
Go to n older pos. in jump list |
Operator & motion
Operators in Vim acts
- on the current selection (visual mode like v, V or ^v) when there is such a selection,
- or must be followed by a motion indicating which part of the text must be modified.
Operators
|
The motion is either one of the motion key (like >% for shift right until match) or an operator motion (like diB for delete inner {} block). See :help operator.
Frequently-used operator motion
iw iW |
inner word inner WORD |
aw aW |
a word a WORD |
i[ ib i( |
inner [] block inner () block |
a[ ab a( |
a [] block a () block |
i" i' |
inner "" string inner '' string |
a" a' |
a "" string a '' string |
Commands
" Search & replace - current line
:s/search/replace/g
" Search & replace - global scope
:%s/search/replace/g
" Set Vim option (here textwidth)
:set {option}=70
" Show value of {option}
:echo &{option}
:set {option}?
" Search / replace in all opened buffers
:bufdo %s/pattern/substitution/ge | update
" Replace current line with register content
VP
Tips for Efficient Editing
- Substitute current line — Use S ( or cc) to replace the current line, while keeping current indentation (instead of ddO to delete current line and open new one)
- Quick variable renaming — Use the following mapping to search for last deleted word
- Rename a variable with ciw for instance, and type the new variable name (use ^R- to start from old name)
- Look for next occurent of the replaced variable with F3 (or ù)
- Repeat replacement with . (dot key)
- Repeat from step 2 (or use n), or N for previous occurrence.
" F3 (an improved UltraEdit F3 ;-) ) search for next occurrence of replaced word (actually register -) - handy for refactorizing code
" Also mapped to ù (AZERTY power!)
nnoremap <F3> /\<<C-R>-\><CR>
nnoremap ù /\<<C-R>-\><CR>
Using this mapping, one can:
This tip works better than using range:s/pattern
, because you don't have to type the name of replaced variable, nor use the word delimiter \<
...\>
, and you don't have to specify a range in advance.
Miscellaneous Tips and Tricks
- Inserting only a single character (http://vim.wikia.com/wiki/Insert_a_single_character):
- Macro
- qq to start recording a macro q. End macro with q again.
- @q to replay macro, followed by . to replay it again.
- Visual Block
- Ctrl-v to start VISUAL BLOCK mode.
- Shift-I to insert some text at the start of each line of selected block.
- wrap-around
- Set option whichwrap or ww that allows specified keys that move the cursor left/right to move to the previous/next line when the cursor is on the first/last character in the line.
- In Vim, <space> and <backspace> are set to wrap-around by default.
- Read-only viewer (with syntax highlighting):
- Retab To convert tabs in current file to current tab settings, use command
- View differences in vim
- Interaction with X Clipboard vim can use the X clipboard if it has been compiled with the clipboard feature (run
set incsearch
, moves cursor as search pattern is typed. Ctrl-L to type letter under cursor, Ctrl-R Ctrl-W to type current word.- References: http://vim.wikia.com/wiki/Best_Vim_Tips
- type
:help ctrl<C-D>
, to get a list of all ctrl sequence. Type <C-D> in command line for auto-completion. - Support 256 colors in gnome-terminal: add
set t_Co=256
in ~/.vimrc ([8]) - Use
:make
and:grep
instead of:!make
or:!grep
. Then use:cwin
or:copen
to view the results of either make or grep in a coloured list (from [9]). - (from [10]), The
:g
command is useful to apply a command to all lines matching a search. - Write the following in files ~/.vim/after/syntax/c.vim and ~/.vim/after/syntax/cpp.vim (or symlink) to highlight C/++ delimiters (see [11]):
- Replace a word with yanked text (see tip [12])
- Quickly switch between opened buffers. The commands
:b
and:sb
accepts partial buffer name when specifying which buffer to edit: - Various command to interact with the shell:
- Save a file you edited without the needed permissions (source [13])
- Delete all trailing spaces ([14]):
- Promote window to tab (see [15])
- Find in files within Vim (commands
:grep
,:lgrep
,:vimgrep
,:lvimgrep
)
Define this custom command to quickly look for current word, and displays the quicklist window:
- Use
:E[xplore]
for explore directory of current file (from netrw)
:nnoremap <space> :exec "normal i".nr2char(getchar())."\e"<CR>
$ vi -R sensitive_file
$ view sensitive_file
:retab
[7]. For instance to convert tabs into space
:set expandtab
:retab
vimdiff file1.txt file2.txt
vim --version
and see if you have +clipboard in the output). In that case, yanking to the +
register, or simply selecting with the mouse, will actually copy in the X clipboard, hence allowing other applications, or even other instances of vim to exchange text snippets. Also, it will ease the copy-paste of indented text, since in that case, vim will first disable autoindentation before pasting the text (see option paste
).
On system like Ubuntu, you need to install an instance of gvim (like package vim-gnome or vim-gtk) to have feature +clipboard
turned on (i.e. installing package vim is not enough).
When set mouse=a
, use shift-mouse to still use the xterm copy/paste (see mouse-using).
:set paste " Enable paste mode, i.e. disable autoindent, mapping... "
:set nopaste " Disable paste mode (back to normal...) "
" delete all lines matching pattern
:g/pattern/d
" delete all lines *NOT* matching pattern (:v same as :g!)
:g!/pattern/d
:v/pattern/d
syn match cDelimiter "[&\.!^,;:<>=|+%*-]"
syn match cParenDelimiter "[][(){}]"
hi def link cDelimiter Delimiter
hi def link cParenDelimiter Delimiter
yiw " Yank word under cursor "
... " Move to next word "
viwp " Replace current word with yanked text. "
...
viwp
...
:ls " List buffer list, say you have a file verylongfilename_spec.c and anotherverylong_code.c"
:b spec " Will switch to buffer verylongfilename_spec.c"
:sb code " Will split the window and switch to buffer anotherverylong_code.c"
:!{cmd} | Execute {cmd} with the shell. |
:!! | Repeat last ":!{cmd}". |
:[range]r[ead] !{cmd} | Execute {cmd} and insert its standard output below the cursor or the specified line. |
:[range]w[rite] [++opt] !{cmd} | Execute {cmd} with [range] lines as standard input. |
:w !sudo tee %
:%s/\s\+$// " Remove all trailing spaces
:%s/\s\+$ " We can omit substitution text if blank
Add this to .vimrc to have vim remove automatically trailing spaces before saving
autocmd BufWritePre * :%s/\s\+$//e
:noremap <C-W>t :tabedit <C-R>%<CR>gT<C-W>qgt
" We must embed :grep in :execute or otherwise vim will append /dev/null
" to :cw command and will complain of E488: trailing characters
command! GREP :execute "grep -R <cword> ./src"|:cw
Command-line mode Tips
- Ex special characters — These are special character that can be used in executed command line (
:! ...
) or when ex is expecting a filename (see also:help <cword>
): - Insert register / object <C-R> — these can be used to insert some register content or text from context (see also
:help c_CTRL-R
):
<cword> replaced with word under cursor
<CWORD> replaced with WORD under cursor
<cfile> replaced with pathname under cursor
...
<C-R>* insert X11 clipboard content
<C-R>+ insert clipboard content
<C-R>= expression register. You are prompted to enter an expression
<C-R><C-W> insert word under cursor
<C-R><C-A> insert WORD under cursor
Example of expressions:
nmap <C-@><C-@> :cs find s <C-R>=expand("<cword>")<CR><CR>
Clipboard support
- On Linux, install gvim to get full clipboard support
- On Terminator, use also shortcuts ^S-c and ^S-V to copy & paste.
- On Cygwin, install gvim and a X server.
- vim will not have clipboard support. But similar result can be obtained by using
:set paste
, theni
, followed by S-Insert (under mintty) - gvim under Cygwin/X will have clipboard support.
- There is also some plugin (e.g. [16])
- vim will not have clipboard support. But similar result can be obtained by using
- Alternatively, install Win32 gvim (but this versions is not correctly integrated in cygwin, or requires use of wrapper)
Plugins
SnipMate
C
main main() inc #include <...> Inc #include "..." Def #ifndef ... #define ... #endif def #define ifdef #ifdef ... #endif #if #if ... #endif once #ifndef HEADER_H .... # define HEADER_H ... #endif (Header Include-Guard) if If (...) { ... } el else { ... } t ... ? ... : ... (tertiary conditional) do do ... while ( ... ) wh while (...) { ... } for for (... = 0; ...; ...) { ... } forr for (... = ...; ...; ...) { ... } fun ... function(...) { ... } fund ... function(...;) td typedef st struct tds typedef struct tde typedef enum pr printf fpr fprintf . [ ... ] un unsigned
CPP
readfile snippet for reading file map std::map<... , ...> map... vector std::vector<...> v... ns namespace ... { ... } cl class { public: ... private: };
Building from Sources
See
To Do
- Done Find a way to prevent vim to mess up with my register when deleting text.
- Auto-complete, use cursor keys instead of up/down to search in the drop down list.
- Look at Virtual-edit (see http://vim.wikia.com/wiki/Add_trailing_blanks_to_lines_for_easy_visual_blocks)
- Other links:
- http://www.faqs.org/docs/Linux-HOWTO/C-editing-with-VIM-HOWTO.html
- http://www.ibiblio.org/pub/linux/docs/howto/translations/nl/onehtml/Vim-HOWTO-NL.html
Bugs
- [2010-07-22] - (to bugs@vim.org) 'winfixheight' not honored when botright split is closed.
- (2011-07-27) - infinite loop when using :bn after a :edit dir/ (breaks plugin minibufexpl.vim)
{{{content}}}