Vim
VIM
VIM = Vi IMproved
"Vim is an editor designed to work like that most venerable of UNIX editors, vi. Vim doesn't just clone vi; it extends vi with features like multi-level undo, a graphical interface (if you want it), windows, block operations, on-line help and syntax coloring.
When you first start using Vim, it will be 100% compatible with vi. You won't notice any of Vim's fancy features until you activate them.
Luckily, it's easy to convince Vim that we know we're actually in Vim and not in vi. Vim customizations are stored in a file called .vimrc in your home directory. If Vim sees that you have a .vimrc file—even if that file is empty—Vim will turn off vi-compatibility mode, which will configure Vim as Vim, rather than vi." [1]
vimrc
/etc/vimrc (or ~/.vimrc):
set nocompatible " Use Vim defaults (much better!) set bs=indent,eol,start " allow backspacing over everything in insert mode set ruler " show the cursor position all the time syntax on " syntax highlighting
set backspace=2 set nocp set bs=2
Comments are preceeded with " to end of line (unless second " found)
" this is a comment
Save settings to file:
:mkvimrc [file]
Use <vimrc> instead of any .vimrc
vim -u <vimrc> vim -u /dev/null
CentOS 5 default settings:
version 6.0 if &cp | set nocp | endif let s:cpo_save=&cpo set cpo&vim nmap gx <Plug>NetrwBrowseX nnoremap <silent> <Plug>NetrwBrowseX :call netrw#NetrwBrowseX(expand("<cWORD>"),0) let &cpo=s:cpo_save unlet s:cpo_save set background=dark set backspace=indent,eol,start set fileencodings=utf-8,latin1 set helplang=en set history=50 set hlsearch set nomodeline set ruler set viminfo='20,\"50 " vim: set ft=vim :
Python .vimrc
" Kenneth's Preferences set nobackup " don't create backup files "set nohlsearch " don't highlight search results set hlsearch " do highlight search results set incsearch " incremental search set ignorecase " ignore case during search set smartcase " do case sensitive search when upper case is typed set shiftwidth=4 " shift blocks in 4 space increments set tabstop=4 " the (typewriter) tab stops are every 4 spaces set smarttab " tab at beginning of line inserts 4 spaces (shiftwidth) set showmatch " briefly highlight matching bracket set matchtime=1 " highlight match for 0.1 seconds set background=dark " black background set shiftwidth=4 " shift blocks by 4 spaces set shortmess=at " use short messages so we don't have to hit enter set expandtab " expand tabs into spaces set scrolloff=5 " always show 5 lines before & after cursor set shell=bash " use bash for the command shell set shellcmdflag=-lc " make bash startup as a login shell for ~/.bashrc "set nowrap " do not wrap long lines set visualbell " flash the screen rather than beep set noerrorbells " don't beep on errors set wildmenu " enable filename tab completion set ruler " display the ruler: shows cursor position set cpoptions+=$ " display '$' at end of cw sequence set title " display filename and vim info in window title bar set modelines=5 " search the first and last 5 lines for "vim:" modeline set backspace=2 " backspace deletes set wildignore=*.o,*.class,*.pyc,*.pyo,*.a,*.so,*.dll,*.exe,core,*.jar,*.zip "let loaded_matchparen = 1 " don't highlight parenthesis match filetype indent on "if v:version > 700 " set cursorline " underline the current line "endif if &t_Co > 2 || has( "gui_running" ) syntax on endif if has( 'mouse' ) set mouse=a " enable mouse endif if has( "autocmd" ) " open the file in the last place we were editing autocmd BufReadPost * \ if line("'\"") > 1 && line("'\"") <= line("$") | \ exe "normal! g'\"" | \ endif endif "folding settings set foldmethod=indent "fold based on indent set foldnestmax=10 "deepest fold is 10 levels set nofoldenable "dont fold by default set foldlevel=10 "this is just what i use " Auto clear trailing white space in Python files func! DeleteTrailingWS() exec "normal mz" %s/\s\+$//ge exe "normal `z" endfunc autocmd BufWrite *.py :call DeleteTrailingWS()
Compatability
-N
- "No-compatible mode. Reset the ’compatible’ option. This will make Vim behave a bit better, but less Vi compatible, even though a .vimrc file does not exist."
Basic Vi Keys
Movement:
0 Start of current line $ End of current line [home] Start of current line [end] End of current line ^ Move the cursor to the first non-whitespace character. + Move the cursor to the first non-whitespace character in the next line. - Move the cursor to the first non-whitespace character in the previous line. _ Move the cursor to the first non-whitespace character. g _ End of current line (last non white space character) % Move the cursor to the matching parenthesis or brace. Ctrl-F Forward one screen Ctrl-B Back one screen
Search:
/text Search for text (forwards) / Repeat forward search ?text Search for text (backwards) ? Repeat previous search backwards n Repeat previous search N Repeat previous search, but it opposite direction
Line Number Movement:
Ctrl-G Display line number of cursor nG Move cursor to line number n :n Move cursor to line number n G Move to last line in file
Insert:
A Append to end of current line I Insert at beginning of line o Open line above cursor O Open line below cursor
ESC End of insert mode Ctrl-U Delete current line dd Delete current line ndd Delete n lines J Join two lines d^ Delete to beginning of line d$ Delete to end of line p Insert buffer after cursor P Insert buffer before cursor u Undo last change Ctrl-r Redo last change x Delete current cursor position X Delete back one character nX Delete previous n characters ~ Toggle upper/lower case y Copy current line to new buffer yy Copy current line "xyy Copy current line into buffer x "Xd Delete and append into buffer x "xp Put contents of buffer x
:e [file] open file, with tab completion :w [file] write to file, with tab completion :enew close file, keep vim open
Source: Unix Manuals - vi Reference
References:
- Mastering the VI editor - http://www.eng.hawaii.edu/Tutor/vi.html
Create Tab Character
In edit mode ('i') insert a tab character with: (if your tab is set to spaces)
ctrl+v ctrl+i
Block Select
V - selects entire lines v - selects range of text ctrl-v - selects columns
d - delete selection y - copy selection p - paste selection
Mark Text
m[letter] - start selection (eg. 'ma') d'[letter] - copy selection lines y'[letter] - copy selection lines d`[letter] - copy selection text y`[letter] - copy selection text p - paste selection
Tutorials
Status
:args display the argument list :file display file name ^L ^G redraw screen, show filename and position g^G show cursor column, line, and character position ga show ASCII value of character under cursor gf open file which filename is under cursor
Searching
Search:
Search STRING forward : / STRING. Search STRING backward: ? STRING.
Repeat search: n Repeat search in opposite direction: N (SHIFT-n)
Reference: Vi: Search and Replace
To search for text (with regular expression):
/text /[a-z]as
To clear highlighted search results: [2]
1) /somenonexistingtext 2) :noh 3) add "nmap <SPACE> <SPACE>:noh<CR>" to .vimrc, which will clear on space bar
Reference: Vi: Search and Replace
Replacing
:s/OLD/NEW First occurrence on current line: :s/OLD/NEW/g Globally (all) on current line: :1,15s/OLD/NEW/g Between two lines 1,15: :%s/OLD/NEW/g Every occurrence in file: :%s/OLD/NEW/g Every occurrence in file: :%s/OLD/NEW/gc Every occurrence in file w/ conf: :%s/OLD/NEW/gci Every occurrence w/ conf case insensitve: :.,$s/OLD/NEW/g Start from the current line (.) to the last line ($) inclusive.
Reference: Vi: Search and Replace
Ranged replace:
:32,56s/guy/gal/g
Global replace:
:%s/search_string/replacement_string/g
Replace upper case to lower case:
:%s/[A-Z]/\L&/g :%s/.*/\L&/
Replace lower case to upper case:
:%s/[a-z]/\U&/g :%s/.*/\U&/
Reference: Vi: Search and Replace
External
shows your current working directory.
:!pwd
reads the results from the date command into a new line following the cursor.
:r !date
Auto Indent
set cindent
set cindent set smartindent set autoindent set expandtab set tabstop=2 set shiftwidth=2 set cinkeys=0{,0},:,0#,!,!^F
References:
Insert Literal Tab
You can use "[ctrl]+v [tab]" to insert a literal tab when "expandtab" is enabled.
<CTRL-V><Tab>
Source: How to insert Tab character when expandtab option is ON in VIM - Stack Overflow http://stackoverflow.com/questions/4781070/how-to-insert-tab-character-when-expandtab-option-is-on-in-vim
Disable Auto Indent
To turn off autoindent when you paste code, there's a special "paste" mode.
:set paste
Then paste your code. Note that the text in the tooltip now says -- INSERT (paste) --.
After you pasted your code, turn off the paste-mode, so that auto-indenting when you type works correctly again.
:set nopaste
To disable file based indenting for the current session:
:setlocal indentexpr= :setl inde=
More extreme version:
:setl noai nocin nosi inde=
References:
- editor - Turning off auto indent when pasting text into vim - Stack Overflow - http://stackoverflow.com/questions/2514445/turning-off-auto-indent-when-pasting-text-into-vim
- http://vim.wikia.com/wiki/How_to_stop_auto_indenting - How to stop auto indenting - Vim Tips Wiki
- Toggle auto-indenting for code paste - Vim Tips Wiki - http://vim.wikia.com/wiki/Toggle_auto-indenting_for_code_paste
Highlight Parenthesis
Use % to jump between matching parenthesis.
The :showmatch option is also useful: it can reduce the need for %, the cursor will briefly jump to the matching brace when you insert one.
Parenthesis highlighting is handled by the pi_paren module.
Vim documentation: pi_paren - http://vimdoc.sourceforge.net/htmldoc/pi_paren.html
To permanently disable this plugin, add the following to ~/.vimrc (not sure why you would want to):
You can avoid loading this plugin by setting the "loaded_matchparen" variable: :let loaded_matchparen = 1
To disable the plugin after it was loaded use this command: :NoMatchParen
And to enable it again: :DoMatchParen
"There's a plugin to do the highlighting thing. Sorry, it's been awhile since I used vim and was thinking showmatch highlighted also. [3]
- :help showmatch
- There's a link in the help files to pi_paren.txt
- pi_paren.txt. Put your cursor on that and hit ctrl-] and it'll jump you to the docs.
- or directly with :help pi_paren.txt
References:
- Moving to matching braces - Vim Tips Wiki - http://vim.wikia.com/wiki/Moving_to_matching_braces
Vim Tip Wiki
http://vim.wikia.com/wiki/Vim_Tips_Wiki
Super Star Search
This tip shows how to search using Vim, including use of * (the super star) to search for the current word.
http://vim.wikia.com/wiki/VimTip1
In normal mode, move the cursor to any word. Press * to search forwards for the next occurrence of that word, or press # to search backwards.
Using * or # searches for the exact word at the cursor (searching for rain would not find rainbow).
Use g* or g# if you don't want to search for the exact word.
Multi-line Edits
Insert 20 lines of the following:
20iHello world! <Enter> <escape>
Multi-line insert (with VIM only):
- Enter visual block mode: ctrl-v
- Select rows with arrow keys
- press 'I' to insert text
- can press 'c' to cut the text, and then do insert
- Type text to insert
- Press escape to insert on multi lines
Ruler not showing
If you don't want to see the ruler all the time but want to know where you are, use "CTRL-G" or "g CTRL-G".
To turn the ruler on/off:
:set ruler :ser noruler
CentOS by default only includes the package vim-minimal. This was not compiled with "+cmdline_info".
The solution is to do a "yum install vim-enhanced" and use "vim" instead of "vi", or use "alias vi=/usr/bin/vim"
To see what 'vi' was compiled with: [4]
:version
Vim Settings - Tips
Some very useful commands I use to make working with vim much more elegant and easier:
show / hide line numbers
:set number :set nonumber :set numberwidth=1
enable / disable syntax highlighting
:syntax on :syntax off
If vim does not recognize the filetype, set the filetype manually
:set filetype=filetype
example
:set filetype=php
show ruler (cursor coordinates)
:set ruler
show vim mode (INSERT / REPLACE / ...)
:set showmode
show matching parentheses
:set showmatch
replace tabs with spaces
:set expandtab
number of spaces per tab
:set shiftwidth=2
As expandtab is not always desired (e.g. for Makefiles tabs are necessary and would lead to a syntax error when replaced by spaces) you can use autocmd to set it only for certain filetypes. Example
:filetype on :autocmd FileType php :set expandtab
automatic indentation (e.g. code blocks between braces)
:set cindent
Use this option with caution (same as with expandtab)
case insensitive search
:set ignorecase
show invisible characters
:set list
Line Numbers
Show line numbers:
:set number :set nu
Hide line numbers:
:set number! :set nu! :set nonumber
Line number width:
:set numberwidth=1
Auto enabled numbers - append following line to your ~/.vimrc file:
set number
Jump to line number:
[number(s)] [shift]+[G] 300[shift]+[G]
Jump to line number from command line:
vi +[linenumber] [file] vi +300 myfile.txt
References:
Line Wrap
Turn line wrapping on:
:set wrap
Turn line wrapping off:
:set nowrap
Searching
Find pattern
/[pattern]
Incremental search:
:set incsearch
Incremental searching means that as you enter your search pattern, Vim will show you the next match as you type each letter.
Ignore case:
:set ignorecase
Smart case search:
:set smartcase
What if I really do want to search based on case distinctions? Will I have to set and unset ignorecase each time I want to search a different way? In vi, the answer, unfortunately, is yes. Vim is a little more subtle, though, in that it offers the smartcase option as well. If both ignorecase and smartcase are set, Vim will ignore the case of the search only if the search pattern is all in lower-case. But if there are any upper-case characters in the search pattern, Vim will assume you really want to do a case-sensitive search and will do its matching accordingly.
Keep Some Context: scrolloff
:set scrolloff=2
The 2 means I want at least two lines of context visible around the cursor at all times. You can set this to any number you like. Vim will scroll your file so that your cursor will never be closer to the top and bottom edge of the screen than the number of lines you specify.
Colors
Colors:
:colors darkblue
For colors, add colors=darkblue to your .vimrc and that's it.
Save Settings
Save settings to .virmc:
:mkv[imrc][!] [file] :mkv
Like ":mkexrc", but the default is ".vimrc" in the current directory. The ":version" command is also written to the file. {not in Vi} (Vim documentation: starting)
Spell Check
The spell check includes misspelled word highlighting.
Turn on spell check:
:set spell :set nospell :setlocal spell spelllang=en_us
Navigation:
]s — move to the next mispelled word [s — move to the previous mispelled word zg — add a word to the dictionary zug — undo the addition of a word to the dictionary z= — view spelling suggestions for a mispelled word
In Insert mode:
CTRL-X s - find suggestions (can use up/down, top item is original) CTRL-N - next suggestion CTRL-P - previous suggestion (select top to revert to original)
Help:
:help spell
Code Folding
Settings in .vimrc:
"folding settings set foldmethod=indent "fold based on indent set foldnestmax=10 "deepest fold is 10 levels set nofoldenable "dont fold by default set foldlevel=10 "initial fold level on enable
za - toggle folding zM - fold everything zR - unfold everything with zR zm - fold one level zr - unfold one level zo - open fold zO - open all folds in current fold zc - close fold zf5j - manually force fold '5' lines zfa} - manually fold to next '}' help :folding - if you get stuck.
References:
- Code folding in vim – Smarticus - http://smartic.us/2009/04/06/code-folding-in-vim/
- Folding - Vim Tips Wiki - http://vim.wikia.com/wiki/Folding
- A Collection of Vim Tips | Ayman Hourieh - http://aymanh.com/a-collection-of-vim-tips
Hex Mode
Vim provides hex capability through the external program xxd
:%!xxd # to convert to hex :%!xxd -r # to convert back
Add the following to ~/.vimrc to enable CTRL-H hex mode (make sure to return from Hex mode before saving):
" " HEX MODE " nnoremap <C-H> :Hexmode<CR> inoremap <C-H> <Esc>:Hexmode<CR> vnoremap <C-H> :<C-U>Hexmode<CR> " ex command for toggling hex mode - define mapping if desired command -bar Hexmode call ToggleHex() " helper function to toggle hex mode function ToggleHex() " hex mode should be considered a read-only operation " save values for modified and read-only for restoration later, " and clear the read-only flag for now let l:modified=&mod let l:oldreadonly=&readonly let &readonly=0 let l:oldmodifiable=&modifiable let &modifiable=1 if !exists("b:editHex") || !b:editHex " save old options let b:oldft=&ft let b:oldbin=&bin " set new options setlocal binary " make sure it overrides any textwidth, etc. let &ft="xxd" " set status let b:editHex=1 " switch to hex editor %!xxd else " restore old options let &ft=b:oldft if !b:oldbin setlocal nobinary endif " set status let b:editHex=0 " return to normal editing %!xxd -r endif " restore values for modified and read only state let &mod=l:modified let &readonly=l:oldreadonly let &modifiable=l:oldmodifiable endfunction
References:
- Improved hex editing - Vim Tips Wiki - http://vim.wikia.com/wiki/Improved_hex_editing
- Hex dump - Vim Tips Wiki - http://vim.wikia.com/wiki/Hex_dump
Multiple Buffers - Windows
keywords: multiple buffers / multiple windows
Documentation: http://vimdoc.sourceforge.net/htmldoc/windows.html
Command mode:
# To create/open a file in a horizontal buffer below: :new filename.txt :sp filename.txt
# To create/open a file in a vertical buffer on the right: :vert new filename.txt :vnew filename.txt :vsp filename.txt :vs filename.txt
# split current buffer horizontal :sp
# split current buffer vertifical :vsp :vs
Open multiple files split horizontally:
vim -o file1.txt file2.txt file3.txt
Open multiple files split vertically:
vim -O file1.txt file2.txt file3.txt
Visual Mode Keys:
ctrl+w ctrl+w - switch windows ctrl+w [right] - switch to right windows ctrl+w [left] - switch to left windows 2 ctrl+g - identify buffer and file ctrl+w n - new buffer horizontal split (no similar vert command)
ctrl+w s - open current buffer in second horizontal split ctrl+w v - open current buffer in second buffer vertical split ctrl+w q - close buffer
Note: to exit, you have to close out all windows, one at a time, or use: [5]
:wa # write changes to all buffers :xa # save and exit all buffers :qa # quit all buffers :qa! # quit all buffers (without saving)
swarthmore tricks: [6]
:e filename - edit another file :split filename - split window and load another file ctrl-w up arrow - move cursor up a window ctrl-w ctrl-w - move cursor to another window (cycle) ctrl-w_ - maximize current window ctrl-w= - make all equal size 10 ctrl-w+ - increase window height size by 10 lines ctrl-w < - shrink vertical window width by 1 ctrl-w > - expand vertical window width by 1 20ctrl-w < - shrink vertical window width by 20 20ctrl-w > - expand vertical window width by 20 :vsplit file - vertical split :sview file - same as split, but readonly :hide - close current window :only - keep only this window open :ls - show current buffers :b 2 - open buffer #2 in this window
References:
- Vim documentation: windows - http://vimdoc.sourceforge.net/htmldoc/windows.html
- Vim Editing Multiple Files and Windowing Support Under Linux / UNIX - http://www.cyberciti.biz/faq/vim-editing-multiple-files-with-windows-buffers/
- unix - How to open a new file in vim in a new window - Stack Overflow - http://stackoverflow.com/questions/10760310/how-to-open-a-new-file-in-vim-in-a-new-window
- vim tips and tricks: multiple windows - http://www.cs.swarthmore.edu/help/vim/windows.html
- gvim - How do I open a blank new file in a split in Vim? - Super User - http://superuser.com/questions/212257/how-do-i-open-a-blank-new-file-in-a-split-in-vim
- Save all open buffers at once - Vim Tips Wiki - http://vim.wikia.com/wiki/Save_all_open_buffers_at_once
Python
New as of 2013.05.15:
" Kenneth's Preferences set nobackup " don't create backup files "set nohlsearch " don't highlight search results set hlsearch " do highlight search results set incsearch " incremental search set ignorecase " ignore case during search set smartcase " do case sensitive search when upper case is typed set shiftwidth=4 " shift blocks in 4 space increments set tabstop=4 " the (typewriter) tab stops are every 4 spaces set smarttab " tab at beginning of line inserts 4 spaces (shiftwidth) set showmatch " briefly highlight matching bracket set matchtime=1 " highlight match for 0.1 seconds set background=dark " black background set shiftwidth=4 " shift blocks by 4 spaces set shortmess=at " use short messages so we don't have to hit enter set expandtab " expand tabs into spaces set scrolloff=5 " always show 5 lines before & after cursor set shell=bash " use bash for the command shell set shellcmdflag=-lc " make bash startup as a login shell for ~/.bashrc "set nowrap " do not wrap long lines set visualbell " flash the screen rather than beep set noerrorbells " don't beep on errors set wildmenu " enable filename tab completion set ruler " display the ruler: shows cursor position set cpoptions+=$ " display '$' at end of cw sequence set title " display filename and vim info in window title bar set modelines=5 " search the first and last 5 lines for "vim:" modeline set backspace=2 " backspace deletes set wildignore=*.o,*.class,*.pyc,*.pyo,*.a,*.so,*.dll,*.exe,core,*.jar,*.zip "let loaded_matchparen = 1 " don't highlight parenthesis match filetype indent on "if v:version > 700 " set cursorline " underline the current line "endif if &t_Co > 2 || has( "gui_running" ) syntax on endif if has( 'mouse' ) set mouse=a " enable mouse endif if has( "autocmd" ) " open the file in the last place we were editing autocmd BufReadPost * \ if line("'\"") > 1 && line("'\"") <= line("$") | \ exe "normal! g'\"" | \ endif endif "folding settings set foldmethod=indent "fold based on indent set foldnestmax=10 "deepest fold is 10 levels set nofoldenable "dont fold by default set foldlevel=10 "this is just what i use
Python .vimrc:
" KENNETH SETTINGS set nocp " turn off compatibility mode set nomodeline " do not allow files to dictate vim behavior set incsearch " incremental search set ignorecase " ignore case during search set visualbell " flash the screen rather than beep set noerrorbells " don't beep on errors set background=dark " black background syntax on " turn on syntax highlighting set hlsearch " highligh last search pattern set nowrap " do not wrap long lines set scrolloff=5 " always show 5 lines before & after cursor set ruler " show the cursor position all the time set backspace=2 " allow backspace deletion set bs=indent,eol,start " allow backspacing over everything in insert mode set shiftwidth=4 " shift blocks in 4 space increments set tabstop=4 " the (typewriter) tab stops are every 4 spaces set expandtab " expand tab into spaces set smarttab " tab at beginning of line inserts 4 spaces (shiftwidth) filetype indent on " turn on auto indent for specific file types
vimdiff
See vimdiff