您正在查看: VIM 分类下的文章

vi命令详解

文本编辑器是所有计算机系统中最常用的一种工具。UNIX下的编辑器有ex,sed和vi等,其中,使用最为广泛的是vi,而vi命令繁多,论坛里好像这方面的总结不多,以下稍做总结,以资共享!渴望更正和补充!
 
进入vi的命令
vi filename :打开或新建文件,并将光标置于第一行首
vi +n filename :打开文件,并将光标置于第n行首
vi + filename :打开文件,并将光标置于最后一行首
vi +/pattern filename:打开文件,并将光标置于第一个与pattern匹配的串处
vi -r filename :在上次正用vi编辑时发生系统崩溃,恢复filename
vi filename....filename :打开多个文件,依次进行编辑

移动光标类命令
h :光标左移一个字符
l :光标右移一个字符
space:光标右移一个字符
Backspace:光标左移一个字符
k或Ctrl+p:光标上移一行
j或Ctrl+n :光标下移一行
Enter :光标下移一行
w或W :光标右移一个字至字首
b或B :光标左移一个字至字首
e或E :光标右移一个字至字尾
) :光标移至句尾
( :光标移至句首
}:光标移至段落开头
{:光标移至段落结尾
nG:光标移至第n行首
n+:光标下移n行
n-:光标上移n行
n$:光标移至第n行尾
H :光标移至屏幕顶行
M :光标移至屏幕中间行
L :光标移至屏幕最后行
0:(注意是数字零)光标移至当前行首
$:光标移至当前行尾

屏幕翻滚类命令
Ctrl+u:向文件首翻半屏
Ctrl+d:向文件尾翻半屏
Ctrl+f:向文件尾翻一屏
Ctrl+b;向文件首翻一屏
nz:将第n行滚至屏幕顶部,不指定n时将当前行滚至屏幕顶部。

插入文本类命令
i :在光标前
I :在当前行首
a:光标后
A:在当前行尾
o:在当前行之下新开一行
O:在当前行之上新开一行
r:替换当前字符
R:替换当前字符及其后的字符,直至按ESC键
s:从当前光标位置处开始,以输入的文本替代指定数目的字符
S:删除指定数目的行,并以所输入文本代替之
ncw或nCW:修改指定数目的字
nCC:修改指定数目的行

删除命令
ndw或ndW:删除光标处开始及其后的n-1个字
do:删至行首
d$:删至行尾
ndd:删除当前行及其后n-1行
x或X:删除一个字符,x删除光标后的,而X删除光标前的
Ctrl+u:删除输入方式下所输入的文本

搜索及替换命令
/pattern:从光标开始处向文件尾搜索pattern
?pattern:从光标开始处向文件首搜索pattern
n:在同一方向重复上一次搜索命令
N:在反方向上重复上一次搜索命令
:s/p1/p2/g:将当前行中所有p1均用p2替代
:n1,n2s/p1/p2/g:将第n1至n2行中所有p1均用p2替代
:g/p1/s//p2/g:将文件中所有p1均用p2替换

选项设置
all:列出所有选项设置情况
term:设置终端类型
ignorance:在搜索中忽略大小写
list:显示制表位(Ctrl+I)和行尾标志($)
number:显示行号
report:显示由面向行的命令修改过的数目
terse:显示简短的警告信息
warn:在转到别的文件时若没保存当前文件则显示NO write信息
nomagic:允许在搜索模式中,使用前面不带“\”的特殊字符
nowrapscan:禁止vi在搜索到达文件两端时,又从另一端开始
mesg:允许vi显示其他用户用write写到自己终端上的信息

最后行方式命令
:n1,n2 co n3:将n1行到n2行之间的内容拷贝到第n3行下
:n1,n2 m n3:将n1行到n2行之间的内容移至到第n3行下
:n1,n2 d :将n1行到n2行之间的内容删除
:w :保存当前文件
:e filename:打开文件filename进行编辑
:x:保存当前文件并退出
:q:退出vi
:q!:不保存文件并退出vi
:!command:执行shell命令command
:n1,n2 w!command:将文件中n1行至n2行的内容作为command的输入并执行之,若不指定n1,n2,则表示将整个文件内容作为command的输入
:r!command:将命令command的输出结果放到当前行

寄存器操作
"?nyy:将当前行及其下n行的内容保存到寄存器?中,其中?为一个字母,n为一个数字
"?nyw:将当前行及其下n个字保存到寄存器?中,其中?为一个字母,n为一个数字
"?nyl:将当前行及其下n个字符保存到寄存器?中,其中?为一个字母,n为一个数字
"?p:取出寄存器?中的内容并将其放到光标位置处。这里?可以是一个字母,也可以是一个数字
ndd:将当前行及其下共n行文本删除,并将所删内容放到1号删除寄存器中。


永久显示行号:
linux: echo "set nu">>~/.vimrc

sol: echo "set nu" >> ~/.exrc

在每个用户的主目录下,都有一个 vi 的配置文件".vimrc"或".exrc",
用户可以编辑它,使这些设置在每次启动 vi 时,都有效。
例如,加入如下设置行:
set nu 显示行号
set nonu 不显示行号
set ic 查找时不考虑大小写
set noic 查找时考虑大小写
set softtabstop=4 tab键为4个字符

linux:.bash_profile
EXINIT="set nu";export EXINIT
sol: .profile
EXINIT="set nu";export EXINIT


set 设置 vi 的选项,例如 set nu 表示每行前显示行号,在选项前
加no则表示清除该选项,例如 set nonu 表示每行前不显示行
号,下面是一些常用的选项:
ai 自动缩进
aw 编辑下一文件前自动存盘
ic 查找字符串时不区分大小写
nu 每行前显示行号
sm 输入)及}时显示与之配对的( 或 {
slow 插入时延迟屏幕刷新
ws 使查找能绕过文件尾从头进行
wa 写文件之前不作对文件的检查

Best of Vim Tips

------------------------------------------------------------------------------
" new items marked *N* , corrected items marked *C*
" searching
/joe/e                      : cursor set to End of match
/joe/e+1                    : cursor set to End of match plus 1
/joe/s-2                    : cursor set to Start of match minus 2
/joe/+3                     : find joe move cursor 3 lines down
/^joe.*fred.*bill/          : find joe AND fred AND Bill (Joe at start of line)
/^[A-J]/                    : search for lines beginning with one or more A-J
/begin\_.*end               : search over possible multiple lines
/fred\_s*joe/               : any whitespace including newline *C*
/fred\|joe                  : Search for FRED OR JOE
/.*fred\&.*joe              : Search for FRED AND JOE in any ORDER!
/\<fred\>/                  : search for fred but not alfred or frederick *C*
/\<\d\d\d\d\>               : Search for exactly 4 digit numbers
/\D\d\d\d\d\D               : Search for exactly 4 digit numbers
/\<\d\{4}\>                 : same thing
/\([^0-9]\|^\)%.*%          : Search for absence of a digit or beginning of line
" finding empty lines
/^\n\{3}                    : find 3 empty lines
/^str.*\nstr                : find 2 successive lines starting with str
/\(^str.*\n\)\{2}           : find 2 successive lines starting with str
" using rexexp memory in a search
/\(fred\).*\(joe\).*\2.*\1
" Repeating the Regexp (rather than what the Regexp finds)
/^\([^,]*,\)\{8}
" visual searching
:vmap // y/<C-R>"<CR>       : search for visually highlighted text
:vmap <silent> //    y/<C-R>=escape(@", '\\/.*$^~[]')<CR><CR> : with spec chars
" \zs and \ze regex delimiters :h /\zs
/<\zs[^>]*\ze>              : search for tag contents, ignoring chevrons
" zero-width :h /\@=
/<\@<=[^>]*>\@=             : search for tag contents, ignoring chevrons
/<\@<=\_[^>]*>\@=           : search for tags across possible multiple lines
" searching over multiple lines \_ means including newline
/<!--\_p\{-}-->                   : search for multiple line comments
/fred\_s*joe/                     : any whitespace including newline *C*
/bugs\(\_.\)*bunny                : bugs followed by bunny anywhere in file
:h \_                             : help
" search for declaration of subroutine/function under cursor
:nmap gx yiw/^\(sub\<bar>function\)\s\+<C-R>"<CR>
" multiple file search
:bufdo /searchstr/                : use :rewind to recommence search
" multiple file search better but cheating
:bufdo %s/searchstr/&/gic   : say n and then a to stop
" How to search for a URL without backslashing
?http://www.vim.org/        : (first) search BACKWARDS!!! clever huh!
" Specify what you are NOT searching for (vowels)
/\c\v([^aeiou]&\a){4}       : search for 4 consecutive consonants
/\%>20l\%<30lgoat           : Search for goat between lines 20 and 30 *N*
/^.\{-}home.\{-}\zshome/e   : match only the 2nd occurence in a line of "home" *N*
:%s/home.\{-}\zshome/alone  : Substitute only the occurrence of home in any line *N*
" find str but not on lines containing tongue
^\(.*tongue.*\)\@!.*nose.*$
\v^((tongue)@!.)*nose((tongue)@!.)*$
.*nose.*\&^\%(\%(tongue\)\@!.\)*$ 
:v/tongue/s/nose/&/gic
"----------------------------------------
"substitution
:%s/fred/joe/igc            : general substitute command
:%s//joe/igc                : Substitute what you last searched for *N*
:%s/~/sue/igc               : Substitute your last replacement string *N*
:%s/\r//g                   : Delete DOS returns ^M
" Is your Text File jumbled onto one line? use following
:%s/\r/\r/g                 : Turn DOS returns ^M into real returns
:%s=  *$==                  : delete end of line blanks
:%s= \+$==                  : Same thing
:%s#\s*\r\?$##              : Clean both trailing spaces AND DOS returns
:%s#\s*\r*$##               : same thing
" deleting empty lines
:%s/^\n\{3}//               : delete blocks of 3 empty lines
:%s/^\n\+/\r/               : compressing empty lines
:%s#<[^>]\+>##g             : delete html tags, leave text (non-greedy)
:%s#<\_.\{-1,}>##g          : delete html tags possibly multi-line (non-greedy)
:%s#.*\(\d\+hours\).*#\1#   : Delete all but memorised string (\1) *N*
" VIM Power Substitute
:'a,'bg/fred/s/dick/joe/igc : VERY USEFUL
" duplicating columns
:%s= [^ ]\+$=&&=            : duplicate end column
:%s= \f\+$=&&=              : same thing
:%s= \S\+$=&&               : usually the same
" memory
%s#.*\(tbl_\w\+\).*#\1#     : produce a list of all strings tbl_*   *N*
:s/\(.*\):\(.*\)/\2 : \1/   : reverse fields separated by :
:%s/^\(.*\)\n\1$/\1/        : delete duplicate lines
" non-greedy matching \{-}
:%s/^.\{-}pdf/new.pdf/      : delete to 1st pdf only
" use of optional atom \?
:%s#\<[zy]\?tbl_[a-z_]\+\>#\L&#gc : lowercase with optional leading characters
" over possibly many lines
:%s/<!--\_.\{-}-->//        : delete possibly multi-line comments
:help /\{-}                 : help non-greedy
" substitute using a register
:s/fred/<c-r>a/g            : sub "fred" with contents of register "a"
:s/fred/<c-r>asome_text<c-r>s/g  
:s/fred/\=@a/g              : better alternative as register not displayed
" multiple commands on one line
:%s/\f\+\.gif\>/\r&\r/g | v/\.gif$/d | %s/gif/jpg/
:%s/a/but/gie|:update|:next : then use @: to repeat
" ORing
:%s/goat\|cow/sheep/gc      : ORing (must break pipe)
:%s/\v(.*\n){5}/&\r         : insert a blank line every 5 lines *N*
" Calling a VIM function
:s/__date__/\=strftime("%c")/ : insert datestring
" Working with Columns sub any str1 in col3
:%s:\(\(\w\+\s\+\)\{2}\)str1:\1str2:
" Swapping first & last column (4 columns)
:%s:\(\w\+\)\(.*\s\+\)\(\w\+\)$:\3\2\1:
" format a mysql query 
:%s#\<from\>\|\<where\>\|\<left join\>\|\<\inner join\>#\r&#g
" filter all form elements into paste register
:redir @*|sil exec 'g#<\(input\|select\|textarea\|/\=form\)\>#p'|redir END
:nmap ,z :redir @*<Bar>sil exec 'g@<\(input\<Bar>select\<Bar>textarea\<Bar>/\=form\)\>@p'<Bar>redir END<CR>
" substitute string in column 30 *N*
:%s/^\(.\{30\}\)xx/\1yy/
" decrement numbers by 3
:%s/\d\+/\=(submatch(0)-3)/
" increment numbers by 6 on certain lines only
:g/loc\|function/s/\d/\=submatch(0)+6/
" better
:%s#txtdev\zs\d#\=submatch(0)+1#g
:h /\zs
" increment only numbers gg\d\d  by 6 (another way)
:%s/\(gg\)\@<=\d\+/\=submatch(0)+6/
:h zero-width
" rename a string with an incrementing number
:let i=10 | 'a,'bg/Abc/s/yy/\=i/ |let i=i+1 # convert yy to 10,11,12 etc
" as above but more precise
:let i=10 | 'a,'bg/Abc/s/xx\zsyy\ze/\=i/ |let i=i+1 # convert xxyy to xx11,xx12,xx13
" find replacement text, put in memory, then use \zs to simplify substitute
:%s/"\([^.]\+\).*\zsxx/\1/
" Pull word under cursor into LHS of a substitute
:nmap <leader>z :%s#\<<c-r>=expand("<cword>")<cr>\>#
" Pull Visually Highlighted text into LHS of a substitute
:vmap <leader>z :<C-U>%s/\<<c-r>*\>/
" substitute singular or plural
:'a,'bs/bucket\(s\)*/bowl\1/gic   *N*
----------------------------------------
" all following performing similar task, substitute within substitution
" Multiple single character substitution in a portion of line only
:%s,\(all/.*\)\@<=/,_,g     : replace all / with _ AFTER "all/"
" Same thing
:s#all/\zs.*#\=substitute(submatch(0), '/', '_', 'g')#
" Substitute by splitting line, then re-joining
:s#all/#&^M#|s#/#_#g|-j!
" Substitute inside substitute
:%s/.*/\='cp '.submatch(0).' all/'.substitute(submatch(0),'/','_','g')/
----------------------------------------
" global command display 
:g/gladiolli/#              : display with line numbers (YOU WANT THIS!)
:g/fred.*joe.*dick/         : display all lines fred,joe & dick
:g/\<fred\>/                : display all lines fred but not freddy
:g/^\s*$/d                  : delete all blank lines
:g!/^dd/d                   : delete lines not containing string
:v/^dd/d                    : delete lines not containing string
:g/fred/,/joe/d             : not line based (very powerfull)
:g/fred/,/joe/j             : Join Lines *N*
:g/-------/.-10,.d          : Delete string & 10 previous lines
:g/{/ ,/}/- s/\n\+/\r/g     : Delete empty lines but only between {...}
:v/\S/d                     : Delete empty lines (both types)
:v/./,/./-j                 : compress empty lines
:g/^$/,/./-j                : compress empty lines
:g/<input\|<form/p          : ORing
:g/^/put_                   : double space file (pu = put)
:g/^/m0                     : Reverse file (m = move)
:g/^/m$                     : No effect! *N*
:'a,'bg/^/m'b               : Reverse a section a to b
:g/^/t.                     : duplicate every line
:g/fred/t$                  : copy(transfer) lines matching fred to EOF
:g/stage/t'a                : copy (transfer) lines matching stage to marker a (cannot use .) *C*
:g/^Chapter/t.|s/./-/g      : Automatically underline selecting headings *N*
:g/\(^I[^^I]*\)\{80}/d      : delete all lines containing at least 80 tabs
" perform a substitute on every other line
:g/^/ if line('.')%2|s/^/zz / 
" match all lines containing "somestr" between markers a & b
" copy after line containing "otherstr"
:'a,'bg/somestr/co/otherstr/ : co(py) or mo(ve)
" as above but also do a substitution
:'a,'bg/str1/s/str1/&&&/|mo/str2/
:%norm jdd                  : delete every other line
" incrementing numbers (type <c-a> as 5 characters)
:.,$g/^\d/exe "norm! \<c-a>": increment numbers
:'a,'bg/\d\+/norm! ^A       : increment numbers
" storing glob results (note must use APPEND) you need to empty reg a first with qaq. 
"save results to a register/paste buffer
:g/fred/y A                 : append all lines fred to register a
:g/fred/y A | :let @*=@a    : put into paste buffer
:let @a=''|g/Barratt/y A |:let @*=@a
" filter lines to a file (file must already exist)
:'a,'bg/^Error/ . w >> errors.txt
" duplicate every line in a file wrap a print '' around each duplicate
:g/./yank|put|-1s/'/"/g|s/.*/Print '&'/
" replace string with contents of a file, -d deletes the "mark"
:g/^MARK$/r tmp.txt | -d
" display prettily
:g/<pattern>/z#.5           : display with context
:g/<pattern>/z#.5|echo "=========="  : display beautifully
" Combining g// with normal mode commands
:g/|/norm 2f|r*                      : replace 2nd | with a star
"send output of previous global command to a new window
:nmap <F3>  :redir @a<CR>:g//<CR>:redir END<CR>:new<CR>:put! a<CR><CR>
"----------------------------------------
" Global combined with substitute (power editing)
:'a,'bg/fred/s/joe/susan/gic :  can use memory to extend matching
:/fred/,/joe/s/fred/joe/gic :  non-line based (ultra)
:/biz/,/any/g/article/s/wheel/bucket/gic:  non-line based *N*
----------------------------------------
" Find fred before beginning search for joe
:/fred/;/joe/-2,/sid/+3s/sally/alley/gIC
"----------------------------------------
" create a new file for each line of file eg 1.txt,2.txt,3,txt etc
:g/^/exe ".w ".line(".").".txt"
"----------------------------------------
" chain an external command
:.g/^/ exe ".!sed 's/N/X/'" | s/I/Q/    *N*
"----------------------------------------
" Operate until string found *N*
d/fred/                                :delete until fred
y/fred/                                :yank until fred
c/fred/e                               :change until fred end
"----------------------------------------
" Summary of editing repeats *N*
.      last edit (magic dot)
:&     last substitute
:%&    last substitute every line
:%&gic last substitute every line confirm
g%     normal mode repeat last substitute
g&     last substitute on all lines
@@     last recording
@:     last command-mode command
:!!    last :! command
:~     last substitute
:help repeating
----------------------------------------
" Summary of repeated searches
;      last f, t, F or T
,      last f, t, F or T in opposite direction
n      last / or ? search
N      last / or ? search in opposite direction
----------------------------------------
" Absolutely essential
----------------------------------------
* # g* g#           : find word under cursor (<cword>) (forwards/backwards)
%                   : match brackets {}[]()
.                   : repeat last modification 
@:                  : repeat last : command (then @@)
matchit.vim         : % now matches tags <tr><td><script> <?php etc
<C-N><C-P>          : word completion in insert mode
<C-X><C-L>          : Line complete SUPER USEFUL
/<C-R><C-W>         : Pull <cword> onto search/command line
/<C-R><C-A>         : Pull <CWORD> onto search/command line
:set ignorecase     : you nearly always want this
:set smartcase      : overrides ignorecase if uppercase used in search string (cool)
:syntax on          : colour syntax in perl,HTML,php etc
:set syntax=perl    : force syntax (usually taken from file extension)
:h regexp<C-D>      : type control-D and get a list all help topics containing
                      regexp (plus use TAB to Step thru list)
----------------------------------------
" MAKE IT EASY TO UPDATE/RELOAD _vimrc
:nmap ,s :source $VIM/_vimrc
:nmap ,v :e $VIM/_vimrc
:e $MYVIMRC         : edits your _vimrc whereever it might be  *N*
" How to have a variant in your .vimrc for different PCs *N*
if $COMPUTERNAME == "NEWPC"
ab mypc vista
else
ab mypc dell25
endif
----------------------------------------
" splitting windows
:vsplit other.php       # vertically split current file with other.php *N*
----------------------------------------
"VISUAL MODE (easy to add other HTML Tags)
:vmap sb "zdi<b><C-R>z</b><ESC>  : wrap <b></b> around VISUALLY selected Text
:vmap st "zdi<?= <C-R>z ?><ESC>  : wrap <?=   ?> around VISUALLY selected Text
----------------------------------------
"vim 7 tabs
vim -p fred.php joe.php             : open files in tabs
:tabe fred.php                      : open fred.php in a new tab
:tab ball                           : tab open files
" vim 7 forcing use of tabs from .vimrc
:nnoremap gf <C-W>gf
:cab      e  tabe
:tab sball                           : retab all files in buffer (repair) *N*
----------------------------------------
" Exploring
:e .                            : file explorer
:Exp(lore)                      : file explorer note capital Ex
:Sex(plore)                     : file explorer in split window
:browse e                       : windows style browser
:ls                             : list of buffers
:cd ..                          : move to parent directory
:args                           : list of files
:args *.php                     : open list of files (you need this!)
:lcd %:p:h                      : change to directory of current file
:autocmd BufEnter * lcd %:p:h   : change to directory of current file automatically (put in _vimrc)
----------------------------------------
" Changing Case
guu                             : lowercase line
gUU                             : uppercase line
Vu                              : lowercase line
VU                              : uppercase line
g~~                             : flip case line
vEU                             : Upper Case Word
vE~                             : Flip Case Word
ggguG                           : lowercase entire file
" Titlise Visually Selected Text (map for .vimrc)
vmap ,c :s/\<\(.\)\(\k*\)\>/\u\1\L\2/g<CR>
" titlise a line
nmap ,t :s/.*/\L&/<bar>:s/\<./\u&/g<cr>  *N*
" Uppercase first letter of sentences
:%s/[.!?]\_s\+\a/\U&\E/g
----------------------------------------
gf                              : open file name under cursor (SUPER)
:nnoremap gF :view <cfile><cr>  : open file under cursor, create if necessary
ga                              : display hex,ascii value of char under cursor
ggVGg?                          : rot13 whole file
ggg?G                           : rot13 whole file (quicker for large file)
:8 | normal VGg?                : rot13 from line 8
:normal 10GVGg?                 : rot13 from line 8
<C-A>,<C-X>                     : increment,decrement number under cursor
                                  win32 users must remap CNTRL-A
<C-R>=5*5                       : insert 25 into text (mini-calculator)
----------------------------------------
" Make all other tips superfluous
:h 42            : also http://www.google.com/search?q=42
:h holy-grail
:h!
----------------------------------------
" disguise text (watch out) *N*
ggVGg?                          : rot13 whole file (toggles)
:set rl!                        : reverse lines right to left (toggles)
:g/^/m0                         : reverse lines top to bottom (toggles)
----------------------------------------
" Markers & moving about
'.               : jump to last modification line (SUPER)
`.               : jump to exact spot in last modification line
g;               : cycle thru recent changes (oldest first)
g,               : reverse direction 
:changes
:h changelist    : help for above
<C-O>            : retrace your movements in file (starting from most recent)
<C-I>            : retrace your movements in file (reverse direction)
:ju(mps)         : list of your movements
:help jump-motions
:history         : list of all your commands
:his c           : commandline history
:his s           : search history
q/               : Search history Window (puts you in full edit mode) (exit CTRL-C)
q:               : commandline history Window (puts you in full edit mode) (exit CTRL-C)
:<C-F>           : history Window (exit CTRL-C)
----------------------------------------
" Abbreviations & Maps
" Following 4 maps enable text transfer between VIM sessions
:map   <f7>   :'a,'bw! c:/aaa/x       : save text to file x
:map   <f8>   :r c:/aaa/x             : retrieve text 
:map   <f11>  :.w! c:/aaa/xr<CR>      : store current line
:map   <f12>  :r c:/aaa/xr<CR>        : retrieve current line
:ab php          : list of abbreviations beginning php
:map ,           : list of maps beginning ,
" allow use of F10 for mapping (win32)
set wak=no       : :h winaltkeys
" For use in Maps
<CR>             : carriage Return for maps
<ESC>            : Escape
<LEADER>         : normally \
<BAR>            : | pipe
<BACKSPACE>      : backspace
<SILENT>         : No hanging shell window
#display RGB colour under the cursor eg #445588
:nmap <leader>c :hi Normal guibg=#<c-r>=expand("<cword>")<cr><cr>
map <f2> /price only\\|versus/ :in a map need to backslash the \
# type table,,, to get <table></table>       ### Cool ###
imap ,,, <esc>bdwa<<esc>pa><cr></<esc>pa><esc>kA
----------------------------------------
" Simple PHP debugging display all variables yanked into register a
iab phpdb exit("<hr>Debug <C-R>a  ");
----------------------------------------
" Using a register as a map (preload registers in .vimrc)
:let @m=":'a,'bs/"
:let @s=":%!sort -u"
----------------------------------------
" Useful tricks
"ayy@a           : execute "Vim command" in a text file
yy@"             : same thing using unnamed register
u@.              : execute command JUST typed in
"ddw             : store what you delete in register d *N*
"ccaw            : store what you change in register c *N*
----------------------------------------
" Get output from other commands (requires external programs)
:r!ls -R         : reads in output of ls
:put=glob('**')  : same as above                 *N*
:r !grep "^ebay" file.txt  : grepping in content   *N*
:20,25 !rot13    : rot13 lines 20 to 25   *N*
!!date           : same thing (but replaces/filters current line)
" Sorting with external sort
:%!sort -u       : use an external program to filter content
:'a,'b!sort -u   : use an external program to filter content
!1} sort -u      : sorts paragraph (note normal mode!!)
:g/^$/;,/^$/-1!sort : Sort each block (note the crucial ;)
" Sorting with internal sort
:sort /.*\%2v/   : sort all lines on second column *N*
----------------------------------------
" Multiple Files Management (Essential)
:bn              : goto next buffer
:bp              : goto previous buffer
:wn              : save file and move to next (super)
:wp              : save file and move to previous
:bd              : remove file from buffer list (super)
:bun             : Buffer unload (remove window but not from list)
:badd file.c     : file from buffer list
:b3              : go to buffer 3 *C*
:b main          : go to buffer with main in name eg main.c (ultra)
:sav php.html    : Save current file as php.html and "move" to php.html
:sav! %<.bak     : Save Current file to alternative extension (old way)
:sav! %:r.cfm    : Save Current file to alternative extension
:sav %:s/fred/joe/           : do a substitute on file name
:sav %:s/fred/joe/:r.bak2    : do a substitute on file name & ext.
:!mv % %:r.bak   : rename current file (DOS use Rename or DEL)
:help filename-modifiers
:e!              : return to unmodified file
:w c:/aaa/%      : save file elsewhere
:e #             : edit alternative file (also cntrl-^)
:rew             : return to beginning of edited files list (:args)
:brew            : buffer rewind
:sp fred.txt     : open fred.txt into a split
:sball,:sb       : Split all buffers (super)
:scrollbind      : in each split window
:map   <F5> :ls<CR>:e # : Pressing F5 lists all buffer, just type number
:set hidden      : Allows to change buffer w/o saving current buffer
----------------------------------------
" Quick jumping between splits
map <C-J> <C-W>j<C-W>_
map <C-K> <C-W>k<C-W>_
----------------------------------------
" Recording (BEST TIP of ALL)
qq  # record to q
your complex series of commands
q   # end recording
@q to execute
@@ to Repeat
5@@ to Repeat 5 times
qQ@qq                             : Make an existing recording q recursive *N*
" editing a register/recording
"qp                               :display contents of register q (normal mode)
<ctrl-R>q                         :display contents of register q (insert mode)
" you can now see recording contents, edit as required
"qdd                              :put changed contacts back into q
@q                                :execute recording/register q
" Operating a Recording on a Visual BLOCK
1) define recording/register
qq:s/ to/ from/g^Mq
2) Define Visual BLOCK
V}
3) hit : and the following appears
:'<,'>
4)Complete as follows
:'<,'>norm @q
----------------------------------------
"combining a recording with a map (to end up in command mode)
:nnoremap ] @q:update<bar>bd
----------------------------------------
" Visual is the newest and usually the most intuitive editing mode
" Visual basics
v                               : enter visual mode
V                               : visual mode whole line
<C-V>                           : enter VISUAL BLOCK mode
gv                              : reselect last visual area (ultra)
o                               : navigate visual area
"*y or "+y                      : yank visual area into paste buffer  *C*
V%                              : visualise what you match
V}J                             : Join Visual block (great)
V}gJ                            : Join Visual block w/o adding spaces
`[v`]                           : Highlight last insert
:%s/\%Vold/new/g                : Do a substitute on last visual area *N*
----------------------------------------
" Delete first 2 characters of 10 successive lines
0<c-v>10j2ld
----------------------------------------
" how to copy a set of columns using VISUAL BLOCK
" visual block (AKA columnwise selection) (NOT BY ordinary v command)
<C-V> then select "column(s)" with motion commands (win32 <C-Q>)
then c,d,y,r etc
----------------------------------------
" how to overwrite a visual-block of text with another such block *C*
" move with hjkl etc
Pick the first block: ctrl-v move y
Pick the second block: ctrl-v move P <esc>
----------------------------------------
" text objects :h text-objects                                     *C*
daW                                   : delete contiguous non whitespace
di<   yi<  ci<                        : Delete/Yank/Change HTML tag contents
da<   ya<  ca<                        : Delete/Yank/Change whole HTML tag
dat   dit                             : Delete HTML tag pair
diB   daB                             : Empty a function {}
das                                   : delete a sentence
----------------------------------------
" _vimrc essentials
:set incsearch : jumps to search word as you type (annoying but excellent)
:set wildignore=*.o,*.obj,*.bak,*.exe : tab complete now ignores these
:set shiftwidth=3                     : for shift/tabbing
:set vb t_vb=".                       : set silent (no beep)
:set browsedir=buffer                 : Maki GUI File Open use current directory
----------------------------------------
" launching Win IE
:nmap ,f :update<CR>:silent !start c:\progra~1\intern~1\iexplore.exe file://%:p<CR>
:nmap ,i :update<CR>: !start c:\progra~1\intern~1\iexplore.exe <cWORD><CR>
----------------------------------------
" FTPing from VIM
cmap ,r  :Nread ftp://209.51.134.122/public_html/index.html
cmap ,w  :Nwrite ftp://209.51.134.122/public_html/index.html
gvim ftp://www.somedomain.com/index.html # uses netrw.vim
----------------------------------------
" appending to registers (use CAPITAL)
" yank 5 lines into "a" then add a further 5
"a5yy
10j
"A5yy
----------------------------------------
[I     : show lines matching word under cursor <cword> (super)
----------------------------------------
" Conventional Shifting/Indenting
:'a,'b>>
" visual shifting (builtin-repeat)
:vnoremap < <gv
:vnoremap > >gv
" Block shifting (magic)
>i{
>a{
" also
>% and <%
----------------------------------------
" Redirection & Paste register *
:redir @*                    : redirect commands to paste buffer
:redir END                   : end redirect
:redir >> out.txt            : redirect to a file
" Working with Paste buffer
"*yy                         : yank to paste
"*p                          : insert from paste buffer
" yank to paste buffer (ex mode)
:'a,'by*                     : Yank range into paste
:%y*                         : Yank whole buffer into paste
:.y*                         : Yank Current line to paster
" filter non-printable characters from the paste buffer
" useful when pasting from some gui application
:nmap <leader>p :let @* = substitute(@*,'[^[:print:]]','','g')<cr>"*p
----------------------------------------
" Re-Formatting text
gq}                          : Format a paragraph
gqap                         : Format a paragraph
ggVGgq                       : Reformat entire file
Vgq                          : current line
" break lines at 70 chars, if possible after a ;
:s/.\{,69\};\s*\|.\{,69\}\s\+/&\r/g
----------------------------------------
" Operate command over multiple files
:argdo %s/foo/bar/e          : operate on all files in :args
:bufdo %s/foo/bar/e
:windo %s/foo/bar/e
:argdo exe '%!sort'|w!       : include an external command
:bufdo exe "normal @q" | w   : perform a recording on open files
:silent bufdo !zip proj.zip %:p   : zip all current files
----------------------------------------
" Command line tricks
gvim -h                    : help
ls | gvim -                : edit a stream!!
cat xx | gvim - -c "v/^\d\d\|^[3-9]/d " : filter a stream
gvim -o file1 file2        : open into a split
" execute one command after opening file
gvim.exe -c "/main" joe.c  : Open joe.c & jump to "main"
" execute multiple command on a single file
vim -c "%s/ABC/DEF/ge | update" file1.c
" execute multiple command on a group of files
vim -c "argdo %s/ABC/DEF/ge | update" *.c
" remove blocks of text from a series of files
vim -c "argdo /begin/+1,/end/-1g/^/d | update" *.c
" Automate editing of a file (Ex commands in convert.vim)
vim -s "convert.vim" file.c
#load VIM without .vimrc and plugins (clean VIM)
gvim -u NONE -U NONE -N
" Access paste buffer contents (put in a script/batch file)
gvim -c 'normal ggdG"*p' c:/aaa/xp
" print paste contents to default printer
gvim -c 's/^/\=@*/|hardcopy!|q!'
" gvim's use of external grep (win32 or *nix)
:grep somestring *.php     : creates a list of all matching files
" use :cn(ext) :cp(rev) to navigate list
:h grep
" Using vimgrep with copen                              *N*
:vimgrep /keywords/ *.php
:copen
----------------------------------------
" GVIM Difference Function (Brilliant)
gvim -d file1 file2        : vimdiff (compare differences)
dp                         : "put" difference under cursor to other file
do                         : "get" difference under cursor from other file
" complex diff parts of same file *N*
:1,2yank a | 7,8yank b
:tabedit | put a | vnew | put b
:windo diffthis 
----------------------------------------
" Vim traps
In regular expressions you must backslash + (match 1 or more)
In regular expressions you must backslash | (or)
In regular expressions you must backslash ( (group)
In regular expressions you must backslash { (count)
/fred\+/                   : matches fred/freddy but not free
/\(fred\)\{2,3}/           : note what you have to break
----------------------------------------
" \v or very magic (usually) reduces backslashing
/codes\(\n\|\s\)*where  : normal regexp
/\vcodes(\n|\s)*where   : very magic
----------------------------------------
" pulling objects onto command/search line (SUPER)
<C-R><C-W> : pull word under the cursor into a command line or search
<C-R><C-A> : pull WORD under the cursor into a command line or search
<C-R>-                  : pull small register (also insert mode)
<C-R>[0-9a-z]           : pull named registers (also insert mode)
<C-R>%                  : pull file name (also #) (also insert mode)
<C-R>=somevar           : pull contents of a variable (eg :let sray="ray[0-9]")
----------------------------------------
" List your Registers
:reg             : display contents of all registers
:reg a           : display content of register a
:reg 12a         : display content of registers 1,2 & a *N*
"5p              : retrieve 5th "ring" 
"1p....          : retrieve numeric registers one by one
:let @y='yy@"'   : pre-loading registers (put in .vimrc)
qqq              : empty register "q"
qaq              : empty register "a"
:reg .-/%:*"     : the seven special registers *N*
:reg 0           : what you last yanked, not affected by a delete *N*
"_dd             : Delete to blackhole register "_ , don't affect any register *N*
----------------------------------------
" manipulating registers
:let @a=@_              : clear register a
:let @a=""              : clear register a
:let @a=@"              : Save unnamed register *N*
:let @*=@a              : copy register a to paste buffer
:let @*=@:              : copy last command to paste buffer
:let @*=@/              : copy last search to paste buffer
:let @*=@%              : copy current filename to paste buffer
----------------------------------------
" help for help (USE TAB)
:h quickref             : VIM Quick Reference Sheet (ultra)
:h tips                 : Vim's own Tips Help
:h visual<C-D><tab>     : obtain  list of all visual help topics
                        : Then use tab to step thru them
:h ctrl<C-D>            : list help of all control keys
:helpg uganda           : grep HELP Files use :cn, :cp to find next
:helpgrep edit.*director: grep help using regexp
:h :r                   : help for :ex command
:h CTRL-R               : normal mode
:h /\r                  : what's \r in a regexp (matches a <CR>)
:h \\zs                 : double up backslash to find \zs in help
:h i_CTRL-R             : help for say <C-R> in insert mode
:h c_CTRL-R             : help for say <C-R> in command mode
:h v_CTRL-V             : visual mode
:h tutor                : VIM Tutor
<C-[>, <C-T>            : Move back & Forth in HELP History
gvim -h                 : VIM Command Line Help
:cabbrev h tab h        : open help in a tab *N*
----------------------------------------
" where was an option set
:scriptnames            : list all plugins, _vimrcs loaded (super)
:verbose set history?   : reveals value of history and where set
:function               : list functions
:func SearchCompl       : List particular function
----------------------------------------
" making your own VIM help
:helptags /vim/vim64/doc  : rebuild all *.txt help files in /doc
:help add-local-help
----------------------------------------
" running file thru an external program (eg php)
map   <f9>   :w<CR>:!c:/php/php.exe %<CR>
map   <f2>   :w<CR>:!perl -c %<CR>
----------------------------------------
" capturing output of current script in a separate buffer
:new | r!perl #                   : opens new buffer,read other buffer
:new! x.out | r!perl #            : same with named file
:new+read!ls
----------------------------------------
" create a new buffer, paste a register "q" into it, then sort new buffer
:new +put q|%!sort
----------------------------------------
" Inserting DOS Carriage Returns
:%s/$/\<C-V><C-M>&/g          :  that's what you type
:%s/$/\<C-Q><C-M>&/g          :  for Win32
:%s/$/\^M&/g                  :  what you'll see where ^M is ONE character
----------------------------------------
" automatically delete trailing Dos-returns,whitespace
autocmd BufRead * silent! %s/[\r \t]\+$//
autocmd BufEnter *.php :%s/[ \t\r]\+$//e
----------------------------------------
" perform an action on a particular file or file type
autocmd VimEnter c:/intranet/note011.txt normal! ggVGg?
autocmd FileType *.pl exec('set fileformats=unix')
----------------------------------------
" Retrieving last command line command for copy & pasting into text
i<c-r>:
" Retrieving last Search Command for copy & pasting into text
i<c-r>/
----------------------------------------
" more completions
<C-X><C-F>                        :insert name of a file in current directory
----------------------------------------
" Substituting a Visual area
" select visual area as usual (:h visual) then type :s/Emacs/Vim/ etc
:'<,'>s/Emacs/Vim/g               : REMEMBER you dont type the '<.'>
gv                                : Re-select the previous visual area (ULTRA)
----------------------------------------
" inserting line number into file
:g/^/exec "s/^/".strpart(line(".")."    ", 0, 4)
:%s/^/\=strpart(line(".")."     ", 0, 5)
:%s/^/\=line('.'). ' '
----------------------------------------
#numbering lines VIM way
:set number                       : show line numbers
:map <F12> :set number!<CR>       : Show linenumbers flip-flop
:%s/^/\=strpart(line('.')."        ",0,&ts)
#numbering lines (need Perl on PC) starting from arbitrary number
:'a,'b!perl -pne 'BEGIN{$a=223} substr($_,2,0)=$a++'
#Produce a list of numbers
#Type in number on line say 223 in an empty file
qqmnYP`n^Aq                       : in recording q repeat with @q
" increment existing numbers to end of file (type <c-a> as 5 characters)
:.,$g/^\d/exe "normal! \<c-a>"
" advanced incrementing
http://vim.sourceforge.net/tip_view.php?tip_id=150
----------------------------------------
" advanced incrementing (really useful)
" put following in _vimrc
let g:I=0
function! INC(increment)
let g:I =g:I + a:increment
return g:I
endfunction
" eg create list starting from 223 incrementing by 5 between markers a,b
:let I=223
:'a,'bs/^/\=INC(5)/
" create a map for INC
cab viminc :let I=223 \| 'a,'bs/$/\=INC(5)/
----------------------------------------
" generate a list of numbers  23-64
o23<ESC>qqYp<C-A>q40@q
----------------------------------------
" editing/moving within current insert (Really useful)
<C-U>                             : delete all entered
<C-W>                             : delete last word
<HOME><END>                       : beginning/end of line
<C-LEFTARROW><C-RIGHTARROW>       : jump one word backwards/forwards
<C-X><C-E>,<C-X><C-Y>             : scroll while staying put in insert
----------------------------------------
#encryption (use with care: DON'T FORGET your KEY)
:X                                : you will be prompted for a key
:h :X
----------------------------------------
" modeline (make a file readonly etc) must be in first/last 5 lines
// vim:noai:ts=2:sw=4:readonly:
" vim:ft=html:                    : says use HTML Syntax highlighting
:h modeline
----------------------------------------
" Creating your own GUI Toolbar entry
amenu  Modeline.Insert\ a\ VIM\ modeline <Esc><Esc>ggOvim:ff=unix ts=4 ss=4<CR>vim60:fdm=marker<esc>gg
----------------------------------------
" A function to save word under cursor to a file
function! SaveWord()
   normal yiw
   exe ':!echo '.@0.' >> word.txt'
endfunction
map ,p :call SaveWord()
----------------------------------------
" function to delete duplicate lines
function! Del()
 if getline(".") == getline(line(".") - 1)
   norm dd
 endif
endfunction

:g/^/ call Del()
----------------------------------------
" Digraphs (non alpha-numerics)
:digraphs                         : display table
:h dig                            : help
i<C-K>e'                          : enters ?i<C-V>233                         : enters ?(Unix)
i<C-Q>233                         : enters ?(Win32)
ga                                : View hex value of any character
#Deleting non-ascii characters (some invisible)
:%s/[\x00-\x1f\x80-\xff]/ /g      : type this as you see it
:%s/[<C-V>128-<C-V>255]//gi       : where you have to type the Control-V
:%s/[€-]//gi                     : Should see a black square & a dotted y
:%s/[<C-V>128-<C-V>255<C-V>01-<C-V>31]//gi : All pesky non-asciis
:exec "norm /[\x00-\x1f\x80-\xff]/"        : same thing
#Pull a non-ascii character onto search bar
yl/<C-R>"                         :
/[^a-zA-Z0-9_[:space:][:punct:]]  : search for all non-ascii
----------------------------------------
" All file completions grouped (for example main_c.c)
:e main_<tab>                     : tab completes
gf                                : open file under cursor  (normal)
main_<C-X><C-F>                   : include NAME of file in text (insert mode)
----------------------------------------
" Complex Vim
" swap two words
:%s/\<\(on\|off\)\>/\=strpart("offon", 3 * ("off" == submatch(0)), 3)/g
" swap two words
:vnoremap <C-X> <Esc>`.``gvP``P
" Swap word with next word
nmap <silent> gw    "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l> *N*
----------------------------------------
" Convert Text File to HTML
:runtime! syntax/2html.vim        : convert txt to html
:h 2html
----------------------------------------
" VIM has internal grep
:grep some_keyword *.c            : get list of all c-files containing keyword
:cn                               : go to next occurrence
----------------------------------------
" Force Syntax coloring for a file that has no extension .pl
:set syntax=perl
" Remove syntax coloring (useful for all sorts of reasons)
:set syntax off
" change coloring scheme (any file in ~vim/vim??/colors)
:colorscheme blue
" Force HTML Syntax highlighting by using a modeline
# vim:ft=html:
" Force syntax automatically (for a file with non-standard extension)
au BufRead,BufNewFile */Content.IE?/* setfiletype html
----------------------------------------
:set noma (non modifiable)        : Prevents modifications
:set ro (Read Only)               : Protect a file from unintentional writes
----------------------------------------
" Sessions (Open a set of files)
gvim file1.c file2.c lib/lib.h lib/lib2.h : load files for "session"
:mksession                        : Make a Session file (default Session.vim)
:q
gvim -S Session.vim               : Reload all files
----------------------------------------
#tags (jumping to subroutines/functions)
taglist.vim                       : popular plugin
:Tlist                            : display Tags (list of functions)
<C-]>                             : jump to function under cursor
----------------------------------------
" columnise a csv file for display only as may crop wide columns
:let width = 20
:let fill=' ' | while strlen(fill) < width | let fill=fill.fill | endwhile
:%s/\([^;]*\);\=/\=strpart(submatch(1).fill, 0, width)/ge
:%s/\s\+$//ge
" Highlight a particular csv column (put in .vimrc)
function! CSVH(x)
    execute 'match Keyword /^\([^,]*,\)\{'.a:x.'}\zs[^,]*/'
    execute 'normal ^'.a:x.'f,'
endfunction
command! -nargs=1 Csv :call CSVH(<args>)
" call with
:Csv 5                             : highlight fifth column
----------------------------------------
" folding : hide sections to allow easier comparisons
zf}                               : fold paragraph using motion
v}zf                              : fold paragraph using visual
zf'a                              : fold to mark
zo                                : open fold
zc                                : re-close fold
:help folding
----------------------------------------
" displaying "non-asciis"
:set list
:h listchars
----------------------------------------
" How to paste "normal commands" w/o entering insert mode
:norm qqy$jq
----------------------------------------
" manipulating file names
:h filename-modifiers             : help
:w %                              : write to current file name
:w %:r.cfm                        : change file extention to .cfm
:!echo %:p                        : full path & file name
:!echo %:p:h                      : full path only
:!echo %:t                        : filename only
:reg %                            : display filename
<C-R>%                            : insert filename (insert mode)
"%p                               : insert filename (normal mode)
/<C-R>%                           : Search for file name in text
----------------------------------------
" delete without destroying default buffer contents
"_d                               : what you've ALWAYS wanted
"_dw                              : eg delete word (use blackhole)
----------------------------------------
" pull full path name into paste buffer for attachment to email etc
nnoremap <F2> :let @*=expand("%:p")<cr> :unix
nnoremap <F2> :let @*=substitute(expand("%:p"), "/", "\\", "g")<cr> :win32
----------------------------------------
" Simple shell script to rename files w/o leaving vim
$ vim
:r! ls *.c
:%s/\(.*\).c/mv & \1.bla
:w !sh
:q!
----------------------------------------
" count words in a text file
g<C-G>
----------------------------------------
" example of setting your own highlighting
:syn match DoubleSpace "  "
:hi def DoubleSpace guibg=#e0e0e0
----------------------------------------
" reproduce previous line word by word
imap ]  @@@<ESC>hhkyWjl?@@@<CR>P/@@@<CR>3s
nmap ] i@@@<ESC>hhkyWjl?@@@<CR>P/@@@<CR>3s
" Programming keys depending on file type
:autocmd bufenter *.tex map <F1> :!latex %<CR>
:autocmd bufenter *.tex map <F2> :!xdvi -hush %<.dvi&<CR>
----------------------------------------
" reading Ms-Word documents, requires antiword
:autocmd BufReadPre *.doc set ro
:autocmd BufReadPre *.doc set hlsearch!
:autocmd BufReadPost *.doc %!antiword "%"
----------------------------------------
" a folding method
vim: filetype=help foldmethod=marker foldmarker=<<<,>>>
A really big section closed with a tag <<< 
--- remember folds can be nested --- 
Closing tag >>> 
----------------------------------------
" Return to last edit position (You want this!) *N*
autocmd BufReadPost *
     \ if line("'\"") > 0 && line("'\"") <= line("$") |
     \   exe "normal! g`\"" |
     \ endif
----------------------------------------
" store text that is to changed,deleted in register a
"act<                                 :  Change Till < *N*
----------------------------------------
" Just Another Vim Hacker JAVH
vim -c ":%s%s*%Cyrnfr)fcbafbe[Oenz(Zbbyranne%|:%s)[[()])-)Ig|norm Vg?"
----------------------------------------
__END__

学习VIM

第一部分:VI简介

Vi的历史

Vi前身ed,是一个单行文本编辑器;

vi是程序员编辑器;

linux中的多种文本编辑器

vi
linux学习者需要掌握的第一个文本编辑器 大多数Linux系统中缺省使用的文本编辑器

Emacs
用于编辑程序源代码文件的文本编辑器

nano
在字符界面提供了菜单操作,易用性较好

gedit
GNOME图形环境中的文本编辑器

注意:如果有两个人同时用vi编辑一个文件,以最后一个人保存的文件为最后版本。

VI和VIM的区别

它们都是多模式编辑器,不同的是vim 是vi的升级版本,它不仅兼容vi的所有指令,而且还有一些新的特性在里面。vim的这些优势主要体现在以下几个方面: 

易用性 vi只能运行于unix中,而vim不仅可以运行于unix,windows ,mac等多操作平台。
语法加亮 vim可以用不同的颜色来加亮你的代码。
可视化操作(ESC+V) 就是说vim不仅可以在终端运行,也可以运行于x window、mac os、windows。
对vi的完全兼容 某些情况下,你可以把vim当成vi来使用

vim提供三种模式

20101008-223834

命令模式:控制光标移动,删除字符,段落复制(按ESC)

进入编辑模式/插入模式:新增文字及修改文字
i光标当前处插入
I光标当前行首插入

a光标之后插入
A光标所在行的行尾插入

o光标所在行之后新起一行插入
O光标所在行之前新起一行插入

末行模式:保存文件,离开vi,以及其他设置(从命令模式进入,按:)

第二部分 VI编辑器的基本使用

1.进入Vi的命令
vi filename :打开或新建文件,将光标置于第一行首
vi +n filename :打开文件,并将光标置于第n行首
vi + filename :打开文件,并将光标置于最后一行行首
vi + /pattern filename:打开文件,并将光标置于与pattern匹配的串处
vi -r filename:在上次正用vi编辑时发生系统崩溃,恢复filename

-r用于恢复系统突然崩溃时正在编辑的文件
-R用于以只读方式打开文件
+n用来指明进入vi后直接位于文件的第n行,如果不指定n,则位于最后一行

2.vi中的文件操作

(1)打开新文件

打开新的文件到vi编辑器中

:e filename

打开新的文件到vi编辑器中,并放弃对当前文件的修改

:e! filename

读取文件内容到当前vi编辑器中

:r filename

(2)文件保存与另存为

保存文件

保存对vi编辑器中已打开文件的修改

:w

另存为文件

将vi编辑器中的内容另存为指定文件名

:w myfile

ZZ:连按2次Z键,可将当前正在编辑的文件保存并结束vi (命令模式)

(3)退出VI编辑器的多种方法

未修改退出

没有对vi编辑器中打开的文件进行修改,或已对修改进行了保存,直接退出vi编辑器

:q

保存并退出

对vi编辑器中的文件进行保存并退出vi编辑器

:qw

不保存退出

放弃对文件内容的修改,并退出vi编辑器

:q!

3.光标移动

在编辑模式下按ESC键可进入到命令模式

命令 说明
h 将光标向左移动一格
l 将光标向右移动一格
j 将光标向下移动一格
k 将光标向上移动一格
0 数字0,将光标移动到该行的行首
$ 将光标移动到该行的行末
H 将光标移动到该屏幕的顶端
M 将光标移动到该屏幕的中间
L 将光标移动到该屏幕的底端
gg 将光标移动到文章的首行
G 将光标移动到文章的尾行

nG 将光标移动到文章的第n行

n 将光标向下移动n行
w或W 将光标移动到下一单词

r:在command mode只要将光标停在要修改的位置,然后按r键,就可以修改一个字符

[CTRL][d] 向下半页 ? [PageDown]
[CTRL][f] 向下一页
[CTRL][u] 向上半页?
[CTRL][b] 向上一页 [PageUp]

^ 移动光标到本行最开头的字符处

$ 将光标快速跳转到本行的行尾字符

文件内行间快速跳转

显示每行 :set nu

取消行号:
:se nonu
1G 跳转到文件的首行
G 跳转到文件的末尾行

#G 跳转到文件中的第#行

第三部分:三种模式下的操作

一、命令模式:控制光标移动,删除字符,段落复制(按ESC)

无论用户处于什么状态,按Esc键或组合键Ctrl+[ 就可以进入命令方式。当用户初始进入vi时,也处于这个状态。

用户在命令方式下可以输入各种合法的vi内部命令,这些命令不会回显,而且不需要回车就会被执行

1.光标移动(代替光标键)

命令 说明
h 将光标向左移动一格
l 将光标向右移动一格
j 将光标向下移动一格
k 将光标向上移动一格
0 数字0,将光标移动到该行的行首
$ 将光标移动到该行的行末
H 将光标移动到该屏幕的顶端
M 将光标移动到该屏幕的中间
L 将光标移动到该屏幕的底端
gg 将光标移动到文章的首行
G 将光标移动到文章的尾行

nG 将光标移动到文章的第n行

n 将光标向下移动n行

n- 将光标向上移动n行
w或W 将光标移动到下一单词

r:在command mode只要将光标停在要修改的位置,然后按r键,就可以修改一个字符

[CTRL][d] 向下半页 ? [PageDown]
[CTRL][f] 向下一页
[CTRL][u] 向上半页?
[CTRL][b] 向上一页 [PageUp]

2.命令模式,删除与块操作
在命令模式下可以直接删除字符

(1)在命令模式下键入v则进入块操作:
1、移动光标以选定操作块
2、c 剪切选定块 或 y 复制选定块
3、p 将选定内容贴在光标所在位置右手边

在vi中剪贴
yy:选定光标所在行复制
nyy:复制光标往下n行
yw:选定光标所在词复制
nyw:选定光标所在位置到之后n个单词复制
y$:选定光标所在位置到行尾的部分复制
p:贴在光标所在位置的下一行
P:贴在光标所在位置的上一行
将1行到5行之间的内容拷贝到第10行下  :1,5 co 10
:n1,n2 m n3 用于块移动

(2)在vi中删除
x/:删除一个字符
nx:删除下n个字符
dd:删除当前行
dw:删除当前字符到单词尾(包括空格)的所有字符
de 删除当前字符到单词尾(不包括单词尾部的空格)的所有字符

ndw:删除后n个词
d$:删至行尾
D:删至行尾
d^ 删除当前字符到行首的所有字符

nd$:删除后n行
dG:删除光标所在行到末尾的内容
J 删除光标所在行行尾的换行符,相当于合并当前行和下一行的内容
d1G:删除光标所在位置到第一行的所有内容

ndd:若按3dd键,表示删除当前光标位置的1行与下面两行

:2,8d 删除2-8行

r 修改光标所在字元,r 後接著要修正的字符。

R 进入取替换状态,新增文字会覆盖原先文字,直 到按 [ESC] 回到命令模式下为止。

(3)命令模式,取消操作
u:取消上一个更动 取消到上次打开文件的点上 ctrl+r 撤消刚才的取消
U:取消一行内的所有更动
:e! :放弃所有更动,重新编辑

ZZ:连按2次Z键,可将当前正在编辑的文件保存并结束vi

(4)替换操作
r 替换光标所在处的一个字符,用法,在命令模式下,按下r,然后输入要替换的字符。
R 从光标所在处开始替换字符,按ESC结束
s 替换光标所在处在的字符,并进入插入模式
S 替换光标所在的全行

以下为在末行模式下操作:
替换操作
:s/old/new 替换当前行的第一个字符old为字符new
:s/old/new/g 替换当前行的所有字符old为字符new
:m,ns/old/new/g 替换当前行号m到行号n的所有字符old为字符new
:%s/old/new/g 替换整个文本的所有字符old为字符new

使用替换的确认功能
:s/old/new/c 替换当前行的第一个字符old为字符new并提示用户确认操作
:s/old/new/gc 替换当前行的所有字符old为字符new并提示用户确认操作
:m,ns/old/new/gc 替换当前行号m到行号n的所有字符old为字符new并提示用户确认操作
:%s/old/new/gc 替换整个文本的所有字符old为字符new并提示用户确认操作

(4)其他操作
xp
交换两个字符位置
ddp
上下两行调换
J
上下两行合并
dG
删除所有行
d$
从当前位置删除到行尾
y$
从当前位置复制到行尾, 如果要粘贴到其他地方 p 就可以了

二、进入编辑(插入)模式

如何进入VIM编辑模式 ?
i光标当前处插入
I光标当前行首插入

a光标之后插入
A光标所在行的行尾插入

o光标所在行之后新起一行插入
O光标所在行之前新起一行插入
cw 删除当前光标到所在单词尾部的字符,并进入插入状态
c$ 删除当前光标到行尾的字符,并进入插入状态
c^ 命令删除当前光标之前(不包括光标上的字符)到行首的字符,并进入插入状态

s:删除光标所在字符并进入插入模式

S:删除光标所在行并进入插入模式

三、末行模式在命令模式下输入“:”进入末行模式

这种方式下vi会在屏幕的最后一行显示一个冒号并等待用户输入命令.末行方式下用户输入的命令将回显在最后一行上,并且直到用户输入回车vi才会去执行它

命令执行完毕后,vi自动进入命令状态

:w [文件名] 保存当前文件
:q 如果未对文件做改动则退出
:wq :x 保存当前文件并退出
:q! 放弃存储并退出
:e 文件名 打开另一文件并开始编辑
:r 文件名 在当前光标插入文件内容
:nr <文件> 把<文件>插入到第n行

:r! 命令在当前光标插入命令执行结果
:f filename : 将当前文件重命名为 filename

:e! 将文件回复到原始状态
:!命令 执行shell命令,在vi内使用shell用户在运行vi的过程中不用退出vi就可以运行任何UNIX命令

:sh 转到SHELL

:so <文件> 读取<文件>,再执行文件里面的命令

:n,n1 w 文件名
把从n行到n1行写道另外一个文件中

:7 跳到第7行
:n1,n2 co n3 用于块复制
:n1,n2 m n3 用于块移动
:n1,n2 d 用于块删除

查找命令
/string、?string——从光标所在处向后或向前查找相应的字符串的命令。
n 定位下一个匹配的被查找字符串
N 定位上一个匹配的被查找字符串

替换操作
:s/old/new 替换当前行的第一个字符old为字符new
:s/old/new/g 替换当前行的所有字符old为字符new
:m,ns/old/new/g 替换当前行号m到行号n的所有字符old为字符new
:%s/old/new/g 替换整个文本的所有字符old为字符new

使用替换的确认功能
:s/old/new/c 替换当前行的第一个字符old为字符new并提示用户确认操作
:s/old/new/gc 替换当前行的所有字符old为字符new并提示用户确认操作
:m,ns/old/new/gc 替换当前行号m到行号n的所有字符old为字符new并提示用户确认操作
:%s/old/new/gc 替换整个文本的所有字符old为字符new并提示用户确认操作

:set [all]
vi or ex 的编辑状态
如 显示每行 :set nu
取消行号:
:se nonu
:X
然后系统会提示输入密码, 输入密码后存盘退出(用wq), 保存后就加密了
下次编辑时使用vi -x filename, 系统会提示你输入密码

:set ignorecase 查找时不考虑大小写
:set noic 查找时考虑大小写

:n,n1 w 文件名
把从n行到n1行写道另外一个文件中

:syntax enable

Ctrl+g或G:按此组合键,则会在最下方的last line处显示

光标所在位置的行数,以及文章的总行数。

nG:n为数字,若按下20G键,则可将光标移到第20行

vi多文件操作命令

1.使用vi打开多个文件

在输入vi命令时使用多个文件名作为参数

vi file1 file2 file3 ...

2.vi多文件操作命令

:args 显示多文件信息

:next 向后切换文件

:prev 向前切换文件

:first 定位首文件

:last 定位尾文件

Ctrl + ^ 快速切换到编辑器中切换前的文件

定制VI会话:

:set nu 显示每行

:se nonu 取消行号
:set ignorecase 查找时不考虑大小写
:set noic 查找时考虑大小写
:set list 显示不可视字符
:set nolist 不显示不可视字符
:set showmode 显示当前操作模式
:set shownomode 不显示当前操作模式
:set all 显示所有的vi环境变更可能取值及当前设置值
:set backup 是否自动储存备份文件
:set nobackup
:set ruler 是否在右下角显示状态行说明
:syntax enable

第三部分:常见问题及应用技巧

---- 1.在一个新文件中读/etc/passwd中的内容,取出用户名部分。

---- vi file
---- :r /etc/passwd 在打开的文件file中光标所在处读入/etc/passwd
---- :%s/:.*//g 删除/etc/passwd中用户名后面的从冒号开始直到行尾的所有部分。
---- 您也可以在指定的行号后读入文件内容,例如使用命令“:3r /etc/passwd”从新文件的第3行开始读入 /etc/passwd的所有内容。
---- 我们还可以使用以下方法删掉文件中所有的空行及以#开始的注释行。
---- #cat squid.conf.default | grep -v '^$' | grep -v '^#'

---- 2.在打开一个文件编辑后才知道登录的用户对该文件没有写的权限,不能存盘,需要将所做修改存入临时文件。

---- vi file
---- :w /tmp/1 保存所做的所有修改,也可以将其中的某一部分修改保存到临时文件,例如仅仅把第20~59行之间的内容存盘成文件/tmp/1,我们可以键入如下命令。
---- vi file
---- :20,59w /tmp/1

---- 3.用VI编辑一个文件,但需要删除大段的内容。

---- 首先利用编辑命令“vi file”打开文件,然后将光标移到需要删除的行处按Ctrl+G显示行号,再到结尾处再按Ctrl+G,显示文件结尾的行号。
---- :23,1045d 假定2次得到的行号为23和1045,则把这期间的内容全删除,也可以在要删除的开始行和结束行中用ma、mb命令标记,然后利用“:'a,'bd”命令删除。

---- 4.在整个文件的各行或某几行的行首或行尾加一些字符串。

---- vi file
---- :3,$s/^/some string / 在文件的第一行至最后一行的行首插入“some string”。
---- :%s/$/some string/g 在整个文件每一行的行尾添加“some string”。
---- :%s/string1/string2/g 在整个文件中替换“string1”成“string2”。
---- :3,7s/string1/string2/ 仅替换文件中的第3行到第7行中的“string1”成“string2”。
---- 注意: 其中s为substitute,%表示所有行,g表示global。

---- 5.同时编辑2个文件,拷贝一个文件中的文本并粘贴到另一个文件中。

---- vi file1 file2
---- yy 在文件1的光标处拷贝所在行
---- :n 切换到文件2 (n=next)
---- p 在文件2的光标所在处粘贴所拷贝的行
---- :N 切换回文件1

---- 6.替换文件中的路径。

---- 使用命令“:%s#/usr/bin#/bin#g”可以把文件中所有路径/usr/bin换成/bin。也可以使用命令“:%s//usr/bin//bin/g”实现,其中“”是转义字符,表明其后的“/”字符是具有实际意义的字符,不是分隔符。

----7.分割窗口
vi -o file1 file2 水平分割窗口编辑两个文件
vi -O file1 file2 垂直分割窗口编辑两个文件
在不同窗口之间移动,使用ctrl+w命令

用vim对文件进行加密
加密:

方法一:

vim -x filename

方法二:

在vim中对正在编辑的文件进行加密,切换到末行模式
:X

解密
在vim中对正在编辑的文件进行解密,切换到末行模式

:set key=""

:wq

其他

用彩色的vi写程序

  修改$HOME中的.vimrc,把color值设为true
  把环境变量VIMRUNTIME设成vim的路径名
  例:/usr/share/vim
  在vi中键入
  :syntax on回车
  :so $VIMRUNTIME/syntax/java.vim回车(现在版本的vi支持无数程序语法色彩档,都在
syntax/下,看一眼吧:))
  如果不喜欢所用的xterm背景色,可以用xterm -bg LightBlue(或其他喜欢的颜色)启动,
或者修改.Xresouce的xterm background项。
  vi -o xxx.java xxxx.java

vim的配置文件:/etc/vim/vimrc