显示标签为“Vim”的博文。显示所有博文
显示标签为“Vim”的博文。显示所有博文

星期一, 十二月 08, 2008

vim中改变显示颜色

VIM中可以使用 :colorscheme 来切换vim的显示,包括字体颜色,背景颜色等。

如我就是用的evening的现实模式

 :colorscheme evening

默认情况下有下面一些值可以设置:

 :colorscheme
blue delek evening murphy ron torte
darkblue desert koehler pablo shine zellner
default elflord morning peachpuff slate

星期四, 十一月 27, 2008

vim 在新的标签页(tab)打开help

open help window in a new tab.

:tab h pattern

星期二, 十月 07, 2008

vim中使用重定向

:redir 可以将vim的命令行输出重定向到文件中

例子:
:redir!>/tmp/vim-setting.txt|:set all

在linux下面可以直接使用下面的命令
vim -c ':redir!>/tmp/all-my-settings.txt|:set|q' ; vim /tmp/all-my-settings.txt

星期二, 九月 30, 2008

使用vim在行首加入行号

有下面几种方法:
  • :%s/^/\=line(".")." "/
  • :%s/^/\=printf('%4s ',line('.'))

在linux下面可以使用 cat和nl工具:
  • :%!cat -n



星期六, 二月 02, 2008

vim 替换技巧 (zz)

这两个技巧是近期看到的,记录下来,以免忘记。

[技巧一]

第一个是在VIM邮件列表中看到的,给出了一个如何统计文章字数的方法。

统计一个完整文件的字数,可以使用Unix下的wc工具,它能够统计一个文件的行数、单词数和字符数。

如果只想统计一个特定的模式出现的次数,wc工具就无能为力了,这时候可以用VIM的替换功能。

假定想统计文章中出现的单词的数目,可以使用下面的命令:

:%s/\w//gn

简单解释一下,这种命令实际上是报告整个文件中出现的单词的数目,命令分解如下:

%s            在整个文件中替换 (:help :s )
\w           匹配一个字 (word) (:help /\w )
g           替换行内所有出现的匹配 (:help :s_flags)
          只报告匹配的数目,并不真正进行替换(:help :s_flags)

如果是使用LaTeX写论文的话,可以用这种方式排除LaTeX的控制字符,统计出论文中的实际字数,参考文档列出的邮件中给出了这样的一个示例。

VIM中":help count-items"以及":help count-bytes",可以看到更多统计数目的方法。

 

[技巧二]

 

这个技巧是在水木社区的VIM版看到的(http://www.newsmth.org/bbsdoc.php?board=VIM )

这个文章是关于如何将一串十进制数字转换为16进制数字,使用VIM完成转换的最简单方法如下:

:%s/\d\+/\=printf("%X", submatch(0))/g

这条命令的原理是,把一串数字,用printf()函数的输出替换掉,printf()函数输出的正是这串数字的16进制形式。

分解如下:

%s            在整个文件中替换 (:help :s )
\d\+            匹配一个或多个数字 (:help /\d  :help /\+ )
\=           使用表达式的结果进行替换 (:help /\w )
printf        按指定格式输出 (:help printf() )
submatch()    返回:s命令中的指定匹配字符串 (:help submatch() )
g           替换行内所有出现的匹配 (:help :s_flags)

看来,替换命令的巧妙使用可以完成很多意想不到的功能!

星期二, 十月 30, 2007

best of vim tips

# note 015 : Best of Vim Tips                                          current
------------------------------------------------------------------------------
David Rayner (zzapper) 15 Years of Vi + 3 years of Vim and still learning
21Sep04 : Last Update
  • zzapper's Tips Page
    ------------------------------------------------------------------------------
    __BEGIN__
    ------------------------------------------------------------------------------
    # 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.*fred.*bill/ : normal
    /^[A-J]\+/ : search for lines beginning with one or more A-J
    /begin\_.*end : search over possible multiple lines
    /fred\_s*joe/i : any whitespace including newline
    /fred\|joe : Search for FRED OR JOE
    /\([^0-9]\|^\)%.*% : Search for absence of a digit or beginning of line
    /.*fred\&.*joe : Search for FRED AND JOE in any ORDER!
    /\<fred\>/i : search for fred but not alfred or frederick
    /\<\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
    # finding empty lines
    /^\n\{3} : find 3 empty lines
    # Specify what you are NOT searching for (vowels)
    /\c\v([^aeiou]&\a){4} : search for 4 consecutive consanants
    # 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
    # searching over multiple lines \_ means including newline
    /<!--\_p\{-}--> : search for multiple line comments
    /fred\_s*joe/i : any whitespace including newline
    /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
    :argdo /searchstr
    # How to search for a URL without backslashing
    ?http://www.vim.org/ : search BACKWARDS!!! clever huh!
    ----------------------------------------
    #substitution
    :%s/fred/joe/igc : general substitute command
    :%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
    # IF YOU ONLY WANT TO KNOW ONE THING
    :'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/\(.*\):\(.*\)/\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/\=@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/
    # ORing
    :%s/suck\|buck/loopy/gc : ORing (must break pipe)
    # 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:
    # 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>
    # 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
    # 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>*\>/
    ----------------------------------------
    # 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 (see tip 227)
    :g/fred.*joe.*dick/ : display all lines fred,joe & dick
    :g/\<fred\>/ : display all lines fred but not freddy
    :g/<pattern>/z#.5 : display with context
    :g/<pattern>/z#.5|echo "==========" : display beautifully
    :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/{/ ,/}/- s/\n\+/\r/g : Delete empty lines but only between {...}
    :v/./.,/./-1join : compress empty lines
    :g/^$/,/./-j : compress empty lines
    :g/<input\|<form/p : ORing
    :g/^/pu _ : double space file (pu = put)
    :g/^/m0 : Reverse file (m = move)
    :g/fred/t$ : copy lines matching fred to EOF
    :g/stage/t'a : copy lines matching stage to marker a
    :%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)
    :g/fred/y A : append all lines fred to register a
    :'a,'b g/^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.ex | -d
    ----------------------------------------
    # Global combined with substitute (power editing)
    :'a,'bg/fred/s/joe/susan/gic : can use memory to extend matching
    :g/fred/,/joe/s/fred/joe/gic : non-line based (ultra)
    ----------------------------------------
    # Find fred before beginning search for joe
    :/fred/;/joe/-2,/sid/+3s/sally/alley/gIC
    ----------------------------------------
    # Absolutely essential
    ----------------------------------------
    * # g* g# : find word under cursor (<cword>) (forwards/backwards)
    % : match brackets {}[]()
    . : repeat last modification
    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
    :syntax on : colour syntax in Perl,HTML,PHP etc
    :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
    ----------------------------------------
    #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
    ----------------------------------------
    # Exploring
    :Exp(lore) : file explorer note capital Ex
    :Sex(plore) : file explorer in split window
    :ls : list of buffers
    :cd .. : move to parent directory
    :args : list of files
    :lcd %:p:h : change to directory of current file
    :autocmd BufEnter * lcd %:p:h : change to directory of current file automatically (put in _vimrc)
    ----------------------------------------
    # Buffer Explorer (Top Ten Vim Script)
    # needs bufexplorer.vim http://www.vim.org/script.php?script_id=42
    \be : buffer explorer list of buffers
    \bs : buffer explorer (split window)
    ----------------------------------------
    # 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>
    # Uppercase first letter of sentences
    :%s/[.!?]\_s\+\a/\U&\E/g
    ----------------------------------------
    gf : open file name under cursor (SUPER)
    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)
    ----------------------------------------
    # Makes all other tips superfluous
    :h 42 : also http://www.google.com/search?q=42
    :h holy-grail
    :h!
    ----------------------------------------
    # Markers & moving about
    '. : jump to last modification line (SUPER)
    `. : jump to exact spot in last modification line
    g; : cycle thru recent changes (oldest first) (new in vim6.3)
    g, : reverse direction (new in vim6.3)
    :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
    q: : commandline history Window
    :<C-F> : history Window
    ----------------------------------------
    # Abbreviations & maps
    :map <f7> :'a,'bw! c:/aaa/x
    :map <f8> :r c:/aaa/x
    :map <f11> :.w! c:/aaa/xr<CR>
    :map <f12> :r c:/aaa/xr<CR>
    :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
    #display RGB colour under the cursor eg #445588
    :nmap <leader>c :hi Normal guibg=#<c-r>=expand("<cword>")<cr><cr>
    ----------------------------------------
    # Using a register as a map (preload registers in .vimrc)
    :let @m=":'a,'bs/"
    :let @s=":%!sort -u"
    ----------------------------------------
    # List your Registers
    :reg : display contents of all registers
    :reg a : display content of individual registers
    "1p.... : retrieve numeric registers one by one
    :let @y='yy@"' : pre-loading registers (put in .vimrc)
    ----------------------------------------
    # Useful tricks
    "ayy@a : execute "Vim command" in a text file
    yy@" : same thing using unnamed register
    u@. : execute command JUST typed in
    ----------------------------------------
    # Get output from other commands (requires external programs)
    :r!ls.exe : reads in output of ls
    !!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!!)
    ----------------------------------------
    # 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
    :b 3 : go to buffer 3
    :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
    :sav! %:r.cfm : Save Current file to alternative extension
    :e! : return to unmodified file
    :w c:/aaa/% : save file elsewhere
    :e # : edit alternative file
    :rew : return to beginning of editted 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
    # 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
    ----------------------------------------
    # Visual is the newest and usually the BEST editting mode
    # Visual basics
    v : enter visual mode
    V : visual mode whole line
    <C-V> : enter VISUAL BLOCK mode
    gv : reselect last visual area
    o : navigate visual area
    "*y : yank visual area into paste buffer
    V% : visualise what you match
    V}J : Join Visual block (great)
    ----------------------------------------
    # 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
    ----------------------------------------
    # _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://209.51.134.122/public_html/index.html
    ----------------------------------------
    # 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
    # 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
    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 /foo/
    ----------------------------------------
    # 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 editting 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 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
    ----------------------------------------
    # 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)
    ----------------------------------------
    # manipulating registers
    :let @a=@_ : clear register a
    :let @a="" : clear register a
    :let @*=@a : copy register a to paste buffer
    map <f11> "qyy:let @q=@q."zzz"
    ----------------------------------------
    # help for help
    :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 : Help grep
    :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
    ----------------------------------------
    # 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/vim63/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
    ----------------------------------------
    # Inserting DOS Carriage Returns
    :%s/nubian/<C-V><C-M>&/g : that's what you type
    :%s/nubian/<C-Q><C-M>&/g : for Win32
    :%s/nubian/^M&/g : what you'll see where ^M is ONE character
    :%s/nubian/\r&/g : better
    ----------------------------------------
    # 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)/
    ----------------------------------------
    # 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/[<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>" :
    ----------------------------------------
    # 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
    ----------------------------------------
    # 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:
    ----------------------------------------
    :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 fith 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
    ----------------------------------------
    # displaying "invisible characters"
    :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
    <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
    ----------------------------------------
    # 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 "%"
    ----------------------------------------
    # Just Another Vim Hacker JAVH
    vim -c ":%s%s*%Cyrnfr)fcbafbe[Oenz(Zbbyranne%|:%s)[[()])-)Ig|norm Vg?"
    ----------------------------------------
    __END__
    ----------------------------------------
    If you liked these please return to www.vim.org
    and vote for this tip (It does encourage me!!)
    Tip 305
    ----------------------------------------
    Please email any errors, tips etc to
    david@rayninfo.co.uk
    ----------------------------------------
    updated version at http://www.rayninfo.co.uk/vimtips.html
    ----------------------------------------
    # Information Sources
    ----------------------------------------
    www.vim.org
    comp.editors "VIM" newsgroup
    VIM Webring
    Vim Book
    Searchable VIM Doc
    VIM FAQ
    VimTips in Chinese
    ----------------------------------------
    # : commands to neutralise < for HTML display and publish
    yy@" to execute following commands
    :w!|sav! vimtips.html|:/^__BEGIN__/,/^__END__/s#<#\<#g|:/tip[f]tp/|n
    :w!|!tipftp
    ----------------------------------------

  • vim技巧—找出欲搜尋字樣的數目

    方法是:%s/pattern/&/g
    其中的pattern可以用正規表示式


    星期二, 八月 28, 2007

    Vim tab (标签) 的使用

    标签(tab)是 Vim7的新功能,

    编辑多个文件时就不用开多个Vim了,

    也不用每次想着保存再n了。




    常用命令:



    命令 说明 快捷键
    :tab new 新建一个标签页
    :tabedit 在新标签页打开文件
    :tabnext 下一个标签页 <C-PageDown>
    :tabp[revious] 上一个标签页 <C-PageUp>

    星期六, 八月 25, 2007

    Vim 新书快递

    Hacking Vim: A Cookbook to get the Most out of the Latest Vim Editor


    看了一下介绍,讲的是Vim7.0,最新的版本,但是不适合初学者,对有一定Vim基础的应该是一本比较好的书,还没有下载完,一会先去浏览一下,看介绍的,我对一些章节还是挺感兴趣的,比如:auto-completion 和 folding。

    下面是书的介绍:


    This cookbook contains ready-to-use hacks to solve problems Vim users encounter daily, from personalizing Vim to optimizations that boost productivity. It does not cover basic use of the editor but focuses on making life easier for experienced Vim users. Vim is a highly configurable, open-source, multi-platform text editor that is included as standard in most Linux distributions. It can edit code in any language, has a scripting language that allows extensions to its functionality, and is editor of choice for many programmers. This book is up to date with the new features in Vim 7.0. Chapters cover: changing the appearance of the Vim editor; improved file and buffer navigation ; using templates, auto-completion, folding, sessions, and registers; formatting text and code and using external formatting scripts; Vim scripts and scripting. Each recipe has a self-contained description of the task it covers, how to use it, the benefits of using it, and compatibility with earlier versions of Vim.





    Back in the early days of the computer revolution, system resources were limited and developers had to figure out new ways to optimize their applications. This was also the case with the text editors of that time. One of the most popular editors of that time was an editor called Vim. It was optimized to near-perfection for the limited system resources on which it ran.





    The world has come a long way since then, and even though the system resources have grown, many still stick with the Vim editor.





    At first sight, the Vim editor might not look like much. However, if you look beneath the simple user-interface, you will discover why this editor is still the favorite editor for so many people, even today!
    This editor has nearly every feature you would ever want, and if it's not in the editor, it is possible to add it by creating plugins and scripts. This high level of flexibility makes it ideal for many purposes, and it is also why Vim is still one of the most advanced editors.





    New users join the Vim user community every day and want to use this editor in their daily work, and even though Vim sometimes can be complex to use, they still favor it above other editors. This is a book for these Vim users.





    With this book, Vim users can make their daily work in the editor more comfortable and thereby optimize their productivity. In this way they will not only have an optimized editor, but also an optimized work-flow. The book will help them move from just using Vim as a simple text editor to a situation where they feel at home and can use it for many of their daily tasks.





    Good luck and happy reading!