Vous êtes sur la page 1sur 227

*vimtips.txt* This file comes from the Vim Online tip database.

These tips were downloaded on Wed, 13 Nov 2002 09:45:54 -0800 More tips can be found at http://vim.sf.net/tip_index.php A new tip file can be downloaded from http://vim.sf.net/tip_download.php Thanks for using vim online.

VimTip 1: the super star http://vim.sf.net/tip_view.php?tip_id=1 When a discussion started about learning vim on the vim list Juergen Salk mentio ned the "*" key as something that he wished he had know earlier. When I read the mail I had to go help on what the heck the "*" did. I also wish I had known ear lier... Using the "*" key while in normal mode searches for the word under the cursor. If that doesn't save you a lot of typing, I don't know what will.

VimTip 2: easy edit of files in the same directory http://vim.sf.net/tip_view.php?tip_id=2 It was often frustrating when I would open a file deep in the code tree and then realize I wanted to open another file in that same directory. Douglas Potts tau ght me a nice way to do this. Add the following snipit to your vimrc: " " " if Edit another file in the same directory as the current file uses expression to extract path from current file's path (thanks Douglas Potts) has("unix") map ,e :e <C-R>=expand("%:p:h") . "/" <CR> else map ,e :e <C-R>=expand("%:p:h") . "\" <CR> endif Then when you type ,e in normal mode you can use tab to complete to the file. Yo u can also expand this to allow for spitting, etc. Very very nice.

VimTip 3: use vim to quickly compile java files http://vim.sf.net/tip_view.php?tip_id=3 For a number of years I used vim on an SGI box. When I left my job at SGI I went to a company that developed on PCs. For 2 years I used IDEs. I was unhappy. I w as frustrated. I couldn't figure out why. (Beyond my machine crashing twice a da y.) Finally I upgraded to windows 2000 (kind of stable!) and started using vim a s an IDE. All was good. Here is how you use vim to compile your java:

1. While I'm sure this works with javac, javac is slow slow slow. So download th e Jikes complier first. (Jikes is from ibm, search on google for jikes and you w ill find it..available on most platforms.) 2. Add the following to your vimrc: set makeprg=jikes -nowarn -Xstdout +E % set errorformat=%f:%l:%c:%*\d:%*\d:%*\s%m 3. When you are editing a java file type :make and it will compile the current f ile and jump you to the first error in the file (if any). Read ":help quickfix" for how to move between errors. To setup your classpath environment either launch gvim from a shell that has you r classpath/path setup or use the "let" command to configure it in your vimrc.

VimTip 4: Any word completion http://vim.sf.net/tip_view.php?tip_id=4 Either when programming or writing, I tend to have some identifiers or words tha t I use all the time. By sheer accident, I noticed the 'ctrl-n' command, that wi ll attempt to complete the word under the cursor. Hit it once, and it will try t o complete it with the first match in the current file. If there is no match, it will (at least in the case of C code) search through all files included from th e current one. Repeated invocations will cycle through all found matches.

VimTip 5: Quickly searching for a word http://vim.sf.net/tip_view.php?tip_id=5 To search for a word under the cursor in the current file you can use either the "*" or "#" keys. The "*" key will search for the word from the current cursor position to the end of the file. The "#" key will search for the word from the current cursor position to the top of the file. Note that the above two keys will search for the whole word and not the partial word. This is equivalent to using the <word> pattern in the search commands (/ and ?). To search for partial matches, you can use the "g*" and "g#" key sequence. You can also use the mouse to search for a word. This will only work in the GUI version of VIM (gvim) or a console version of VIM in an xterm which accepts a mouse. Also, the 'mousemodel' should be set to 'extend'. Add the following line to your .vimrc: set mousemodel=extend

To search for a word under position to the end of the on the word using the left direction, press the shift the right mouse button.

the cursor from the current cursor file, press the shift key and click mouse button. To search in the opposite key and click on the word using the

To get more help on these, use :help :help :help :help :help :help * # g* g# <S-LeftMouse> <S-RightMouse>

VimTip 6: Using the % key http://vim.sf.net/tip_view.php?tip_id=6 The % key can be used 1. To jump to a matching opening or closing parenthesis, square bracket or a curly brace i.e. ([{}]) 2. To jump to start or end of a C-style comment /* */. 3. To jump to a matching #if, #ifdef, #else, #elif, #endif C preprocessor conditionals. To get more information about this, do :help % The % key can be extended to support other matching pairs by modifying the "matchpairs" option. Read the help on :help matchpairs

VimTip 7: Jumping to the start and end of a code block http://vim.sf.net/tip_view.php?tip_id=7 To jump to the beginning of a C code block (while, switch, if etc), use the [{ command. To jump to the end of a C code block (while, switch, if etc), use the ]} command. The above two commands will work from anywhere inside the code

block. To jump to the beginning of a parenthesis use the [( command. To jump to the end of a parenthesis use the ]) command. To get more help on these commands, do :help :help :help :help [{ ]} [( ])

VimTip 8: Jumping to the declaration of a local/global variable http://vim.sf.net/tip_view.php?tip_id=8 'gd' command: To jump to the declaration of a local variable in a C program, position the cursor on the name of the variable and use the gd command. 'gD' command: To jump to the declaration of a global variable in a C program, position the cursor on the name of the variable and use the gD command.

VimTip 9: Displaying a variable/macro definition http://vim.sf.net/tip_view.php?tip_id=9 To display the definition of a variable, place the cursor on the variable and use the [i command. To display a macro definition, place the cursor on the macro name and use the [d command. Note that these commands will work most of the time (not all the time). To get more help on these commands, use :help [i :help [d

VimTip 10: Jumping to previosuly visited locations in a file http://vim.sf.net/tip_view.php?tip_id=10

Vim remembers all the locations visited by you in a file in a session. You can jump to the older locations by pressing the Ctrl-O key. You can jump to the newer locations by pressing the Ctrl-I or the <Tab> key. To get more help on these keys, use :help CTRL-O :help CTRL-I :help jump-motions

VimTip 11: Completing words quicky in insert mode http://vim.sf.net/tip_view.php?tip_id=11 In Insert mode, press the Ctrl-p or Ctrl-n key to complete part of a word that has been typed. This is useful while typing C programs to complete long variable and function names. This also helps in avoiding typing mistakes. Note that using the 'complete' option, you can complete keywords defined in one of the include files, tag file, etc. To get more help on this, use :help :help :help :help i_Ctrl-N i_Ctrl-P ins-completion complete

VimTip 12: Converting tabs to spaces http://vim.sf.net/tip_view.php?tip_id=12 To insert space characters whenever the tab key is pressed, set the 'expandtab' option: set expandtab With this option set, if you want to enter a real tab character use Ctrl-V<Tab> key sequence. To control the number of space characters that will be inserted when the tab key is pressed, set the 'tabstop' option. For example, to insert 4 spaces for a tab, use: set tabstop=4

After the 'expandtab' option is set, all the new tab characters entered will be changed to spaces. This will not affect the existing tab characters. To change all the existing tab characters to match the current tab settings, use :retab To change the number of space characters inserted for indentation, use the 'shiftwidth' option: set shiftwidth=4 For example, to get the following coding style, - No tabs in the source file - All tab characters are 4 space characters use the following set of options: set tabstop=4 set shiftwidth=4 set expandtab Add the above settings to your .vimrc file. To get more help on these options, use :help tabstop :help shiftwidth :help expandtab

VimTip 13: Incremental search http://vim.sf.net/tip_view.php?tip_id=13 To move the cursor to the matched string, while typing the search string, set the following option in the .vimrc file: set incsearch You can complete the search by pressing the Enter key. To cancel the search, press the escape key.

VimTip 14: Highlighting all the search pattern matches http://vim.sf.net/tip_view.php?tip_id=14 To highlight all the search pattern matches in a file set the following option:

:set hlsearch After this option is set, if you search for a pattern, all the matches in the file will be highlighted in yellow. To disable the highlighting temporarily, use the command :nohlsearch This command will remove the highlighting for the current search. The highlighting will come back for the next search. To disable the highlighting completely, set the following option: :set nohlsearch By default, the hlsearch option is turned off. To get more help on this option, use :help 'hlsearch' :help :nohlsearch

VimTip 15: Displaying status line always http://vim.sf.net/tip_view.php?tip_id=15 To display the status line always, set the following option in your .vimrc file: set laststatus=2 The advantage of having the status line displayed always is, you can see the current mode, file name, file status, ruler, etc. To get more help on this, use :help laststatus

VimTip 16: Avoiding the "Hit ENTER to continue" prompts http://vim.sf.net/tip_view.php?tip_id=16 To avoid the "Hit ENTER to continue" prompt, use the 'shortmess' option. Add the following line to your .vimrc file: set shortmess=a

Also, you can increase the height of the command line to 2 set cmdheight=2 The default command height is 1. To get more help on these options, use :help hit-enter :help shortmess :help cmdheight

VimTip 17: Erasing previosuly entered characters in insert mode http://vim.sf.net/tip_view.php?tip_id=17 In insert mode, to erase previously entered characters, set the following option: set backspace=2 By default, this option is empty. If this option is empty, in insert mode, you can not erase characters entered before this insert mode started. This is the standard Vi behavior. To get more help on this, use :help 'backspace'

VimTip 18: Cleanup your HTML http://vim.sf.net/tip_view.php?tip_id=18 From Johannes Zellner on the vim list: You can use vim's makeprg and equalprg to clean up HTML. First download html tid y from http://www.w3.org/People/Raggett/tidy/. Then use the following commands. vim6? exe 'setlocal equalprg=tidy -quiet -f '.&errorfile setlocal makeprg=tidy -quiet -e % vim5? exe 'set equalprg=tidy -quiet -f '.&errorfile set makeprg=tidy -quiet -e % At this point you can use make to clean up the full file or you can use = to cle an up sections.

:help = :help equalprg :help makeprg

VimTip 19: line numbers... http://vim.sf.net/tip_view.php?tip_id=19 I have started doing all my code reviews on a laptop because of the number comma nd. :set number will put line numbers along the left side of a window :help number

VimTip 20: Are *.swp and *~ files littering your working directory? http://vim.sf.net/tip_view.php?tip_id=20 Have you ever been frustrated at swap files and backups cluttering up your working directory? Untidy: ons.txt ons.txt~ README README~ tester.py tester.py~ Here are a couple of options that can help: set set backupdir=./.backup,.,/tmp directory=.,./.backup,/tmp

This way, if you want your backups to be neatly grouped, just create a directory called '.backup' in your working directory. Vim will stash backups there. The 'directory' option controls where swap files go. If your working directory is not writable, Vim will put the swap file in one of the specified places.

VimTip 21: easy pasting to windows apps http://vim.sf.net/tip_view.php?tip_id=21

In Vim, the unnamed register is the " register, and the Windows Clipboard is the * register. This means that if you yank something, you have to yank it to the * register if you want to paste it into a Windows app. If this is too much trouble, set the 'clipboard' option to 'unnamed'. Then you always yank to *. So pasting to windows apps doesn't require prefixing "* : set clipboard=unnamed

VimTip 22: handle common typos for :commands http://vim.sf.net/tip_view.php?tip_id=22 I frequently hold the shift key for too long when typing, for instance :wq, and end up with :Wq. Vim then whines "Not an editor command: Wq" In my .vimrc, I have taught vim my common typos: command! Q quit command! W write command! Wq wq " this one won't work, because :X is already a built-in command command! X xit

VimTip 23: Vim xterm title http://vim.sf.net/tip_view.php?tip_id=23 Check out your .vimrc. If 'set notitle' is an entry, comment it out with a quota tion mark ("). Now your xterm should inherit the title from Vim. e.g. 'Vim - ~/.vimrc'. This can be quite nice when programming and editing lots of f iles at the same time. by [jonasbn@wanadoo.dk]

VimTip 24: changing the default syntax highlighting http://vim.sf.net/tip_view.php?tip_id=24 Here are some pointers to the vim documentation. Notice that the mechanism is different in vim 6.0 and vim 5.x. 1. I want *.foo files to be highlighted like HTML files. :help new-filetype http://www.vim.org/html/autocmd.html#new-filetype 2. I want to define a syntax file for *.bar files. Read the above and also

:help mysyntaxfile http://www.vim.org/html/syntax.html#mysyntaxfile 3. I want to make a few changes to the existing syntax highlighting. Depending on the x in 5.x, either read the above and page down a few screens, or you may b e able to skip right to :help mysyntaxfile-add http://www.vim.org/html/syntax.html#mysyntaxfile-add 4. I want to change some of the colors from their defaults. Again, read :help mysyntaxfile http://www.vim.org/html/syntax.html#mysyntaxfile

VimTip 25: color highlighting on telnet (esp w/ SecureCRT) http://vim.sf.net/tip_view.php?tip_id=25 The following settings in .vimrc will enable color highlighting when using Secur eCRT and may work on other telnet packages. The terminal type should be selected as ANSI and color enabled. if !has("gui_running") set t_Co=8 set t_Sf=^[[3%p1%dm set t_Sb=^[[4%p1%dm endif The ^[ is entered as "<ctrl-v><esc>"

VimTip 26: Getting rid of ^M - mixing dos and unix http://vim.sf.net/tip_view.php?tip_id=26 If you work in a mixed environment you will often open files that have ^M's in t hem. An example would be this: -----------------------------------------------------------------import java.util.Hashtable; ^M import java.util.Properties; ^Mimport java.io.IOException; import org.xml.sax.AttributeList; ^M import org.xml.sax.HandlerBase; ^Mimport org.xml.sax.SAXException; /**^M * XMLHandler: This class parses the elements contained^M * within a XML message and builds a Hashtable^M [snip] ------------------------------------------------------------------

Notice that some programs are not consistent in the way they insert the line bre aks so you end up with some lines that have both a carrage return and a ^M and s ome lines that have a ^M and no carrage return (and so blend into one). There ar e two steps to clean this up. 1. replace all extraneous ^M: :%s/^M$//g BE SURE YOU MAKE the ^M USING "CTRL-V CTRL-M" NOT BY TYPING "CARROT M"! This exp ression will replace all the ^M's that have carriage returns after them with not hing. (The dollar ties the search to the end of a line) 2. replace all ^M's that need to have carriage returns: :%s/^M//g Once again: BE SURE YOU MAKE the ^M USING "CTRL-V CTRL-M" NOT BY TYPING "CARROT M"! This expression will replace all the ^M's that didn't have carriage returns after them with a carriage return. Voila! Clean file. Map this to something if you do it frequently. :help ffs - for more info on file formats thanks to jonathan merz, douglas potts, and benji fisher

VimTip 27: Convert hex to dec http://vim.sf.net/tip_view.php?tip_id=27 when you check the output of objdump, you'll confused by the $0xFFFFFFc operand, this function translate the hexcamal to decimal. function! Hex2Dec() let lstr = getline(".") let hexstr = matchstr(lstr, '0x[a-f0-9]+') while hexstr != "" let hexstr = hexstr + 0 exe 's#0x[a-f0-9]+#'.hexstr."#" let lstr = substitute(lstr, '0x[a-f0-9]+', hexstr, "") let hexstr = matchstr(lstr, '0x[a-f0-9]+') endwhile endfunction usage: 5,8call Hex2Dec()

VimTip 28: add a line-number to every line without cat or awk alike utilities. http://vim.sf.net/tip_view.php?tip_id=28

With Unix-like environment, you can use cat or awk to generate a line number eas ily, because vim has a friendly interface with shell, so everything work in vim as well as it does in shell. :%!call -n or :%!awk '{print NR,$0}' But, if you use vim in MS-DOS, of win9x, win2000, you loss these tookit. here is a very simple way to archive this only by vim: fu! LineIt() exe ":s/^/".line(".")."/" endf Well, a sequence composed with alphabet is as easy as above: exe "s/^/".nr2char(line("."))."/"

VimTip 29: reverse all the line with only 7 keystroke in vim http://vim.sf.net/tip_view.php?tip_id=29 :g/^/m0 well, 1. : bring you to command-line mode(also known as ex-mode) from normal-mode(also known as command mode). 2. g means you'll take an action through the whole file, generally perform a sea rch, `v' also perform a search but it match the line not match the canonical exp ression. 3. / begins the regular express 4. ^ is a special character respect the start of a line. 5. the second / ends the regular express and indicate that the remains is action to do. 6. m means move, `t` and `co' for copy, `d' for delete 7. 0 is the destination line. you can use :g/regexp/t$ to filter all lines and pick the match line together and copy them to the end of the buffer or :g/regexp/y A to put them into a register(not eax, ebx...)

VimTip 30: Increasing or decreasing numbers http://vim.sf.net/tip_view.php?tip_id=30 To increase a number under or nearest to the right of the cursor, go to Normal m ode and type: Ctrl-A To decrease, type: Ctrl-X

Using this in a macro simplifies generating number sequences a lot.

VimTip 31: Find and Replace http://vim.sf.net/tip_view.php?tip_id=31 To find and replace one or more occurences of a given text pattern with a new text string, use the s[ubstitute] command. There are a variety of options, but these are what you most probably want: :%s/foo/bar/g find each occurance of 'foo' and replace it with 'bar' w ithout asking for confirmation :%s/foo/bar/gc find each occurance of 'foo' and replace it with 'bar' a sking for confirmation first :%s/<foo>/bar/gc 'foo' with 'bar' :%s/foo/bar/gci oo' with 'bar' :%s/foo/bar/gcI ' with 'bar' find (match exact word only) and replace each occurance of find (case insensitive) and replace each occurance of 'f find (case sensitive) and replace each occurance of 'foo

NB: Without the 'g' flag, replacement occurs only for the first occurrence in ea ch line. For a full description and some more interesting examples of the substitute comm and refer to :help substitute See also: :help cmdline-ranges :help pattern :help gdefault

VimTip 32: Write your own vim function(scripts) http://vim.sf.net/tip_view.php?tip_id=32 compare to C and shell(bash), herein is some vim specifics about vim-script: 1. A function name must be capitalized. hex2dec is invalid Hex2dec is valid

while in c and shell(bash), both lowercase and uppercase is allowed. 2. how to reference the parameters fu! Hex2dec(var1, var2) let str=a:var1 let str2=a:var2 you must prefix the parameter name with "a:", and a:var1 itself is read-only in c, you reference the parameter directly and the parameter is writable. 3. how to implement variable parameter fu! Hex2dec(fixpara, ...) a:0 is the real number of the variable parameter when you invoke the functi on, with :Hex2dec("asdf", 4,5,6), a:0=3, and a:1=4 a:2=5 a:3=6 you can combine "a:" and the number to get the value while i<a:0 exe "let num=a:".i let i=i+1 endwhile in c, the function get the real number by checking the additional parameter s uch as printf family, or by checking the special value such as NULL 4. where is the vim-library yes, vim has its own function-library, just like *.a in c :help functions 5. can I use += or ++ operator? Nop, += and ++ (and -=, -- and so on)operator gone away in vim. 6. How can I assign a value to a variables and fetch its value? let var_Name=value let var1=var2 like it does in c, except you must use let keyword 7. Can I use any ex-mode command in a function? As I know, yes, just use it directly, as if every line you type appears in the familar : 8. Can I call a function recurse? Yes, but use it carefully to avoid infinte call. 9. Can I call another function in a function? Course, like C does. 10. Must I compile the function? No, you needn't and you can't, just :so script_name, after this you can call the function freely. 11. Is it has integer and char or float data type? No, like perl, vim script justify the variable type depend upon the context :let a=1 :let a=a."asdf" :echo a you'll get `1asdf' :let a=1 :let a=a+2 :echo a you'll get 3 But it differs from perl. 12. Must I append a `;' in every statement? No, never do that. ; is required in C, and optional in shell for each statement in a alone line. But is forbidden in vim. if you want combine servals statement in one single line, use ` '. Take your mind that every statement appears in function should be valid in ex -mode(except for some special statement).

VimTip 33: toggle off the line-number when enter on-line help http://vim.sf.net/tip_view.php?tip_id=33 I like the line-number for myself editing. But I hate it in on-line help page be cause it force the screen wrapped. :au filetype help :se nonu

VimTip 34: control the position of the new window http://vim.sf.net/tip_view.php?tip_id=34 :se splitbelow make the new window appears below the current window. :se splitright make the new window appears in right.(only 6.0 version can do a vsplit)

VimTip 35: For programmer: translate // style comment to /* */and vice vesa http://vim.sf.net/tip_view.php?tip_id=35 the ` ' concatenate servals ex-command in one line. It's the key to translate // style comments to /* */ style :g#^s{-}//#s##/*# s#$#*/# the ` ' keep the current line matchs ^s{-}// to perform s#$#*/ /* ... */ ---> //style :g#/*(.{-})*/#//1# /* .... .... ..... */ =====> //...... //...... //...... style: ? Anyone implement it?

VimTip 36: Using Gnu-info help in vim http://vim.sf.net/tip_view.php?tip_id=36 K in normal bring you the man page about the keyword under current cursor. :nnoremap <F1> :exe ":!info ".expand("<cword>")

Now press F1 while the cursor is hold by a keyword such as printf will bring you to Gnu-info help page :h <F1> :h nnoremap

VimTip 37: The basic operation about vim-boolean optionals http://vim.sf.net/tip_view.php?tip_id=37 :set number switch the number on :set nonumber switch it off :set invnumber or :set number! switch it inverse against the current setting :set number& get the default value vim assums. replace number with any legal vim-boolean optionals, they all works well. for vim-non-boolean optionals :set optional& also works properly.

VimTip 38: Cursor one line at a time when :set wrap http://vim.sf.net/tip_view.php?tip_id=38 If your tierd of the cursor jumping past 5 lines when :set wrap then add these m appings to you vimrc file. nnoremap nnoremap vnoremap vnoremap nnoremap nnoremap vnoremap vnoremap inoremap inoremap j gj k gk j gj k gk <Down> gj <Up> gk <Down> gj <Up> gk <Down> <C-o>gj <Up> <C-o>gk

What they do is remap the cursor keys to use there `g' equvilant. See :help gj

VimTip 39: Undo and Redo

http://vim.sf.net/tip_view.php?tip_id=39 To undo recent changes, use the u[ndo] command: u U t line) CTRL-R undo last change (can be repeated to undo preceding commands) return the line to its original state (undo all changes in curren Redo changes which were undone (undo the undo's).

For a full description of the undo/redo commands refer to :help undo

VimTip 40: Insert a file http://vim.sf.net/tip_view.php?tip_id=40 To insert the contents of a file (or the output of a system command) into the current buffer, use the r[ead] command: Examples: :r foo.txt :0r foo.txt :r !ls :$r !pwd inserts the file foo.txt below the cursor inserts the file foo.txt above the first line inserts a listing of your directory below the cursor inserts the current working directory below the last line

For more information about the r[ead] command refer to: :help read See also: :help cmdline-ranges :help !cmd

VimTip 41: Command-history facilities for Oracle/sqlplus user http://vim.sf.net/tip_view.php?tip_id=41 First of all, thanks Benji fisher, Stefan Roemer... and others in vim@vim.org which spend much time to answer questions, sometimes foolish question asked by someone like me. Without their I can't get the final solution for my sqlplus work descripted follows.

As Oracle user known, sqlplus has a very bad command-line edition environment. It has no command-history, don't support most of getline facilities. which MySQL and shell does it well. Even Microsoft recogonize this point. In Windows2000, doskey is installed by default. Below is my vim-solution to sqlplus, which record the command-history when you use edit(sqlplus builtin command) to open the editor specified by EDITOR environment variable. It saves the SQL statement into a standalone file such as .sqlplus.history Every time you open the file afiedt.buf(sqlplus's default command-buffer file), you get two splited windows, the buffer above is afiedt.buf, the buffer below is .sqlplus.history, you can see every SQL statement in the windows. If you want to use SQL statement in line 5 to replace the current command-buffer, just press 5K, then :xa to back to you sqlplus. and use / to repeat the command saved in command-buffer file called afiedt.buf by default. It can't process multi-line SQL statement convinencely. Todo this, just use you favorite vim trick to do that: fu! VimSQL() nnoremap <C-K> :<C-U> exe "let linenum=".v:count<CR>:1,$-1d<CR><C-W>j:exe lin enum."y"<CR><C-W>kP let linenum=line("$") 1,$-1w! >> ~/.sqlplus.history e ~/.sqlplus.history execute ":$-".(linenum-1).",$m0" %!uniq if line("$")>100 101,$d endif b# set splitbelow sp ~/.sqlplus.history au! BufEnter afiedt.buf endf au BufEnter afiedt.buf call VimSQL()

VimTip 42: Using marks http://vim.sf.net/tip_view.php?tip_id=42 To mark one or more positions in a file, use the m[ark] command. Examples: ma 'a set current cursor location as mark a jump to beginning of line of mark a

`a d'a d`a c'a y`a :marks

jump to postition of mark a delete from current line to line of mark a delete from current cursor position to mark a change text from current line to line of mark a yank text to unnamed buffer from cursor to mark a list all the current marks

NB: Lowercase marks (a-z) are valid within one file. Uppercase marks (A-Z), also called file marks, are valid between files. For a detailed description of the m[ark] command refer to :help mark See also: :help various-motions

VimTip 43: Using abbreviations http://vim.sf.net/tip_view.php?tip_id=43 To define abbreviations, use the ab[breviate] command. Examples: :ab rtfm read the fine manual - Whenever you type 'rtfm' followed by a <space> (or <esc> or <cr>) vim will expand this to 'read the fine manual'. :ab :una[bbreviate] rtfm :abc[lear] - list all defined abbreviations - remove 'rtfm' from the list of abbreviations - remove all abbreviations

NB: To avoid expansion in insert mode, type CTRL-V after the last character of t he abbreviation. For a detailed description of the ab[breviate] command and some more examples re fer to :help abbreviations

VimTip 44: Repeat last changes http://vim.sf.net/tip_view.php?tip_id=44 Simple text changes in normal mode (e.g. "dw" or "J") can be repeated with the " ." command. The last command-line change (those invoked with ":", e.g. ":s/foo/bar") can be repeated with the "@:" command. For more informations about repeating single changes refer to: :help single-repeat

VimTip 45: Using command-line history http://vim.sf.net/tip_view.php?tip_id=45 You can recall previous command lines from a history table by hitting the <Up> and <Down> cursor keys in command-line mode. For example, this can be used to find the previous substitute command: Type ":s" and then <Up>. There are separate history tables for the ':' commands and for previous '/' or '?' search strings. To display the history of last entered commands or search strings, use the :his[tory] command: :his :his s Display command-line history. Display search string history.

For a detailed description of the command-line history refer to: :help cmdline-history See also: :help Cmdline-mode

VimTip 46: Win32 binaries with perl, python, and tcl http://vim.sf.net/tip_view.php?tip_id=46 > Does anyone know if windows binaries of vim 5.7 are available with perl and > python support turned on? ftp://vim.sourceforge.net/pub/vim/upload_binaries/ http://vim.sourceforge.net/bin_download/

VimTip 47: Swapping characters, words and lines http://vim.sf.net/tip_view.php?tip_id=47 To swap two characters or lines, use the following commands: xp ddp delete the character under the cursor and put it afterwards. (In other words, it swaps the characters.) delete the current line and put it afterwards. (In other words, it swaps the lines.)

Unfortunately there is no universal solution to swap two words. You may try the following ones, but don't expect too much of them: dawwP delete the word under the cursor, move forward one word and put it back after the cursor. (In other words, it swaps the current and following word.) delete the word under the cursor, move backward on word and put it back after the cursor. (In other words, it swaps the current and preceeding word.)

dawbP

VimTip 48: Moving around http://vim.sf.net/tip_view.php?tip_id=48 You can save a lot of time when navigating through the text by using appropriate movements commands. In most cases the cursor keys, <PageUp> or <PageDown> are NOT the best choice. Here is a selection of some basic movement commands that hopefully helps you to acquire a taste for more: e w 3w b 3b move move move move move to the end of a word forward to the beginning of a word forward three words backward to the beginning of a word backward three words move same move same to as to as the end of the line $ the beginning of the line 0

$ <End> 0 <Home> ) ( } {

- jump forward one sentence - jump backward one sentence - jump forward one paragraph - jump backward one paragraph

H M L

- jump to the top of the display - jump to the middle of the display - jump to the bottom of the display

'm - jump to the beginning of the line of mark m `m - jump to the location of mark m G - jump to end of file 1G - jump to beginning of file 50G - jump to line 50 '' - return to the line where the cursor was before the latest jump `` - return to the cursor position before the latest jump (undo the jump). % - jump to corresponding item, e.g. from an open brace to its matching closing brace For some more interesting movement commands (especially those for programmers) refer to: :help motion.txt :help search-commands

VimTip 49: Switching case of characters http://vim.sf.net/tip_view.php?tip_id=49 To switch the case of one or more characters use the "~", "gU" or "gu" commands. Examples: ~ 3~ g~~ U gUU u guu switch case of character under cursor (in visual-mode: switch case of highlighted text) switch case of next three characters switch case of current line in visual-mode: make highlighted text uppercase make current line uppercase in visual-mode: make highlighted text lowercase make current line lowercase make current word uppercase make current word lowercase

gUaw guaw -

For some more examples refer to :help ~

See also: :help simple-change

VimTip 50: Recovering files http://vim.sf.net/tip_view.php?tip_id=50 If your computer has crashed while editing a file, you should be able to recover the file by typing vi -r <filename> where <filename> is the name of the file you were editing at the time of the crash. If you were editing without a file name, give an empty string as argument: vim -r "" To get a list of recoverable files start vim without arguments: vim -r For more information about file recovery refer to: :help recovery

VimTip 51: Entering german umlauts http://vim.sf.net/tip_view.php?tip_id=51 To enter german umlauts (or any other of those weired characters) not available on your keyboard use 'digraphs': In insert-mode type for example: CTRL-K "a CTRL-K ^e which gives an '' and 'e' with a hat. You can also set the digraph option: :set digraph (or :set dg) With digraph option set you can enter " <BS> a

^ <BS> e which gives the same result. To get a list of currently defined digraphs type :dig[graphs] For more information about defining and using digraphs refer to: :help digraph.txt

VimTip 52: Scrolling synchronously http://vim.sf.net/tip_view.php?tip_id=52 If you want to bind two or more windows such that when one window is scrolled, the other windows are scrolled simultaneously, set the 'scrollbind' option for these windows: :set scrollbind When a window that has 'scrollbind' set is scrolled, all other 'scrollbind' windows are scrolled the same amount, if possible. For more information about the 'scrollbind' option refer to :help scoll-binding

VimTip 53: Better colors for syntax highlighting http://vim.sf.net/tip_view.php?tip_id=53 For syntax highlighting there are two sets of default color maps: One for a light and another one for a dark background. If you have a black background, use the following command to get a better color map for syntax highlighting: :set background=dark You have to switch off and on again syntax highlighting to activate the new color map: :syntax off :syntax on For a detailled description of syntax highlighting refer to :help syntax.txt

See also the Vim syntax support file: $VIMRUNTIME/syntax/synload.vim

VimTip 54: View a Java Class File Decompiled thru Vim http://vim.sf.net/tip_view.php?tip_id=54 Hi All, Wish u could view a Java Class File using Vim, Well ur query ends here. First of all u will need a Java Decompiler to decompile the Class File. I would suggest the JAD decompiler by Pavel Kouznetsov http://www.geocities.com/SiliconValley/Bridge/8617/jad.html Its a command line decompiler and absolutely free. U can use any command line decompiler of ur choice. Next create a vimscript file called jad.vim as ######################### FILE START ################ augr class au! au bufreadpost,filereadpost *.class %!d:jad.exe -noctor -ff -i -p % au bufreadpost,filereadpost *.class set readonly au bufreadpost,filereadpost *.class set ft=java au bufreadpost,filereadpost *.class normal gg=G au bufreadpost,filereadpost *.class set nomodified augr END ######################## FILE END ##################### Note:- Keep the Jad.exe in a directory with out white spaces. The -p options directs JAD to send the output to standard output instead of a .jad file. Other options are described on the JAD site. Next add the following line in the .vimrc file. so jad.vim Next time u do vim abc.class. Viola u have the source code for abc.class. NOTE:- I have written the script so as to open the class file read only, So that u dont accidently modify it. U can also exted this script to unjar a jar file and then view each file in the JAR file. thanks bhaskar Any suggestions are welcome

VimTip 55: previous buffer http://vim.sf.net/tip_view.php?tip_id=55

One of the keys to vim is buffer management. If I have to use another IDE that m akes me click on a tab every time I want to look at another file I'm going to go postal. So of course you know about :ls which lists all the current open buffers. This g ets a little unweildly once you have a full project open so you can also use :b <any snipit of text> <tab> to complete to an open buffer. This is really nice be cause you can type any fragment of a file name and it will complete to the match ing file. (i.e. RequestManager.java can be completed using "tma"<tab> or "req"<t ab> or "r.java"<tab>). Now for awhile I was also using :bn and :bp which jumps you to the next and prev ious buffer respectively. I found I was often frustrated because I wanted :bp to be the previous buffer I was in, not the previous buffer in the list. So (drum roll) the reason I wrote this tip was because of: :b# jump to the previous buffer you were in. Very very handy. The only thing nicer a re tag, but that's a tip for another time. :help buffers :help bn :help bp If anybody knows where to get help on # in this context please add notes.

VimTip 58: how to avoid obliterating window layout http://vim.sf.net/tip_view.php?tip_id=58 If you take the time to lay out several windows with vim (especially vertically in version 6), you may be bummed when you hit an errant key and find that all but what one window disappears. What happens: while navigating between windows, you hit <C-W>j, <C-W>k, etc. At some point you accidently hit <C-W> but then don't follow with a window command. Now hitting 'o' to start insert mode issues a command equivalent to :only, and closes all windows execept for the one you are in (unless some windows have unsaved changes in them). How to avoid this: petition the vim-dev mailing list about how :only is sufficient for the infrequenty use this might get (j/k). Really: use mapping to disable the <C-W>o functionality; put this in your .vimrc: nnoremap <C-W>O :echo "sucker"<CR> nnoremap <C-W>o :echo "sucker"<CR> nnoremap <C-W><C-O> :echo "sucker"<CR> references:

:help :only :help CTRL-W_o That is all. Scott

VimTip 62: Applying substitutes to a visual block http://vim.sf.net/tip_view.php?tip_id=62 If you'd like to apply a substitute, or even any ex command, to a visual-block selected text region (ctrl-v and move), then you'll want Stefan Roemer's http://www.erols.com/astronaut/vim/vimscript/vis.vim . Just source it in, and then press ":B". On the command line you'll see :'<,'>BCtrl-V Just continue with the substitute or whatever... :'<,'>B s/abc/ABC/g and the substitute will be applied to just that block of text! Example: Ctrl-V Select.......... ......Type ..................just the central.... ......:B s/abc/ABC/g ..................four "abc"s.............. ..................----------------.... ...------------..................abcabcabcabc............ ......abcabcabcabc ..................abcabcabcabc............ ......abcABCABCabc ..................abcabcabcabc............ ......abcABCABCabc ..................abcabcabcabc............ ......abcabcabcabc (dots inserted to retain tabular format)

VimTip 63: Applying substitutes to a visual block http://vim.sf.net/tip_view.php?tip_id=63 If you'd like to apply a substitute, or even any ex command, to a visual-block selected text region (ctrl-v and move), then you'll want Stefan Roemer's http://www.erols.com/astronaut/vim/vimscript/vis.vim . Just source it in, and then press ":B". On the command line you'll see :'<,'>BCtrl-V Just continue with the substitute or whatever... :'<,'>B s/abc/ABC/g

and the substitute will be applied to just that block of text! Example: Ctrl-V Select.......... ......Type ..................just the central....... ......:B s/abc/ABC/g ..................four "abc"s................. ..................---------............ ...------------..................abcabcabcabc............ ......abcabcabcabc ..................abcabcabcabc............ ......abcABCABCabc ..................abcabcabcabc............ ......abcABCABCabc ..................abcabcabcabc............ ......abcabcabcabc (dots inserted to retain tabular format)

VimTip 64: Always set your working directory to the file you're editing http://vim.sf.net/tip_view.php?tip_id=64 Sometimes I think it's helpful if your working directory is always the same as t he buffer you are editing. You need to put this in your .vimrc: function! CHANGE_CURR_DIR() let _dir = expand("%:p:h") exec "cd " . _dir unlet _dir endfunction autocmd BufEnter * call CHANGE_CURR_DIR() Doing this will make a "cd" command to your the current buffer each time you swi tch to it. This is actually similar to vimtip#2 but more automatic. You should see for more details: :help autocmd :help expand :help function Note: This tip was contributed by somebody on the list a while ago (sorry for no reference) and it has been extremely helpful to me. Thanks!

VimTip 65: Insert line number into the actuall text of the file. http://vim.sf.net/tip_view.php?tip_id=65 Although :set number will add nice line number for you At time you may wish to a ctually place the line numbers into the file. For example on GNU Unix you can ac omplish a simular task using cat -n file > new_file In VIM you can use the global command to do this :g/^/exec "s/^/".strpart(line(".")." ", 0, 4)

What this does is run the exec comand on every line that matches /^/ (All) The exec command taks a string and executes it as if it were typed in. line(".")." " -> returns the number of the current line plus four spaces. strpart("123 ", 0, 4) -> returns only the first four characters ("123 "). "s/^/123 " -> substituts the begining of the line with "123 ".

VimTip 66: Transfer text between two Vim 'sessions', http://vim.sf.net/tip_view.php?tip_id=66 This one is a one of my favorites from Dr. Chip, and I haven't seen it come across vim tips yet... Can use either visual, or marking to denote the text. " transfer/read and write one block of text between vim sessions " Usage: " `from' session: " ma " move to end-of-block " xw " " `to' session: " move to where I want block inserted " xr " if has("unix") nmap xr :r $HOME/.vimxfer<CR> nmap xw :'a,.w! $HOME/.vimxfer<CR> vmap xr c<esc>:r $HOME/.vimxfer<CR> vmap xw :w! $HOME/.vimxfer<CR> else nmap xr :r c:/.vimxfer<CR> nmap xw :'a,.w! c:/.vimxfer<CR> vmap xr c<esc>:r c:/.vimxfer<cr> vmap xw :w! c:/.vimxfer<CR> endif

VimTip 67: Ascii Value http://vim.sf.net/tip_view.php?tip_id=67 Sometimes we, the programmers, need the value of a character, don't we? You can learn the ascii value of a character by pressing g and a keys.(ga)! It displays the value in dec, hex and octal...

VimTip 68: Delete key http://vim.sf.net/tip_view.php?tip_id=68 Don't worry if your delete key does not work properly. Just press <CTRL>-Backspace. It works under both mode(insert or normal).

VimTip 69: dot makes life easier http://vim.sf.net/tip_view.php?tip_id=69 You can copy and paste the last changes you made in the last insert mode without using y and p by pressing . (just dot). Vim memorizes the keys you pressed and echos them if you hit the dot key. You must be in command mode as usual. It can be helpful...

VimTip 70: running a command on all buffers http://vim.sf.net/tip_view.php?tip_id=70 From Peter Bismuti on the vim list: How to global search and replace in all buffers with one command? You need the AllBuffers command: :call AllBuffers("%s/string1/string2/g") "put this in a file and source it function AllBuffers(cmnd) let cmnd = a:cmnd let i = 1 while (i <= bufnr("$")) if bufexists(i) execute "buffer" i execute cmnd endif let i = i+1 endwhile endfun ":call AllBuffers("%s/foo/bar/ge update") Thanks Peter!

VimTip 71: Transfer text between two gvim sessions using clipboard

http://vim.sf.net/tip_view.php?tip_id=71 If you use gvim, you can transfer text from one instance of gvim into another on e using clipboard. It is convenient to use * (star) register, like this: In one instance yank two lines into clipboard: "*2yy Paste it in another instance in normal mode: "*p or in insert mode: <Ctrl-R>*

VimTip 72: Remove unwanted empty lines http://vim.sf.net/tip_view.php?tip_id=72 Sometimes to improve the readability of the document I insert empty lines, which will be later removed. To get rid off them try: :%g/^$/d This will remove a l l empty line in the document. Some other tipps you can find under www.linuxclass.de/vim.phtml

VimTip 73: Using vim as calculator http://vim.sf.net/tip_view.php?tip_id=73 Basic calculations can done within vim easily by typing (insert-mode): STRG (=CTRL) + R followed by = then for example 2+2 and hit RETURN the result 4 will be printed in the document. Some other tipps you can find under www.linuxclass.de/vim.phtml

VimTip 74: Using Vim as an outline processor http://vim.sf.net/tip_view.php?tip_id=74 With the addition of folding, Vim6 can function as a high performance outline pr ocessor. Simply :set ai and in insert mode use backspace to promote and tab to d emote headlines. In command mode, << promotes (n<< to promote multiple lines), and >> demotes. Al so, highlight several headlines and < or > to promote or demote. :set foldmethod=indent, and then your z commands can expand or collapse headline

trees, filewide or by the tree. The VimOutliner GPL distro contains the scripts and configs to easily configure Vim6 as an outliner, including scripts to create tag files enabling interoutline hyperlinking. The VimOutliner project is at http://www.troubleshooters.com/projects/vimoutline r/index.htm. Steve (Litt) slitt@troubleshooters.com

VimTip 75: Remap CAPSLOCK key in Windows 2000 Professional and NT4.0 http://vim.sf.net/tip_view.php?tip_id=75 If you're Windows 2000 Professional user and got tired to move your hands off ba sic row when hitting <ESC> key here the solution (not for Windows 9x.): remap CapsLock key as <ESC> key. It's located in useful position. Put this lines into <EscLock.reg> file and start it in explorer.Reboot.Enjoy. REGEDIT4 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout] "Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,01,00,3a,00,00,00,00,00 To restore you capslock back just delete this entry from Registry and reboot. And below is remapping <capslock> as <Left Control>: REGEDIT4 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout] "Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,1d,00,3a,00,00,00,00,00

VimTip 76: Folding for Quickfix http://vim.sf.net/tip_view.php?tip_id=76 The Quickfix mode aims to "speed up the edit-compile-edit cycle" according to ': help quickfix'. After executing ':make' or ':grep' it is possible to skim throug h the list of errors/matches and the appropriate source code locations with, for instance, the ':cnext' command. Another way to get a quick overview is to use VIMs folding mode, to fold away al l the error-free/match-free regions. The script at the end of this message can be used for this purpose. It is at the moment not elaborate enough to put it up as a 'script'; but it might give someo ne inspiration to do so. Big restrictions / bugs are as follows: 1. Vim Perl interface is required, i.e. the output of ':version' must contain '+ perl' (People with Vim scripting knowledge might fix this)

2. Works only for one file, i.e. the current buffer. 3. It's a quick hack. Sample usage: (a) edit a file, (b) do ':grep regexp %' to get a quickfix error l ist and (c) ':source foldqf.vim' will fold as described Increasing the value of $CONTEXT gives you more context around the error regions . Here comes it, it should be 7 lines: ---foldqf.vim cwindow perl $CONTEXT = 0; perl @A = map { m/\ (\d+)\ /; $1 +0 } $curbuf->Get(1..$curbuf->Count()); close normal zD perl sub fold { VIM::DoCommand( $_[0] . ',' . ($_[1]) . "fold" ) if( $_[0] < $_[ 1] ); } perl $last = 0; for (@A) { fold( $last+1+$CONTEXT, $_-1-$CONTEXT ); $last = $_; }; VIM::DoCommand(($A[-1]+1+$CONTEXT ) . ',$fold' );

VimTip 77: Displaying search results using folds http://vim.sf.net/tip_view.php?tip_id=77 A guy I work with told me about a function that an old IBM text editor had that he said was useful, and that is to create folds in the file after a search such that every line that is visible contains the search pattern(except possibly the first). All lines that do not contain the search pattern are folded up to the la st occurence of the pattern or the top of the file. One use for such a function is to be able to make a quick and dirty api of a sou rce file. For example, if working in Java, you could run the function using the pattern "public protected private" and ithe results would be that only the meth od headers would be visible (well, close enough). function! Foldsearch(search) normal zE "erase all folds to begin with normal G$ "move to the end of the file let folded = 0 "flag to set when a fold is found let flags = "w" "allow wrapping in the search let line1 = 0 "set marker for beginning of fold while search(a:search, flags) > 0 let line2 = line(".") "echo "pattern found at line # " line2 if (line2 -1 > line1) "echo line1 . ":" . (line2-1) "echo "A fold goes here." execute ":" . line1 . "," . (line2-1) . "fold" let folded = 1 "at least o ne fold has been found endif let line1 = line2 "update marker let flags = "W" "turn off wrapping endwhile

" Now create the last fold which goes to the end of the file. normal $G let line2 = line(".") "echo "end of file found at line # " line2 if (line2 > line1 && folded == 1) "echo line1 . ":" . line2 "echo "A fold goes here." execute ":". line1 . "," . line2 . "fold" endif endfunction " Command is executed as ':Fs pattern'" command! -nargs=+ -complete=command Fs call Foldsearch(<q-args>) " View the methods and variables in a java source file." command! Japi Fs public\ protected\ private

VimTip 78: rotating mail signatures http://vim.sf.net/tip_view.php?tip_id=78 For people using mutt and vim for mail, the following script will allow you to i nsert a new signature (and again and again if you don\'t like the current one) a t the bottom of your mail. This is usefull eg when you don\'t want to send a pot entially offensive quote to someone you don\'t know very well (or a mailing list ), but are too lazy to delete the quote, open your quotes file, and cut and past e another one in. (I put it here in \'tips\' and not in \'scripts\' because it i s imo too short to be a \'real\' script) " " " " " " " " " " " " " rotate_sig.vim Maintainer: Roel Vanhout <roel@2e-systems.com> Version: 0.1 Last Change: Tuesday, June 12, 2001 Mapping I use: nmap ,r :call RotateSig()<CR> Usage: -Make sure you delimit your sig with '-- ', or adjust the script -Adjust the last execute to a command that prints a sig to stdout Known problems: - You'll get an error message when you're below the last '^-- $' in your mail (nothing bad though - just an notfound marker)

function! RotateSig() normal mQG execute '?^-- $' execute ':nohl' normal o<ESC> normal dG normal <CR> execute 'r !~/bin/autosig ~/.quotes \%' normal `Q endfunction

VimTip 79: How to use :grep to get a clickable list of function names http://vim.sf.net/tip_view.php?tip_id=79 The following function will make a :cwindow window with a line per function in the current C source file. NOTE: It writes the file as a side effect. Invoke with ':call ShowFunc()' You may want to do :nmap <somekey> :call ShowFunc()<CR> function! ShowFunc() let gf_s = &grepformat let gp_s = &grepprg let &grepformat = '%*\k%*\sfunction%*\s%l%*\s%f %*\s%m' let &grepprg = 'ctags -x --c-types=f --sort=no -o -' write silent! grep % cwindow let &grepformat = gf_s let &grepprg = gp_s endfunc

VimTip 80: Restore cursor to file position in previous editing session http://vim.sf.net/tip_view.php?tip_id=80 Here's something for your <.vimrc> which will allow you to restore your cursor p osition in a file over several editing sessions. This technique uses the viminf o option: Ex. set viminfo='10,\"100,:20,%,n~/.viminfo au BufReadPost * if line("'\"") > 0 if line("'\"") <= line("$") exe("norm '\ "") else exe "norm $" endif endif If you're on Unix, the viminfo is probably fine as is (but check up on Vim's hel p for viminfo to see if you like the settings above). For Windows you'll need t o change the "n" suboption to something like Ex. set viminfo='10,\"100,:20,%,nc:\\some\\place\\under\\Windoz\\_viminfo This tip is a somewhat improved version of the example given for :he line() in the Vim on-line documentation.

VimTip 81: Substitution of characters and lines in VIM is made far easier with t he s and S commands http://vim.sf.net/tip_view.php?tip_id=81 Substitute Characters ----------------------------------I was just editing a file that contained the same leading string on many lines. example: foo_bar_baz1=a foo_bar_baz1=abc674 foo_bar_baz1=qrs foo_bar_baz1=m1 foo_bar_baz1=bz90 foo_bar_baz1=bc ... Needing to only substitute a portion of the string, I referred to a VIM referenc e card and discovered a command answering my need exactly. The s command is used to subsitute a certain number of characters. In my example file above, if I onl y needed to subsititute the characters foo_bar, I set the cursor on the first ch aracter where I'd like the subsitution to begin and type 7s. VIM drops the chara cters foo_bar and goes to insert mode, waiting for the substitution text. Substitute Lines ----------------------After years of using vi and VIM and always deleting multiple lines in order to r eplace them, I just discovered the S command. If you need to subsitute three lin es of text, simply type 3S. VIM drops the three lines and goes into insert mode, waiting for the subsitution text.

VimTip 82: letting variable values be overwritten in a script http://vim.sf.net/tip_view.php?tip_id=82 this is a simple function i wrote to get the value of a variable from three diff erent places (in that order): the current buffer, the global setting or from th e script itself. this allows me to set a default value for a configuration variable inside my scr ipt and the user to change it on a global level by setting the same variable wit h a g: prepended. then, they can further set it on a per-buffer level by the th e b: mechanism. one of the examples for this might be my comments script (not u ploaded). i have a variable in there that determines whether comment characters (// for java, for example) are placed the beginning of the line or just before the first-non-blanks in the text. i set up a default in my script: let s:comments_hug_start_of_line=0 " comments should hug the text

that's fine as a default, but if i want to overwrite it for vim scripts, i just put the following in my ftplugin/vim.vim: let b:comments_hug_start_of_line=1 always " vim comments should hug the first column,

" tries to return the buffer-specific value of a variable; if not " found, tries to return the global value -- if that's not found " either, returns the value set in the script itself function! GetVar(varName) if (exists ("b:" . a:varName)) exe "let retVal=b:" . a:varName elseif (exists ("g:" . a:varName)) exe "let retVal=g:" . a:varName elseif (exists ("s:" . a:varName)) exe "let retVal=s:" . a:varName else retVal=-1 endif return retVal endfunction personally, i never let it get to the -1 state by always having an s: set with S OME default value.

VimTip 83: how to indent (useful for source code) http://vim.sf.net/tip_view.php?tip_id=83 Here is the most useful vim command that I know of and I'm surprised that it's n ot yet in the tips list. I use the indent features of vim all the time. Basically, it lets you indent you r source code. SETUP: To make indentation work nicely I have the following in my .vimrc file: set et set sw=4 set smarttab these make vim behave nicely when indenting, giving 4 spaces (not tabs) for each "tabstop". HOW TO USE: in command mode, == will indent the current line selecting a range of lines (with shift-v) then == will indent your selection typing a number then == will indent that many lines, starting from your cursor (you get the idea, there are many other things you can do to select a range of l ines) Tell me that isn't great?

VimTip 84: Changing the behaviour of . to include visual mode http://vim.sf.net/tip_view.php?tip_id=84 one of the things i do a lot in vim is to make a change to the beginning or end of the line (such as adding the text '// remove' at the end of java debug code). a quick way of doing this is to use a to append the text to the end of the first line and then move down one, hit . (repeat last edit), move down, hit . etc. etc. the following mapping allows one to simply highlight the region in question and hit . -- it will automatically execute the . once on each line: " allow the . to execute once for each line of a visual selection vnoremap . :normal .<CR> another thing i do a lot is to record a quick macro in the "a" register and then play it back a number of times. while @@ can be used to repeat the last register used, my recorded macros sometimes use other registers so @@ doesn't necessarily give me the same results as @a. also, i have mapped ' to ` because i like to go to the precise location of my marks -- always -- and never to the beginning of the line. this leaves my ` key unused. so: " make ` execute the contents of the a register nnoremap ` @a then, in keeping with the visual . above, i did the same for the ` -- is thexecutes @a once on each highlighed line. vnoremap ` :normal @a<CR> as an example, say i have the following lines of java code: public String m_asdf; public String m_lkhj; public int m_hjkhjkh; and, for some reason, i need to get the following: "asdf" "lkhj" "hjkhjkh" i record the following into a: ^cf_"<ESC>$r" the ^ is because my java code is indented and i don't want to go to column 0 and the <esc> is an actual escape i hit to exit insert mode. then, i simply select (visually) the other lines (only two in case -admittedly not an overly useful example) and just hit `.

VimTip 85: How to mimic the vim 6.0 plugin feature with older versions http://vim.sf.net/tip_view.php?tip_id=85 If you do not have vim 6.0, but would like to mimic the plugins directory featur e then copy and paste this into your vimrc: exec "source " . substitute(glob($VIM."/plugins/*.vim"), "\n", "\nsource ", "g") It will automatically source every vim script file located in the vim/plugins di rectory. Now, to add a new plugin, just drop the script in this directory and vim will au tomatically find it.

VimTip 86: Helps undo 1 line when entered many http://vim.sf.net/tip_view.php?tip_id=86 When U entered text, U cannot undo only 1 line, for example, when U press "u", a ll entered in last "insert" text removed. If U add this line to .vimrc: inoremap <Return> <Return>^O^[ where "^O" or "^[" is 1 char "u" will undo (remove) only 1 line.

VimTip 87: Get vim 5.x window in vim 6.x http://vim.sf.net/tip_view.php?tip_id=87 The format of the window title in vim 5.x (well, at least for 5.7,.8, for Win32) used to be VIM - <full filename with path>. It's not in the win32 binary of 6. 0an that I found. I want my old way back. Turns out, all that it takes to get it back is :set title titlestring=VIM\ -\ %F "make sure that the window caption setting is turned on and set caption to vim 5.x style Oh, however, one thing I did like about the 6.0 style is that it puts the word " help" in the title when the current buffer is a help file; so, I just tacked %h to my titlestring giving: :set title titlestring=VIM\ -\ %F\ %h "make sure that the window caption setting is turned on and set caption to vim 5.x style see also: :he 'titlestring' :he 'statusline'

"for the format for titlestring

VimTip 88: How to maximize vim on entry (win32) http://vim.sf.net/tip_view.php?tip_id=88 Maybe it's just because I have far too small of a monitor, because I can get dis tracted while coding if I have other stuff on the screen, or because I starting using vim on a console, but I definitely like my vim window maximized. Anyway, sticking the following in your vimrc will always maximize your vim window on sta rtup. au GUIEnter * simalt ~x :he win16-maximized

VimTip 89: Get more screen real estate by hidding toolbar and/or menus http://vim.sf.net/tip_view.php?tip_id=89 I use gvim over console vim because gvim is much more readable (under Windows). However, that doesn't mean I want to dedicate screen space to things I'll never use (i.e. the toolbar and the menus). Anyway, you can give the following a try if you'd like. set guioptions-=T "get rid of toolbar set guioptions-=m "get rid of menu Oh, yeah. If you decide that you don't really like being without your the toolb ar or menus, issue the following: set guioptions+=T "bring back toolbar set guioptions+=m "bring back menu see also: :he 'guioptions

VimTip 90: Encryption http://vim.sf.net/tip_view.php?tip_id=90 You can encrypt your texts by using vim. :X prompts for an encryption key. After writing your key, if you save your document it will be encrypted and no one else (but you and vim) can read your documents. If you reopen the file, VIM will ask for the key.

If you want to disable encryption, just type :set key= if you forget your key you will lose your document. So please DO NOT forget your key,

VimTip 91: Dictionary completions http://vim.sf.net/tip_view.php?tip_id=91 This tip will will explain how to use the dictionary completion facilities provi ded by vim. This can be useful if you use vim to type your email, edit code, et c. Dictionary completion is one of many search facilites provided by Insert mode co mpletion. It allows the user to get a list of keywords, based off of the curren t word at the cursor. This is useful if you are typing a long word (e.g. acknow ledgeable) and don't want to finish typing or don't remember the spelling. To start, we must first tell vim where our dictionary is located. This is done via the 'dictionary' option. Below is an example. Your location may vary. Se e :help 'dictionary' for hints as to where you should look. :set dictionary-=/usr/share/dict/words dictionary+=/usr/share/dict/words Now, to use this list we have to enter insert mode completion. This is done by hitting CTRL-X while in insert mode. Next, you have to specify what you want to complete. For dictionaries use CTRL-K. Once in this mode the keys CTRL-N and CTRL-P will cycle through the matches. So, to complete the word "acknowledgeabl e" I would do the following in insert mode: acknow<CTRL-X><CTRL-K><CTRL-N> It can be cumbersome to type CTRL-X CTRL-K for many different completions. So, vim gives us a shortcut. While in insert mode CTRL-N and CTRL-P will cycle thro ugh a predetermined set of completion sources. By default, dictionary completio n is not a part of this set. This set is defined by the 'complete' option. The refore, we must add dictionary to this as shown below: :set complete-=k complete+=k Now, while in insert mode we can type the following to complete our example: acknow<CTRL-N><CTRL-N> This shortcut may not save a whole lot of typing. However, I find that it requi res less hand movement to only worry myself with two key combinations, rather th an 4. I find that the completion facilites provided by vim save me a *HUGE* amount of typing. These savings can be realized in only a short amount of time if you are editing some code with functions and variables that have long names with unders cores in them. For more help: help ins-completion

help help help help

compl-dictionary 'complete' 'dictionary' :set+=

VimTip 92: Reducing 'doc' directory size http://vim.sf.net/tip_view.php?tip_id=92 As everyone knows, the $VIMRUNTIME/doc is increasing rapidly in size. The direct ory contained so many plain-text documents that I often compress them to save my diskspace. With the support of VIM's GZIP plugin, VIM will automatically uncomp ress the files when we need to read them. Here is my procedure: 1. If you have the source, go to 'runtime/doc' and edit 'doctags.c', change printf("%s\t%s\t/*", p1, argv[0]); to printf("%s\t%s.gz\t/*", p1, argv[0]); then make. This is to modify the tag, or you'll have to change the 'tags' f ile by hand if you don't have doctags.c. 2. Edit the new generated 'tags' file to rename 'help.txt.gz' back to 'help.txt' because it's hard-written in VIM executable binary. :% s/help\.txt\.gz/help\.txt/g 3. Copy the new 'tags' to $VIMRNUTIME/doc and run 'gzip *.txt; gunzip help.txt' On VIM 6.0an, we can reduce the original size (3302k) to 1326k. I don't know if this helps, but if someone likes to compress documents... this c an be reffered :)

VimTip 93: if you use 'highlight search' feature, map a key to :noh http://vim.sf.net/tip_view.php?tip_id=93 It is very convenient to use 'hlsearch' option. However it can be annoying to h ave the highlight stick longer than you want it. In order to run it off you hav e to type at least 4 keystrokes, ":noh". So, it's a good idea to map this to a key. I like to map it to control-n. This is the line I use in my .vimrc file t o do it: nmap <silent> <C-N> :silent noh<CR>

VimTip 94: Questions & Answers about using tags with Vim http://vim.sf.net/tip_view.php?tip_id=94 Using tags file with Vim -----------------------This document gives you a idea about the various facilities available

in Vim for using a tags file to browse through program source files. You can read the Vim online help, which explains in detail the tags support, using :help tagsearch.txt. You can also use the help keywords mentioned in this document to read more about a particular command or option. To read more about a particular command or option use, :help <helpkeyword> in Vim. 1. How do I create a tags file? You can create a tags file either using the ctags utility or using a custom script or utility. Help keyword(s): tag 2. Where can I download the tools to generate the tags file? There are several utilities available to generate the tags file. Depending on the programming language, you can use any one of them. 1. Exuberant ctags generates tags for the following programming language files: Assembler, AWK, ASP, BETA, Bourne/Korn/Zsh Shell, C, C++, COBOL, Eiffel, Fortran, Java, Lisp, Make, Pascal, Perl, PHP, Python, REXX, Ruby, S-Lang, Scheme, Tcl, and Vim. You can download exuberant ctags from http://ctags.sourceforge.net/ 2. On Unix, you can use the /usr/bin/ctags utility. This utility is present in most of the Unix installations. 3. You can use jtags for generating tags file for java programs. You can download jtags from: http://www.fleiner.com/jtags/ 4. You can use ptags for generating tags file for perl programs. You can download ptags from: http://www.eleves.ens.fr:8080/home/nthiery/Tags/ 5. You can download scripts from the following links for generating tags file for verilog files: http://www.probo.com/vtags.htm http://www.cs.albany.edu/~mosh/Perl/veri-tags http://www.verilog.net/vrtags.txt 6. You can download Hdrtag from the following linke: http://www.erols.com/astronaut/vim/index.html#Tags This utility generates tags file for the following programming languages: assembly, c/c++, header files, lex, yacc,LaTeX, vim, and Maple V. 7. You can also use the following scripts which are part of the Vim runtime files: pltags.pl - Create tags file for perl code tcltags - Create tags file for TCL code shtags.pl - Create tags file for shell script

Help keyword(s): ctags 3. How do I generate a tags file using ctags? You can generate a tags file for all the C files in the current directory using the following command: $ ctags *.c You can generate tags file for all the files in the current directory and all the sub-directories using (this applies only to exuberant ctags): $ ctags -R . You can generate tags file for all the files listed in a text file named flist using (this applies only to exuberant ctags) $ ctags -L flist 4. How do I configure Vim to locate a tags file? You can set the 'tags' option in Vim to specify a particular tags file. set tags=/my/dir/tags Help keyword(s): 'tags', tags-option 5. How do I configure Vim to use multiple tags files? The 'tags' option can specify more than one tags file. The tag filenames are separated using either comma or spaces. set tags=/my/dir1/tags, /my/dir2/tags 6. How do I configure Vim to locate a tags file in a directory tree? Note that the following will work only in Vim 6.0 and above. You can set the 'tags' option to make Vim search for the tags file in a directory tree. For example, if the 'tags' option is set like this: set tags=tags;/ Vim will search for the file named 'tags', starting with the current directory and then going to the parent directory and then recursively to the directory one level above, till it either locates the 'tags' file or reaches the root '/' directory. Help keyword(s): file-searching 7. How do I jump to a tag? There are several ways to jump to a tag location. 1. You can use the 'tag' ex command. For example, :tag <tagname>

will jump to the tag named <tagname>. 2. You can position the cursor over a tag name and then press Ctrl-]. 3. You can visually select a text and then press Ctrl-] to jump to the tag matching the selected text. 4. You can click on the tag name using the left mouse button, while pressing the <Ctrl> key. 5. You can press the g key and then click on the tag name using the left mouse button. 6. You can use the 'stag' ex command, to open the tag in a new window. For example, :stag func1 will open the func1 definition in a new window. 7. You can position the cursor over a tag name and then press Ctrl-W ]. This will open the tag location in a new window. Help keyword(s): :tag, Ctrl-], v_CTRL_], <C-LeftMouse>, g<LeftMouse>, :stag, Ctrl-W_] 8. How do I come back from a tag jump? There are several ways to come back to the old location from a tag jump. 1. You can use the 'pop' ex command. 2. You can press Ctrl-t. 3. You can click the right mouse button, while pressing the <Ctrl> key. 4. You can press the g key and then click the right mouse button. Help keyword(s): :pop, Ctrl-T, <C-RightMouse>, g<RightMouse> 9. How do I jump again to a previously jumped tag location? You can use the 'tag' ex command to jump to a previously jumped tag location, which is stored in the tag stack. Help keyword(s): tag 10. How do I list the contents of the tag stack? Vim remembers the location from which you jumped to a tag in the tag stack. You can list the current tag stack using the 'tags' ex command. Help keyword(s): :tags, tagstack 11. How do I jump to a particular tag match, if there are multiple matching tags? In some situations, there can be more than one match for a tag. For example, a C function or definition may be present in more than one file in a source tree. There are several ways to jump to a specific tag from a list of matching tags. 1. You can use the 'tselect' ex command to list all the tag matches. For example,

:tselect func1 will list all the locations where func1 is defined. You can then enter the number of a tag match to jump to that location. 2. You can position the cursor over the tag name and press g] to get a list of matching tags. 3. You can visually select a text and press g] to get a list of matching tags. 4. You can use the 'stselect' ex command. This will open the selected tag from the tag list in a new window. 5. You can position the cursor over the tag name and press Ctrl-W g] to do a :stselect. Help keyword(s): tag-matchlist, :tselect, g], v_g], :stselect, Ctrl-W_g] 12. I want to jump to a tag, if there is only one matching tag, otherwise a list of matching tags should be displayed. How do I do this? There are several ways to make Vim to jump to a tag directly, if there is only one tag match, otherwise present a list of tag matches. 1. You can use the 'tjump' ex command. For example, :tjump func1 will jump to the definition func1, if it is defined only once. If func1 is defined multiple times, a list of matching tags will be presented. You can position the cursor over the tag and press g Ctrl-]. You can visually select a text and press g Ctrl-] to jump or list the matching tags. You can use the 'stjump' ex command. This will open the matching or selected tag from the tag list in a new window. You can press Ctrl-W g Ctrl-] to do a :stjump.

2. 3. 4. 5.

Help keyword(s): :tjump, g_Ctrl-], v_g_CTRL-], :stjump, Ctrl-W_g_Ctrl-] 13. How do browse through a list of multiple tag matches? If there are multiple tag matches, you can browse through all of them using several of the Vim ex commands. 1. To go to the first tag in the list, use the 'tfirst' or 'trewind' ex command. 2. To go to the last tag in the list, use the 'tlast' ex command. 3. To go to the next matching tag in the list, use the 'tnext' ex command. 4. To go to the previous matching tag in the list, use the 'tprevious' or 'tNext' ex command. Help keyword(s): :tfirst, :trewind, :tlast, :tnext, :tprevious, :tNext 14. How do I preview a tag?

You can use the preview window to preview a tag, without leaving the original window. There are several ways to preview a tag: 1. You can use the 'ptag' ex command to open a tag in the preview window. 2. You can position the cursor on a tag name and press Ctrl-W } to open the tag in the preview window. 3. You can use the 'ptselect' ex command to do the equivalent of the 'tselect' ex command in the preview window. 4. You can use the 'ptjump' ex command to do the equivalent of the 'tjump' ex command in the preview window. 5. You can position the cursor on the tag and press Ctrl-W g} to do a :ptjump on the tag. Help keyword(s): :preview-window, :ptag, Ctrl-W_}, :ptselect, :ptjump, Ctrl-W_g} 15. How do I browse through the tag list in a preview window? If there are multiple tag matches, you can browse through all of them in the preview window using several of the Vim ex commands. 1. To go to the first tag in the list, use the 'ptfirst' or 'ptrewind' ex command. 2. To go to the last tag in the list, use the 'ptlast' ex command. 3. To go to the next matching tag in the list, use the 'ptnext' ex command. 4. To go to the previous matching tag in the list, use the 'ptprevious' or 'ptNext' ex command. Help keyword(s): :ptfirst, :ptrewind, :ptlast, :ptnext, :ptprevious, :ptNext 16. How do I start Vim to start editing a file at a given tag match? While starting Vim, you can use the command line option '-t' to supply a tag name. Vim will directly jump to the supplied tag location. Help keyword(s): -t 17. How do I list all the tags matching a search pattern? There are several ways to go through a list of all tags matching a pattern. 1. You can list all the tags matching a particular regular expression pattern by prepending the tag name with the '/' search character. For example, :tag /<pattern> :stag /<pattern> :ptag /<pattern> :tselect /<pattern> :tjump /<pattern> :ptselect /<pattern> :ptjump /<pattern> 2. If you have the 'wildmenu' option set, then you can press

the <Tab> key to display a list of all the matching tags in the status bar. You can use the arrow keys to move between the tags and then use the <Enter> key to select a tag. 3. If you don't have the 'wildmenu' option set, you can still use the <Tab> key to browse through the list of matching tags. Help keyword(s): tag-regexp, wildmenu 18. What options are available to control how Vim handles the tags file? You can use the following options to control the handling of tags file by Vim: 1. 'tagrelative' - Controls how the file names in the tags file are treated. When on, the filenames are relative to the directory where the tags file is present. 2. 'taglength' - Controls the number of significant characters used for recognizing a tag. 3. 'tagbsearch' - Controls the method used to search the tags file for a tag. If this option is on, binary search is used to search the tags file. Otherwise, linear search is used. 4. 'tagstack' - Controls how the tag stack is used. Help keyword(s): 'tagrelative', 'taglength', 'tagbsearch', 'tagstack' 19. Is it possible to highlight all the tags in the current file? Yes. Read the Vim online help on "tag-highlight". 20. Is it possible to create a menu with all the tags in the current file? Yes. It is possible to create a menu with all the tags in the current file using a Vim script. Download the TagsMenu.vim script from the following link: http://members.home.net/jayglanville/tagsmenu/TagsMenu.html 21. Is there a workaround to make the Ctrl-] key not to be treated as the telnet escape character? The default escape characters for telnet in Unix systems is Ctrl-]. While using Vim in a telnet session, if you use Ctrl-] to jump to a tag, you will get the telnet prompt. There are two ways to avoid this problem: 1. Map the telnet escape character to some other character using the "-e <escape character>" telnet command line option 2. Disable the telnet escape character using the "-E" telnet

command line option. Help keyword(s): telnet-CTRL-]

VimTip 95: How do I pipe the output from ex commands into the text buffer? http://vim.sf.net/tip_view.php?tip_id=95 This is a *request* for a tip. I need to be able to pipe the output of a :blah ex command into the vim text buffer for editing. I wanted to do this many times for different reasons and could never find a way! I would just love to be able to do :hi --> textBuffer and examine the output at my own leasure scrolling up and down and using vim search commands on it. Same thing for :set all, and other things. Considering that cut and paste is horribl e in windows, I can't for example do :set guioptions? then cut and paste! So I have to retype it, or cut and paste from the help manual. I really want to be a ble to pipe the output of ex commands into the text buffer. Can someone help me ?

VimTip 96: Cooperation of Gvim and AutoCad [MTEXT] http://vim.sf.net/tip_view.php?tip_id=96 You can - like me :o) - use gvim, like replacement of internal AutoCad MTEXT ed itor. You need switch variable MTEXTED to "gvim" (or maybe fullpath, something l ike "c:\vim\vim60aq\gvim" ), and to your _vimrc you can put line: autocmd BufRead,BufNewFile *.tmp source c:\vim\aacad.vim And when you edit MTEXT in acad, menu AutoCad will be for your use in gvim (only in INSERT and VISUAL mode) [NOTE: Only I can't start gvim like gvim -y (for any other person, not so accust omed vith gvim) or start gvim from gvim.lnk or gvim.bat (I'am using windows95) a nd automatic skip to INSERT mode -latest word star, on end of script- is without functionality(?) Maybe someone advise me?? ] Well, script aacad.vim is listed here: "VIM menu for AutoCad's MTEXT editation "brz; mailto:brz@centrum.cz; 8. 8. 2001 " Version Mk.I "-------------------------------------------------------------------------imenu vmenu imenu vmenu imenu &AutoCad.Insert.Space \~ &AutoCad.Insert.Space <Esc>`<i\~<Esc>% &AutoCad.Insert.Backslash \\ &AutoCad.Insert.Backslash <Esc>`<i\\<Esc>% &AutoCad.Insert.Brackets \{\}<Esc>F\i

vmenu &AutoCad.Insert.Brackets <Esc>`>a\}<Esc>`<i\{<Esc>% imenu &AutoCad.Insert.Paragraph \P vmenu &AutoCad.Insert.Paragraph <Esc>`>a\P<Esc>% imenu &AutoCad.-SEP1- : imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu imenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu imenu vmenu imenu vmenu imenu vmenu &AutoCad.Colour.Red \C1; &AutoCad.Colour.Red <Esc>`>a\C7;<Esc>`<i\C1;<Esc>% &AutoCad.Colour.Yellow \C2; &AutoCad.Colour.Yellow <Esc>`>a\C7;<Esc>`<i\C2;<Esc>% &AutoCad.Colour.Green \C3; &AutoCad.Colour.Green <Esc>`>a\C7;<Esc>`<i\C3;<Esc>% &AutoCad.Colour.Cyan \C4; &AutoCad.Colour.Cyan <Esc>`>a\C7;<Esc>`<i\C4;<Esc>% &AutoCad.Colour.Blue \C5; &AutoCad.Colour.Blue <Esc>`>a\C7;<Esc>`<i\C5;<Esc>% &AutoCad.Colour.Violet \C6; &AutoCad.Colour.Violet <Esc>`>a\C7;<Esc>`<i\C6;<Esc>% &AutoCad.Colour.Black \C7; &AutoCad.Colour.Black <Esc>`>a\C7;<Esc>`<i\C7;<Esc>% &AutoCad.Colour.D_Grey \C8; &AutoCad.Colour.D_Grey <Esc>`>a\C7;<Esc>`<i\C8;<Esc>% &AutoCad.Colour.L_Grey \C9; &AutoCad.Colour.L_Grey <Esc>`>a\C7;<Esc>`<i\C9;<Esc>% &AutoCad.Font.Arial \fArial; &AutoCad.Font.Arial <Esc>`<i\fArial;<Esc>% &AutoCad.Font.Symbol \Fsymbol; &AutoCad.Font.Symbol <Esc>`<i\Fsymbol;<Esc>% &AutoCad.Font.RomanC \Fromanc; &AutoCad.Font.RomanC <Esc>`<i\Fromanc;<Esc>% &AutoCad.Font.RomanS \Fromans; &AutoCad.Font.RomanS <Esc>`<i\Fromans;<Esc>% &AutoCad.Font.RomanD \Fromand; &AutoCad.Font.RomanD <Esc>`<i\Fromand;<Esc>% &AutoCad.Font.RomanT \Fromant; &AutoCad.Font.RomanT <Esc>`<i\Fromant;<Esc>% &AutoCad.Size.0_5x \H0.5x; &AutoCad.Size.0_5x <Esc>`<i\H0.5x;<Esc>% &AutoCad.Size.1_5x \H1.5x; &AutoCad.Size.1_5x <Esc>`<i\H1.5x;<Esc>% &AutoCad.Size.2x \H2x; &AutoCad.Size.2x <Esc>`<i\H2x;<Esc>% &AutoCad.Size.3x \H3x; &AutoCad.Size.3x <Esc>`<i\H3x;<Esc>% &AutoCad.Effects.Set_Out_1_5 \T1.5; &AutoCad.Effects.Set_Out_1_5 <Esc>`>a\T1;<Esc>`<i\T1.5;<Esc>% &AutoCad.Effects.Set_Out_2 \T2; &AutoCad.Effects.Set_Out_2 <Esc>`>a\T1;<Esc>`<i\T2;<Esc>% &AutoCad.Effects.-SEP3- : &AutoCad.Effects.Tilt_15deg &AutoCad.Effects.Tilt_15deg &AutoCad.Effects.Tilt_20deg &AutoCad.Effects.Tilt_20deg &AutoCad.Effects.Tilt_30deg &AutoCad.Effects.Tilt_30deg \Q15; <Esc>`>a\Q0;<Esc>`<i\Q10;<Esc>% \Q20; <Esc>`>a\Q0;<Esc>`<i\Q20;<Esc>% \Q30; <Esc>`>a\Q0;<Esc>`<i\Q30;<Esc>%

imenu imenu vmenu imenu vmenu imenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu vmenu imenu

&AutoCad.Effects.-SEP4- : &AutoCad.Effects.Change_Width_0_5x \W0.5; &AutoCad.Effects.Change_Width_0_5x <Esc>`>a\W1;<Esc>`<i\W0.5;<Esc>% &AutoCad.Effects.Change_Width_2x \W2; &AutoCad.Effects.Change_Width_2x <Esc>`>a\W1;<Esc>`<i\W2;<Esc>% &AutoCad.Effects.-SEP5- : &AutoCad.Effects.Justify_Down \A0; &AutoCad.Effects.Justify_Down <Esc>`<i\A0;<Esc>% &AutoCad.Effects.Justify_Middle \A1; &AutoCad.Effects.Justify_Middle <Esc>`<i\A1;<Esc>% &AutoCad.Effects.Justify_Up \A2; &AutoCad.Effects.Justify_Up <Esc>`<i\A2;<Esc>% &AutoCad.Effects.Overlined_Characters \O\o<Esc>F\i &AutoCad.Effects.Overlined_Characters <Esc>`>a\O<Esc>`<i\o<Esc>% &AutoCad.Effects.Underlined_Characters \L\l<Esc>F\i &AutoCad.Effects.Underlined_Characters <Esc>`>a\l<Esc>`<i\L<Esc>% &AutoCad.Effects.Index_Top \S^;

imenu &AutoCad.-SEP6- : imenu &AutoCad.Help <CR><CR>***Quit Editor: press Alt-F4 and 'No' ***<CR><CR> star

VimTip 97: How do I add a current time string inside Vim? http://vim.sf.net/tip_view.php?tip_id=97 This is a *request* for a tip. Sometimes (eg. editing HTML pages) I need to add a timestamp string to my editin g buffer. On UNIX systems, I can use :r!date to get a localized date time string; but on Windows ('date' on Windows will quer y the user to input new date) or other platforms which does not have 'date' command, how do I get a timestamp easily?

VimTip 98: Getting vim help from mailing lists and newsgroups. http://vim.sf.net/tip_view.php?tip_id=98 There have been a few "requests for tips" entered into the tips database lately. If you have specific questions that aren't answered by the existing tips, ther e are a couple of resources that may be more appropriate: The mailing list vim@vim.org is for vim users. If you send an email to vim-help @vim.org, you'll get a message back telling you how to subscribe, as well as how to request old messages and contact the list maintainer. This mailing list is also archived at http://groups.yahoo.com/group/vim.

The newsgroup comp.editors discusses many different editors, but most of the tra ffic is about vim. When posting, it is appreciated if you include "vim" in the subject line. The comp.editors newsgroup is archived at http://groups.google.co m/groups?hl=en&safe=off&group=comp.editors. Using the tips database for asking questions is not likely to work well. For ex ample, if you ask a question titled "Searching for strings in a file" and I read this site and see that tip, I'm not going to read it if I already know how to s earch for strings in a file. In comp.editors and vim@vim.org, people expect to find questions from others and are therefore more likely to see your questions. After finding the answer to your question, please consider whether it would make an appropriate tip, and if so, add it to the tips database.

VimTip 99: How to tell what syntax highlighting group *that* is! http://vim.sf.net/tip_view.php?tip_id=99 Here's a (what should be a one-line) map to help you tell just what syntax highlighting groups the item under the cursor actually is: map <F10> :echo "hi<" . synIDattr(synID(line("."),col("."),1),"name") . '> tra ns<' . synIDattr(synID(line("."),col("."),0),"name") . "> lo<" . synIDattr(synID trans(synID(line("."),col("."),1)),"name") . ">"<CR> Once known you can override the current highlighting with whatever you want. If you're debugging a syntax highlighting file (a rare occupation), sometimes you'll wish to know the entire chain of syntax highlighting. For that, check out http://www.erols.com/astronaut/vim/vimscript/hilinks.vim

VimTip 100: Jump to tag (e.g. help topic) with German keyboard (PC) http://vim.sf.net/tip_view.php?tip_id=100 You're a newbie in vim and need some ":help"? Well, help.txt reads: "Jump to a subject: Position the cursor on a tag between bars and hit CTRL-]. " Unfortunately there is no "]" key on German keyboards. On Win32 try CTRL-+ (Strg -+), on Linux console I use CTRL-AltGr-9 (Strg-AltGr-9). Kind regards

VimTip 101: Change automatically to the directory the file in the current buffer is in http://vim.sf.net/tip_view.php?tip_id=101 To change automatically to the directory the file in the current buffer is in add a line (below) to the file .vimrc . The file .vimrc should have the following if-statement to control the autocmd fe ature: if has("autocmd") < ... lot of autocmd stuff ... > " Change to the directory the file in your current buffer is in autocmd BufEnter * :cd %:p:h endif " has("autocmd") Add the line above the endif and restart vim/gvim.

VimTip 102: smart mapping for tab completion http://vim.sf.net/tip_view.php?tip_id=102 I'm used to complete words with <tab>, however when editing source I can't just map that to vim keyword completion because I sometime need to insert real tabs, since it mostly happen when at the beginning of the line or after a ; and before a one line comma (java, c++ or perl anyone...) I've come to find the following really usefull This is how you can map the <tab> key in insert mode while still being able to u se it when at the start of a line or when the preceding char is not a keyword ch aracter. in a script file in a plugin directory or in your .vimrc file: first define a function which returns a <tab> or a <C-N> depending on the contex t: function InsertTabWrapper() let col = col('.') - 1 if !col getline('.')[col - 1] !~ '\k' return "\<tab>" else return "\<c-p>" endif endfunction then define the appropriate mapping: inoremap <tab> <c-r>=InsertTabWrapper()<cr> the trick here is the use of the <c-r>= in insert mode to be able to call your f unction without leaving insert mode. :help i_CTRL-R

Benoit

VimTip 103: Move to next/previous line with same indentation http://vim.sf.net/tip_view.php?tip_id=103 When working with Python and other languages which don't use braces, it's useful to be able to jump to and from lines which have the same indentation as the lin e you are currently on. nn <M-,> k:call search ("^". matchstr (getline (line (".")+ 1), '\(\s*\)') ."\\S ", 'b')<CR>^ nn <M-.> :call search ("^". matchstr (getline (line (".")), '\(\s*\)') ."\\S")<C R>^ will map Alt-< and Alt-> in Normal mode to upward and downward searching for lin es with the same indent as the current line.

VimTip 104: using vim to complement Perl's DBI::Shell http://vim.sf.net/tip_view.php?tip_id=104 DBI::Shell is a Perl module that is used as a shell interface to Perl's popular DBI (database interface) package. Forget your favorite SQL navigation gui and gi ve this method a shot. This has only been tested in UNIX. 1. run dbish (runs DBI::Shell; installed with DBI::Shell) and connect to any dat abase 2. in dbish, set /format box 3. enter your query 4. to execute query, type "/ vim -" This runs the query and pipes the output to the standard input of vim. Here are some follow-up tips: -use gvim instead of vim so a new window will pop up -set nowrap once in vim -make a syntax highlighting file for me! -Adam Monsen

VimTip 105: combining move and scroll http://vim.sf.net/tip_view.php?tip_id=105 I sometimes found myself moving down a few lines about the same number of lines with <C-E> to put same place as it started. I decided I wanted to respectively) to the move-and-scroll operation. with j, then scrolling down the cursor in roughly the map <C-J> (and <C-K>, First, I did

:map <C-J> <C-E>j This was pretty good, but behaved funny at the beginning and end of files. Then, I realized that <C-D> already combined move and scroll, so I figured that giving <C-D> a count of 1 would do it: :map <C-J> 1<C-D> Unfortunately, this permanently attaches a count to <C-D> (ugh!), so I have to undo that: :map <C-J> 1<C-D>:set scroll=0<CR> This has the drawback of not necessarily resetting scroll to its original value, but since I never change scroll, it's good enough for me. It would be nice if there were a version of <C-D> that did not have the side-affect of changing scroll. Happy vimming, Andrew

VimTip 106: Mail signature rotation: Supersimple one-line solution http://vim.sf.net/tip_view.php?tip_id=106 Hallo, next solution for _most_simple_ signature rotater: You can only put one line to your .vimrc _vimrc: map <Leader>ms :e c:\sign.txt<CR>ggV/--<CR>k"*xG$a<C-R><C-O>*<Esc>:w<CR>:bd<CR>G $a<C-M><Esc>"*P Must exist file (from eg above) c:\sign.txt, with content: -first signature -second signature -third signature -When You finished mail, only call shortcut \ms and 'first signature' will be ins ert in your mail. In c:\sign.txt will be first signature pushed to the end of th is file. When You want use other signature, only press 'u' and \ms again (Or You can change \ms to e.g. <F12>, indeed. ) You can change this and append o ne part like 'basic' from command and append 'changing' part from .signature fil e, as you like... Ok, one unpleasant thing is here: your signature must not contain '--' (signatur e separator)... Anyhow, I find it useful brz* <brz@centrum.cz> http://brz.d2.cz/

VimTip 107: C/C++: convert enum to string table http://vim.sf.net/tip_view.php?tip_id=107 When testing your own C/C++ programs you sometimes wish to have a trace output, which shows you, which enum value is used. You can do this by creating a string table for that enum type, which contains the enum identifyer as a string. e.g. printf ("%s", MyEnumStringTable [ MyEnumVal] ); You can create the complete string table by - marking the lines containing the complete typedef enum - select menu C/C++.transform enum2Stringtab You can create string table entries by - marking the lines within the typedef enum - select menu C/C++.transform enum2String This makes it easy to keep the enum (on changes) consistent to the string table. Add the 31amenu */ CR> 31vmenu */ CR> following lines to your _GVIMRC file: C/C++.transform\ enum2Stringtab :s#[ ]*\\(\\w\\+\\)#/* \\1 "\\1"#<CR>o};<ESC>uOstatic const char* const Names[] = {<ESC><CR>/sdfsdf< C/C++.transform\ enum2Stringtab :s#[ ]*\\(\\w\\+\\)#/* \\1 "\\1"#<CR>o};<ESC>uOstatic const char* const Names[] = {<ESC><CR>/sdfsdf< :s#[ :s#[ ]*\\(\\w\\+\\)#/* \\1 ]*\\(\\w\\+\\)#/* \\1 */ */

31amenu C/C++.transform\ enum2String "\\1"#<CR>o}<ESC>/sdfsdf<CR> 31vmenu C/C++.transform\ enum2String "\\1"#<CR>o}<ESC>/sdfsdf<CR>

hint: '/sdfsdf' is added for deactivating search highlighting, ok, you'll sure find a better way to do this.

VimTip 108: Toggle a fold with a single keystroke http://vim.sf.net/tip_view.php?tip_id=108 When viewing/editing a folded file, it is often needed to inspect/close some fol d. To speed up these operation use the following (put in your $HOME/.vimrc): " Toggle fold state between closed and opened. " " If there is no fold at current line, just moves forward. " If it is present, reverse it's state. fun! ToggleFold() if foldlevel('.') == 0 normal! l else

if foldclosed('.') < 0 . foldclose else . foldopen endif endif " Clear status line echo endfun " Map this function to Space key. noremap <space> :call ToggleFold()<CR> See :help folding for more information about folding.

VimTip 109: jump between files http://vim.sf.net/tip_view.php?tip_id=109 Often I know I'm likely to edit many files. I run 'vim *.pl' and get a whole bun ch of open files. To make jumping between files to a pleasure, I defined to mapss: map <f1> :previous<cr> map <f2> :next<cr> Press F1 to go back and F2 to go forward. -Kirill

VimTip 110: text->html table converter. http://vim.sf.net/tip_view.php?tip_id=110 Below are two functions and a mapping which will convert lines of plain text int o HTML table code. For example, you have several lines like: ----------------------------------------------1 2 3 4 5 6 --------------------------------------------------by visualizing all the 7 lines and press <F5>, you can change the text into

<table><tr> <td>1</td> <td>2</td> <td>3</td> </tr><tr> <td>4</td> <td>5</td> <td>6</td> </tr></table> which will eventually render into a table. So the rule is: Every line is a table item, every empty line means starting of a new table row.

"A text->html table code converter "By: Wenzhi Liang wzhliang@yahoo.com "You can distribute/change this file freely as long as you keep the title area. Thanks func Table() let end=line("'>") let start=line("'<") let i=start wh i <= end exe ":" . i let e=Empty() if e == 1 exe "normal I</tr><tr>" else exe "normal I<td>A</td>>" endif let i=i+1 endwh exe "normal o</tr></table><<" exe ":" . start exe "normal O<table><tr><<" endfunc vmap <F5> <ESC>:call Table()<CR> func Empty() let line_nr= line (".") let a=getline ( line_nr ) let m=match(a, "\\S") if m == -1 return 1 else return 0 endif endfunc

VimTip 111: Printing with syntax highlighting independent of your normal highlig

hting http://vim.sf.net/tip_view.php?tip_id=111 I have found it undesirable to use :hardcopy directly because it uses the t syntax highlighting to determine how to print the text. For example, I o print comments in italics, but I don't like italic fonts on the screen. ip will show you how to set up a colorscheme for printing and use it only ou print. curren like t This t when y

I copied an existing colorscheme to ~/.vim/colors/print.vim, and changed all the lines like this: highlight Normal ctermbg=DarkGrey ctermfg=White guifg=White guibg=grey20 to this: highlight clear Normal Then I set the syntax groups how I wanted them to be printed on the printer: highlight Comment highlight Constant etc.... term=italic term=bold cterm=italic cterm=bold gui=italic gui=bold

I then defined the following command in my .vimrc file: command! -nargs=* Hardcopy call DoMyPrint("<args>") And, finally, I defined this function in my .vimrc: function DoMyPrint(args) let colorsave=g:colors_name color print exec "hardcopy ".a:args exec 'color '.colorsave endfunction After this is complete, you can do: :Hardcopy > /tmp/out.ps or just :Hardcopy (Note the capital H)

VimTip 112: Back and forth between indented lines again http://vim.sf.net/tip_view.php?tip_id=112 Paul Wright posted a tip which explained how to jump back and forth between line s with the same indentation level. I do this a lot, so I came up with this sligh tly more comprehensive solution. The example mappings below work as follows: [l and ]l jump to the previous or the next line with the same indentation level as the one you're currently on.

[L and ]L jump to the previous or the next line with an indentation level lower than the line you're currently on. These movements also work in visual mode and (only as of one of the 6.0 alpha ve rsions) in operator pending mode, meaning that you can do a d]l. The motion is s pecified as being exclusive when in operator pending mode. When might you use this? If you're writing programs in Python, Haskell, or editi ng XML files, they will be very useful. E.g. in XML you can jump to the outer en closing tag, or the next matching tag. I use it for practically anything I edit, so it's not limited to this.

" " " " " " " " " " " " " "

NextIndent() Jump to the next or previous line that has the same level or a lower level of indentation than the current line. exclusive (bool): true: false: fwd (bool): true: false: lowerlevel (bool): true: false: skipblanks (bool): true: false: Motion is exclusive Motion is inclusive Go to next line Go to previous line Go to line with lower indentation level Go to line with the same indentation level Skip blank lines Don't skip blank lines

function! NextIndent(exclusive, fwd, lowerlevel, skipblanks) let line = line('.') let column = col('.') let lastline = line('$') let indent = indent(line) let stepvalue = a:fwd ? 1 : -1 while (line > 0 && line <= lastline) let line = line + stepvalue if ( ! a:lowerlevel && indent(line) == indent \ a:lowerlevel && indent(line) < indent) if (! a:skipblanks strlen(getline(line)) > 0) if (a:exclusive) let line = line - stepvalue endif exe line exe "normal " column . " " return endif endif endwhile endfunc " Moving nnoremap nnoremap nnoremap nnoremap vnoremap vnoremap back and <silent> <silent> <silent> <silent> <silent> <silent> forth between lines of same or lower indentation. [l :call NextIndent(0, 0, 0, 1)<cr> ]l :call NextIndent(0, 1, 0, 1)<cr> [L :call NextIndent(0, 0, 1, 1)<cr> ]L :call NextIndent(0, 1, 1, 1)<cr> [l <esc>:call NextIndent(0, 0, 0, 1)<cr>m'gv'' ]l <esc>:call NextIndent(0, 1, 0, 1)<cr>m'gv''

vnoremap vnoremap onoremap onoremap onoremap onoremap

<silent> <silent> <silent> <silent> <silent> <silent>

[L ]L [l ]l [L ]L

<esc>:call NextIndent(0, 0, 1, 1)<cr>m'gv'' <esc>:call NextIndent(0, 1, 1, 1)<cr>m'gv'' :call NextIndent(0, 0, 0, 1)<cr> :call NextIndent(0, 1, 0, 1)<cr> :call NextIndent(1, 0, 1, 1)<cr> :call NextIndent(1, 1, 1, 1)<cr>

VimTip 113: Translator in vim (Windows solution) http://vim.sf.net/tip_view.php?tip_id=113 Hallo, today I found script "translate.vim", but on Windows this will be probabl y difficult to run it (maybe with Cygwin is it possible). I've simpler solution of keymap for vim interlacing to dictionary: Must exist file with vocabulary (e.g. "an-cs.txt"), which is called for word und er cursor. In 'normal' is only displayed window with translations, in 'insert' i s word under cursor deleted and is insert selected form of word from translantio n window (select it by mouse and than press right button: It works fine on W2k). Key _F12_ is looking for "word", shifted _S-F12_ is looking for "pattern". For windows is needed agrep, which is localy placed on http://www.tgries.de/agre p/index.html map <F12> b"*yw<Esc>:! c:/bin/agrep -wih <C-R>* "c:/dict/an-cs.txt"<CR> imap <F12> <Esc>b"*yw<Esc>:! c:/bin/agrep -wih <C-R>* "c:/dict/an-cs.txt"<CR>dwi <C-R>* map <S-F12> b"*yw<Esc>:! c:/bin/agrep -ih <C-R>* "c:/dict/an-cs.txt"<CR> imap <S-F12> <Esc>b"*yw<Esc>:! c:/bin/agrep -ih <C-R>* "c:/dict/an-cs.txt"<CR>dw i <C-R>* brz* <brz@centrum.cz>

VimTip 114: Browsing by paragraph http://vim.sf.net/tip_view.php?tip_id=114 It can be done by reaching the blank lines in up and down directions just by pre ssing { } ---- For going to the blank line above the paragraph ---- For going to the blank line below the paragraph

VimTip 115: Browsing by paragraph http://vim.sf.net/tip_view.php?tip_id=115 It can be done by reaching the blank lines in up and down directions just by pre ssing

{ }

---- For going to the blank line above the paragraph ---- For going to the blank line below the paragraph

VimTip 116: Search all occurances of the word under cursor in all the open files http://vim.sf.net/tip_view.php?tip_id=116 Sometimes it is useful to know all the occurances of the word under cursor in al l the open files. This can be done by pressing [I ( bracket and capital I ) . it shows the results found in the command window.

VimTip 117: FAST SEARCH ACROSS THE PROJECT http://vim.sf.net/tip_view.php?tip_id=117 Searching for a word across the project wastes most of the developres time, whic h can be avoided by the use of GNU Id_utils with VIM. The procedure needs to be followed is as follows: download GNU idutils 3.2d (mkid,lid,fid,fnid,xtokid) from http://www.mossbayeng.com/~ron/vim/builds.html uncompress and store these files in the directory from where vim is running. goto the top level directory of the project, and run mkid, it will create ID fil e in that directory (As it is time consuming process, so be patient). copy this file ID to the directory from where vim is running. USAGE: Put these lines in your .vimrc: map _u :call ID_search()<Bar>execute "/\\<" . g:word . "\\>"<CR> map _n :n<Bar>execute "/\\<" . g:word . "\\>"<CR> function ID_search() let g:word = expand("<cword>") let x = system("lid --key=none ". g:word) let x = substitute(x, "\n", " ", "g") execute "next " . x endfun To use it, place the cursor on a word, type "_u" and vim will load the file that contains the word. Search for the next ocurance of the word in the same file with "n". Go to the next file with "_n". The mapping of "_u" and "_n" can be done to some other key as per your preferenc e but I use ^K and ^L for this purpose.

VimTip 118: Configuring gVim as Internet Explorer 'View Source' editor http://vim.sf.net/tip_view.php?tip_id=118 Within the registry, you can specify the source editor to be used by Internet Ex plorer when {View Source} is selected. Unfortunately, you can't specify a quoted filename argument here, i.e. "%1". The editor specified is supposed to handle f ilenames which contain spaces. This will cause problems for Vim because Vim trea ts each space as an argument separator. If an unquoted filename contains spaces, Vim treats the filename as multiple arguments and will open multiple files inst ead of one. To workaround this problem a quoted filename has to be passed to Vim . This can be done by creating the following Visual Basic Script file gVim.vbs: '--- gVim.vbs ----------------------------------------------------------------'function: Start gvim, combining multiple arguments to single file argument. 'changes: 20010905: Quoted 'oWShell.Run' filename argument, allowing spaces. ' 20010518: Created. 'author: Freddy Vulto <fvu@fvu.myweb.nl> ' Making variable declaration mandatory option explicit dim oWShell, sArg, sFile ' set ' for Create script object oWShell = CreateObject("wscript.shell") Loop through arguments each sArg in wscript.arguments ' Add argument to filename sFile = sFile & sArg & " " next ' Remove excess space sFile = Trim(sFile) ' Run Vim with file argument. Additional arguments: ' -R: View file readonly ' -c "set syntax=html": Use HTML syntax-highlighting ' NOTE: Use "-c ""set ft=html""" to make it work for Vim v6. oWShell.Run _ """D:\Programs\Vim\Vim58\gvim.exe """ & _ "-R """ & sFile & """ " & _ "-c ""set syntax=html""" ' Destroy script object set oWShell = NOTHING The source editor now can be specified by adding the following key to the regist ry: HKEY_LOCAL_MACHINE - Software - Microsoft - Internet Explorer - View Source Editor - Editor Name

(Default) = D:\Programs\Vim\gvim.vbs

Freddy Vulto <fvu@fvu.myweb.nl> http://fvu.myweb.nl/Projects/Vim/Web/vim.htm

VimTip 119: Explorer startup and shutdown http://vim.sf.net/tip_view.php?tip_id=119 I really like the new explorer window, but I wanted it to function a little more seemlessly in the editor. The following code does two things. First, the expl orer is started when vim is started. I also noticed and fixed that the explore rs size is not equal to the window size, hence the strange behavior when popping between two windows. The other major function of the code is to close the expl orer when it's the only window that's left. I'd actually like to take this a st ep further and close the window if the last _document_ window is closed. I'd pr efer that multiple explorers or help windows don't keep the application running - only having a file open keeps the application running. But I didn't see an ea sy way to do this... anyone else? BTW, thank you Bram for the help figuring this out. Code (which currently lives in my _vimrc): " FILE BROWSER STARTUP func OpenFileWindow() " :runtime plugin/*.vim ng this

" this would be useful if you were calli

" function from the .vimrc directly let g:explDetailedList=1 " show size and date by default let g:explVertical=1 " Split vertically let g:explStartRight=0 " Put new explorer window to the left of the current window :Sexplore set nonu set winwidth=15 " Make the width of the window match the explore r setting "let g:explVertical=0 " Split vertically doautocmd fileExplorer BufEnter " Forces the directory refresh to occur :winc l " change to the document window endfunc func CloseIfLast() if exists("b:completePath") " this is how I determine that I'm in an explorer window let n = winnr() wincmd p if n == winnr() quit " quit the window endif wincmd p endif endfunc if has("autocmd") if !exists("rudyautocommands") let rudyautocommands = 1

autocmd VimEnter * call OpenFileWindow() autocmd WinEnter * call CloseIfLast() endif endif

VimTip 120: Compiling Java with Sun JDK (javac) within VIM http://vim.sf.net/tip_view.php?tip_id=120 The $VIMRUNTIME/compiler has 'jikes.vim', but there's nothing for traditional Su n JDK(javac), so I tried (Only tested on Win 2000): " Vim Compiler File javac.vim " Compiler: Sun/IBM JDK: Javac if exists("current_compiler") finish endif let current_compiler = "javac" " Javac defaults to printing output on stderr and no options can convert, so we have to set 'shellpipe' setlocal shellpipe=2> " 2> works on Win NT and UNIX setlocal makeprg=javac\ #<.java setlocal errorformat=%f:%l:%m " Sorry I'm not familiar with 'errorformat', so I set it very simple.

VimTip 121: Using vim as a syntax-highlighting pager http://vim.sf.net/tip_view.php?tip_id=121 If you want to use Vim's syntax highlighting in a "more"-style pager, here's one way to set it up: First, create a vimrc like the following -- I called mine ~/.vimrc.more ---8<---cut here---8<--" No compatibility -- necessary for mappings to work. set nocompatible " Status line set laststatus=0 set cmdheight=1 set nomodifiable set readonly

" Only in version 6.0

" Syntax colouring -- lines taken from syntax.txt discussion on colour xterms. " See ':help color-xterm'. Use appropriate lines for your own set-up. if has("terminfo") set t_Co=16 set t_Sf=[3%p1%dm set t_Sb=[4%p1%dm else set t_Co=16 set t_Sf=[3%dm set t_Sb=[4%dm endif " My xterms have a navy-blue background, so I need this line too. set background=dark " Turn syntax on syntax on " Key bindings. nmap b <C-B><C-G> nmap q :q<CR> " To type the following line, type *two* C-V's followed by two spaces. This " is how you map the spacebar. nmap ^V <C-F><C-G> ---8<---cut here---8<--Then, to use this .vimrc, add an alias. If you're using tcsh, the syntax will be something like: alias vmore "vim -u ~/.vimrc.more" Then you can type "vmore [filename]" to view a file in this "pager". Spacebar will move down, 'b' will move back up, and 'q' quits. You can add mappings for other keys if you want to, also.

VimTip 122: Skip blank lines when folding text. http://vim.sf.net/tip_view.php?tip_id=122 I love the text folding capabilities of vim. I didn't like that it would displa y the first line of the range as the "title" for the fold. I like to write my c omments with the "/*" on a line by itself. So I wrote this little function that will skip over anything that isn't a character, and then display whatever it fi nds after that character. Just include this in your ~/.vimrc (or ~/.gvimrc): function GetFirstLineWithChars() let line_num = 0 let charline = matchstr(getline(v:foldstart), '[a-zA-Z][a-zA-Z ]*') while strlen(charline) == 0 let line_num = line_num + 1 let charline = matchstr(getline(v:foldstart + line_num), '[a-zAZ][a-zA-Z ]*') endw return charline endfunction

set foldtext='+'.v:folddashes.substitute(GetFirstLineWithChars(),'\\\/\\\/\\\ \\ *\\\ \\*\\\ {{{\\d\\=','','g') set fillchars=fold: hi folded guibg=black guifg=yellow gui=bold And as an added bonus, for those new to text folding, add this to your .vimrc fi le too: autocmd BufWinLeave *.* mkview autocmd BufWinEnter *.* silent loadview That way whatever folds you set won't get lost when you quit. I had that happen after spending 15 minutes folding up a 3000+ line file. Happy vimming!

VimTip 123: use functionality similar to the * search on multiple files http://vim.sf.net/tip_view.php?tip_id=123 The use of star as in vimtip#1 and vimtip#5 is great, here is how to use this ty pe of search accross a whole directory: Just add the mappings (or choose different letter combinations): map gr :grep <cword> *<cr> map gr :grep <cword> %:p:h/*<cr> map gR :grep \b<cword>\b *<cr> map GR :grep \b<cword>\b %:p:h/*<cr> mapping one will search for the word under the cursor (like g*) in any of the fi les in the current directory mapping two will search for the word under the cursor (like g*) in any of the fi les in the same directory as the current file mapping three will search for the word under the cursor by itself (i.e. surround ed by word boundary like *) in any of the files in the current directory mapping four will search for the word under the cursor by itself (i.e. surrounde d by word boundary like *) in any of the files in the same directory as the curr ent file Benoit

VimTip 124: Number a group of lines http://vim.sf.net/tip_view.php?tip_id=124 Below is a way to number a set of lines. Here is an exaple before and after sna pshot: apple bob pear tree

1 2 3 4 " " " " " " " " " " " " " " " " " " " " " " " " "

apple bob pear tree Description: This provides a command and a function. They both can be called with or without a range. In addition, they can be called with or without arguments. Without a range they operate on the current line. There are two supported arguments. They are described below: arg1 -> the number to start at. The default is one. This will number your selected lines sequentially. The start can be a number, ., $, or, 'x (like getline). arg2 -> Text to append after numbers. The default is a space. Examples: To provide your functionality: :%Nlist 20 :%call Nlist(20) To make a list start at 1: :'<,'>Nlist :'<,'>call Nlist() To number the whole buffer (with it's actual line number): :%Nlist :%call Nlist() To number a subset of lines with their line number (and put a '] ' in front of every number): :'<,'>Nlist . ]\ :'<,'>call Nlist(".", "] ")

command! -nargs=* -range Nlist <line1>,<line2>call Nlist(<f-args>) function! Nlist(...) range if 2 == a:0 let start = a:1 let append = a:2 elseif 1 == a:0 let start = a:1 let append = " " else let start = 1 let append = " " endif " try to work like getline (i.e. allow the user to pass in . $ or 'x) if 0 == (start + 0) let start = line(start) endif exe a:firstline . "," . a:lastline . 's/^/\=line(".")-a:firstline+start.appe nd/' endfunction

VimTip 125: Auto commenting for "}" http://vim.sf.net/tip_view.php?tip_id=125 I always wanted a script that would auto-comment the end of a conditional block. So, I wrote one. This function searches for the previous matching "{", grabs the line, and inserts it as a comment after the "}". If there is no previous ma tching "{", it inserts nothing. So... if (test){ will generate: } // if (test) This is obviously not work if you use a different style. If you use if (test) { then substituting 'getline(".")', use 'getline(line(".") - 1)' should work. Put the following in your .vimrc: au BufNewFile,BufRead *.c,*.cc,*.C,*.h imap } <ESC>:call CurlyBracket()<CR>a function CurlyBracket() let l:my_linenum = line(".") iunmap } sil exe "normal i}" imap } <ESC>:call CurlyBracket()<CR> let l:result1 = searchpair('{', '', '}', 'bW') if (result1 > 0) let l:my_string = substitute(getline("."), '^\s*\(.*\){', '\1', "") sil exe ":" . l:my_linenum sil exe "normal a //" . l:my_string endif endfunction

VimTip 126: how do I get rid of that bold stuff with my xterm? http://vim.sf.net/tip_view.php?tip_id=126 Having problems setting up your syntax highlighting because everything is coming up in bold? You're probably using an 8 color xterm and setting up highlighting lines such as hi Normal ... ctermfg=green . The solution: use numbers! 0=black, 1=red, 2=green, 3=yellow, 4=blue, 5=magenta, 6=cyan, and 7=white. Vim tries to use "bright" colors when its given names (because Windoz machines prefer to use dim text unless its been made bold). Read more about it under :help highlight-ctermfg .

VimTip 127: Preview HTML files quickly http://vim.sf.net/tip_view.php?tip_id=127 I've found while writing HTML files that it can become cumbersome when I have to switch to a web browser, load my page, and move back to VIM regularly to previe w what I've written. I've come up with the following tricks. The first one requires that you have lynx (the text-based browser) installed on your computer (available from http://lynx.isc.org/release/). If your HTML page is primarily text, with few (if any) images, you can set up the following functi on and mapping: function PreviewHTML_TextOnly() let l:fname = expand("%:p" ) new set buftype=nofile nonumber exe "%!lynx " . l:fname . " -dump -nolist -underscore -width " . winwidth( 0 ) endfunction map <Leader>pt :call PreviewHTML_TextOnly()<CR> This will open a new window and display your formatted HTML document in that win dow. Note that bold-face, italics, links, etc. will be lost -- all you will see is the text -- but the "-underscore" parameter to Lynx causes any text that wou ld have been bold, italicized, or underlined to be displayed like _this_. The other trick requires that vim be running on your current machine, and that y ou be running a GUI of some sort (X-Windows, Windows, etc.). You can cause vim to invoke your favorite browser and have it display the file, like this: function PreviewHTML_External() exe "silent !mozilla -remote \"openurl(file://" . expand( "%:p" ) . ")\"" endfunction map <Leader>pp :call PreviewHTML_External()<CR> If you don't use mozilla, you will need to modify the function to use your prefe rred browser. Happy vimming!

VimTip 128: grep, diff, patch, idutils, etc. for Windows systems http://vim.sf.net/tip_view.php?tip_id=128 If you use Vim on Windows, and you wish you had some of those nifty UNIX co mmand-line tools, but do not feel like installing all of Cygwin, you can get many of the most-used tools from Ron Aaron's web site:

http://www.mossbayeng.com/~ron/vim/builds.html Since Ron is a big Vim fan (see http://www.mossbayeng.com/~ron/vim/vimrant.html ) you can count on these tools' working well with Vim. For some hints on how to use them, read :help :grep :help lid inside Vim. Happy Vimming!

VimTip 129: Removing automatic comment leaders http://vim.sf.net/tip_view.php?tip_id=129 If you include the "r" flag in the 'formatoptions' option (:help 'fo' , :he lp fo-table ) then the comment leader is inserted automatically when you start a new line in a comment. For example, in TeX the " %" character is the comment leader, and you might type % % % n % This is a tex file. The comment leaders on all lines but the first were generated automatically. This is the last line of the comment, but Vim will insert the comment leader o the next line.

You can get rid of the comment leader (along with anything you may already have typed on the line) without affecting the indent, if any, by typing "<C-U>" while in Insert mode. Related point: if you want to adjust the indent while in Insert mode, you can use "<C-D>" (to Decrease the indent) or "<C-T>" (to increase it). In the docs for Vim 6.0, this is described in the users' manual, :help 30.4 .

VimTip 130: disabling default ftplugins http://vim.sf.net/tip_view.php?tip_id=130 For an overview of ftplugins (filetype plugins) see :help ftplugins If you want to disable all ftplugins, or disable a particular default ftplugin, see :help :filetype :help ftplugin-overrule If you have your own ftplugins, and you want to disable all the default ones, th en do NOT include a check for b:did_ftplugin in your ftplugin files, and add the li ne

:autocmd BufEnter * let b:did_ftplugin = 1 to your VIMRC file, BEFORE the ":filetype ftplugin on" line.

VimTip 131: Scroll alternate window http://vim.sf.net/tip_view.php?tip_id=131 This mapping allow you to quickly scroll inactive window when displaying several windows concurrently. nmap <silent> <M-Down> :call ScrollOtherWindow("down")<CR> nmap <silent> <M-Up> :call ScrollOtherWindow("up")<CR> fun! ScrollOtherWindow(dir) if a:dir == "down" let move = "\<C-E>" elseif a:dir == "up" let move = "\<C-Y>" endif exec "normal \<C-W>p" . move . "\<C-W>p" endfun PS: Original idea and discussion of this tip appeared on vim@vim.org mailing lis t, I'm just prettified it a little.

VimTip 132: window zooming convenience http://vim.sf.net/tip_view.php?tip_id=132 i frequently have multiple windows open in vim -- this reduces the number of lin es each window displays -- i almost always have my windows either all the same s ize or the current one as big as possible. the following function can be toggled on or off by typing <Leader>max (i can do this quite quickly); just change the mapping at the bottom to something else if you prefer. this causes the current window to be as big as possible (moving into another win dow causes that one to become big) and all the others get very small. i actuall y use this ALL the time. turning it off (by typing the hotkey sequence again) w ill cause all windows to have the same height. "toggles whether or not the current window is automatically zoomed function! ToggleMaxWins () if exists ('g:windowMax') au! maxCurrWin exe "normal \<c-w>=" unlet g:windowMax

else augroup maxCurrWin " au BufEnter * exe "normal \<c-w>_\<c-w>\<bar>" " " only max it vertically au! BufEnter * exe "normal \<c-w>_" augroup END do maxCurrWin BufEnter let g:windowMax=1 endif endfunction map <Leader>max :call ToggleMaxWins ()<CR>

VimTip 133: Windo and Bufdo http://vim.sf.net/tip_view.php?tip_id=133 i like bufdo and windo but i don't like the fact that the commands end in a diff erent window/buffer than from where i executed them. these versions (starts wit h a capital letter) will restore the current window or buffer when the command's done. for example, to turn on line numbers everywhere, i use :Windo set nu -- :windo s et nu does the trick also but leaves me in a different window than where i start ed. " just like windo but restores the current window when it's done function! WinDo(command) let currwin=winnr() execute 'windo ' . a:command execute currwin . 'wincmd w' endfunction com! -nargs=+ -complete=command Windo call WinDo(<q-args>) " just like bufdo but restores the current buffer when it's done function! BufDo(command) let currBuff=bufnr("%") execute 'bufdo ' . a:command execute 'buffer ' . currBuff endfunction com! -nargs=+ -complete=command Bufdo call BufDo(<q-args>)

VimTip 134: View Source in IE6 using VIM http://vim.sf.net/tip_view.php?tip_id=134 You can change the "View Source" editor of IE6 by adding the following to the Wi ndows Registry. Change the path in case you installed VIM in another location. [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\View Source Editor\Edit

or Name] @="C:\\vim\\vim60\\gvim.exe"

VimTip 135: Vim buffer FAQ http://vim.sf.net/tip_view.php?tip_id=135 Vim provides various commands and options to support editing multiple buffers. This document covers some of the questions asked about using multiple buffers with Vim. You can get more detailed information about Vim buffer support using ":help windows.txt" in Vim. You can also use the help keywords mentioned in this document to read more about a particular command or option. To read more about a particular command or option use, ":help <helpkeyword>" in Vim. 1. What is a Vim buffer? A buffer is a file loaded into memory for editing. All opened files are associated with a buffer. There are also buffers not associated with any file. Help keyword(s): windows-intro 2. How do I identify a buffer? Vim buffers are identified using a name and a number. The name of the buffer is the name of the file associated with that buffer. The buffer number is a unique sequential number assigned by Vim. This buffer number will not change in a single Vim session. Help keyword(s): :buffers 3. How do I create a buffer? When you open a file using any of the Vim commands, a buffer is automatically created. For example, if you use the ":edit file" command to edit a file, a new buffer is automatically created. 4. How do I add a new buffer for a file to the buffer list without opening the file? You can add a new buffer for a file without opening it, using the ":badd" ex command. For example, :badd f1.txt :badd f2.txt The above commands will add two new buffers for the files f1.txt and f2.txt to the buffer list. Help keyword(s): :badd 5. How do I get a list of all the existing buffers? You can get a list of all the existing buffers using the ":buffers" or ":ls" or ":files" ex command. This list is called the 'buffer list'. In Vim 6.0, to display all the buffers including unlisted buffers, use the ":buffers!" or ":ls!" or ":files!" ex command.

Help keyword(s): :buffers, :ls, :files 6. How do I delete a buffer? You can delete a buffer using the ":bdelete" ex command. You can use either the buffer name or the buffer number to specify a buffer. For example, :bdelete f1.txt :bdelete 4 The above commands will delete the buffer named "f1.txt" and the fourth buffer in the buffer list. The ":bdelete" command will remove the buffer from the buffer list. In Vim 6.0, when a buffer is deleted, the buffer becomes an unlisted-buffer and is no longer included in the buffer list. But the buffer name and other information associated with the buffer is still remembered. To completely delete the buffer, use the ":bwipeout" ex command. This command will remove the buffer completely (i.e. the buffer will not become a unlisted buffer). Help keyword(s): :bdelete, :bwipeout 7. How do I delete multiple buffers? You can delete multiple buffers in several ways: 1. Pass a range argument to the ":bdelete" command. For example, :3,5bdelete This command will delete the buffers 3, 4 and 5. 2. Pass multiple buffer names to the ":bdelete" command. For example, :bdelete buf1.txt buf2.c buf3.h This command will delete buf1.txt, buf2.c and buf3.h buffers. In this example, after typing ":bdelete buf", you can press <Ctrl-A> to expand all the buffer names starting with 'buf'. Help keyword(s): :bdelete, :bwipeout 8. How do I remove a buffer from a window? You can remove a buffer displayed in a window in several ways: 1. Close the window or edit another buffer/file in that window. 2. Use the ":bunload" ex command. This command will remove the buffer from the window and unload the buffer contents from memory. The buffer will not be removed from the buffer list. Help keyword(s): :bunload 9. How do I edit an existing buffer from the buffer list? You can edit or jump to a buffer in the buffer list in several ways: 1. Use the ":buffer" ex command passing the name of an existing buffer or the buffer number. Note that buffer name completion can be used here by pressing the <Tab> key. 2. You can enter the buffer number you want to jump/edit and press the Ctrl-^ key.

3. Use the ":sbuffer" ex command passing the name of the buffer or the buffer number. Vim will split open a new window and open the specified buffer in that window. 4. You can enter the buffer number you want to jump/edit and press the Ctrl-W ^ or Ctrl-W Ctrl-^ keys. This will open the specified buffer in a new window. Help keyword(s): :buffer, :sbuffer, CTRL-W_^, CTRL-^ 10. How do I browse through all the available buffers? You can browse through the buffers in the buffer list in several ways: 1. To jump to the first buffer in the buffer list, use ":brewind" ex command. 2. To jump to the first buffer in the buffer list in a the ":sbfirst" or ":sbrewind" ex command. 3. To edit the next buffer in the buffer list, use the command. 4. To open the next buffer in the buffer list in a new ":sbnext" ex command. 5. To edit the previous buffer in the buffer list, use or ":bNext" ex command. 6. To open the previous buffer in the buffer list in a the ":sbprevious" or ":sbNext" ex command. 7. To open the last buffer in the buffer list, use the command. 8. To open the last buffer in the buffer list in a new ":sblast" ex command. the ":bfirst" or new window, use ":bnext" ex window, use the the ":bprevious" new window, use ":blast" ex window, use the

Help keyword(s): :bfirst, :brewind, :sbfirst, :sbrewind, :bnext, :sbnext, :bprevious, :bNext, :sbprevious, :sbNext, :blast, :sblast 11. How do I open all the buffers in the buffer list? You can open all the buffers present in the buffer list using the ":ball" or ":sball" ex commands. Help keyword(s): :ball, :sball 12. How do I open all the loaded buffers? You can open all the loaded buffers in the buffer list using the ":unhide" or ":sunhide" ex commands. Each buffer will be loaded in a separate new window. Help keyword(s): :unhide, :sunhide 13. How do I open the next modified buffer? You can open the next or a specific modified buffer using the ":bmodified" ex command. You can open the next or a specific modified buffer in a new window using the ":sbmodified" ex command. Help keyword(s): :bmodified, :sbmodified 14. I am using the GUI version of Vim (gvim), is there a simpler way for using the buffers instead of the ex commands? Yes. In the GUI version of Vim, you can use the 'Buffers' menu, which simplifies the use of buffers. All the buffers in the buffer list are listed in this menu. You can select a buffer name from this menu to edit the buffer. You can also delete a buffer or browse the buffer list.

Help keyword(s): buffers-menu 15. Is there a Vim script that simplifies using buffers with Vim? Yes. You can use the bufexplorer.vim script to simplify the process of using buffers. You can download the bufexplorer script from: http://lanzarotta.tripod.com/vim.html 16. Is it possible to save and restore the buffer list across Vim sessions? Yes. To save and restore the buffer list across Vim session, include the '%' flag in the 'viminfo' option. Note that if Vim is invoked with a filename argument, then the buffer list will not be restored from the last session. To use buffer lists across sessions, invoke Vim without passing filename arguments. Help keyword(s): 'viminfo', viminfo 17. How do I remove all the entries from the buffer list? You can remove all the entries in the buffer list by starting Vim with a file argument. You can also manually remove all the buffers using the ":bdelete" ex command. 18. What is a hidden buffer? A hidden buffer is a buffer with some unsaved modifications and is not displayed in a window. Hidden buffers are useful, if you want to edit multiple buffers without saving the modifications made to a buffer while loading other buffers. Help keyword(s): :buffer-!, 'hidden', hidden-buffer, buffer-hidden 19. How do I load buffers in a window, which currently has a buffer with unsaved modifications? By setting the option 'hidden', you can load buffers in a window that currently has a modified buffer. Vim will remember your modifications to the buffer. When you quit Vim, you will be asked to save the modified buffers. It is important to note that, if you have the 'hidden' option set, and you quit Vim forcibly, for example using ":quit!", then you will lose all your modifications to the hidden buffers. Help keyword(s): 'hidden' 20. Is it possible to unload or delete a buffer when it becomes hidden? The following works only in Vim 6.0 and above. By setting the 'bufhidden' option to either 'hide' or 'unload' or 'delete', you can control what happens to a buffer when it becomes hidden. When 'bufhidden' is set to 'delete', the buffer is deleted when it becomes hidden. When 'bufhidden' is set to 'unload', the buffer is unloaded when it becomes hidden. When 'bufhidden' is set to 'hide', the buffer is hidden. Help keyword(s): 'bufhidden' 21. How do I execute a command on all the buffers in the buffer list? In Vim 6.0, you can use the ":bufdo" ex command to execute an ex command on all the buffers in the buffer list. Help keyword(s): :bufdo

22. When I open an existing buffer from the buffer list, if the buffer is already displayed in one of the existing windows, I want Vim to jump to that window instead of creating a new window for this buffer. How do I do this? When opening a buffer using one of the split open buffer commands (:sbuffer, :sbnext), Vim will open the specified buffer in a new window. If the buffer is already opened in one of the existing windows, then you will have two windows containing the same buffer. You can change this behavior by setting the 'switchbuf' option to 'useopen'. With this setting, if a buffer is already opened in one of the windows, Vim will jump to that window, instead of creating a new window. Help keyword(s): 'switchbuf' 23. What information is stored as part of a buffer? Every buffer in the buffer list contains information about the last cursor position, marks, jump list, etc. 24. What is the difference between deleting a buffer and unloading a buffer? When a buffer is unloaded, it is not removed from the buffer list. Only the file contents associated with the buffer are removed from memory. When a buffer is deleted, it is unloaded and removed from the buffer list. In Vim 6, a deleted buffer becomes an 'unlisted' buffer. Help keyword(s): :bunload, :bdelete, :bwipeout, unlisted-buffer 25. Is it possible to configure Vim, by setting some option, to re-use the number of a deleted buffer for a new buffer? No. Vim will not re-use the buffer number of a deleted buffer for a new buffer. Vim will always assign the next sequential number for a new buffer. The buffer number assignment is implemented this way, so that you can always jump to a buffer using the same buffer number. One method to achieve buffer number reordering is to restart Vim. If you restart Vim, it will re-assign numbers sequentially to all the buffers in the buffer list (assuming you have properly set 'viminfo' to save and restore the buffer list across vim sessions). Help keyword(s): :buffers 26. What options do I need to set for a scratch (temporary) buffer? The following works only in Vim 6.0 and above. You can set the the following options to create a scratch (temporary) buffer: :set buftype=nofile :set bufhidden=hide :setlocal noswapfile This will create a buffer which is not associated with a file, which does not have a associated swap file and will be hidden when removed from a window. Help keyword(s): special-buffers, 'buftype' 27. How do I prevent a buffer from being added to the buffer list? The following works only in Vim 6.0 and above. You can prevent a buffer from being added to the buffer list by resetting the 'buflisted' option.

:set nobuflisted Help keyword(s): 'buflisted' 28. How do I determine whether a buffer is modified or not? There are several ways to find out whether a buffer is modified or not. The simplest way is to look at the status line or the title bar. If the displayed string contains a '+' character, then the buffer is modified. Another way is to check whether the 'modified' option is set or not. If 'modified' is set, then the buffer is modified. To check the value of modified, use :set modified? You can also explicitly set the 'modified' option to mark the buffer as modified like this: :set modified Help keyword(s): 'modified' 29. How can I prevent modifications to a buffer? The following works only in Vim 6.0 and above. You can prevent any modification to a buffer by re-setting the 'modifiable' option. To reset this option, use :set nomodifiable To again allow modifications to the buffer, use: :set modifiable Help keyword(s): 'modifiable' 30. How do I set options specific to the current buffer? The following works only in Vim 6.0 and above. You can set Vim options which are specific to a buffer using the "setlocal" command. For example, :setlocal textwidth=70 This will set the 'textwidth' option to 70 only for the current buffer. All other buffers will have the default or the previous 'textwidth' value. Help keyword(s): 'setlocal', local-options 31. How do I define mappings specific to the current buffer? The following works only in Vim 6.0 and above. You can define mappings specific to the current buffer by using the keyword "<buffer>" in the map command. For example, :map <buffer> ,w /[.,;]<CR> Help keyword(s): :map-local 32. How do I define abbreviations specific to the current buffer? The following works only in Vim 6.0 and above. You can define abbreviations specific to the current buffer by using the keyword "<buffer>" in the :abbreviate command. For example,

:abb <buffer> FF for (i = 0; i < ; ++i) Help keyword(s): :abbreviate-local

VimTip 136: Remapping Alt, Ctrl and Caps in Win2k http://vim.sf.net/tip_view.php?tip_id=136 Since I installed Win2K on my laptop, I had been unable to locate a utilitie tha t would simply enable me to remap my Crtl Alt and Caps the way I think they shou ld be and the way they were until MS kill all competition in computing, that is Crtl on the left of the letter A, Alt to the left bottom of the letter Z and Cap s approximately until the C. After some research, I came across a tip posted here by juano@mindspring.com. I tried to make sense of it and then downloaded the MS scan keys map at the URL he mentionned. Extrapolating his tip, I wrote this ASCI file that I named keys2000.reg : Regedit4 [HKey_Local_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout] "Scancode Map"=hex:00,00,00,00,00,00,00,00,04,00,00,00,3A,00,38,00,38,00,1D,00,1 D,00,3A,00,00,00,00 Once you have saved this file, left click on it from Explorer and answer yes to the prompt "do you want to enter this into the registry". Reboot and you are done. A few explanations :04 stands for 3 remappings (Caps lock to Control, Control to Alt and Alt to Caps Lock) plus the closing one which is always required (1 rema pping would require 02, 2 would require 03, and so on). 3A,00,38 remaps Caps to Left Alt, 38,00,1D remaps Left Alt to Left Ctrl and 1D,00,3A remaps Left Ctrl to Caps Lock since 3A=Caps, 1D=Left Ctrl and 38=Left Alt. Based on Juano tip and on this one, I believe a lot of remapping can be done as long as you keep the separators 00 and remember to add one to the number of rema ppings. What I do not know is how far you can extend this instruction without ge tting into trouble with the registry. At worst, if you keyboard does not behave as expected, go into the registry and delete this instruction (be careful here s ince it is easy to confuse this instruction with the Keyboard LayoutS (S for emp hasis) which must not be deleted. Again, thanks to Juano@mindspring.com who got me going and suggested I post my t ip. Took me some time to retrieve the VIM Url but fortunately, I had printed his tip. Regards

VimTip 137: automatically wrap left and right http://vim.sf.net/tip_view.php?tip_id=137 I hate it when I hit left (or h) and my screen flickers. I want it to go up to the next line. Ditto fir right (or l). Below are two functions / mappings to h elp with that. I'm pretty sure that if you remove the <silent>, then it will wo rk in 5.x... nnoremap <silent> <Left> :call WrapLeft()<cr> nnoremap <silent> <Right> :call WrapRight()<cr> nnoremap <silent> h nnoremap <silent> l function! WrapLeft() let col = col(".") if 1 == col " don't wrap if we're on the first line if 1 == line(".") return endif normal! k$ else normal! h endif endfunction function! WrapRight() let col = col(".") if 1 != col("$") let col = col + 1 endif if col("$") == col " don't wrap if we're on the last line if line("$") == line(".") return endif normal! j1 else normal! l endif endfunction :call WrapLeft()<cr> :call WrapRight()<cr>

VimTip 138: Getting name of the function http://vim.sf.net/tip_view.php?tip_id=138 Hi All, While browsing code one always needs to know which function you are currently lo

oking. Getting the name is very painful when the functions are lengthy and you a re currently browsing NOT near to the start of the function. You can get the fun ction's name by using this simple mapping. Just place this in your .vimrc. map _F ma[[k"xyy`a:echo @x<CR> now _F will display which function you are currently in. Enjoy the power of Vim -Nitin Raut PS: The working is as follows, mark the current line with a, jump to the previou s '{' in the first column, go one line up, yank the line in register x, return t o the mark a, echo the value of register x, which is the wanted function name.

VimTip 139: Alignment: =, LaTeX tables, declarations, etc http://vim.sf.net/tip_view.php?tip_id=139 Check out http://www.erols.com/astronaut/vim/textab.html and see some examples of text alignment (its hopeless to do it here with proportional fonts). You'll be able to download textab source, a Windows-based textab executable, and a scriptfile containing a convenient interface (ttalign.v im). The textab program coupled with <ttalign.vim> lets you: 1. align C language statements on their = += -= /= etc symbols 2. align C language declararations: separate columns for types, *[, variable names, initializations (=), and comments (// or /* .. */) 3. align C/C++ language comments (//, /* .. */) 4. align C/C++ language (ansi) function argument lists 5. align LaTeX tables on their && separators 6. align HTML tables with </TD><TD> separators 7. align on several characters: < ? : @ ; (or modify them to handle whatever alignment characters you want)

VimTip 140: tip using embedded perl interpreter http://vim.sf.net/tip_view.php?tip_id=140 When writing scripts using the embedded interpreter available if vim has the +pe rl ore +perl/dyn on gives you access to this powerfull and FAST scripting language (especially fast compared to vim scripts) there are some gotchas. First:

never embed complex perl command in the body of a vim function this will be reco mpiled and evaled each time for a tremendous loss of time.instead to it like this perl << EOF sub mySub { #some usefull perl stuff } EOF function! MyFunction perl mySub "an argument", "another" endfunction to pass computed argument to your perl sub use the vim exec command function! MyFunction exec "perl mySub " . aLocalVar . ", " b:aBufferLocalVar endfunction It may be very hard to debug your perl sub since the output of the perl compiler is somehow lost in the middle of nowhere and the debugger is not available. When a compilation error occurs in your sub definition you'll get an error messa ge when you try to call it saying that the sub does not exists. One thing which I have found very usefull is to write a fake VIM module with stu b methods which will allow you to use the command line perl interpretor to at leas t compile your program. You could make your stub smart enough to fake a vim and use the debugger. Here is a sample for such a fake module defining just those method which I was using. package VIM; use diagnostics; use strict; sub VIM::Eval { $_ = shift; print "Eval $_\n"; { return '^(?!!)([^\t]*)\t[^\t]*\t(.*);"\t([^\t]*)\tline:(\d*).* $' if (/g:TagsBase_pattern/); return $ARGV[0] if (/b:fileName/); return '$3' if (/g:TagsBase_typePar/); return '$1' if (/g:TagsBase_namePar/); return '$4' if (/g:TagsBase_linePar/); return 'Ta&gs' if (/s:menu_name/); return $ARGV[1] if (/g:TagsBase_groupByType/); die "unknown eval $_"; } } sub VIM::Msg { my $msg = shift; print "MSG $msg\n"; }

sub VIM::DoCommand { my $package; my $filename; my $line; ($package, $filename, $line) = caller; my $command = shift; print "at $filename $line\n"; print "DoCommand $command\n"; } 1; Then you can copy other your perl code in a separate file and add a use VIM; at the top and your set to debug. Good Vimming good perling. Benoit PS: this tips are probably true for other scripting languages

VimTip 141: Add your function heading with a keystroke http://vim.sf.net/tip_view.php?tip_id=141 Below is a tip that the C/C++ Newbies may find interesting and handy to use. Th e following code will add a function heading and position your cursor just after Description so that one can document as one proceeds with code. function FileHeading() let s:line=line(".") call setline(s:line,"/************************************************** *") call append(s:line,"* Description - ") call append(s:line+1,"* Author Mohit Kalra") call append(s:line+2,"* Date ".strftime("%b %d %Y")) call append(s:line+3,"* ************************************************ */") unlet s:line endfunction imap <F4> <esc>mz:execute FileHeading()<RET>`zjA Where <esc> stands for ^V+ESC and <RET> for ^V+ENTER

VimTip 142: Automatic function end commenting for C++ and Java http://vim.sf.net/tip_view.php?tip_id=142 Some people have a habit of adding the function name as a comment to the end of

that function, if it is long, so that he/she knows which function the '}' ends. Here's a way to automate the process. Use the following abbreviation: iab }// } // END: <esc>10h%$?\w\+\s*(<cr>"xy/\s*(<cr>/{<cr>:nohl<cr>%$"xpa If you now end the function with '}//', the follwoing string will be automatical ly generated: '} //END: functionname'

VimTip 143: Use of Vim folds for javadocs http://vim.sf.net/tip_view.php?tip_id=143 Hi, The fold-method marker can be effectively use to set the folds in your Java sour ce. Define some marker and place it inside HTML comments <!-- xx -->. This way , it does not affect the Javadocs generated without the necessity of a seprate c omment line. e.g. /** * <!-- zz.FOLDSTART class AbcClass --> * The class description. * ... */ public class AbcClass { /** * <!-- method zz.FOLDSTART someMethod() --> * Method description. */ public void someMethod(); ... } /* zz.END: AbcClass */ /* Put this at the end of your file */ /* vim:fdm=marker fmr=zz.FOLDSTART,zz.END fdl=2 fdc=2: */ Now, the files will be opened with the methods neatly folded. You can use "zR" to open all folds (or click on the "+" at the left column). Sameer.

VimTip 144: recording keystrokes by "q" for repested jobs

http://vim.sf.net/tip_view.php?tip_id=144 The most useful feature that I find in VIM is the "recording" feature (:help rec ording). I have used this to automatically insert function headers, re-indent l ines, and convert some 34 source files into HTML. This feature is most useful when you want to do some repeated jobs, which you ca nt do easily using ".". You can set about writing a function, define a mapping, etc, but then these things might take time. By recording, you can try out and find the actual keystrokes that does the job. To start recording, press "q" in normal mode followed by any of "0-9a-z". This will start recording the keystrokes to the register you choose. You can also se e the word "recording" in the status(?) line. You can start the key sequences t hat you want to record. You can go to insert mode and type if you want. To stop recording, press "q" in the normal mode. To playback your keystrokes, press "@" followed by the character you choose. Pr essing "@@" will repeat the same again. Sameer.

VimTip 145: Changing DOS style end of line to UNIX, or vise-versa http://vim.sf.net/tip_view.php?tip_id=145 Those of us doomed to work in both the Unix and Windows world have many times en countered files that were create/editted on systems other that the one we are on at the ti me of our edits. We can easily correct the dreaded '^M' at the end of our Unix lines, or make files have more than one line in DOS by: To change from <CR><LF> (DOS) to just <LF> (Unix): :set fileformat=unix :w Or to change back the other way: :set fileformat=dos :w It also works for Apple land: :set fileformat=mac :w And to tell the difference: set statusline=%<%f%h%m%r%=%{&ff}\ %l,%c%V\ %P ^^^^^ This shows what the current file's format is. Happy Vimming!

VimTip 146: opening multiple files from a single command-line http://vim.sf.net/tip_view.php?tip_id=146 i use the :split command a lot -- both to open a second window containing the cu rrently edited file and to edit a new file altogether (with the :split <filename > option). however, i also like to be able to edit more than one file and calli ng :sp multiple times is inconvenient. so, i created the following command, fun ction and abbreviation: function! Sp(...) if(a:0 == 0) sp else let i = a:0 while(i > 0) execute 'let file = a:' . i execute 'sp ' . file let i = i - 1 endwhile endif endfunction com! -nargs=* -complete=file Sp call Sp(<f-args>) cab sp Sp this retains the behaviour of :sp in that i can still type :sp (the abbreviation takes care of that). :Sp takes any number of files and opens them all up, one after the other. the things i have noticed are that this causes 'sp' to be expanded to 'Sp' every where, even in search patterns. also, prepending 'vert' doesn't work. if there is interest, i'll do that.

VimTip 147: How to write a plugin http://vim.sf.net/tip_view.php?tip_id=147 This tip gives a skeleton for writing a plugin; Vim's help files have plenty of details (:he plugin, :he write-plugin, :he plugin-details). # -----------------------------------------------------------------------------# Exit when your app has already been loaded (or "compatible" mode set) if exists("loaded_YourAppName") &cp finish endif # Public Interface: # AppFunction: is a function you expect your users to call # PickAMap: some sequence of characters that will run your AppFunction

# Repeat these three lines as needed for multiple functions which will # be used to provide an interface for the user if !hasmapto('<Plug>AppFunction') map <unique> <Leader>PickAMap <Plug>AppFunction endif # Global Maps: # map <silent> <unique> <script> <Plug>AppFunction \ :set lz<CR>:call <SID>AppFunc<CR>:set nolz<CR> # -----------------------------------------------------------------------------# AppFunction: this function is available vi the <Plug>/<script> interface above fu! <SID>AppFunction() ..whatever.. # your script function can set up maps to internal functions nmap <silent> <left> :set lz<CR>:silent! call <SID>AppFunction2<CR>:set nolz<CR> # your app can call functions in its own script and not worry about name # clashes by preceding those function names with <SID> call <SID>InternalAppFunction(...) # or you could call it with call s:InternalAppFunction(...) endf # -----------------------------------------------------------------------------# InternalAppFunction: this function cannot be called from outside the # script, and its name won't clash with whatever else the user has loaded fu! <SID>InternalAppFunction(...) ..whatever.. endf # -----------------------------------------------------------------------------Plugins are intended to be "drop into <.vim/plugin>" and work. The problem that the <Plug>, <SID>, etc stuff is intended to resolve: what to do about functions that have the same names in different plugins, and what to do about maps that use the same sequence of characters? The first problem is solved with <SID> (a script identifier number) that vim assigns: program with it and your users will be happier when your stuff works with all their other stuff. The second problem: what to about those maps is addressed with <Plug>, <unique>, etc. Basically the idea is: let the user know that there are clashes and don't overwrite previously existing maps. Use the user's preferred map-introducer sequence (I like the backslash, but there are many keyboards which make producing backslashes unpleasant, and those users usually prefer something else). What I like to do is to have a pair of start/stop maps to reduce my impact on the namespace. When the starting map is used, it kicks off a starting function that introduces all the maps needed. When the stopping map is used, it not only removes the maps the starter made but restores any maps the user had had that would have clashed. I also use the start/stop pair of functions to set and restore options that cause my scripts difficulties. Check out DrawIt.vim's SaveMap() function for a way to save user maps. Restoring maps with it is easy:

if b:restoremap != "" exe b:restoremap unlet b:restoremap endif So you can see it sets up a string variable with all the maps that the user had that would have clashed with my application. One final thing: if your application needs to share information between its various functions, see if you can use s:varname (a variable that only your script's functions can access) or b:varname (a variable that anything associated with the buffer your application is running with can access) instead of using global variables. Good luck and happy Vimming!

VimTip 148: Make great use of those homemade menus http://vim.sf.net/tip_view.php?tip_id=148 Accidently discovered that using <alt><Menu Hotletter><cr> (e.g <alt>b<cr> - for the buffer menu) causes the menu to break out in a seperate window. Selecting the menu with the mouse and then hitting enter does not seem to do it. I will have to learn to add hotletters to my menus now so that the mouse can tak e a break. I am a total newbie with vim, but constantly amazed....

VimTip 149: Automatically update your diff upon writing. http://vim.sf.net/tip_view.php?tip_id=149 When trying to reconcile differences between files, and using the new 'diff' functionality in Vim 6.0 you may want to automatically update the differences as you are working along. A convienent time is when you write out either of the files you are diff'ing. This autocmd will take care of doing that for you. " If doing a diff. Upon writing changes to file, automatically update the " differences au BufWritePost * if &diff == 1 au BufWritePost * :diffupdate au BufWritePost * endif

VimTip 150: Generating a column of increasing numbers http://vim.sf.net/tip_view.php?tip_id=150 You can use the "Visual Incrementing" script from http://www.erols.com/astronaut/vim/index.html#VimFuncs to convert a block of numbers selected via ctrl-v (visual block) into a column of increasing integers. Select the column, press :I<CR>, and the first line's number will be used as a starting value. Subsequent lines's numbers will be incremented by one. If the ctrl-v block is "ragged right", which can happen when "$" is used to select the right hand side, the block will have spaces appended as needed to straighten it out. If the strlen of the count exceeds the visual-block allotment of spaces, then additional spaces will be inserted. Example: Put cursor on topmost zero, select column with ctrl-v, then :I vector[0]= vector[0]= vector[0]= vector[0]= vector[0]= 1; vector[0]= 1; 1; vector[1]= 1; 1; --> vector[2]= 1; 1; vector[3]= 1; 1; vector[4]= 1;

This script works with both vim 5.7 (:so visincr.vim) or vim 6.0 (source it as for vim 5.7 or drop it into the .vim/plugin directory).

VimTip 151: an ascii table http://vim.sf.net/tip_view.php?tip_id=151 There is an ascii table in the vim-help files, but it's hard to find. Thus, I s hall give a pointer to it: :help digraph-table

VimTip 152: Spelling checkers for: Dutch, English, German, Hungarian, and Yiddis h http://vim.sf.net/tip_view.php?tip_id=152 Under http://www.erols.com/astronaut/vim/index.html#vimlinks_scripts are links to spelling checkers for Dutch, English, German, Hungarian, and Yiddish, all based on the original engspchk.vim. The spelling checker provides as-you-type spell checking; with vim6.0 it will avoid checking on partially typed words.

Provided are several maps: \et \es \en \ep \ea : : : : : add save move move look word under cursor into database for just this file word under cursor into database (permanently) cursor to the next spelling error cursor to the previous spelling error for alternative spellings of word under cursor

To use \ea you will need agrep: agrep source: ftp://sunsite.unc.edu/pub/Linux/utils/text/agrep-2.04.tar.Z agrep Win exe: http://www.tgries.de/agrep To use the spell checkers just source it in: ex. so engspchk.vim To read more about it see http://www.erols.com/astronaut/vim/index.html#Spelling

VimTip 153: Making Parenthesis And Brackets Handling Easier http://vim.sf.net/tip_view.php?tip_id=153 1) ++++++++++++++++++++++++++ "Automatic" bracket setting ++++++++++++++++++++++ +++++++ 2) +++++++++++++ Further improvement of parenthesis/bracket expanding ++++++++++ +++++++ 3) ++++++++++++++++++++++++++++ "Late" bracketing of text ++++++++++++++++++++++ +++++++ 4) +++++++++++++++++++++++++++++ Conclusion ++++++++++++++++++++++++++++++++++++ ++ ++++ ================================================================================ ======= 1) ++++++++++++++++++++++++++ "Automatic" bracket setting ++++++++++++++++++++++ +++++++ To automatically insert a closing parenthesis when typing an opening parenthesis you can insert the following simple mapping to your vimrc: :inoremap ( ()<ESC>i This ends up with the cursor between the opening and the closing parenthesis in insert mode. You can apply this and the following tips, of course, with the kind of parenthes is/bracket character you want to, i.e. (, {, [, < ..... and, pretty useful as well, quotation marks ",',.... (to be continued) 2) +++++++++++++++ Further improvement of parenthesis/bracket expanding ++++++++ ++++++++++

I you are ready with filling the parenthesis/brackets, you likely want to "escape" from the brackets again to continue coding. To make this pretty comfortable, I invented the following kind of mappings, whic h get out of the last expanded parenthesis/bracket, regardless of the actual type of it, a nd enter append mode again. I mapped this kind of "getaway" with CTRL_j, you may use your favorite keystroke with it. ... :inoremap ( ()<ESC>:let leavechar=")"<CR>i :inoremap [ []<ESC>:let leavechar="]"<CR>i ... :imap <C-j> <ESC>:exec "normal f" . leavechar<CR>a Explanation: The variable "leavechar" contents the actual char which is to "esca pe" from. 3) ++++++++++++++++++++++++++++ "Late" bracketing of text ++++++++++++++++++++++ +++++++ Occasionally I later want already written text parts to put in parenthesis. I use the following macro, which brackets previously visually selected text. I mapped it with _(. :vnoremap _( <ESC>`>a)<ESC>`<i(<ESC> Furthermore, a sort of mapping for bracketing a *single word* is conceivable. Because this is not as general like the kind of visual mode mapping, I use this kind of "word bracketing" only for surrounding the word right behind the cu rsor in insert mode with **. I use the following macro to "emphasize" the word i just typed, for newsgroup articles. :imap _* <Esc>bi*<Esc>ea*<Space> 4) ++++++++++++++++++++++++++++++ Conclusion +++++++++++++++++++++++++++++++++++ +++++++ Since I use these macros, I never caused a syntax error because of missing brackets, and furthermore I can quickly insert parenthesis and qutotes into code and non-code files. JH 04.11.2001

VimTip 154: Mappings to facilitate the creation of text http://vim.sf.net/tip_view.php?tip_id=154

" " " " " " " " " " " " " " " " " " " " "

Mappings to facilitate the creation of text Author: Suresh Govindachar sgovindachar@yahoo.com Date: November 5, 2001 While typing text to create a document, I often end up hitting <Esc>, issuing some commands (with or without ":") and getting back to typing by issuing a command such as "i", "O", "s" etc. I looked into using "set insertmode" to speed up such actions, but found that too confusing. I have come up with a set of mappings that have speeded up my process of creating documents. I have saved these mappings in a file, named FullScreenVI.vim, in vim's plugin directory. Perhaps you will find these mappings helpful too. Please send me feedback. allow overriding the Alt key winaltkeys=no enable viewing messages from commands issued using the mappings presented he cmdheight=2

"To set "To re set

"The fundamental mapping that makes full-screen editing possible imap <A-o> <C-o> imap <A-;> <C-o>: "Basic motions imap <A-h> <Left> imap <A-j> <Down> imap <A-k> <Up> imap <A-l> <Right> imap <A-f> <PageDown> imap <A-b> <PageUp> imap <A-^> <Home> imap <A-$> <End> "Numbers for repeats imap <A-1> <C-o>1 imap <A-2> <C-o>2 imap <A-3> <C-o>3 imap <A-4> <C-o>4 imap <A-5> <C-o>5 imap <A-6> <C-o>6 imap <A-7> <C-o>7 imap <A-8> <C-o>8 imap <A-9> <C-o>9 "Basic searches imap <A-/> <C-o>/ imap <A-*> <C-o>* imap <A-#> <C-o># imap <A-n> <C-o>n imap <A-N> <C-o>N

"Deleting imap <A-x> <C-o>x imap <A-d> <C-o>d imap <A-D> <C-o>D "Yanking and putting imap <A-y> <C-o>y imap <A-Y> <C-o>Y imap <A-p> <C-o>p imap <A-P> <C-o>P "Common prefixes: marking, matching etc. imap <A-~> <C-o>~ imap <A-m> <C-o>m imap <A-`> <C-o>` imap <A-"> <C-o>" imap <A-%> <C-o>% imap <A-h> <C-o>:h imap <A-s> <C-o>:s "Interacting with the 'outside' imap <A-!> <C-o>:! imap <A-w> <C-o>:w<CR> imap <A-e> <C-o>:e "Other commands imap <A-u> <C-o>u imap <A-.> <C-o>.

VimTip 155: Decompile Java .class files automatically http://vim.sf.net/tip_view.php?tip_id=155 Here's a plugin to automatically decompile Java .class files as they're read in. Tweak the javap flags for what you want to see. I didn't post this as a scrip t because it's too simple and it's really more useful for demonstrating how to r ead decompilable files (or other binary files that can be converted to text). function s:ReadClass(dir, classname) execute "cd " . a:dir execute "0read !javap -c " . a:classname 1 setlocal readonly setlocal nomodified endfunction autocmd BufReadCmd *.class \ call <SID>ReadClass(expand("<afile>:p:h"), expand("<afile>:t:r"))

VimTip 156: describe <table name> from vim http://vim.sf.net/tip_view.php?tip_id=156 i had some trouble with the sqlplus scripts (probably my fault). but it seemed a little heavy for what i need, usually all i want is a listing of the columns f or a given table while i'm whipping on some sql inside vim. so i wrote a bash script (describe)... ~~~~~~~~~~~~~~~begin describe script #!/usr/bin/bash f=aTempFile.sql u=<uName> p=<pWord> d=<dBase> echo "/* describe for $1" echo "describe $1;" > $f; echo "quit;" >> $f; sqlplus -S $u/$p@$d @$f rm -f $f; echo " end describe for $1 */" ~~~~~~~~~~~~~~~end describe script your path needs to include the script (as well as sqlplus), then from vim you ca n just type.... :r !describe <tableName> and you get a listing of the table columns slammed into wherever your cursor was , complete with java/c comments

VimTip 157: Incredible new functionality http://vim.sf.net/tip_view.php?tip_id=157 if you get away from vim and get any other editor that was built *after* 1970... .

VimTip 158: Using Computer Modern TT as gvim font (Win32) http://vim.sf.net/tip_view.php?tip_id=158 If you really like the Computer Modern typewriter font (as seen in most TeX dist ributions) you can use it as the font in gvim! (looks excellent with font smooth ing turned on)

First, get hold of the free Blue Sky Type 1 PS versions of the CM fonts from you r local CTAN mirror. Unpack to a suitable directory. Next locate the cmtt8.pfb file and open it (in Vim, naturally ;) - find the line saying dup 32 /visiblespace put and change it to dup 32 /space put

that is, inserting enough spaces to keep the file size exactly the same (IMPORTANT!) Save the file in Mac format (:set fileformat=mac). Now install the cmtt.pfm file - in Win9x/NT4, you'll need Adobe Type Manager (free download), but in Win2k, you can just drop the .pfm file into the Fonts fo lder. Now in your _gvimrc: set guifont=CMTT8:h11:cSYMBOL (use whatever height you like instead of h11) ..and enjoy! It's the first scalable font I can bear to edit code in... %-)

VimTip 159: Keystroke Saving Substituting and Searching http://vim.sf.net/tip_view.php?tip_id=159 1) ++++++++++++++ Saving Keystrokes for common Searching and Substituting ++++++ +++++ --- a) Searching b) Substituting -------------------------------------------------2) ++++ Searching for resp. Substituting of the current word under the cursor + +++++ --- a) Searching b) Substituting -------------------------------------------------3) ++ Searching and Substituting for an arbitrary visually selected part of text ++++ --- a) Searching b) Substituting -------------------------------------------------4) ++++++++++++++++++++++++++++++++ Conclusion ++++++++++++++++++++++++++++++++ +++++ ================================================================================ ===== 1) ++++++++++++++ Saving Keystrokes for common Substituting and Searching ++++++ +++++ a) Searching ............ Sorry, there is not much that can be saved for common Searching. It's just hitti ng

/mypattern<RETURN> b) Substituting ......... I think, common substitution requires pretty many keystrokes. So I use the following macro with my favorite substitution options: :map <F4> :%s//gc<Left><Left><Left> This ends up with the cursor after the first '/' in the commandline. To complete it, you only have to enter -> myoldpattern/mynewpattern<RETURN> Remark: I mapped it to <F4> (cause of tribute to the <F4> of the good old Norton Commander editor). You may map it where you want to. 2) ++++ Searching for resp. Substituting of the current word under the cursor + +++++ a) Searching ............ If you don't know how to look for the next occurence of the word under the curso r, you should *now* type :help * or :help star or refer to the tips vimtip #1 or vimtip #5 ((Tip within tip: To make your pattern more visible, look for :help hls)) b) Substituting ......... The following macro extends the one above with automatically inserting the curre nt word under the cursor into the from - pattern of the :s command. :map <S-F4> :%s/<C-r><C-w>//gc<Left><Left><Left> To complete it, just enter -> mynewpattern<RETURN> I use this i.e. for reliable and quickly renaming a variable in the entire buffe r. I mapped it to Shift-<F4>. You may map it to the keystroke you want. Explanation: CTRL-v+CTRL-w expands to the word under the cursor. 3) ++ Searching and Substituting for an arbitrary visually selected part of text ++++ If you want to look or substitute (for) an *arbritary* pattern (which already ex ists at least once in your text), the following 2 mappings do it for you. The advantage is that you dont have to type again or cut & paste the appropriate text but only have to visually select it. a) Searching ........... :vmap / y:execute "/".escape(@",'[]/\.*')<CR>

This immediately finds to the next occurence of the previously visually selected text. b) Substituting ......... :vmap <F4> y:execute "%s/".escape(@",'[]/\')."//gc"<Left><Left><Left><Left> Again, as in the mapping in chapter 2), you just have to complete it by entering -> mynewpattern<RETURN> Explanation/Discussion: What both Substituting and Searching in this way generally does is: - *y*anking the selected text - Inserting the visually selected via adressing the '"' register with '@"' as a parameter of the escape() function going finally into the 'myoldpattern' part. The trickery problem is, if you have characters in your myoldpattern, which ar e regular expression chars, they are recognized and threated accordingly. That is most likely not what you wanted. To escape them, these chars have to be declared by the second parameter of the excape() function, which then escapes them with a backslash. The few characters above work for me. If you run into probl ems, you should check for additional regexp chars in your text, and try to escape t hem by adding them to the escape() function parameter. 4) ++++++++++++++++++++++++++++++++ Conclusion ++++++++++++++++++++++++++++++++ +++++ With the appropriate mappings in your vimrc you can save keystrokes when Searchi ng or Substituting and avoid typing errors. That way, you can take lunch sooner

VimTip 161: Dutch spelling checker http://vim.sf.net/tip_view.php?tip_id=161 Download at http://www.thomer.com/thomer/vi/nlspchk.vim.gz. This sciript is based on Charles E. Campbell's English spelling checker script f or ViM (http://users.erols.com/astronaut/vim/) and Piet Tutelaers' Dutch word li st (http://www.ntg.nl/spell-nl-v5b/) using Thomas Khler's script (http://jeanluc -picard.de/vim/gerspchk/create). In other words, I didn't do much.

VimTip 162: write plugin with explorer like interfaces http://vim.sf.net/tip_view.php?tip_id=162

Several plugins use a text base interface based on a special buffer, this is the case of the standard explorer plugin, several bufexplorer plugins, the option b uffer and others... Here is a quick guide in how to do this Writing a special buf script using a special buffer is a common technic when writing Vim scripts, i t is used by explorer, bufexplorer, DirDiff... I'm currently writing one for TagsBase.vim http://vim.sourceforge.net/scripts/script.php?script_id=100 and I'll use this document to take notes on how to do it. Setting up the buffer Opening the window TODO Using a setup function Principle we can use a specific function to open and setup the s pecial buffer. s:SetupBuf() Setup Function advantage since the command will be defined in the main script y ou can use script local functions Using a special filetype Principle we can also use a new filetype and distribute a syntax and an ftplugin for this filetype, the only thing needed in this case is to set the filetype after creating the buffer Filetype advantage better separations of different parts of your script. If the main function of your plugin is not to have this special buffer then it is nice to avoid clutering it. Things which needs to be done to setup the buffer The buffer should not be listed and does not correspond to a fil e * setlocal buftype=nofile options always local to buffer * set nobuflisted * set bufhidden=delete * set nomodifiable Setup the syntax for this buffer see :help syntax This is usually done in two steps, first describe the syntax groups using :syn commands then setup the hilighting using :hi def link commands. Usually it is best to link the newly defined groups to predefine one s in order to make the coloring work fine with colorschemes . You'll find the list of predefined group by doing: :help group-name Setup the special mappings since we have chosen to use the set nomodifiable optio n

our buffer will never be in insert mode. All our mappi ng are in Normal, Visual or operator pending, they should therefore use the map, nmap, vmap and omap mapping com mand plus the associated 'nore' version. I usually find it better to use the 'nore' version to avoid surprises du e to mapping in the user configuration. We also want our mappings to be local to the special buffer so all the commands will use the <buffer> modif ier. Finally we want our mappings not to polute the status bar so we use the <silent> modifier Putting all this together we end up with mapping comma nds which look like: noremap <buffer> <silent> {lhs} {rhs} Setup the special command we will then setup special commands for this buffer. Like for the mapping there are some precautions to take: we don't want an error message if the command is defin ed twice so we use the command! variant. We want a command local to our buffer wo we use the -buffer attribute. The rests of the command attribute s and options depend on the actual command. So our commands look like: command! -buffer {attr} {cmd} {rep} where attr is optional.

VimTip 163: Toggle Search Highlighting http://vim.sf.net/tip_view.php?tip_id=163 " Map H to toggle search highlighting map H :let &hlsearch = !&hlsearch<CR>

VimTip 164: Make non-ASCII characters displayed on console http://vim.sf.net/tip_view.php?tip_id=164 I had a problem with VIM on the FreeBSD console: it didn't display characters li ke German umlauts correctly, but escaped them with a tilde. The solution is to t each VIM about printable characters. I use the following on my .vimrc:

set isprint=@,128-255

VimTip 165: Deleting a buffer without closing the window http://vim.sf.net/tip_view.php?tip_id=165 I'm not sure if this functionality is already within Vim, but I sometimes I find it useful to keep a split window from closing when deleting a buffer. This has already been discussed on the vim@vim.org mailing list. However, I feel this s olution is a little easier to use. " " " " Put this into .vimrc or make it a plugin. Mapping :Bclose to some keystroke would probably be more useful. I like the way buflisted() behaves, but some may like the behavior of other buffer testing functions.

command! Bclose call <SID>BufcloseCloseIt() function! <SID>BufcloseCloseIt() let l:currentBufNum = bufnr("%") let l:alternateBufNum = bufnr("#") if buflisted(l:alternateBufNum) buffer # else bnext endif if bufnr("%") == l:currentBufNum new endif if buflisted(l:currentBufNum) execute("bdelete ".l:currentBufNum) endif endfunction

VimTip 166: Mapping caps lock to esc in XWindows http://vim.sf.net/tip_view.php?tip_id=166 (This originally appeared on the vim mailing list as post by Adam Monsen http:// groups.yahoo.com/group/vim/message/19856) If you want to completely swap caps lock and escape, you have to replace the "Lock" on caps lock. Drop this file in your home dir:<br> -----------start------------<br> ! Swap caps lock and escape<br> remove Lock = Caps_Lock<br>

keysym Escape = Caps_Lock<br> keysym Caps_Lock = Escape<br> add Lock = Caps_Lock<br> ------------end-------------<br> and call it ".speedswapper". Then open a terminal and type<br> $ xmodmap .speedswapper<br> and you'll be twice as efficient in vim. Who needs caps lock anyway? The swappin g lasts for the duration of the X session, so you can put it in a .xinitrc or si milar startup file. As far as other people using my laptop, I'd rather they didn 't! Using a Dvorak layout might protect me even more... :)

VimTip 167: Using vim as a man-page viewer under Unix http://vim.sf.net/tip_view.php?tip_id=167 To use vim as a man-page viewer involves setting an environment variable: sh, ksh: export MANPAGER="col -b csh : setenv MANPAGER "col -b view -c 'set ft=man nomod nolist' -" view -c 'set ft=man nomod nolist' -"

Put one of the above two lines into your <.profile> or <.login> file as appropriate for your shell. The man pages will then be displayed with vim called as "view" and will use the <man.vim> syntax highlighting. I myself use some additional highlighting which is enabled by putting the following file into <.vim/after/syntax/man.vim>. I usually use the <astronaut> colorscheme (also available from this archive); those who use bright backgrounds may find the colors selected for manSubSectionStart and manSubSection something they'll want to change: --------------------------------------------------------------------" DrChip's additional <man.vim> stuff syn match manSectionHeading SectionNumber syn match manSectionNumber syn region manDQString contains=manSQString syn region manSQString syn region manSQString syn region manBQString syn region manBQSQString syn match manBulletZone syn case match syn keyword manBullet contained syn match manBullet contained syn match manSubSectionStart syn match manSubSection hi hi hi hi hi hi link link link link link link manSectionNumber manDQString manSQString manBQString manBQSQString manBullet "^\s\+[0-9]\+\.[0-9.]*\s\+[A-Z].*$" contains=man "^\s\+[0-9]\+\.[0-9]*" start='[^a-zA-Z"]"[^", )]'lc=1 contained end='"'

start="[ \t]'[^', )]"lc=1 end="'" start="^'[^', )]"lc=1 end="'" start="[^a-zA-Z`]`[^`, )]"lc=1 end="[`']" start="``[^),']" end="''" transparent "^\s\+o\s" contains=manBullet o "\[+*]" "^\*" skipwhite nextgroup=manSubSection ".*$" contained

Number String String String String Special

hi manSubSectionStart term=NONE cterm=NONE gui=NONE ctermfg=black ctermbg= black guifg=navyblue guibg=navyblue hi manSubSection term=underline cterm=underline gui=underline ctermfg =green guifg=green set ts=8 ---------------------------------------------------------------------

VimTip 168: Viewing the actual XPM data in GVIM http://vim.sf.net/tip_view.php?tip_id=168 GVIM has an excellent syntax highlighting for XPM images, but sometimes it's use ful to view the actual data. This can be achieved by searching for everything, t ype in "/." and all characters will be highlighted and therefore the old colouri ng is lost. To regain the normal highlighting you can search for a non-existent sequence, like "/foo".

VimTip 169: <Tab> = <C-I> and <Esc> = <C-[> http://vim.sf.net/tip_view.php?tip_id=169 An FAQ on the vim users' mailing list is whether <Tab> and <C-I> can be mapped to different things. The answer is no. As I understand it, this is a low level issue: <Tab> and <C-I> are different names for the same ASCII code, and there is no way for vim to tell them apart. Similarly, <Esc> and <C-[> are the same thing.

VimTip 170: Repeating a sequence of commands without defining a macro http://vim.sf.net/tip_view.php?tip_id=170 Imagine. You have just finished a complicated modification of a file, involving numerous replace commands :%s/xxx/yyyy/g, and other ex commands. Then you realize, you have done it a little bit wrong, and you have to begin all the operation again, just to change one replace string, or do one more operation "somewhere 10 commands ago". Or you realize, you will have to do the same stuff tomorrow with another file. or you realize, you want to perform the same sequence

of commands, you have typed a few days ago You should have made it a macro (normal command q), but you haven't. Nothing is lost yet. You go to the command line (by typing :) and press Ctrl+F. (Ctrl+F in other modes scrolls the screen) You get a temporary window, listing the history of command line. It is possible to yank appropriate lines here, make a new file called $VIMRUNTIME/macros/something.vim put those lines here, edit them and save see :help cedit Then you can call the macro using :source something.vim You might want to set variable 'history' to a higher number then default in your vimrc file like :set history=300 see :help history :help vimrc

VimTip 171: Do you know the "g/" and "g?" commands? http://vim.sf.net/tip_view.php?tip_id=171 Directly from the Vim Todo list: 7 For Visual mode: Command to do a search for the string in the marked area. Only when less than two lines. Use "g/" and "g?".

In other words, a way to search for visually selected text !! :-) "==== vsearch.vim ==== " Visual mode search vmap g/ :call VsearchPatternSave()<cr>/<c-r>/<cr> vmap g? :call VsearchPatternSave()<cr>?<c-r>/<cr> function! VsearchPatternSave() let l:temp = @@

normal gvy let @/ = substitute(escape(@@, '/\'), "\n", "\\\\n", "g") let @@ = l:temp unlet l:temp endfunction "==== END ==== Normally, this file should reside in the plugins directory and be automatically sourced. If not, you must manually source this file using ':source vsearch.vim'. In Visual mode, highlight the text for searching. Then you can use the default visual key mappings g/ - search forwards g? - search backwards Visual searches behave like normal searches. The 'n' and 'N' commands work as they should, and the search history correctly records each search. Multi-line searches behave as they should (this corrects the 'yank-only' method mentioned in the Vim help files). Block visual searches do not work yet. Hopefully, someone can figure out a way to do this easily. I've only tested this on Win2000 and Redhat Linux 7.1. I'm not really clear on how the carriage returns are dealt with on other systems. Anyway, enjoy!

VimTip 172: Using Ispell on a highlighted region http://vim.sf.net/tip_view.php?tip_id=172 Suppose you would like to use Ispell to check a word or region that you've visually highlighted. The following macro will do the job. Just type Shift-Insert while in visual mode. vnoremap <S-Insert> <C-C>`<v`>s<Space><Esc>mq:e ispell.tmp<CR>i<C-R>"<Esc>:w<CR> :! xterm -bg ivory -fn 10x20 -e ispell %<CR><CR>:e %<CR><CR>ggVG<Esc>`<v`>s<Esc> :bwipeout!<CR>:!rm ispell.tmp*<CR>`q"_s<C-R>"<Esc> This is based on Chip Campbell's macro which uses Ispell on the whole file (in normal mode). noremap <S-Insert> :w<CR>:! xterm -bg ivory -fn 10x20 -e ispell %<CR><Space>:e % <CR><Space> Carl Mueller

VimTip 173: Switch between splits very fast (for multi-file editing) http://vim.sf.net/tip_view.php?tip_id=173

I am a Web developer and I use Vim as my primary editor. Most programming projects (and Web programming projects, in particular) are spre ad out over multiple files, which you often want to have open concurrently. If y ou don't already know, Vim supports this very well! Just use: :sp name-of-another-file-to-edit My problems were that (1) it took too long to move between files, and (2) the fi les were taking up too much room on the screen. (1) In order to move to the file in the split above my current window, I was typ ing Ctrl-W, Up (move up a window) Ctrl-W, _ (maximize the menu). That's four key strokes (more if you count Ctrl and Shift), and they are all over the keyboard. To help avoid this problem, I created this mapping in my .vimrc: map <C-J> <C-W>j<C-W>_ map <C-K> <C-W>k<C-W>_ Now I can hold down Ctrl and move between windows with the standard Vim movement keys. Much, much quicker! (2) By default, Vim displays the current line of each minimized file, which (to me) isn't much help and takes up too much screen real estate. I use this line in my .vimrc: set wmh=0 This sets the minimum window height to 0, so you can stack many more files befor e things get crowded. Vim will only display the filename. Hope this helps those of you who are working on projects with large numbers of f iles you're constantly flipping through. Happy Vimming!

VimTip 174: Footnotes http://vim.sf.net/tip_view.php?tip_id=174 ab ab ab ab ab (1 (2 (3 (4 (5 [1]<esc>:/^--\s/-1/<cr>o<insert><cr>Footnotes:<cr>----------<cr>[1] [2]<esc>:/^Footnotes\:/+2/<cr>o<insert>[2] [3]<esc>:/^Footnotes\:/+3/<cr>o<insert>[3] [4]<esc>:/^Footnotes\:/+4/<cr>o<insert>[4] [5]<esc>:/^Footnotes\:/+5/<cr>o<insert>[5]

VimTip 175: how to make VIM as ur default editor even without root ac. http://vim.sf.net/tip_view.php?tip_id=175 hi, if u have installed vim in your home directory somewhere

and u don't have a root account, and you want to make VIM the default editor for anything u do. i.e if ur using SQLplus and want to edit a sql command. normally typing edit brings up the vi editor and not vim editor. to solve this problem. define these three variables in your .profile VIM=<base directory where vim executable is placed> VIMRUNTIME=<base direcoty where vim runtimes are kept> EDITOR=$VIM/vim note if u have installed vim with another name, say vim.exe then change EDITOR=$VIM/vim to EDITOR=$VIM/vim.exe source the .profile and viola. next time u start an editor from any program u have the vim editor. Njoy.

VimTip 176: Autocheckout from perforce http://vim.sf.net/tip_view.php?tip_id=176 The following code automatically checks out files from perforce when the user mo difies them. It first confirms the check-out with the user. (Perforce is a commercial version control system. I imagine this could be modif ied for RCS, CVS, etc., but I don't use those.) I'm a vim newbie -- I've used vi since 1984, but just started with vim a couple days ago. Color me impressed! Please excuse any stupidity in the code.. Note that this function needs the "P4HOME" environment variable to be set. I co uld extract it by invoking "p4 client", but I don't want to invoke p4 every time I start vim. So I assume the user sets it in the environment. " Set a buffer-local variable to the perforce path, if this file is under the pe rforce root. function IsUnderPerforce() if exists("$P4HOME") if expand("%:p") =~ ("^" . $P4HOME) let b:p4path = substitute(expand("%:p"), $P4HOME, "//depot", "") endif endif endfunction " Confirm with the user, then checkout a file from perforce. function P4Checkout() if exists("b:p4path") if (confirm("Checkout from Perforce?", "&Yes\n&No", 1) == 1) call system("p4 edit " . b:p4path . " > /dev/null") if v:shell_error == 0 set noreadonly endif endif endif endfunction

if !exists("au_p4_cmd") let au_p4_cmd=1 au BufEnter * call IsUnderPerforce() au FileChangedRO * call P4Checkout() endif

VimTip 177: Highlight matching brackets as one moves in normal mode (plugin) http://vim.sf.net/tip_view.php?tip_id=177 Check out http://www.erols.com/astronaut/vim/index.html#VimFuncs for a plugin script which highlights matching brackets. The script has two always-on maps: \[i : start [HiMtchBrkt] mode \[s : stop [HiMtchBrkt] mode The plugin will save all user maps and options that the plugin uses and will restore them when the mode is stopped.

VimTip 178: Making a "derived" colorscheme without copy & paste http://vim.sf.net/tip_view.php?tip_id=178 Suppose there's a colorscheme that you're pretty fond of, but hate one or two pa rticular aspects about. For example, I love the "blue" colorscheme that ships w ith vim, but I find it's colors for the non-active status line to be unreadable. Here's how to create a colorscheme which extends "blue" without copying it to a new file and editing it. In my ~/.vim/colors, I created a "my-blue.vim" file with these contents: "these lines are suggested to be at the top of every colorscheme hi clear if exists("syntax_on") syntax reset endif "Load the 'base' colorscheme - the one you want to alter runtime colors/blue.vim "Override the name of the base colorscheme with the name of this custom one let g:colors_name = "my-blue" "Clear the colors for any items that you don't like hi clear StatusLine hi clear StatusLineNC "Set up your new & improved colors hi StatusLine guifg=black guibg=white hi StatusLineNC guifg=LightCyan guibg=blue gui=bold

That's all there is to it.

VimTip 179: Simplify help buffer navigation http://vim.sf.net/tip_view.php?tip_id=179 Vim is distributed with comprehensive help system, which has basic hyperlink sup port you can press <C-]> over some subject or 'some option' to read more about part icular term. The following mappings simplify help buffer navigation: pressing s(or S) will find next(previous) subject from cursor position pressing o(or O) will find next(previous) option from cursor position pressing Enter will jump to subject under cursor pressing Backspace will return from the last jump Put them into help filetype plugin (like ~/.vim/ftplugin/help.vim on UNIX). nmap nmap nmap nmap nmap nmap <buffer> <buffer> <buffer> <buffer> <buffer> <buffer> <CR> <C-]> <BS> <C-T> o /'[a-z]\{2,\}'<CR> O ?'[a-z]\{2,\}'<CR> s /\ \S\+\ <CR> S ?\ \S\+\ <CR>

VimTip 180: Reload your filetype/syntax plugin http://vim.sf.net/tip_view.php?tip_id=180 Ever tried to write/debug your own filetype/syntax plugin? It's an iterative process which involves editing plugin code and testing it on s ome sample file. To see changes you made in your plugin simply do :e on sample file. This will force Vim to reload all buffer-specific files, including your plugin.

VimTip 181: get the vim patched source http://vim.sf.net/tip_view.php?tip_id=181 Hi, there has been a number of person (including) asking in the vim list how to keep

up with Bram's incredible bug correction and patch writing skills, but there is a great way to do this! Use the cvs source which is available at http://sourceforge.net/cvs/?group_id=8 it is kept up to date and its a lot easier than applying all the patch in order. Benoit

VimTip 182: Keep your cursor centered vertically on the screen http://vim.sf.net/tip_view.php?tip_id=182 i hope i don't hear a collective 'DUH!' from around the world but i just did thi s and i think it's kinda cool. in your .vimrc add... map j jzz map k kzz so whenever you go up or down, vim does that and then re-centers. obviously it doesn't work when you page up/ down.

VimTip 183: Select a buffer from those matching a pattern http://vim.sf.net/tip_view.php?tip_id=183 The :bu command will take a pattern as an argument and jump to the matching buff er. However, it's not very helpful if there is more than one buffer matching th e pattern. In that case, it will jump to the first match, which may not be what you want. The following function and user-command will print a list of the mat ching buffers in the command-line area, and allow you to select one of the match ing buffers by number. "Select from buffers matching a certain pattern "the 'pattern' argument shouldn't be prepended with a slash function! BufSel(pattern) let bufcount = bufnr("$") let currbufnr = 1 while currbufnr <= bufcount if(bufexists(currbufnr)) let currbufname = bufname(currbufnr) if(match(currbufname, a:pattern) > -1) echo currbufnr . ": ". bufname(currbufnr) endif endif let currbufnr = currbufnr + 1 endwhile let desiredbufnr = input("Enter buffer number: ") if(strlen(desiredbufnr) != 0) exe ":bu ". desiredbufnr endif

endfunction "Bind the BufSel() function to a user-command command! -nargs=1 Bs :call BufSel("<args>")

VimTip 184: How to obscure text instantaneously http://vim.sf.net/tip_view.php?tip_id=184 Hi, Lets say your writing some imp. doc. and your colleague comes along. you don't wan't him to see what you are typing. so u start fumbling to type :wq! or switch with Alt-TAB. etc. but wouldn't it be nice to just obsucre the text temporarily, so that u don't have to quit or swith to another application using Alt-tab. (and if u don;t have any other window open u can;t even use alt-tab) well rot-13 comes to help. vim has a built in rot-13 encoder. jut put the follwoing in your .vimrc map <F3> ggVGg? so next time some body comes along just press <F3> and all the buffer will be rot-13 encoded. to decode just press <f3> again. Njoy

VimTip 185: Make vim the editor for files with unregistered extensions in Window s http://vim.sf.net/tip_view.php?tip_id=185 Normally in Windows, if you try to "launch" a file whose extension is not regist ered with the system, the OS will prompt you for what editor you would like to u se to open the file. A much more appealing solution, in my mind, is to make vim the default editor for any unregistered extension. To set vim up as the default editor for unregistered extensions, follow these st eps: 1. Copy the following into a file named unregistered.reg -------------begin unregistered.reg----------------REGEDIT4 [HKEY_CLASSES_ROOT\Unknown\shell\Open\Command] @="d:\\program files\\vim\\vim60\\gvim.exe \"%1\"" -------------end unregistered.reg----------------2. Import unregistered into your registry. This can be done in vim by executing the following :!regedit "unregistered.reg" Disclaimer: This has been tested only on NT4.

VimTip 186: Making search powerful http://vim.sf.net/tip_view.php?tip_id=186 My tip is just a bunch of mappings that can be used while searching.

VimTip 187: Making search powerful http://vim.sf.net/tip_view.php?tip_id=187 (Sorry, I think I accidentally added an incomplete tip) My tip is just a bunch of mappings that can be used while searching. What it does? o. Extend your current search. (kinda emacs search where you can search each o ccurences one by one and go back to the cursor position. o. Scroll/position during mapping. o. Other miscellaneous stuffs ;) read on How to use? o. copy and paste the mappings into a file o. open vim (like vim .profile) o. :so <saved-file> o. start using the mappings Note: In case these mappings dont work run like, 'vim -u NONE -U NONE -c "so the-sa ved-file.vim"' Some of my mappings override the default vim bindings. (like Ctrl-A, Ctrl-Q). I selected those because, I feel by taking those I can do all the search stuff with my left hand. One thing I did not like with this is, I usually miss the "search hit bottom" message. I could have handled that by complicating the current mappings, but I preferred to make it simple Mappings Used / => regular forward search start ? => regular backward search start Rest of the mappings are used during search Ctrl-A => search again forward (In normal mode, search forward with the word un der cursor) Ctrl-Q => search again backward (in normal mode, search backward with the word under cursor)

Ctrl-X => restore cursor (use at any point of time/during-any-operation mention ed during searching) Ctrl-F => search with the word under cursor Ctrl-G => incrementally add the letters following the search pattern (in curren t line) Ctrl-T Ctrl-T => search for the exact Ctrl-T Ctrl-Y => search partial (just strips \< and \>) Ctrl-E => scroll up during searching Ctrl-Y => scroll down during searching Ctrl-Z Ctrl-Z => position the cursor to mid of screen (like zz in normal) Ctrl-Z Ctrl-A => position the cursor to top of screen (like zt in normal) Ctrl-Z Ctrl-X => position the cursor to bottom of screen (like zb in normal) Misc: Ctrl-K during search save the current matching line Ctrl-K in normal mode pastes the saved line C mappings Ctrl-V Ctrl-G search for the global variable of the search pattern/word under cu rsor Ctrl-V Ctrl-H search for the local variable of the search pattern/word under cur sor " --- cut n paste from here to end of document --se nocp incsearch " core mappings noremap / mg/ noremap ? mg? ounmap / ounmap ? noremap <C-A> mg"gyiw/<C-R>g cnoremap <C-A> <CR>/<Up> cnoremap <C-X> <CR>`g cnoremap <C-Q> <CR>?<Up> " extending current search mappings cnoremap <C-F> <CR>yiw<BS>/<C-R>" cnoremap <C-G> <CR>y/<Up>/e+1<CR><BS>/<C-R>=escape(@",'.*\/?')<CR> " miscellaneous: copy current line during search and later paste in NORMAL mode cnoremap <C-K> <CR>"hyy?<Up><CR>/<Up> noremap <C-K> "hp " exact/partial search mappings cnoremap <C-T><C-T> <Home>\<<C-End>\> cnoremap <C-T><C-Y> <Home><Del><Del><End><Del><Del> " C global/local variable search mappings noremap <C-V><C-G> mgyiw<CR>gg/\<<C-R>"\> noremap <C-V><C-H> mgyiw?^{<CR>/\<<C-R>"\> cnoremap <C-V><C-G> <CR>yiwgg/\<<C-R>"\> cnoremap <C-V><C-H> <CR>yiw?^{<CR>/\<<C-R>"\> " positioning/scrolling during search mappings cnoremap <C-E> <CR>mt<C-E>`t<BS>/<Up> cnoremap <C-Y> <CR><C-Y><BS>/<Up> cnoremap <C-Z><C-A> <CR>zt<BS>/<Up> cnoremap <C-Z><C-X> <CR>zb<BS>/<Up> cnoremap <C-Z><C-Z> <CR>zz<BS>/<Up>

" VISUAL mappings vnoremap / ymg/<C-R>=escape(@",'.*\/?')<CR> vnoremap ? ymg?<C-R>=escape(@",'.*\/?')<CR>

VimTip 188: Searching for more than one word at the same time. http://vim.sf.net/tip_view.php?tip_id=188 Did you know that with VIM u can search for more than one word with a single command. say you want to search all occurances of "bill" or "ted", or "harry" in a text. in normal mode do the following. /\(bill\)\ \(ted\)\ \(harry\) <Enter> this will match all instances of either "bill", or "ted", or "harry" in your text. the key is the \(\) and \ operators. \(\) group characters in a word and \ is for ORing. this is so cool u can even use it for replacing text. to replace all instances of "bill" or "ted" or "harry" with "greg" do the following :%s/\(bill\)\ \(ted\)\ \(harry\)/greg/g <enter> (note :- if u have set the option "gdefault" u don't need the "g" at the end of the above command) I don't know of any other editor which can do this, with so much ease. Rock on VIM Njoy

VimTip 189: Make Ctrl-Backspace delete previous word (like GTK inputs) http://vim.sf.net/tip_view.php?tip_id=189 Stuff this into your ~/.gvimrc and then you'll be able to type Control-Backspace to delete the previous word. I had gotten so used to C-BS working a certain wa y in all my editors with a ceezy input area (like mozilla/galeon, gabber, etc... ), that I wanted the same behaviour when I used gvim. " map control-backspace to delete the previous word :imap <C-BS> <Esc>vBc Simple, I know, but reasonably useful. --Robert

VimTip 190: XP > I-Explorer > HTML Editor < REG files http://vim.sf.net/tip_view.php?tip_id=190 The issue is permitting other programs, besides NOTEPAD, be the HTML editor under Internet Explorer. (Adding "Edit" as a New Action in the publicly exposed Files Types for HTM/L does NOT do the job.) Given below are two REG files for vim. Just cut 'em up where indicated. They have been tested under Windows XP. -------------------------------------------------------CUT HERE--------------Windows Registry Editor Version 5.00 ; ; ; ; ; ; GOAL: Set gvim as HTML editor in Internet Explorer 6.0 Vim version : 6.0 Windows version: XP EASY USAGE: name this file iex-vim60.reg and double click on it Hard Usage: IMPORT this file using REGEDIT.EXE found in c:\WINDOWS Last modified date : Dec 16, 2001

; gvim is expected in "C:\Program Files\Vim\vim60\gvim.exe" ; Be sure to also reset Explorer>Tools>Internet Options>Programs ; Microsoft documentation ; http://msdn.microsoft.com/workshop/browser/configuration/clientreg/clientregis trylayout.asp ; Add Vim in the list of supported HTML editors [HKEY_CLASSES_ROOT\.htm\OpenWithList\Vim] [HKEY_CLASSES_ROOT\.htm\OpenWithList\Vim\shell] [HKEY_CLASSES_ROOT\.htm\OpenWithList\Vim\shell\edit] [HKEY_CLASSES_ROOT\.htm\OpenWithList\Vim\shell\edit\command] @="\"C:\\Program Files\\Vim\\vim60\\gvim.exe\" \"%1\"" ; Do NOT add to .html, registry for .htm type suffices ;[HKEY_CLASSES_ROOT\.html\OpenWithList\Vim] ;[HKEY_CLASSES_ROOT\.html\OpenWithList\Vim\shell] ;[HKEY_CLASSES_ROOT\.html\OpenWithList\Vim\shell\edit] ;[HKEY_CLASSES_ROOT\.html\OpenWithList\Vim\shell\edit\command] ;@="\"C:\\Program Files\\Vim\\vim60\\gvim.exe\" \"%1\"" ; OPTIONAL: Within Internet Explorer "View Source" with gvim ; but prefer to use Edit button (got to add this) on Toolbar ;[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\View Source Editor] ;[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\View Source Editor\Edi tor Name] ;@="C:\\Program Files\\Vim\\vim60\\gvim.exe"

; ============================================= EOF -------------------------------------------------------CUT HERE--------------Windows Registry Editor Version 5.00 ; ; ; ; ; ; GOAL: UNINSTALL gvim as HTML editor in Internet Explorer 6.0 Vim version : 6.0 Windows version: XP EASY USAGE: name this file iex-vim60-uninstall.reg and double click on it Hard Usage: IMPORT this file using REGEDIT.EXE found in c:\WINDOWS Last modified date : Dec 16, 2001

; gvim is expected in "C:\Program Files\Vim\vim60\gvim.exe" ; Be sure to also reset Explorer>Tools>Internet Options>Programs ; Microsoft documentation ; http://msdn.microsoft.com/workshop/browser/configuration/clientreg/clientregis trylayout.asp [-HKEY_CLASSES_ROOT\.htm\OpenWithList\Vim] [-HKEY_CLASSES_ROOT\.html\OpenWithList\Vim] [-HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\View Source Editor] ; ============================================= EOF -------------------------------------------------------CUT HERE--------------Happy Vimming...

VimTip 191: Transposing http://vim.sf.net/tip_view.php?tip_id=191 You can easily move lines with these maps using <C-Up> and <C-Down> (only in GUI version :( ) (Works in normal, insert, and visual mode, but you can't add a count to them) " Transposing lines nmap <C-Down> :<C-u>move .+1<CR> nmap <C-Up> :<C-u>move .-2<CR> imap <C-Down> <C-o>:<C-u>move .+1<CR> imap <C-Up> <C-o>:<C-u>move .-2<CR> vmap <C-Down> :move '>+1<CR>gv vmap <C-Up> :move '<-2<CR>gv " Transpose chars (like Ctrl-T in emacs, shell...) imap <C-F> <Esc>Xpa

VimTip 192: Latex Help for VIM http://vim.sf.net/tip_view.php?tip_id=192 LaTeX Help for aucTeX `translated' as vim help file. Installing :help add-local-help

VimTip 193: Insert the current filename at cursor postion. http://vim.sf.net/tip_view.php?tip_id=193 I found this one good for when I was starting to learn Java, it simply inserts t he current filename, at the cursor position, when you are in insert mode. Hones tly, its a mish-mash of some other tips I found here, but I thought it might be useful. imap \fn Enjoy! <C-R>=expand("%:t:r")<CR>

VimTip 194: Inserting text in multiple lines http://vim.sf.net/tip_view.php?tip_id=194 Do you know the I key in visual-block mode? Suppose you have let a=2 let b=3 let c=4 You want to make these variables script-wise. Then you move to over a, hit <C-v> , press jj and now press I. You will be in insert mode before a Now enter s:<Esc>, and when you press <Esc>, b and c will have the s: prefix too . See v_b_I Happy vimming! Gergely Kontra

VimTip 195: Switching between files http://vim.sf.net/tip_view.php?tip_id=195

When you edit multiple files, you often need to change windows. You can set up vim in windows and gvim to switch between windows with the common ly used Ctrl-Tab and Ctrl-Shift-Tab The mappings nmap <C-Tab> <C-w>w nmap <C-S-Tab><C-w>W (They wrap around) See also Ctrl-w

VimTip 196: FileName Completion in Shell Scripts http://vim.sf.net/tip_view.php?tip_id=196 In shell scripts, you often define environment variables for diff directory name s. i.e. JAVA_HOME=/opt/java/jdk1.4 PATH=/usr/local/bin:/bin.... Normally typing Ctrl-X Ctrl-F is used to complete FileName under cursor. But this does not work if used on lines given above. This is because vim treats "=" sign as a valid filename character. Since the actual possibility of "=" being in any filename is very less, this char can be removed from the list of valid filename char. set isfname-== putting the above line in .vimrc will remove "=" from the list of valid filename chars. thus u can easyly complete filenames using <Ctrl-X> <Ctrl-F> Njoy

VimTip 197: Open file in already running vim from elsewhere http://vim.sf.net/tip_view.php?tip_id=197 If you want edit new file, and you want do it in alrady running vim, instead o f launching another instance, you may use --remote argument: gvim first_file gvim --remote +split first_file :he --remote It requires X windows (but works in terminal version of vim there too) or MS win dows and built-in client-server mechanism. If there are several instances of vim already running, you may choose to which you talk using --servername :help --servername

VimTip 198: Pasting code with syntax coloring in emails http://vim.sf.net/tip_view.php?tip_id=198 When sending code snippets or diffs to your colleagues either for code review or for something else as email, how nice and clear it will be if you can paste it with the Vim syntax highlighting? I am sure they will be impressed and feel much easier to read the code. It is also very easy and fast (once you practice it) t o do this. This probably works only on windows and requires you to use Internet Explorer an d an email client that understand RTF content coming from clipboard, such as Out look or Outlook Express. At least that would make the process faster. I haven't tried on any other combination though. This is what you need to do: - Open the file containing the code/code snippet/diff etc. in gvim. If you use d ark background for GVim (like me), then I would suggest you to change your color scheme temporarily to something else that has a white background or just use th e "-U NONE" as below: gvim -U NONE <file> - Convert the file into HTML by using the following command at the colon prompt as below: :runtime syntax/2html.vim - The above step will open a new window with the HTML content in it. You might w ant to just save it with the suggested name or write into a temporary file as: :w! c:/tmp/t.html - Open the IE browser window and open the above temp file "c:/tmp/t.html". - Now you select all (press ^A) and copy it (^C). - You are ready to paste it with syntax coloring in any application that accepts RTF content from clipboard, including Outlook or Outlook Express mail composing window.

VimTip 199: maximize window and return to previous split structure http://vim.sf.net/tip_view.php?tip_id=199 Say you have layed out a complex window split structure, and want to temporarily open 1 window with max dimensions, but don't want to lose your split structure. The following function and mappings let you toggle between the split windows a nd on window maximized. The mappings prevent the default behavior of calling :on ly and losing your finely tuned splits. Put this bit in your vimrc file, change mappings if you don't want to override t he defaults: nnoremap <C-W>O :call MaximizeToggle ()<CR> nnoremap <C-W>o :call MaximizeToggle ()<CR> nnoremap <C-W><C-O> :call MaximizeToggle ()<CR>

function! MaximizeToggle() if exists("s:maximize_session") source s:maximize_session call delete(s:maximize_session) unlet s:maximize_session let &hidden=s:maximize_hidden_save unlet s:maximize_hidden_save else let s:maximize_hidden_save = &hidden let s:maximize_session = tempname() set hidden mksession! s:maximize_session only endif endfunction

VimTip 200: Bouncing Parentheses (during insertion) http://vim.sf.net/tip_view.php?tip_id=200 When one is inserting parentheses some folks like to see the cursor bounce off the matching parenthesis. To do that, put the following map into your <.vimrc> file: inoremap ) )<c-o>%<c-o>:sleep 500m<CR><c-o>%<c-o>a Adjust the time delay (its 500 milliseconds above) to suit your needs.

VimTip 201: The meaning of life http://vim.sf.net/tip_view.php?tip_id=201 Use this tip if you need to discover the meaning of life, the universe and every thing. Simply do: :h 42

VimTip 202: debugging window autocommands http://vim.sf.net/tip_view.php?tip_id=202 Don't know how people debug autocommands, but I just found out that you can debu g (at least) those that result due to window close by just doing a debug quit, i .e., :debug quit

Vim will let you step into the autocommands. Try it to believe.

VimTip 203: Make make more helpful http://vim.sf.net/tip_view.php?tip_id=203 I find this a very useful command to use. Add the below 4 lines to your vimrc. Then instead of "make" use "Make". " Command Make will call make and then cwindow which " opens a 3 line error window if any errors are found. " if no errors, it closes any open cwindow. :command -nargs=* Make make <args> cwindow 3

VimTip 204: Some mappings for using cscope with vim. http://vim.sf.net/tip_view.php?tip_id=204 These mappings can make using cscope a fun. You can copy the word under the curs or in one window, and search for it from other window. " Copy and paste the word under cursor map <silent> <C-Space> :let@m=expand("<cword>")<CR> " Use the C-Space word as map <C-F6> :cscope find s map <C-F5> :cscope find c map <C-F7> :cscope find g the search criterion <C-R>=@m<CR><CR> <C-R>=@m<CR><CR> <C-R>=@m<CR><CR>

VimTip 205: Computing a sum of numbers in vim http://vim.sf.net/tip_view.php?tip_id=205 "Sometimes you need to sum a some numbers in vim. There *are* some "that can do the job. But what if the numbers are not in a columns "the same line or are sacttered all across the file? You might also "sum all the numbers in file that look like '1234$', or '54565 Eu' ers. " "There is a very simple trick, using (my favourite) command ":s " "First you define following function :let g:S=0 plugins or are on need to ignoring oth

"In global variable S we later find the result

:function! Sum(number) :let g:S=g:S+a:number :return a:number :endfunction

"The function is defined with a '!', "so it does not complain during debugging "when you are redefining the function "we accumulate the result in global variable S "function returns the argument, so after a :s "command the text remains the same

"you can do issue those few commands from a command line, "or create a small file and put it into your plugin directory, "or write those few commands into a file end issue a command :so %

"how to use this little function: "let's suppose you have a simple column of numbers like " "10 "20 "30 " "you issue command like: :let S=0 :%s/[0-9]\+/\=Sum(submatch(0))/ "the command finds the first number on the line and adds it to the S " "the result is displayed :echo $S "!!!! don't forget to do :let g:S=0 "before use. "you can also use \zs and \ze atoms in a regular expression to "delimit the number, so submatch(0) returns only a number and "the text remains unchanged after 'substitute' "for starter on the wonderfull world of regular expressions see: :help usr_27.txt "for the definition of the search pattern see :help :s :help pattern "for replacement strings begining with \= and special function submatch(0)see :help sub-replace-special "for the *ultimate* guide through the world of regular expressions see book: "Mastering Regular Expressions "Powerful Techniques for Perl and Other Tools "by Jeffrey E.F. Friedl "from O'REILLY "the book does not write about vim, yet here you can learn that ":s command is the most powerfull command you can find in a text editor. "(with the possible exception of :global command)

VimTip 206: Highlight doubled word errors in text http://vim.sf.net/tip_view.php?tip_id=206 An error I sometimes make while working on a LaTeX file is the repetition of a word as in "the the". Most often, such doubled words come about through a careless edit. Doubled words are hard to spot when the first word of the doubled pair is the last word on one line, and the second word of the pair is th e the first word on the next line. There is an example of such an error in the las t sentence. Vim's syntax mechanism can be used to highlight doubled words as an er ror. To obtain this highlighting for TeX and LaTeX files, place the following two lin es: syn match texDoubleWord "\c\<\(\a\+\)\_s\+\1\>" hi def link texDoubleWord Error in a file called tex.vim in the directory that shows up last in your runtimepath (:set runtimepath? to check). This will often be either ~/.vim/after/syntax/tex.vim or $VIM/vimfiles/after/syntax/tex.vim The same effect can be obtained for files of a different filetype, say html, by putting the same lines in a file called html.vim in the same location. For more on the runtimepath, :he runtimepath. For more on syntax highlighting, :he syntax

VimTip 207: editing databases with Vim/Perl/DBI http://vim.sf.net/tip_view.php?tip_id=207 Perl's Data-Base-Independent (DBI) module provides programming language level access to a lot of databases. Vim hosts an embedded Perl interpreter. So it is only a matter of some key strokes to interactively issue DB commands from within Vim or to search, edit, and replace database contents including retrieval and storage. Of course "create table" scripts can be worked upon in Vim as well as storing recurring patterns in Vim functions or Perl modules. Prerequisites: Vim needs to be compiled with Perl support enabled. See the if_perl.txt manual page! The CPAN module DBI as well as an appropriate database driver has to be installed with Perl in order to execute these Vim commands: " connect to perl's dbi module: :perl use dbi;

" connect to the database: :perl $dbh = dbi->connect( "DBI:mysql:$DBNAME:$HOST",$USER,$PASSWORD, { raiseerror => 1}); " perform a simple query: :perl $result = $dbh->selectall_arrayref("show tables;"); " insert the list of tables into the current buffer's top: :perl $curbuf->Append(0, map($_->[0], @{$result})); In MySql the command "show tables;" results in a list of table names. Inserted into a Vim buffer this results in one line per table. You can find more on my web page http://members.chello.at/intelliware/dbEdit

VimTip 208: Alter the display of buffers in the buffers menu http://vim.sf.net/tip_view.php?tip_id=208 If you use the buffers menu, here's where you can change how the buffernames are displayed: menu.vim, function s:BMMunge OLD: let name2 = name2 . ' (' . a:bnum . ')'

displays: .vimrc (1) menu.vim (2) NEW: displays 1. .vimrc 2. menu.vim (with the 1 and the 2 underlined) which is more useful, because you can (almost) always pick the buffer you want w ith one keystroke, the buffernumber, until you get to buffer 10 anyway. Roger let name2 = '&' . a:bnum . '. ' . name2

VimTip 209: backtracking your movements in a file

http://vim.sf.net/tip_view.php?tip_id=209 If you are jumping from one line to another a lot. You may find the "Ctrl-o" command handy. Usually u can set markers in a buffer to keep track of your movements. but Ctrl-o makes it even easier. it takes you back sequentially to all your previous cursor locations in a buffer. just press ctrl-o in normal mode and u will go to your last cursor position. Njoy

VimTip 210: compiling the actual file with gcc http://vim.sf.net/tip_view.php?tip_id=210 if you use set makeprg=gcc\ -o\ %<\ % in your .vimrc, and your actual file is f ile.c, then :make will compile file.c with the output file. (gcc file.c -o file ).

VimTip 211: Rotate color themes http://vim.sf.net/tip_view.php?tip_id=211 This tip is for those who like to change their vim color themes pretty often. I like different themes just for a change in my work environment. To achieve thi s just add the following to your .vimrc or _vimrc file. let themeindex=0 function! RotateColorTheme() let y = -1 while y == -1 let colorstring = "#blue.vim#elflord.vim#evening.vim#koehler.vim #murphy.vim#pablo.vim#ron.vim#" let x = match(colorstring,"#",g:themeindex) let y = match(colorstring,"#",x+1) let g:themeindex = x+1 ":echo x y g:themeindex if y == -1 let g:themeindex = 0 else let themestring = strpart(colorstring,x+1,y-x-1) echo("Setting Theme to-> ".themestring) return ":so $VIMRUNTIME/colors/".themestring endif endwhile endfunction Change the value of colorstring above by changing the line let colorstring = "#blue.vim#elflord.vim#evening.vim#koehler.vim#murphy.vim#pabl o.vim#ron.vim#" You can add your favorite color themes in this string so that you can rotate bet

ween them. Just make sure that any string that you add is in between the # as s hown above. Just follow the format above and things will work. Then assign a key to roate the theme. map <F8> :execute RotateColorTheme() Dunno if there are better ways to do the same. I just did a "help eval" and wro te the above.

VimTip 212: Setting file attributes without reloading a buffer http://vim.sf.net/tip_view.php?tip_id=212 While creating scripts and others executable files with Vim it is needed to set UNIX executable bit on the file. You can do this from inside Vim with :!chmod a+x %. The % represents current buf fer's filename. The problem is that Vim will notice attribute changes and prompt you to reload a file. If you do this, your undo history for the file will be lost. The following function facilitate changing executable attributes without reloadi ng a buffer. Thanks to Bram for the algorithm for this function. fun! SetExecutableBit() let fname = expand("%:p") :checktime exec "au FileChangedShell " . fname . " :echo" :silent !chmod a+x % :checktime exec "au! FileChangedShell " . fname endfun " Create an EX command that will call the function. command -nargs=0 Xbit call SetExecutableBit() Now you can type :Xbit to make the file executable!

VimTip 213: delet all lines containt TXT http://vim.sf.net/tip_view.php?tip_id=213 I needed this one when I was editing an ldif file: I needed to delete all lines containing "profile": :g/profile/d very handydandy

VimTip 214: Current buffer based menus http://vim.sf.net/tip_view.php?tip_id=214 If you have different menus for different filetypes, and you want to have only t he menu relevant to current buffer displayed, you can use this approach: in .vimrc: au BufEnter * if exists('b:BuffEnter') exec b:BuffEnter endif au BufLeave * if exists('b:BuffEnter') exec b:BuffLeave endif In appropriate ftplugin/?.vim, there are assigned commands to create or destroy the menus - here typed in directly, may be of course call to a menu-generating f unction or whatever. let b:BuffEnter='amenu C.added ...' let b:BuffLeave='unmenu! C unmenu C'

VimTip 215: Edit configuration files for a filetype http://vim.sf.net/tip_view.php?tip_id=215 When you open a file, vim may load several scripts to customize itself for editi ng the file type the file is associated with (for example a file "test.c" is ass ociated with the filetype "c"). Such configurations include the setting of syntax highlighting colors (:help syn tax) and support for indentation (:help filetype-indent-on). When you start to override these files for yourself, it can sometimes be confusi ng, which file sets a specific option. The following function can be used, to edit the configuration files which are as sociated with a specific filename. It open a buffer for all files which get load ed. If I invoke it with ':call Edit_ft_conf("test.c")', for example, I end up with t he following buffers / windows: 1 a "[No File]" line 1 2 a "test.c" line 1 3 a= "/usr/local/share/vim/vim60/syntax/c.vim" line 1 4 a "~/.vim/after/syntax/c.vim" line 1 5 #a= "/usr/local/share/vim/vim60/indent/c.vim" line 1 6 %a= "/usr/local/share/vim/vim60/ftplugin/c.vim" line 1 Here comes the function: " Edit filetype configuration files " Usage: ':call Edit_ft_conf("file")' " Purpose: open all scripts which get loaded implicitly by opening "file" " (syntax highlighting, indentation, filetype plugins, ..) " The order of windows reflects the order of script loading (but "file" is " the topmost window)

fun! Edit_ft_conf(name) " we may not do this with a loaded file, since this won't trigger the " configuration file loading as desired. " try calling with 'call Edit_ft_conf("nonexistingfile.<EXT>")' if this " gives you troubles if bufexists(a:name) && bufloaded(a:name) echo "!Attention: buffer for " . a:name . " is loaded, unload first." return endif " split-open the file with verbose set, grab the output into a register " (without clobbering) let safereg = @u redir @u " redirect command output to register @u exec "silent 2verbose split " . a:name " verbose level 2 suffices to catch all scripts which get opened redir END " Parse register @u, looking for smth like: 'sourcing"/usr/local/share/vim/v im60/syntax/c.vim"' let pos = 0 let regexp = 'sourcing "[^"]\+"' while match(@u,regexp,pos) >= 0 let file = matchstr(@u,regexp,pos) let pos = matchend (@u,regexp,pos) let file = strpart(file,10,strlen(file)-11) exec "silent below split " . file endwhile " restore the register let @u = safereg endfun

VimTip 216: calculate equations from within vim http://vim.sf.net/tip_view.php?tip_id=216 The following map and function calculates equations using the program 'bc' (foun d on most linux systems, available for most systems). Visually select the equat ion you want to calculate, then hit ;bc - if the selection ends with an '=' sign , the answer will be appended after the equal, otherwise, the answer is echoed a s a message. The code to put in a vimrc and source is at the end. Equations can span multiple lines, and the full bc syntax is probably supported. Additionally, sin (), cos (), etc, are transformed into the names used by bc ( s () c (), etc). Here are some example lines: 2 * sqrt (2) = 3 * (2 - 1) + 4.0 ^ 6 = 4 / 3 = 3 + 4 -

2 * (1 / (3 + 2)) = define rad (x) { return (x / 180) * 4 * atan (1) } cos (rad (45)) = Select each of these in turn (continguous non-blank lines, and hit ;bc for each) , and this is what you get: 2 * sqrt (2) = 2.82842712474619009760 3 * (2 - 1) + 4.0 ^ 6 = 4099.000000 4 / 3 = 1.33333333333333333333 3 + 4 2 * (1 / (3 + 2)) = 6.60000000000000000000 define rad (x) { return (x / 180) * 4 * atan (1) } cos (rad (45)) = .70710678118654752440 Fun, no? Here is the code you need to put in your vimrc file: vnoremap ;bc "ey:call CalcBC()<CR> function! CalcBC() let has_equal = 0 " remove newlines and trailing spaces let @e = substitute (@e, "\n", "", "g") let @e = substitute (@e, '\s*$', "", "g") " if we end with an equal, strip, and remember for output if @e =~ "=$" let @e = substitute (@e, '=$', "", "") let has_equal = 1 endif " sub common func names for bc equivalent let @e = substitute (@e, '\csin\s*(', "s (", "") let @e = substitute (@e, '\ccos\s*(', "c (", "") let @e = substitute (@e, '\catan\s*(', "a (", "") let @e = substitute (@e, "\cln\s*(", "l (", "") " escape chars for shell let @e = escape (@e, '*()') " run bc, strip newline let answer = substitute (system ("echo " . @e . " \ bc -l"), "\n", "", "") " append answer or echo if has_equal == 1 normal `> exec "normal a" . answer else echo "answer = " . answer

endif endfunction

VimTip 217: Translate &#nnn; in html source to readable ascii http://vim.sf.net/tip_view.php?tip_id=217 I found a website *cough*Tivoli.com*cough* that likes to obfuscate some of its h elp file web pages using &#nnn; instead of normal ascii. If you load the source with Vim (in Opera you can just designate Vim as your source viewing program), you can :so the following code to make it readable. let n = 32 while n < 127 if n == 38 silent! elseif n == silent! else silent! endif let n = n + endwhile

exec '%s/&#38;/\&amp;/g' 47 exec '%s/&#47;/\//g' exec '%s/&#' . n . ';/' . nr2char(n) . '/g' 1

Disclaimer: I hacked this together in about 10 minutes (or possibly longer :). It worked suitably for the website I wrote it for (or possibly "against" :). Yo ur Milage May Vary. See :help eval, :help silent, :help exec, :help :s

VimTip 218: Check for comments, independent of the filetype http://vim.sf.net/tip_view.php?tip_id=218 For some scripts it might be useful to detect, whether a specific position in a buffer is inside of a comment or not. Syntax highlighting can save us the work for parsing the co mments ourselves. The command :echo synIDattr(synIDtrans(synID(line("."), col("."), 0)), "name") echoes the group used for *highlighting* the character at the current cursor pos ition, see ':help synIDtrans()'. It will usually be "Comment" if the cursor is i nside of a comment, so synIDattr(synIDtrans(synID(line("."), col("."), 0)), "name") == "Comment" detects, independent of the filetype (which have their own group 'names' for com ments), if the cursor is inside a comment or not. The expression synIDattr(synIDtrans(synID(line("."), col("."), 0)), "name") =~ 'Comment\ Cons tant\ PreProc'

will detect additionally, if the cursor is inside of a string or some preprocess or statement.

VimTip 219: make from command line, open vim on errors http://vim.sf.net/tip_view.php?tip_id=219 A simple alias (*csh) or shell function (bash) will let you run make from your s hell, then automatically open vim or gvim on the errors (if there were any): csh or tcsh: alias Make 'make \!* & tee make.errors bash: Make () { command make "$@" & tee make.errors ; } gvim -q make.errors -c :copen gvim -q make.errors -c :copen'

If you use vanilla sh or ksh or even cmd.exe, you can probably do the same - add a not if you have ideas.

VimTip 220: Regexp: Match every word except 'foo' http://vim.sf.net/tip_view.php?tip_id=220 This is a regular expression that matches all words except 'foo' \v<(foo>)@!\k+> \v Very magic < Start-of-word (Foo>) The atom 'Foo' followed by end-of-word @! Match (with zero length) when the previous atom doesn't match. \k+ Match one or more Keywords > Match end-of-word. This is a kool example of using \@! in the middle of a regexp. The non-magic version is: \<\(foo\>\)\@!\k\+\>

VimTip 221: indenting "throws" in java

http://vim.sf.net/tip_view.php?tip_id=221 I want to indent java files like this: int x(int y, int z) throws Exception { [...] return something; } By default vim will properly indent "throws" line, but following "{" will not be deindented back to the method declaration. The following indentexpr does the trick: let &indentexpr='getline(v:lnum)=~"^\\s*{" && getline(v:lnum-1)=~"^\\s*throws\\s " ? cindent(v:lnum)-&sw : cindent(v:lnum)' It just checks that the current line starts with "{" and the previous line start s with "throws" and if that is the case, it subtracts one shiftwidth from the nu mber returned by cindent.

VimTip 222: Building vim with color on HP-UX http://vim.sf.net/tip_view.php?tip_id=222 Following the normal steps of running "./configure" and "make" to build vim on an HP-UX 10.20 will result in vim being linked with the termlib library. This library does not support certain termcap capability codes, such as the "Co" code used to query the number of colors supported by the terminal. Consequently, vim will not display colors when used with a color terminal such as a color xterm. One solution to this is to run the configure script with the "--with-tlib=curses" option, like this: ./configure --with-tlib=curses This will cause vim to be linked with the HP-UX curses library, which does support the color termcap capability codes. Note that the xterm that comes standard with HP-UX 10.20 does not display color character attributes. To see colors when running vim in a terminal window, you will also need to install a color terminal emulator such as a recent xterm.

VimTip 223: Reverse Selected Text http://vim.sf.net/tip_view.php?tip_id=223 Suppose you want to reverse some text - I don't know why you would want to - may be you're dyslexic. Anyway, I had a need, so this mapping will reverse visually

selected text. Put the mapping in your vimrc or otherwise source it, then visu ally select the word or words, and hit ;rv - really only works with selections o n one line: vnoremap ;rv c<C-O>:set revins<cr><C-R>"<esc>:set norevins<cr>

VimTip 224: Shifting blocks visually http://vim.sf.net/tip_view.php?tip_id=224 I use the < and > commands on blocks a lot, and it has always annoyed me that if you want to shift more than one 'shiftwidth', you have count how many 'shiftwid th's you want to enter the '[count]>', or restore the selection with "gv". So I' ve cooked up two mappings that come in very handy: :vnoremap < <gv :vnoremap > >gv These mappings will reselect the block after shifting, so you'll just have to se lect a block, press < or > as many times as you like, and press <ESC> when you'r e done to unselect the block. I know it's not rocket science, but it sure has helped me a lot.

VimTip 225: vim can interact with xdvi http://vim.sf.net/tip_view.php?tip_id=225 vim can interact with the tricks that the latest xdvi does: * If one clicks at some place in xdvi, vim automatically jumps to the corresponding line in the LaTeX source file ("reverse search") * Also, from inside vim, one can jump to the corresponding line in xdvi which becomes highlighted ("forward search"). Here is how to do it: * Reverse search: We start a vim server by: vim --servername xdvi We start xdvi(k) on file.dvi by: xdvik -editor "vim --servername xdvi --remote +%l %f" file.dvi At the desired location in xdvi, we press: <ctrl><left_mouse> Then, vim will jump to the corresponding line in the source file. * Forward search: Inside vim, we type, for example, _g which is the following mapping: (the following should be a single line) map _g :execute "!xdvik -name xdvi -sourceposition " . line(".") . expand("%

") . " " . expand("%:r") . ".dvi" <cr><cr> [the command to go to the point of xdvi that corresponds to line, eg, 77 of the source file is (no space after 77) xdvik -name xdvi -sourceposition 77file.tex file.dvi ] For the above to work one needs: 1) A recent version of xdvi or xdvik (>22.39 I think) 2) The package srcltx.sty and \usepackage{srcltx} (which should be commented out when one finishes and is ready for printing etc). 3) Our version of vim should have been compiled with +clientserver (however, my vim doesn't have it and still works, so try it before Bram finds out what is happening and fixes it)

VimTip 226: Edit file under cursor after a horizontal split http://vim.sf.net/tip_view.php?tip_id=226 I use the command 'gf' quite often. But with this command the current buffer is hidden. To avoid that I use the following mapping : map gw <Esc>:sp %<CR> gf With this mapping the file under the cursor is opened after a horizontal split.

VimTip 227: Power of :g http://vim.sf.net/tip_view.php?tip_id=227 :g is something very old and which is very powerful. I just wanted to illustrate the use of it with some examples. Hope, it will be useful for someone. Brief explanation for ":g" ------------------------Syntax is: :[range]:g/<pattern>/[cmd] You can think the working as, for the range (default whole file), execute the colon command(ex) "cmd" for the lines matching <pattern>. Also, for all lines that matched the pattern, "." is set to that particular line (for certain commands if line is not specified "." (current line) is assumed). Some examples ------------Display context (5 lines) for all occurences of a pattern :g/<pattern>/z#.5 :g/<pattern>/z#.5 echo "==========" << same as first, but with some beautification >> Delete all lines matching a pattern :g/<pattern>/d

Delete all blank lines (just an example for above) :g/^\s*$/d Double space the file :g/^/pu =\"\n\" :g/^/pu _ << the above one also works >> Copy all lines matching a pattern to end of file :g/<pattern>/t$ Yank all lines matching a pattern to register 'a' 0"ay0:g/<pattern>/y A Increment the number items from current line to end-of-document by one :.,$g/^\d/exe "normal! \<c-a>" Comment (C) lines containing "DEBUG" statements g/^\s*DEBUG/exe "norm! I/* \<Esc>A */\<Esc>" A Reverse lookup for records (eg: An address book, with Name on start-of-line and fields after a space) :g/<patern>?^\w?p "if only name is interested :g/<patern>/ka ?^\w?p 'ap "if name and the lookup-line is interested :g/<patern>/?^\w? +,/^[^ ]/-1p "if entire record is interested Reverse a file (just to show the power of 'g') :g/^/m0 Foot note Foot note :2,8co15 :4,15t$ :-t$ :m0 :.,+3m$-1 use :v to negate the search pattern Some explanation of commonly used commands with :g Copy lines 2 through 8 after line 15 Copy linesa 4 through 15 towards end of document (t == co) Copy previous line to end of document Move current line to the top of the document Move current line through cur-line+3 to the last but one line of the document Foot note 3: Commands used with :g are ex commands, so a help search should be, :help :<help-topic> eg. :help :k 1: 2: => => => => =>

VimTip 228: Deleting nested reply threads in emails http://vim.sf.net/tip_view.php?tip_id=228 I s > > > find the following setting useful when replying to email threads that have lot of lines like the following: blah > blah > > blah

autocmd FileType mail map <F8> :%g/^> >/d<CR> When replying to a mail and you want to remove everything except what the person you are directly replying to wrote just press F8. From the example above, you would just be left with > blah What it does is simply match any line starting with > > and deletes it. It's no t perfect as sigs and other debris may remain but it takes a lot of the grunt wo rk out of replying to mails.

The autocmd only maps F8 when using mails, this is handy if you use F8 for other things as I do. :help autocmd :help map :help :g

VimTip 229: First thing to try before asking help http://vim.sf.net/tip_view.php?tip_id=229 I've seen several questions asked in the reflector which is available in the hel p files. Yeah, I know the help is huge. But, you can try this command to show a list of r elated topics you are trying: :he <topic><c-d> It is "some topic" followed by the key sequence Ctrl-D. For eg: :he xterm<c-d> will show all the help topics matching xterm. Then you can do completion/copy-npaste the topic you are searching. Of course you can cycle through all the topics thro ugh repeated <TABS>, but if the number of hits are huge, it is cumbersome. Enjoy vimming beginners!!! -Arun

VimTip 230: copy current file to another location from within vim http://vim.sf.net/tip_view.php?tip_id=230 I work on jsp pages in my source tree but I have to copy the jsp files over to t he tomcat directory in order to view my changes.The following mapping will copy the file being edited to another location. command Cpage silent !cp '%:p' "c:/Progra~1/Tomcat/webapps/console/pages/%" Explanation: % refers to the current buffer %:p refers to the path to the file silent suppresses the command prompt window. Usage: :Cpage

VimTip 231: Localized color schemes http://vim.sf.net/tip_view.php?tip_id=231 i frequently like to edit multiple files in the same vim session. however, if i come into vim from another window i frequently hit 'i' and start typing in what ever buffer is currently being used -- this is often the wrong one (requires <es c>, undo, go the other buffer and . to redo). one way to work around this for me is to use a different color scheme depending on what file i'm working on: au BufEnter * if (exists("b:colors_name")) let b:current_colors=colors_name execute "colorscheme " . b:colors_name endif au BufLeave * if (exists("b:current_colors")) nt_colors endif execute "colorscheme " . b:curre

if you define b:colors_name with a particular color scheme name, then the above autocommands will switch to that colorscheme when you enter that window and will return to the original color upon departure. inside ftplugin/java.vim, for example, i might have b:colors_name set to 'mornin g', causing all java files to have a distinguishing color scheme.

VimTip 232: Search JDK help for keyword at cursor http://vim.sf.net/tip_view.php?tip_id=232 If you are using the Win32 version of Vim you can use this tip to search the Jd k help for the keyword under the cursor. You need the winhlp32 version of the Jdk docs from this URL - http://www.conflue nt.fr/javadoc/indexe.html. It is a 16mb D/L and approx 85mb unzipped! I added a command to the popup menu :amenu PopUp.JavaHelp :!start winhlp32 -k <cword> F:\jdk\winhelp\JDK13.HLP <CR And also made a keymapping map J :!start winhlp32 -k <cword> F:\jdk\winhelp\JDK13.HLP <CR> Trivial yes, but I find it quite useful.

VimTip 233: Some tips for using Vim to write Lisp code http://vim.sf.net/tip_view.php?tip_id=233 For some tips on how to use Vim for writing Lisp code, see http://www.lisp-p.org /i000/15-vim.

VimTip 234: Vi(M) Command Line tips & tricks http://vim.sf.net/tip_view.php?tip_id=234 Hi VIMMERs These tips save me wearing out my delicate little fingers with unnecessary keyst rokes. They assume Unix, but I also use them on a Windows Unix Shell (MKS) as well # When I know the file i want to edit is the most recent file in a directory alias -x vew='vi `l\s -t * head -1 `'

#When I know the file I want to edit contains a unique keyword #this is actually in a little shell script call ed vg where the keyword is passe d as parameter $1 #/bin/sh #name vg vi.exe $(grep -isl $1 *) & # some variations alias -x vp='vi `l\s -t *.@(pl cgi) head -1 `' #execute the most recent script (I call this from within VIM with a mapped butto n) alias -x xew='`l\s -t *.pl head -1 `' Cheers zzapper

VimTip 235: Toggle highlight word under cursor, to find cursor. http://vim.sf.net/tip_view.php?tip_id=235 When the screen has scrolled such as during a search, it may be difficult to fin d the cursor. :help %# explains the pattern one can use to highlight the word a round the cursor, which gives a bigger target to look for on the screen. I have this in my .vimrc: function VIMRCWhere() if !exists("s:highlightcursor") match Todo /\k*\%#\k*/ let s:highlightcursor=1 else match None unlet s:highlightcursor endif endfunction map <C-K> :call VIMRCWhere()<CR>

This means that in "normal" mode ctrl-k will toggle the highlight. Todo is a hi ghtlight group whch is particularly easy to see. For further information see ":help s:", ":help match", ":help exists()" and ": help funtion".

VimTip 236: Menu for inserting special characters http://vim.sf.net/tip_view.php?tip_id=236 First, thanks for the script printascii.vim. When looking at the ascii table, I found some characters I'd like to have insert ed when editing. Add the following lines in your _gvimrc and you can select them via menu. (change the names of the menu if you don't have German installed or don't like m y titles). I also made some abbreviations to get separation lines in documentation or code files, e.g. abb dotlin ^M abb cdotlin /* */^M abb fdotlin ^M abb cfdotlin /* */^M abb dlin ======================================================================= ^M abb cdlin /*===================================================================* /^M abb lin -----------------------------------------------------------------------^ M abb clin /*-------------------------------------------------------------------*/ ^M abb ulin _______________________________________________________________________ ^M abb culin /*___________________________________________________________________* /^M abb Ulin ^M abb cUlin /**/^M (you have to substitute ^M with CTRL_V CTRL_M or delete it) 20imenu Editieren.Sonderzeichen.open\ angle\ 20nmenu Editieren.Sonderzeichen.open\ angle\ 20imenu Editieren.Sonderzeichen.close\ angle\ 20nmenu Editieren.Sonderzeichen.close\ angle\ 20imenu Editieren.Sonderzeichen.start\ mark\ 20nmenu Editieren.Sonderzeichen.start\ mark\ ESC> 20imenu Editieren.Sonderzeichen.end\ mark\ 20nmenu Editieren.Sonderzeichen.end\ mark\ 48)<CR><ESC> 20imenu Editieren.Sonderzeichen.fat\ dot\ 20nmenu Editieren.Sonderzeichen.fat\ dot\ ESC> 20imenu Editieren.Sonderzeichen.etc\ \ 20nmenu Editieren.Sonderzeichen.etc\ \ <C-R>=nr2char(171)<CR> a<C-R>=nr2char(171)<CR><ESC> <C-R>=nr2char(187)<CR> a<C-R>=nr2char(187)<CR><ESC> <C-R>=nr2char(132)<CR> a<C-R>=nr2char(132)<CR>< <C-R>=nr2char(148)<CR> a<C-R>=nr2char(1 <C-R>=nr2char(149)<CR> a<C-R>=nr2char(149)<CR>< <C-R>=nr2char(133)<CR> a<C-R>=nr2char(1

\ \ \ \ \ \

33)<CR><ESC> 20imenu Editieren.Sonderzeichen.!underscore\ 20nmenu Editieren.Sonderzeichen.!underscore\ 75)<CR><ESC> 20imenu Editieren.Sonderzeichen.copyright\ 20nmenu Editieren.Sonderzeichen.copyright\ ESC> 20imenu Editieren.Sonderzeichen.paragraph\ 20nmenu Editieren.Sonderzeichen.paragraph\ ESC> 20imenu Editieren.Sonderzeichen.noitamalcxe\ 20nmenu Editieren.Sonderzeichen.noitamalcxe\

\ \ \ \ \ \

<C-R>=nr2char(175)<CR> a<C-R>=nr2char(1 <C-R>=nr2char(169)<CR> a<C-R>=nr2char(169)<CR>< <C-R>=nr2char(167)<CR> a<C-R>=nr2char(167)<CR><

<C-R>=nr2char(161)<CR> a<C-R>=nr2char(161)<CR><ESC>

VimTip 237: If you prefer vertical splits http://vim.sf.net/tip_view.php?tip_id=237 This is just in case there's somebody else who likes to work in a maximized vim window on a high resolution desktop. If you follow good coding practice and make sure your programs use only 80 characters in each row, have you noticed how muc h space lies unused on the right? I find that the following settings keep me from ever seeing another horizontal s plit, unless I specifically ask for it. cabbrev cabbrev cabbrev cabbrev cabbrev cabbrev split vsplit hsplit split sta vertical sta help vertical help new vnew right botright

; A more heavyweight solution for ^W^] function! ToggleSplit (dir) let currFname = bufname ("%") let old = winnr () " Window navigation to ensure the correct window is 'last'. if (a:dir == "u") wincmd k let back="j" elseif (a:dir == "d") wincmd j let back="k" elseif (a:dir == "l") wincmd h let back="l" elseif (a:dir == "r") wincmd l let back="h" endif if (winnr () == old) echo "Ouch"

return endif exec "wincmd " . back quit if (back == "j" back == "k") let orientation = "vsplit" else let orientation = "split" endif if (back == "j" back == "l") let dir = "below" else let dir = "above" endif exec dir . " " . orientation " " . currFname endfunction noremap ^W^] ^W^]:silent call ToggleSplit ("d")<CR> ; Optional. set splitright ; In which case the above mapping becomes: noremap ^W^] :set splitbelow<CR>^W^]:silent call ToggleSplit ("u")<CR>:set nospl itbelow<CR> ; Or you could just set splitbelow ; :-) ; Very elegant and almost perfect, but it screws up if you want to run a command with ranges :-) ;noremap : :vertical<Space> ; EOF

VimTip 238: Very basic session persistence http://vim.sf.net/tip_view.php?tip_id=238 I use the following code in my plugins dir to ease session persistance. If I wan t my session to persist I use :mks! and then whenever I open the Session.vim fil e, my session is restored. If I am working from a restored session and I close V IM, the session is saved automatically. Drawback is that it makes editing the Se ssion.vim file a bit cumbersome ;) au BufRead Session.vim so % au VimLeave * call SaveCurrentSession() function! SaveCurrentSession() if v:this_session != "" exe "mksession! " . v:this_session endif endfunction

VimTip 239: Scroll using arrow keys like browser: map shift-up and shift-down http://vim.sf.net/tip_view.php?tip_id=239 You can make Vim scroll the text using the shifted up/down arrows, sort of like your browser (except with shifted keys :), by mapping Shift-Up to Ctrl-Y and Shi ft-Down to Ctrl-E. map <s-Down> <C-E> map <s-Up> <C-Y> Shift-Down will then scroll down (like moving a scroll-bar down, or like moving a cursor at the bottom of a window down), and Shift-Up will then scroll up (like moving a scroll-bar up, etc). If you'd rather think about the text moving down/up instead of the cursor moving up/down, you can of course swap the mappings. If you normally use j and k for cursor movement, and rarely use the arrow keys, you can map the arrow keys directly, in which case I'd probably map the shifted arrow keys back to cursor movement: map map map map <down> <c-e> <up> <c-y> <s-down> j <s-up> k

See :help ctrl-e, :help ctrl-y, and :help key-mapping. See also :help i_ctrl-o and :help map-modes for how to set up these mappings for use in other modes (like insert mode :). (Vim by default maps s-Down and s-Up to Ctrl-F and Ctrl-B, for both normal and v isual mode. Keep this in mind if you change some of the above mappings to "nmap ", 'cause you'll probably also want to look in to "vmap".)

VimTip 240: Hideall for Vim http://vim.sf.net/tip_view.php?tip_id=240 Xemacs has a hide all function which can make all the function in your C file a fold and close them. And here is something small to achieve similiar under Vim. func! HideAll() syn region myFold start="{" end="}" transparent fold syn sync fromstart set foldnestmax=1 set foldmethod=syntax endfunc

amenu Whatever.Hide\ all :call HideAll()<CR>

VimTip 241: "Hide" Folding Markers http://vim.sf.net/tip_view.php?tip_id=241 I wanted to start using folding without having to get used to seeing the (default) markers, a.k.a {{{ and }}}. So, here are 2 autocmd's that will make them fade to black....bg=black fg=black au BufRead,BufNewfile * syn match fmrkr '"*{{{\ "*}}}' \ syn cluster vimCommentGroup contains=fmrkr \ hi fmrkr term=NONE guibg=black guifg=black \ ctermbg=black ctermfg=black * syn match fmrkr '"*{{{\ "*}}}' \ containedin=vimLineComment contained \ hi fmrkr term=NONE guibg=black guifg=black \ ctermbg=black ctermfg=black

au BufRead,BufNewfile

They both accomplish the same thing, but with different methods, so simply pick one and see those annoying (at least to me) markers fade away. I just tried it out with vim files, but you can easily modify it for any other filetypes. Thanks to Colin's lead with ':help c-syntax' for the 1st au. Thanks to Benji's lead with ':help containedin' for the 2nd au. Understanding most of the syntax.txt document file would also be helpful. To figure out what highlighting group the Marker is in, I would suggest using Chip's vimtip#99. Happy Vimming!

VimTip 242: The power of "\_" in reg-ex http://vim.sf.net/tip_view.php?tip_id=242 One of the most uncelebrated feature of vim 6.0 is the ability to span a search across multiple lines. \_^ maps a begining of line anywhere in search pattern. \_$ ---"----- end ----------------------"-------------------------. \_s ---"------ space ------------"------------------------- . e.g /{\_s will map all white spaces and new-line chars after a "{" The \_ can be appended to other objects as well. such as \_U, \_L, \_. (this o ne's risky) . See :help pattern for more details.

Njoy

VimTip 243: Develop vim modules on Win http://vim.sf.net/tip_view.php?tip_id=243 We're trying to develop txt2pdf.vim http://vim.sourceforge.net/scripts/script.ph p?script_id=283 on Win. It's a very simple module to save the current file and convert it to PDF using o ur txt2pdf tool http://www.sanface.com/txt2pdf.html On our Windows 2000 we've developed it. It works good. Today we've tested the module on Linux. Surprise: it doesn't work. Default Win Vim configure save on Win text in Win way: EOL \r\n. A Vim module made in this way can't work on Linux (probably on every Unix OS). If you want to make a Vim module on Win and you want it can work also on Unix (w e hope the same rula can work also on different OS) you've to save the Vim modul e with Unix EOL (\n). Please send us (sanface@sanface.com) your notes about other OS (e.g. OpenVMS).

VimTip 244: Ask vim where an option was set. http://vim.sf.net/tip_view.php?tip_id=244 When things go wrong, it is sometimes hard to figure out why. For example, an option might be set in the system vimrc file, in a personal vimrc file, in a plugin (global or local), or interactively. Vim will tell you where the current value was set if you ask: :verbose set history? will tell you the current value of the 'history' option, and where it was set.

VimTip 245: Working with Unicode (platform-independent) http://vim.sf.net/tip_view.php?tip_id=245 Here are the main options you will want to set if you want to work with Unicode files in (g)vim (see at bottom what help tags to look for) if has("multi_byte") set encoding=utf-8 " how vim shall represent characte rs internally setglobal fileencoding=utf-8 " empty is also OK (defaults to same a s 'encoding'). Or you may want to set one of the ucs encodings (which " may use less disk sp ace if you use only "alphabetic" scripts such as Latin, Greek, Cyrillic, Hebrew

or Arabic, and " not "ideographic" sc ripts like Chinese, Japanese or Korean. With the ucs encodings it is usually bet ter set bomb " to also set 'bomb' on ('by te-order-mark" option, irrelevant for utf-8 but not for ucs) set termencoding=iso-8859-15 " or whatever is appropriate to your locale (iso-8859-15 is Latin1 + Euro currency sign) set fileencodings=ucs-bom,iso-8859-15,iso-8859-3,utf-8 " or whatever is appropriate to the kinds of files you want to edit " 'fileencodings' defines the heuristic to set 'fillencoding' (local to buffer) when reading an existing file. The first one that matches will be used. " ucs-bom is "ucs with byte-order-mark"; it must not come after ucs-8 i f you want it to be used else echoerr "Sorry, this version of (g)vim was not compiled with +multi_byte" endif In "replace" mode, one utf character (one or more data bytes) replaces one utf c haracter (which need not use the same number of bytes) In "normal" mode, ga shows the character under the cursor as text, decimal, octa l and hex; g8 shows which byte(s) is/are used to represent it In "insert" or "replace" mode, - any character defined on your keyboard can be entered the usual way (even wi th dead keys if you have them, e.g. ) - any character which has a "digraph" (there are a huge lot of them, see :dig after setting enc=utf-8) can be entered with a Ctrl-K prefix - any utf character at all can be entered with a Ctrl-V prefix, either <Ctrl-V > u aaaa or <Ctrl-V> U bbbbbbbb, with 0 <= aaaa <= FFFF, or 0 <= bbbbbbbb <= 7FF FFFFF Unicode can be used to create html "body text", at least for Netscape 6 and prob ably for IE; but on my machine it doesn't display properly as "title text" (i.e. , between <title></title> tags in the <head> part). Gvim will display it properly if you have the fonts for it, provided that you se t 'guifont' to some fixed-width font which has the glyphs you want to use (Couri er New is OK for French, German, Greek, Russian and more, but I'm not sure about Hebrew or Arabic; its glyphs are of a more "fixed" width than those of, e.g. Lu cida Console: the latter can be annoying if you need bold Cyrillic writing). see: :h :h :h :h :h :h :h :h :h :h utf8 'enc' 'fenc' 'fencs' 'tenc' 'bomb' 'guifont' ga g8 i_Ctrl-V_digit

Happy Vimming ! Tony.

VimTip 246: Working with Unicode (the same, rewritten for legibility) http://vim.sf.net/tip_view.php?tip_id=246 1. Where to look for help ------------------------:h utf8 :h encoding-values :h 'enc' :h 'fenc' :h 'fencs' :h 'tenc' :h 'bomb' :h 'guifont' :h ga :h g8 :h :dig :h i_Ctrl-V_digit :h has() 2. What to do (These are *examples*. Modify them to suit your work environment.) ------------if has("multi_byte") set encoding=utf-8 setglobal fileencoding=utf-8 set bomb set termencoding=iso-8859-15 set fileencodings=ucs-bom,iso-8859-15,iso-8859-3,utf-8 else echoerr "Sorry, this version of (g)vim was not compiled with +multi_byte" endif 3. What the above does ---------------------* has("multi_byte") checks if you have the right options compiled-in. If you hav en't got what it takes, it's no use trying to use Unicode. * 'encoding' sets how vim shall represent characters internally. Utf-8 is necess ary for most flavors of Unicode. * 'fileencoding' sets the encoding for a particular file (local to buffer); :set global sets the default value. An empty value can also be used: it defaults to s ame as 'encoding'. Or you may want to set one of the ucs encodings, It might mak e the same disk file bigger or smaller depending on your particular mix of chara cters. Also, IIUC, utf-8 is always big-endian (high bit first) while ucs can be big-endian or little-endian, so if you use it, you will probably need to set 'bo mb" (see below). * 'bomb' (boolean): if set, vim will put a "byte order mark" at the start of ucs files. This option is irrelevant for most non-ucs files (utf-8, iso-8859, etc.) * 'termencoding' defines how your keyboard encodes what you type. The value you put there will depend on your locale: iso-8859-15 is Latin1 + Euro currency sign , but you may want something else for, say, an Eastern European keyboard. * 'fileencodings' defines the heuristic to set 'fileencoding' (local to buffer) when reading an existing file. The first one that matches will be used (and, IIU C, if there is no match, Vim falls back on Latin1). Ucs-bom is "ucs with byte-or der-mark"; it must not come after utf-8 if you want it to be used.

4. Additional remarks --------------------* In "replace" mode, one utf character (one or more data bytes) replaces one utf character (which need not use the same number of bytes) * In "normal" mode, ga shows the character under the cursor as text, decimal, oc tal and hex; g8 shows which byte(s) is/are used to represent it. * In "insert" or "replace" mode, - any character defined on your keyboard can be entered the usual way (even wi th dead keys if you have them, e.g. French circumflex, German umlaut, etc.); - any character which has a "digraph" (there are a huge lot of them, see :dig after setting enc=utf-8) can be entered with a Ctrl-K prefix; - any utf character at all can be entered with a Ctrl-V prefix, either <Ctrl-V > u aaaa or <Ctrl-V> U bbbbbbbb, with 0 <= aaaa <= FFFF, or 0 <= bbbbbbbb <= 7FF FFFFF. * Unicode can be used to create html "body text", at least for Netscape 6 and pr obably for IE; but on my machine it doesn't display properly as "title text" (i. e., between <title></title> tags in the <head> part). * Gvim will display it properly if you have the fonts for it, provided that you set 'guifont' to some fixed-width font which has the glyphs you want to use (Cou rier New is OK for French, German, Greek, Russian and more, but I'm not sure abo ut Hebrew or Arabic; its glyphs are of a more "fixed" width than those of, e.g. Lucida Console: the latter can be awkward if you need bold Cyrillic writing). Happy Vimming ! Tony.

VimTip 247: Preexisting code indentation http://vim.sf.net/tip_view.php?tip_id=247 Using tabs as elementary unit in your code indentation has two advantages: first , you may modify 'tabstop' and immediately all the indentations depths are modif ied according to it; second, your file will be smaller. But how can we change some already-written code in order to convert spaces to ta bs. Very simple! Suppose your old code has an indentation unit of 2 spaces :ret! 2 :x will replace every 2-spaces to one tab, independently from your current tabstop value, and will save the modified file. Then, if you open again the file with tabstop=2, the file will look as before bu t it will be smaller. If you open the file with tabstop=4, the code vill have a more indented look, and so on... Cheers!

VimTip 248: Auto-save the current buffer periodically. http://vim.sf.net/tip_view.php?tip_id=248 I have no idea if this was implemented in vim 5.3 or not, but you can definitely do the following kludge in 6.x by using CursorHold and localtime: - When you start reading a file, set a buffer variable to the current time: au BufRead,BufNewFile * let b:start_time=localtime() - Set a CursorHold event to check to see if enough time has elapsed since the last save and save if not: au CursorHold * call UpdateFile() - Define a function to save the file if needed: " only write if needed and update the start time after the save function! UpdateFile() if ((localtime() - b:start_time) >= 60) update let b:start_time=localtime() else echo "Only " . (localtime() - b:start_time) . " seconds have elapsed so fa r." endif endfunction - Reset the start time explicitly after each save. au BufWritePre * let b:start_time=localtime() Obviously, you should get rid of the else portion once you're certain that this does indeed do what you wanted. The thing to note is that the CursorHold will only fire after 'updatetime' milliseconds of inactivity have elapsed. So, if you type rapidly for one and a half minutes non-stop, it won't actually save anything until you STOP activity long enough. This may be what you want anyway because it won't interrupt your activity with a forced save. The actual save-delay can be changed from '60' to another number (in seconds) or a variable or anything like that. This entire functionality can be easily wrap ped inside a nice script which enables/disables this on a per-buffer basis (mayb e with maps etc.). If desired, I can provide that also.

VimTip 249: C/C++: Quickly insert #if 0 - #endif around block of code http://vim.sf.net/tip_view.php?tip_id=249 One of my favorite macros that I use in vim (and vi) inserts a #if 0 #endif sand wich

around a block of code. I always map this to the 2 key sequence ;' which is th e semi-colon followed by the single quote. Look at your keyboard, you will notice these keys are adjacent to one another. I like this mapping because it's very f ast, my fingers easily roll from one key to the next, obviously YMMV. To use this mapping, go to the line of code that you want the '#if 0' to be on, type ma to mark this line with the marker a, then move to the line that should be las t line just above the '#endif' and press ;' " insert #if 0 - #endif around block of code map ;' mz'aO<Esc>i#if 0<Esc>'zo<Esc>i#endif<Esc> -David Thompson dat1965@yahoo.com

VimTip 250: One big window http://vim.sf.net/tip_view.php?tip_id=250 If you like to see your files in fullscreen, and you have to edit more files, yo u can do the following. * Use only one window * Open further files with :e * type :nm <A-Up> :bp!<CR> * type :nm <A-Down> :bn!<CR> * type :nm <C-F4> :bd!<CR> You can of course change the keys. Now to switch between windows, you can press Alt-Up, and Alt-Down (Just in the GUI, if you use console, don't use Alt key) Another idea is to map them to Ctrl-Tab, and Ctrl-Shift-Tab To close the current file you can press Ctrl-F4

VimTip 251: c/c++: align #endif with corresponding #if/#ifdef http://vim.sf.net/tip_view.php?tip_id=251 If you try to impose any sort of alignment on your preprocessor directives, rath er than just starting them on column 0, this mapping will align the #endif 'corr ectly' when you type '#en', start a new line, and bring you back to the correct alignment to edit code. inoremap <buffer> #en X<BS><Esc>?#if<CR>"zy0^Og0"zpDa#endif<CR>X<BS><Esc>?#end?1<CR>^"zy0^O0"zpDa I am reasonably sure this is insensitive to vim options...

VimTip 252: python script to align statements http://vim.sf.net/tip_view.php?tip_id=252 i know there's some awk scripts out there that do the same thing, and if i were a real trooper i would have written this in vims internal language but... i wrote a python script to align statements. i put this in my .vimrc: map L :!lineUp.py<cr> " of course lineUp.py is somewhere in my path and i have this python file somewhere in my path: http://ophinity.com/res/dotFiles/lineUp.py so now i can just pipe the offending lines thru my code: :5, 10 !lineUp.py or using the mapping above, visually select the lines and press 'L'

VimTip 253: The power of (v75 r- actually...) http://vim.sf.net/tip_view.php?tip_id=253 ' ' as you may well be aware is the goto column motion, and that "75 " will plac e your cursor on column 75 of the current line. That in itself is pretty handy at times, but some true power arises when used in conjuction with visual mode and replace. Or you could just say a sneaky trick : ) v75 rwill repace from the cursor to the end of line with '-' *breakdown* v to turn on visual mode 75 for the count *bar* to goto column r to enter repace - to specify the char to replace. A handy and quick way to make a noticable section of your code (or whatever). A handy way to use this (formated to just drop into DrChip's CStubs): "// -[Feral]--------------------------------------------------------------"// <cursor> elseif wrd == "//" exe "norm! a -[AuthorId]\<esc>$lv75 r-$a\<cr>\<esc>$a " "// -[Feral:146/02@08:31]-------------------------------------------------"// <cursor> elseif wrd == "///"

exe "norm! s -[AuthorId:\<C-R>=strftime('%j/%y@%H:%M')\<CR>]\<es c>$lv75 r-$a\<cr>\<esc>$a " "/* -[Feral:146/02@08:31]-------------------------------------------------" * <cursor> " * -------------------------------------------------------------------- */ elseif wrd == "/*" exe "norm! a -[AuthorId:\<C-R>=strftime('%j/%y@%H:%M')\<CR>]\<es c>$lv75 r-$a\<cr>\<cr>\<esc>2lv72 r-$a */\<esc>k$a " Have to love VIM!

VimTip 254: Using \%[] to easily match parts of a word. http://vim.sf.net/tip_view.php?tip_id=254 This code fragment is suitable to drop into DrChip's CStubs. After much searching I was unable to find a tip nor script number to referance, I believe where I found Dr. Chip's CStubs originally : http://users.erols.com/as tronaut/vim/vimscript/drcstubs.vim Thank you Dr. Chip! (= If you have ever wanted to match parts of a word you may have considered somethi ng like: if wrd == "re" wrd == "ret" wrd == "retu" wrd == "retur" "do something Althought the above works well enough it is a pain to maintain and add new words (not to mention its just a touch messy ;) ) A more elegant (and easier to use I believe) method would be to use \%[] as part of a pattern. For instance, "\\<re\\%[tur]\\>" will match "re", "ret", "retu" or "retur" *breakdown* \\< = start of word re = first letters of word we want to require to match \\%[tur] = optionally match chars bewteen the braces, i.e. 't', 'tu' or 'tur' \\> = end of word So, we can use this as a pattern for match like so (In DrChip's CStubs) elseif match(wrd, "\\<re\\%[tur]\\>") > -1 exe "norm! bdWireturn\<Esc>" Which, I think, is a little better than the longer alternative: " vs elseif wrd == "re" wrd == "ret" wrd == "retu" wrd == "retur" exe "norm! bdWireturn\<Esc>" Just another one of those VIM things that made me smile :)

VimTip 255: arbitrary tags for file names http://vim.sf.net/tip_view.php?tip_id=255 This definitely work on linux and there is probably some windows equivalent. I've started working with tomcat and many many .jsp files. I find this trick to be very helpful. find -name '*.jsp' -printf '%f\t%P\t1\n' sort > jsp.tags This will create a file called jsp.tags with tag entries for each .jsp file. Wi thin Vim I use :set tags+=jsp.tags Now I can to simple :tag file.jsp to quickly switch b/w the many, many .jsp file s. One important note. The utility sort will use the value of LC_COLLATE to sort a ccording to your locale. This will give Vim issues. So try "LC_COLLATE=C sort" instead of plain "sort"

VimTip 256: Opening current Vim file in your Windows browser http://vim.sf.net/tip_view.php?tip_id=256 Hi Vimmers open current file in browser map ,f CR> :update<CR>:silent !start c:\progra~1\intern~1\iexplore.exe file://%:p<

open http link under cursor in your browser map ,i :update<CR>: !start c:\progra~1\intern~1\iexplore.exe <cWORD><CR>

Note use of cWORD (not cword) meaning OUTER Word Works for me in XP & 98 (Original came from a posting by Ralf Arens) zzapper

VimTip 257: fast page up/down. http://vim.sf.net/tip_view.php?tip_id=257

i discovered a cool way to move between pages of the same document in vim 6.1. p ress a number in -normal mode- and the page up/down. the document will move with that number of pages up/down.if the number is greater that the nr of pages, doc ument will move to begin/end of file. i didn't test it on other version.

VimTip 258: how long is the current word? http://vim.sf.net/tip_view.php?tip_id=258 ever wondered how long the current word is? this can be quite useful when editi ng data files. simply add the following to your .vimrc nmap <C-_> :echo 'word' expand("<cword>") ' wordlen =' strlen(expand("<cword>") )<CR> and it will tell you the word under the cursor, and how long it is. and for things that arent words, this addition to your .vimrc works on sections of a line that have been hightligted in visual mode vmap <C-_> "-y:echo 'word' @- ' wordlen =' strlen(@-)<CR> again you see the "word", and its length this may also work on vim 5.x, but i havent checked to make sure.

VimTip 259: removing the toolbar (icons) from gvim http://vim.sf.net/tip_view.php?tip_id=259 Change good or bad usually encounters interia from people in excepting it. gvim 6.0 is the first version that introduced the icons shortcut in shape of a t oolbar under the menu. when we upgraded to the new and improved vim 6.1 from vim 5.7 some of people in our company encountered some problems with their syntax highlighting and some of them objected on the new toolbar which displayed icons for some comm on tasks for people more used to GUI. I finally figured out how to remove this new feature since I also didn't see muc h use for it Here is for all those who haven't figured it out yet In your .gvimrc include the following two lines unmenu ToolBar unmenu! ToolBar Doing this from an open gvim does not remove them but grays them out but doing f rom gvimrc does the job

I was also trying to remove the menus at the top and almost succeeded with a sim ilar technique but somehow the Buffer menu item stays there no matter what. IMHO it is a bug but it could very well be a feature ;) I tried this unmenu * unmenu! * even added this line after the above two but didn't help unmenu Buffers I hope this benefits you all as much as I have benefitted from all your tips

VimTip 260: gvim-->mouse-->popup menu http://vim.sf.net/tip_view.php?tip_id=260 This tip is for those who prefer to do some of the common operations like cut/copy/paste etc using mouse. All u have to do is :set mousemodel=popup by this u get a popup menu on right click of your mouse and u can do all the common operations like undo, cut, copy, paste, select etc using mouse. u can also customise your popup menu by editing $VIMRUNTIME/menu.vim

VimTip 261: Close windows from Gvim poup menu http://vim.sf.net/tip_view.php?tip_id=261 To close windows from the popup menu add these lines to your .gvimrc :amenu PopUp.Close.\ Window :confirm close<CR> :amenu PopUp.Close.\ Other :confirm only<CR> You obviously need ':set mousemodel=popup' in your .gvimrc as well :=)

VimTip 262: Bored of ur arrow shapped mouseptr? http://vim.sf.net/tip_view.php?tip_id=262

here is how u can change the shape of ur mouseptr in gvim. :set mouseshape=n:pencil this will change the shape of the mouseptr to pencil in normal mode. u can choose different shapes for different modes. see :h mouseshape Want more shapes? Then look for the file cursorfont.h in ur X11/ directory. This file contains lots of cursor shape #define definitions, like . #define XC_heart 62 . now :set mouseshape=n:62 will set the shape of the mouseptr to heart in normal mode. -ncr

VimTip 263: color active line http://vim.sf.net/tip_view.php?tip_id=263 This tip shows how to color the active line, the line in which the cursor is, fo r better reading. You should try possibility 2 before 1, IMHO it is mostly usable. possibility 1: :au! CursorHold * let @/ = '\%' . line('.') . 'l.*' :set ut=500 explanation: After 500 ms of waiting for you to hit a key, vim sets the search register to a pattern that matches the current line. problem: Register / holds the search pattern, so you cannot have color the active li ne and search. Therefore another solution: possibility 2: :highlight CurrentLine guibg=darkgrey guifg=white (or whatever colors y ou want) :au! Cursorhold * exe 'match CurrentLine /\%' . line('.') . 'l.*/' :set ut=100 explanation: This solution uses 'match' to highlight a string, it does not interface wit h the current search pattern. addition: Turning the highlighning off: :au! Cursorhold :match none The order of these commands are important. If :match none is executed first , the autocommand would

almost immediately execute another match command. references :help :help :help :help :help to vim help: Cursorhold 'ut' /\%l "/ \%

VimTip 264: F5 Compile and Run, F8 Compile (ala Visual Studio) http://vim.sf.net/tip_view.php?tip_id=264 I love vim, it's my default editor on my Sun, Windows, Linux and *BSD boxen. Th at said, I hate having to flip windows to compile while doing the write->compile ->debug loop. If you're used to Visual Studio and the ability it has to just hit F5 to compile and run the current file or F8 to compile or step through the code you'll appre ciate this... This is my Windows version of this scriplet/tiplet. For other platforms, you'll want to change the IF ELSE loops. You should actually never see the "Unsuccess ful" message from the compile/run loop unless the compiler completely bombs out. This is from my _vimrc... map <F5> :call CompileRunGcc()<CR> map <F8> : call CompileGcc()<CR> func! CompileRunGcc() exec "w" "Save the file exec "!gcc % -o %< && cr 10 && IF EXIST %<.exe (%<) ELSE banner -c = Compile Unsuccessful " exec "i" "jump back where we were endfunc func! CompileGcc() exec "w" exec "!gcc % -o %< && IF EXIST %<.exe (cr 5 && banner -c # Succ ess) ELSE banner -c # Compile Unsuccessful " exec "i" endfunc

VimTip 265: Fast help in full window

http://vim.sf.net/tip_view.php?tip_id=265 You can get fast access to help by writing small script #!/bin/bash vim -c "help $1" -c only now name it eg. vih and from cl $ vih makeprg

VimTip 266: use -S command line switch http://vim.sf.net/tip_view.php?tip_id=266 The -S switch could be used to simplify common idiom: start Vim and source a scr ipt file: gvim -c ":so foobar.vim" got translated into gvim -S foobar.vim Yes, this tip is trivial but I still see the -c ":so x" way too often. Time to u pdate your mind!

VimTip 267: selectively displaying abbreviations http://vim.sf.net/tip_view.php?tip_id=267 Hi Vimmers, abbreviations have always been one of the most useful parts of vi(m), trouble is when you've got too many you forgot what you called them. You can of course list the whole lot with :ab<cr> But did you know that you can type the first few letters of your abbreviations a nd get a list of just thos abs eg :ab php<cr> gives me all my php abs & :ab perl<cr> gives me all my perls also try control-D instrad of <cr> zzapper

VimTip 268: Get cursor position as byte percentage instead of line percentage http://vim.sf.net/tip_view.php?tip_id=268 On line 300 of a thousand line file, Vim will show you that you're 30% through t he file. But what if most of the lines have one character in them, and some of them have twenty thousand? Sometimes it comes in handy to know your percentage through the file in terms of current-byte / total-bytes. I looked through the V im docs and couldn't find a way to do this, so I wrote a Vim function to show it . Put this in your .vimrc: function! Percent() let byte = line2byte( line( "." ) ) + col( "." ) - 1 let size = (line2byte( line( "$" ) + 1 ) - 1) " return byte . " " . size . " " . (byte * 100) / size return (byte * 100) / size endfunction (Uncomment the first return to see intermediate values.) And put this somewhere in your "set statusline=...": %{Percent()}%% See "help statusline", "help eval".

VimTip 269: Syntax highlighting is "out of sync", seems to correct itself with r efresh ?? http://vim.sf.net/tip_view.php?tip_id=269 This one has come across the 'vim' users mailing list many times, and probably comp.editors as well... Summary: see :help :syn-sync and search for 'sync' in your favorite syntax file in $VIMRUNTIME/syntax Long Version: The syntax highlight code utilizes a certain synchronization method to efficient ly figure out syntax highlighting, specifically if you aren't at the very beginning or end of a file. The specific setting is 'syntax sync'. For various file types t he method is set by default in this is setup in the syntax file and one can vary the degree of trouble which VIM goes to to try and figure this out. As an examp le for C, from $VIMRUNTIME/syntax/c.vim: if exists("c_minlines")

let b:c_minlines = c_minlines else if !exists("c_no_if0") let b:c_minlines = 50 " #if 0 constructs can be long else let b:c_minlines = 15 " mostly for () constructs endif endif exec "syn sync ccomment cComment minlines=" . b:c_minlines Where c_minlines is the minimum number of lines that VIM goes backward to try to find the start of a comment for syntax highlighting. If that line whi ch starts a comment is outside of that range, highlighting will appear wrong. You can easily set up something like this in your .vimrc: let c_minlines=500 or even bigger, but realize that it is a performance trade-off and that syntax highlighting will slow things down.

VimTip 270: Insert a single character http://vim.sf.net/tip_view.php?tip_id=270 Using Insert mode to insert a single character feels clumsy (you need 3 keypresses for one character), so here's a slightly easier way: :nmap <space> i_<esc>r Now, when in Normal mode, just press space followed by what it is you want to insert. BUG: Repeating the insertion with . doesn't work.

VimTip 271: easy (un)commenting out of source code http://vim.sf.net/tip_view.php?tip_id=271 Something that I do quite alot is comment out blocks of text, only to uncomment that same block later. The following mappings have proven useful to me. They can be applied using visually selected blocks, or with motion keys. " lhs comments map ,# :s/^/#/<CR> map ,/ :s/^/\/\//<CR> map ,> :s/^/> /<CR> map ," :s/^/\"/<CR> map ,% :s/^/%/<CR> map ,! :s/^/!/<CR> map ,; :s/^/;/<CR>

map ,- :s/^/--/<CR> map ,c :s/^\/\/\\ ^--\\ ^> \\ ^[#"%!;]//<CR> " wrapping comments map ,* :s/^\(.*\)$/\/\* \1 \*\//<CR> map ,( :s/^\(.*\)$/\(\* \1 \*\)/<CR> map ,< :s/^\(.*\)$/<!-- \1 -->/<CR> map ,d :s/^\([/(]\*\\ <!--\) \(.*\) \(\*[/)]\\ -->\)$/\2/<CR> The commands to comment a selection of text are as follows, begining with begini ng-of-line comments: ,# ,/ ,> ," ,% ,! ,; ,,c shell, perl, etc c++ email quote vim latex, prolog assembly?... add single ! scheme don't remember this one... add -clears any of the previous comments

Here are the wrapping comments, each line wrapped individually: ,* ,( ,< ,d c Standard ML html clears any of the wrapping comments

VimTip 272: automaticaly formating pasted text (p=`]) http://vim.sf.net/tip_view.php?tip_id=272 In times past I used a nice editor that had the neat feature of automatically se tting pasted text to the proper indent level. Recently I've begun to miss this s o I went looking in the help and camp up with.... =`] which will format to the end of the pasted text... Perfect to call right after y ou past something as the cursor ends up at the top of the pasted text, thus the mapping: :map <c-p> =`] " by the by the above may should be nmap and I am pretty sure c-p is unused, you r mileage will vary no doubt. However I wanted the formatting to automatically be done so it was two simple (o nce I figured out how!) nnoremap: " [Feral:185/02@14:27] map c-p to what p was (past with no formatting), map p to p and = to end of pasted text. :nnoremap p p=`] :nnoremap <c-p> p

This simply (as the comment hints at) maps normal mode p to what p did (paste) t hen = to `] (last character in the previously changed text). While ctrl+p just d oes what p did. (just in case you find you don't want a bit of text auto formatt ed.). reference: :h :nnoremap :h p :h = :h `] Whatever the name of this idea is, tis something I find handy :) Happy VIMing

VimTip 273: Fast fixing of email quotations (too long lines) http://vim.sf.net/tip_view.php?tip_id=273 When using VIM as your editor of choice, even for email processing - as I do - i t is often unpleasing how some MUA's quote the email body produced by mailers su ch as Outlook. The lines often span across multiple visual lines and its difficu lt to reply on certain parts of it. With VIM, you can quickly fix those quotations to maintain a proper 75 char brea k. For example, when using Mutt, put this line in your .muttrc, or use a custom .vimrc_mail for it: set editor="vim -c 'set fo=tcrq' -c 'set tw=76'" For other MUA's this has to be fitted. However, now, when your quoted email is d isplayed, you can use this VIM sequence to fix it: 1. move cursor to first line of broken paragraph 2. press 'V' and move to the last line of the paragraph you want to fix 3. press 'g' and then 'q'. The marked text will wrap around to your specified te xtwidth (76 in our case) and the quotations will be preserved across the lines

VimTip 274: Some useful mappings for TeX http://vim.sf.net/tip_view.php?tip_id=274 You know, TeX requires a lot of additional formatting code. I'm tired of opening and closing braces, brakets, \beginning and \ending etc. I particularly hate typing \begin and \end. To help myself and to save a few(not a few) keystrokes I naturaly came up to som e solutions, which I wish to share with other TeXnicians and TeXperts whhich use Vim. "===============================cut here=========================

"=============== you can put it in ~/.vim/after/ftplugin/tex.vim =============== " " Note: i_<C-L> " This constructs a skeleton of a TeX environment. " You write a line like this: " floatingfigure:ht<C-L> " and after you press <C-L>, you get: " " \begin[ht]{floatingfigure} " " \end{floatingfigure} " -- INSERT -" " where floatingfigure is the desired environment " ht are options " : is delimiter; in fact, you can use whatever delimiter you want " as long it is not in &iskeyword option. inoremap <buffer> <C-L> \:s/[^][:alnum:]<bar>]\+/,/eg \I\begin{ea}[A]%d%%P \:s/\[,/[/e \:s/,]/]/e \:s/\[]//e \0f{y%o\endpO inoremap <buffer> { {}i inoremap <buffer> [ []i inoremap <buffer> ^ ^{}i inoremap <buffer> _ _{}i inoremap <buffer> \( \(\)hi inoremap <buffer> \[ \[\]hi " Note: v_<C-L> " For this to work, you have to write on a blank line the name of " the desired environment and options (see i_<C-L>) and visual select " (from top to bottom) this and following lines. " After pressing <C-L> the selected lines will be surrounded " with begin/end skeleton of the environment. vnoremap <buffer> <C-L> o \:s/[^][:alnum:]<bar>]\+/,/eg \I\begin{ea}[A]%d%%P \:s/\[,/[/e \:s/,]/]/e \:s/\[]//e \0f{y%gvo\endp " vnoremap <buffer> { di{}P " vnoremap <buffer> [ di[]P vnoremap <buffer> di^{}P vnoremap <buffer> di_{}P vnoremap <buffer> \( di\(\)hP vnoremap <buffer> \[ di\[\]hP " This makes "two spaces after a comma" before every :write au BufWritePre *.tex %s/,\(\S\)/, \1/ge "==================== You can put this in your ~/.vimrc ======================== " If cursor is inside braces and not before comma, blank or opening brace, " exit the brace block and stay in insert mode. " If cursor is outside braces, it inserts a space or perform an abbreviation " as normal. function! CleverSpace()

let CharOnCursor = strpart( getline('.'), col('.')-2, 1) let CharAfterCursor = strpart( getline('.'), col('.'), 1) if CharOnCursor !~ ',\ \s\ (' && CharAfterCursor =~ ')\ ]\ }' normal x endif endfunction inoremap <Space> <Space>:call CleverSpace()<LF>a " I use the last function not only for LaTeX but also in C sources.

VimTip 275: Some useful mappings for TeX http://vim.sf.net/tip_view.php?tip_id=275 You know, TeX requires a lot of additional formatting code. I'm tired of opening and closing braces, brakets, \beginning and \ending etc. I particularly hate typing \begin and \end. To help myself and to save a few(not a few) keystrokes I naturaly came up to som e solutions, which I wish to share with other TeXnicians and TeXperts whhich use Vim. "===============================cut here========================= "=============== you can put it in ~/.vim/after/ftplugin/tex.vim =============== " " Note: i_<C-L> " This constructs a skeleton of a TeX environment. " You write a line like this: " floatingfigure:ht<C-L> " and after you press <C-L>, you get: " " \begin[ht]{floatingfigure} " " \end{floatingfigure} " -- INSERT -" " where floatingfigure is the desired environment " ht are options " : is delimiter; in fact, you can use whatever delimiter you want " as long it is not in &iskeyword option. inoremap <buffer> <C-L> \:s/[^][:alnum:]<bar>]\+/,/eg \I\begin{ea}[A]%d%%P \:s/\[,/[/e \:s/,]/]/e \:s/\[]//e \0f{y%o\endpO inoremap <buffer> { {}i inoremap <buffer> [ []i inoremap <buffer> ^ ^{}i inoremap <buffer> _ _{}i inoremap <buffer> \( \(\)hi inoremap <buffer> \[ \[\]hi " " " " Note: v_<C-L> For this to work, you have to write on a blank line the name of the desired environment and options (see i_<C-L>) and visual select (from top to bottom) this and following lines.

" After pressing <C-L> the selected lines will be surrounded " with begin/end skeleton of the environment. vnoremap <buffer> <C-L> o \:s/[^][:alnum:]<bar>]\+/,/eg \I\begin{ea}[A]%d%%P \:s/\[,/[/e \:s/,]/]/e \:s/\[]//e \0f{y%gvo\endp " vnoremap <buffer> { di{}P " vnoremap <buffer> [ di[]P vnoremap <buffer> di^{}P vnoremap <buffer> di_{}P vnoremap <buffer> \( di\(\)hP vnoremap <buffer> \[ di\[\]hP " This makes "two spaces after a comma" before every :write au BufWritePre *.tex %s/,\(\S\)/, \1/ge "==================== You can put this in your ~/.vimrc ======================== " If cursor is inside braces and not before comma, blank or opening brace, " exit the brace block and stay in insert mode. " If cursor is outside braces, it inserts a space or perform an abbreviation " as normal. function! CleverSpace() let CharOnCursor = strpart( getline('.'), col('.')-2, 1) let CharAfterCursor = strpart( getline('.'), col('.'), 1) if CharOnCursor !~ ',\ \s\ (' && CharAfterCursor =~ ')\ ]\ }' normal x endif endfunction inoremap <Space> <Space>:call CleverSpace()<LF>a " I use the last function not only for LaTeX but also in C sources.

VimTip 276: Function signature previewer http://vim.sf.net/tip_view.php?tip_id=276 Have you ever tried to call a function which parameters you have forgotten? Especially those long named and with long parameter list GTK+ functions like gtk_menu_item_image_from_stock_new(..........) !!! By accident I saw a function in Vim help. It's name was PreviewWord and it allow ed one to jump in the preview window to the tag for the word cursor is on. I _slightly_ modified this function not to need tags file, but to search include d files instead. I wrote another function, which uses the above said one, which triggers PreviewW ord when you open the parenthesis after a function name. Here it is: " Note: " This is literally stolen from Vim help. The only changes are: " (1) if w != "" becomes if w =~ "\k" " (2) exe "silent! ptag " . w becomes exe "silent! psearch " . w " * The first change prevents PreviewWord of searching while cursor is on some

" non-keyword characters, e.g. braces, asterisks, etc. function! PreviewWord() if &previewwindow " don't do this in the preview w indow return endif let w = expand("<cword>") " get the word under cursor if w =~ "\k" " if there is one ":ptag" to it " Delete any existing highlight before showing another tag silent! wincmd P " jump to preview window if &previewwindow " if we really get there ... match none ght wincmd p endif " Try displaying a matching tag for the word under the cursor let v:errmsg = "" exe "silent! psearch " . w if v:errmsg =~ "tag not found" return endif silent! wincmd P " jump to preview window if &previewwindow " if we really get there... if has("folding") silent! .foldopen " don't want a c losed fold endif call search("$", "b") e let w = substitute(w, '\\', '\\\\', "") call search('\<\V' . w . '\>') " position cursor on mat ch " Add a match highlight to the word at this position hi previewWord term=bold ctermbg=green guibg=green exe 'match previewWord "\%' . line(".") . 'l\%' . col(". ") . 'c\k*"' wincmd p endif endif endfunction au! CursorHold *.[ch] nested call PreviewWord() " Note: " When you open a parenthesis after a function name, and at the " line end, that function's definition is previewed through PreviewWord(). " This is inspired from Delphi's CodeInsight technology. " Something similar (PreviewClassMembers) could be written for " the C++ users, for previewing the class members when you type " a dot after an object name. " If somebody decides to write it, please, mail it to me. function! PreviewFunctionSignature() let CharOnCursor = strpart( getline('.'), col('.')-2, 1) if col(".") == col("$") call PreviewWord() endif return "(" " back to old window " to end of previous lin " back to old window " delete existing highli

endfunction inoremap <buffer> ( <C-R>=PreviewFunctionSignature()<LF>

VimTip 277: Function signature previewer http://vim.sf.net/tip_view.php?tip_id=277 Have you ever tried to call a function which parameters you have forgotten? Especially those long named and with long parameter list GTK+ functions like gtk_menu_item_image_from_stock_new(..........) !!! By accident I saw a function in Vim help. It's name was PreviewWord and it allow ed one to jump in the preview window to the tag for the word cursor is on. I _slightly_ modified this function not to need tags file, but to search include d files instead. I wrote another function, which uses the above said one, which triggers PreviewW ord when you open the parenthesis after a function name. Here it is: " Note: " This is literally stolen from Vim help. The only changes are: " (1) if w != "" becomes if w =~ "\k" " (2) exe "silent! ptag " . w becomes exe "silent! psearch " . w " * The first change prevents PreviewWord of searching while cursor is on some " non-keyword characters, e.g. braces, asterisks, etc. function! PreviewWord() if &previewwindow " don't do this in the preview w indow return endif let w = expand("<cword>") " get the word under cursor if w =~ "\k" " if there is one ":ptag" to it " Delete any existing highlight before showing another tag silent! wincmd P " jump to preview window if &previewwindow " if we really get there ... match none ght wincmd p endif " Try displaying a matching tag for the word under the cursor let v:errmsg = "" exe "silent! psearch " . w if v:errmsg =~ "tag not found" return endif silent! wincmd P " jump to preview window if &previewwindow " if we really get there... if has("folding") silent! .foldopen " don't want a c losed fold endif " back to old window " delete existing highli

call search("$", "b") e

" to end of previous lin

let w = substitute(w, '\\', '\\\\', "") call search('\<\V' . w . '\>') " position cursor on mat ch " Add a match highlight to the word at this position hi previewWord term=bold ctermbg=green guibg=green exe 'match previewWord "\%' . line(".") . 'l\%' . col(". ") . 'c\k*"' wincmd p endif endif endfunction au! CursorHold *.[ch] nested call PreviewWord() " Note: " When you open a parenthesis after a function name, and at the " line end, that function's definition is previewed through PreviewWord(). " This is inspired from Delphi's CodeInsight technology. " Something similar (PreviewClassMembers) could be written for " the C++ users, for previewing the class members when you type " a dot after an object name. " If somebody decides to write it, please, mail it to me. function! PreviewFunctionSignature() let CharOnCursor = strpart( getline('.'), col('.')-2, 1) if col(".") == col("$") call PreviewWord() endif return "(" endfunction inoremap <buffer> ( <C-R>=PreviewFunctionSignature()<LF> " back to old window

VimTip 278: all the right moves http://vim.sf.net/tip_view.php?tip_id=278 One of the principles of effective text editing is moving around very efficientl y. Following are some pointers which may help u do that. h j k l w b e W B E move one character left move one row down move one row up move one char. right. move to begining of next word move to begining of previous word move to end of word move to begining of next word after a whitespace move to begining of pervious word before a whitespace move to end of word before a whitespace.

(All the above movements can be preceeded by a numeric value . i.e '4j' will mo ve 4 rows down ) ^ move to first non blank char of the line.

g_ 0 $ gg G nG H M L Ctrl-D Ctrl-U Ctrl-B Ctrl-F

move to last non blank char of the line. moev to begining of line move to end of line. move to first line. move to last line. move to "n"th line. top of screen. middle of screen bottom of screen move half page down move half page up. page-up page down. m

Ctrl-o last cursor position. '[a-z,0-9,A-Z] jump to the marker. (u can set a marker on line by :[a-zA-Z,0-9] and then jump back to it by '[a-z,A-Z0-9] n next matching search pattern N previous matching search pattern * next word under cursor # previous word under cursor. g* next matching search pattern under cursor. g# previous matching search pattern under cursor.

VimTip 279: On Windows, make GVim the default action for double-click with "unkn own file types" http://vim.sf.net/tip_view.php?tip_id=279 I find myself installing the following registry modification for all my PC's now (even other people's PC's). It applies to Microsoft Windows machines only. Th e following is also for Windows 9x... NT or XP or 2000 may require modification s (which I don't care to understand!). The problem: You double-click on a file that doesn't have a 'registered type' an d that pesky "What program should I use?" dialog pops up. Even worse, depending on the installation, the GVim icon may not be listed, and one has to browse to the executable... and then the type becomes forever bonded to being editted wit h GVim (if that box is checked). The standard Vim 6.1 installation does include a "right click to edit" menu item for all files, but a double-click is so much faster! The solution: What if unregistered types would just automatically open up in GVi m? Well, they can.. with a little registry trickery. How to Install it: Step 1. Create a text file called "vimalways.reg" and paste the below text into it. Step 2. Important NOTE: You will have to edit the pathname to correspond to the pathname of your GVim.exe. The text below works fine for a GVim 6.1 default in stallation.

Step 3: Save the file. Step 4: Right-click on the file and select "install". Then you are done! ------ vimalways.reg ------- cut here ------snip---snip--REGEDIT4 [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\*\shell] [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\*\shell\Open with &GVim] @="Open with &GVim" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\*\shell\Open with &GVim\command] @="\"C:\\vim\\vim61\\gvim.exe\" \"%1\"" ----end of file---- cut here----- snip---snip---Note 1. This can't be de-installed automatically, and if you want to remove it, you'll have to edit the registry by hand (annoying, but easy). Note 2. Keep this file around, so when you upgrade your GVim, all you have to d o is modify the pathname (to say, for example, vim62) and then install it again.

Ok, thanks for playing! And thanks to the author(s) of Vim and GVim. If it weren't for them, I'd still be using elvis or stevie!

VimTip 280: Integration with PyUnit testing framework http://vim.sf.net/tip_view.php?tip_id=280 Vim has a wonderful ability to integrate with external tools, like compilers, ma ke, ctags etc. That's one of the reasons we love it. PyUnit can be seen as a "compiler" for the Python test code. To understand it, Vim should be told about the language the PyUnit speaks. This could be done with 'errorformat' option: setlocal efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m This magic spell enables Vim to parse unittest.TextRunner's output and to enter quick-fix mode. To run all your unit tests at once you'll need to setup 'makeprg' option and pro vide a runner. I'm using this setup: setlocal makeprg=./alltests.py And contents of the alltests.py (for the sake of completeness):

#!/usr/bin/env python2 import unittest import sys sys.path.append('unittests') modules_to_test = ( 'fooTest', 'barTest', 'bazTest', ) def suite(): alltests = unittest.TestSuite() for module in map(__import__, modules_to_test): alltests.addTest(unittest.findTestCases(module)) return alltests if __name__ == '__main__': unittest.main(defaultTest='suite') ============== end of the alltests.py file ======================== While talking about it, I'd also suggest to add a couple of mappings. In the end, my vim/files/ftplugin/python.vim looks like this: setlocal makeprg=./alltests.py\ -q setlocal efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m iabbr <buffer> sae self.assertEquals iabbr <buffer> sar self.assertRaises

For details see :help quick-fix, :help 'efm' and :help 'makeprg'. See also: http://c2.com/cgi/wiki?PythonUnit Many thanks to Stefan Roemer who patiently spent quite some time to build 'efm' for me.

VimTip 281: Stateful zz http://vim.sf.net/tip_view.php?tip_id=281 Do you find yourself hitting 'zz' all the time in order to see some context of w hat you're currently working on? If so, then this tip might be for you. If you add the foll owing line in your vimrc, you can toggle zz mode by pressing <Leader>zz. " maintain a constant zz state, second call will toggle it back off map <Leader>zz :let &scrolloff=999-&scrolloff<CR>

VimTip 282: Folding with Regular Expression http://vim.sf.net/tip_view.php?tip_id=282 Well, I've tried to understand some of the folding scripts, but life's too short. Instead, I added the following lines to my vimrc file. set foldexpr=(getline(v:lnum)=~@/)?0:(getline(v:lnum-1)=~@/)\ \ (getline(v:lnum+ 1)=~@/)?1:2 map \z :set foldmethod=expr foldlevel=0 foldcolumn=2<CR> The first line is an extension of foldexpr=(getline(v:lnum)=~@/)?0:1 The second line (re)sets the foldmethod to expr(ession) plus. First search for /regexp/, then fold everything else with \z Use zr to reveal more context (before/after) lines. You could add (getline(v:lnum-2)=~@/)\ \ (getline(v:lnum+2)=~@/)?2:3 but it will take longer as folded lines (the majority) evaluate the full express ion. What could be easier?

VimTip 283: Turn on syntax coloring in Mac OS X http://vim.sf.net/tip_view.php?tip_id=283 This tip is actually for vim 6.1. To turn on syntax coloring in Mac OS X enter t he following commands, or place them in your $HOME/.vimrc file. :set term=builtin_beos-ansi :syntax on

VimTip 284: Mapping to print syntax highlighted buffer in B&W http://vim.sf.net/tip_view.php?tip_id=284 I use this mapping to print syntax highlighted C++ code in B&W This tip needs vimscript #233 print_bw. The mapping is as follows map <C-p> :color print_bw<CR>:hardcopy<CR>:color sean<CR>:syn on<CR> Change ":color sean" to whatever is your chosen color scheme.

Need to change line 7 of print_bw from "syntax reset" to "syntax off" <C-p> on a syntax highlighted buffer turns off syntax highlighting , sets the co lors to B&W, prints the buffer, resets the color scheme and turns on syntax high lighting again.

VimTip 285: Don't use the escape key! http://vim.sf.net/tip_view.php?tip_id=285 Vim (any vi really) is a dream for touch typists... Until you want to switch fro m insert mode to normal mode. Then you've got to reach way up to whack the esca pe key. Or at least that's what I was doing until I realized that (drum roll please) Esc is exactly equivalent to control-[ (that's the control key plus the left square bracket key) That little bit of knowledge, plus mapping my caps lock to another control key, was what turned my fascination with Vim into true love. You never have to lose track of the home row again! For Xfree86 users - you can make the capslock key another control key by adding Option "XkbOptions" "ctrl:nocaps" to the InputDevice section of your XF86Config file. For Windows NT/2000 users - use the following .reg file to do the same thing: REGEDIT4 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout] "Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,1d,00,3a,00,00,00,00,00

VimTip 286: Recover after doing something... ugly. http://vim.sf.net/tip_view.php?tip_id=286 I was once editing a file and wanted to test something. The test was meant to ad d a line at the end of the file, from outside vim. All was fine, but instead of >>, I wrote >. You can imagine what happened... :) If you happen to do something like that, the solution is: :recover

VimTip 287: Cool trick to change numbers http://vim.sf.net/tip_view.php?tip_id=287 In the gvim if you want to decrement any number just put ur curcor on that numbe r in Esc mode and pres <CTRL> X

VimTip 288: A keymapping to generate Java setters and getters automatically http://vim.sf.net/tip_view.php?tip_id=288 This mapping makes it much simpler to write new java classes by simplifying some of the dull repetative coding (ie setters and getters). To use, first write a basic class with the following format: public class MyClass { private <type> <varname> = <initvalue>; private <type> <varname> = initvalue>; // getters // setters } Note the getters/setters comment -- they are important as they are used to place the getters and setters. The mapping is: map jgs mawv/ <Enter>"ty/ <Enter>wvwh"ny/getters<Enter>$a<Enter><Enter>public <E sc>"tpa<Esc>"npbiget<Esc>l~ea()<Enter>{<Enter><Tab>return <Esc>"npa;<Enter>}<Esc >=<Enter><Esc>/setters<Enter>$a<Enter><Enter>public void <Esc>"npbiset<Esc>l~ea( <Esc>"tpa <Esc>"npa)<Enter>{<Enter><Tab>this.<Esc>"npa=<Esc>"npa;<Enter>}<Esc>=< Enter>`ak (the above should be one long line with no spaces between the end of the lines a bove). To use this to generate a class go to the variable that should have a setter/get ter and place the curser at the beginning of the 'private': private <type> <variable> = <initvalue>' ^ Then type:

jgs this will create the first getter/setter and then move up to the next variable. You can just keep typing jgs until all the getters/setters have been generated . This should mapping isn't perfect and someone could probably make it a little cl eaner. It could also relatively easily be adapted to C++. Please feel free to send me any feedback/enhancements as I am trying to compile a list of these.

VimTip 289: Alternative <escape> that allows you to do a "quick and dirty insert " and get out into normal mode http://vim.sf.net/tip_view.php?tip_id=289 This is an alternative key combo for the escape key from the one mentioned by Da vid A. Rogers in vimtip #285. I do a lot of editting in Vim, and I've always found myself in situations where I had to "do a quick insert" - basically (from normal mode), change into insert mode, type in one quick word, then <esc> out, then navigate elsewhere. As has been rightly observed by a lot of people, the <esc> key can sometimes be a little bit out of the way. But that's no problem for ViM, is it? At first, I thought of editting the ViM source code itself, in order to come up with a command that could do things like say "let me jump into insert mode, type a few quick words, then escape out into normal mode when i press something like double <space>". It was only later when reading through the section in Jesse Goerz's "Beginner's Guide to ViM" on remapping (http://newbiedoc.sourceforge.net/tutorials/vim/mappi ng-vim.html) that I got inspired to retake a look at using remapping as an alter native instead. This is what I came up with.. Use whatever is comfortable for you - single or do uble <Shift-space> :map! <S-space> <esc> :map! <S-space><S-space> <esc> With this quick combo ("Shift", + <space>), one can easily (and might I add, int uitively) "do a quick insert" and exit quickly out into normal mode. I guess I a lways thought the <space> would be a good way to do this sort of thing, since it is after all, so intuitive in the typing process. So why not make it such that it can "escape" you out into normal mode as well? Just type 'i', to go into inse rt mode, type in your stuff, and once you're done, hit Shift-space!

VimTip 290: Text Processing With Integrated Spell Checking http://vim.sf.net/tip_view.php?tip_id=290 I have written an HTML document to help others use Vim as a basic text processin g application. It discusses how to integrate spell checking, dictionary, and the saurus applications. It also talks about wrapping lines, indentation, justificat ion, and the vim settings that effect the behavior of these operations. The docu ment can be found at: http://www.highley-recommended.com/text-processing.html Everything has been tested with UNIX, Linux, Windows, and Windows with Cygwin pa tforms.

VimTip 291: ^P & auto filling of variables and text http://vim.sf.net/tip_view.php?tip_id=291 Do you know you can auto fill the variable and names as you type your code ? Thi s will help most of the programmers, who always try hard to remember the variabl e names and browse through all the files to find out the variable name. Use Ctrl+P and Ctrl+N to autofill the variables names etc. Just practice, you will feel the ease of using vim

VimTip 292: vim + cscope + cygwin http://vim.sf.net/tip_view.php?tip_id=292 I've found that vim + cscope + cygwin does not work. The problem seems to be tha t in sprintf(cmd, "exec %s -dl -f %s", prog, csinfo[i].fname); vim execs cscope with the "-dl" options, causing it to fail. It is probably a cs cope bug, but a simple workaround is top build vim without thad "d": sprintf(cmd, "exec %s -l -f %s", prog, csinfo[i].fname); seems to work for me!

VimTip 293: remember where you had ended reading help http://vim.sf.net/tip_view.php?tip_id=293 You could jump to the last place you had been while reading Vim help files if yo

u add this to your .vimrc file: au BufLeave * if &ft == "help" Then use 'H to go to the mark H. To work between Vim runs 'viminfo' option should be setup to save file marks. See :help 'viminfo' and :help file-marks for more information. mark H endif

VimTip 294: Use Ctrl-S to save current or new files. http://vim.sf.net/tip_view.php?tip_id=294 I wanted to have a single key stroke that would save existing files, or call the file browser. Here's a key map for Ctrl-S to accomplish that (place in vimrc file): if has("gui_running") " If the current buffer has never been saved, it will have no name, " call the file browser to save it, otherwise just save it. :map <silent> <C-S> :if expand("%") == ""<CR>:browse confirm w<CR>:else<CR>:co nfirm w<CR>:endif<CR> endif Tom Kimpton

VimTip 295: Line/word/file/whatever completion http://vim.sf.net/tip_view.php?tip_id=295 In addition to vimtip #291 you can use whole <C-x> completion mode. It can compl ete whole lines (<C-x>l, then <C-p>, <C-n>), filenames (<C-f>), keywords, words from custom dictionary and many, many others. During coding it usually saves a L OT of key strokes ;) This mode has many other powerful features, for example whe n completing word (by <C-x><C-p> or just by <C-p>) you can continue completion w ith another <C-x><C-p>. For example, after writing such text: this is first line second line is here Placing cursor at third line and pressing <C-x>l will double last line - <C-n>, <C-p> in this moment can be used to manipulate completed line. Or, instead of co mpleting whole line you can press 'f' and then complete by <C-p> which will resu lt in 'first' word. After that you can <C-x><C-p> to get 'line' word (since this is next word after 'first'). Try yourself for other powerful combinations.

VimTip 296: Attach the currently open file to email http://vim.sf.net/tip_view.php?tip_id=296 This is very simple, but most people don't seem to take advantage of this. Often you have some file (source code or other text file) already open in an existing vim session and you need to attach it with an email. It is very simple. - First copy the filename into clipboard. For this I put the following mappi ng in vimrc and press <F2>: nnoremap <F2> :let @*=expand("%:p")<cr> - Go to your email compose window and use your regular file attachment menu (Insert->File in outlook) and press ^V (or whatever key to paste clipboard) and press Enter. That is all there to it. If you are on windows and your email client doesn't acc ept forward-slashes, then you might want to change the map to: nnoremap <F2> :let @*=substitute(expand("%:p"), "/", "\\", "g")<cr> HTH, Hari

VimTip 297: Start in insert mode without loosing your escape key http://vim.sf.net/tip_view.php?tip_id=297 There are two parts to this, each is fairly simple. First, I want to start in insert mode. Well "set im!" in my vimrc did the job, but I lost the escape key. Second, I have found that often times, when I'm in command mode, I hit escape tr ying to get back into insert mode. I am always rewarded with a beep, telling me once again I made that mistake. So I mapped esc in command mode to set insert mode (":set im") and I mapped esc in insert mode to unset insert mode (<c-o>:set im) Well then I realized if you hit "i" in command mode, escape woulding work the first time. So here's the cod e to add to your vimrc: set im! map <esc> :set im!<cr> map i :set im!<cr> map! <esc> <c-o>:set im!<cr> see :help insert " " " " start in insert mode escape in command mode goes to insert mode i in command mode goes to insert mode escape in insert mode goes to command mode

VimTip 298: Changing case with regular expressions http://vim.sf.net/tip_view.php?tip_id=298 I stumbled across this factoid on a website about vi. I haven't been able to loc

ate it in the Vim documentation, but it works in Vim, and it's very handy. There are times that you might like to go through a file and change the case of characters that match some arbitrary criteria. If you understand regular express ions well, you can actually do this fairly easily. It's as simple as placing \U or \L in front of any backreferences in your regula r expressions. Vim will make the text in the backreference uppercase or lowercas e (respectively). (A "backreference" is a part of a regular expression that refers to a previous p art of a regular expression. The most common backrefernces are &, \1, \2, \3, .. . , \9). Some examples that demonstrate the power of this technique: Lowercase the entire file :%s/.*/\L&/g (& is a handy backreference that refers to the complete text of the match.) Uppercase all words that are preceded by a < (i.e. opening HTML tag names): :%s/<\(\w*\)/<\U\1/g Please add a note if you know where this is in the documentation. I have done Ct rl-D searches on upper, lower, \U, and \L with no luck.

VimTip 299: Open file under cursor. http://vim.sf.net/tip_view.php?tip_id=299 A little thing that I did and found quite useful: function! OpenFileUnderCursor() let FileName = expand("<cfile>") let OldPath = getcwd() silent cd %:p:h execute "silent sp +e " . FileName execute "silent cd " . OldPath endfunction map! silent <M-e> :call OpenFileUnderCursor()<CR> Then use Alt+E on a filename to open it (relative to the directory the current f ile resides in).

VimTip 300: Making a tags file for IDL (Interactive Data Language) http://vim.sf.net/tip_view.php?tip_id=300 I have recently began using the tags features of vim (:help tags) with my fortra n codes and come to appreciate their power. I also do a lot of coding in IDL (I

nteractive Data Language), but found that ctags did not have native support for IDL. If you take the time you can learn how to get ctags to support IDL, but I found, after a search of usenet, that someone else has already done this and wri tten a perl script called idltags. It is part of an emacs package (is anyone st ill reading?) that you need to download, called idlwave, which is located at: http://idlwave.org/ and currently (I don't know if this will change) the direct download link is http://idlwave.org/download/idlwave.tar.gz In the usenet pages the maintainer, JD Smith, was suggesting that idlwave had ou tgrown idltags and was not sure it was still needed, so I don't know how long it will be available.

VimTip 301: Edit files in path, or related. http://vim.sf.net/tip_view.php?tip_id=301 You can write a little shell function that will let you easily edit any file tha t is in the path, or which's location can be retrieved with the whereis tool. Th is is something similar to what I have in /etc/profile: function vvim() { vim `whereis $1 cut -d: -f2` } function ggvim() { gvim `whereis $1 cut -d: -f2` } Then just type, for example, "vvim ls", and you'll start vim with /bin/ls and /u sr/share/man/ls.1.gz loaded :) (it's not very useful to edit /bin/ls, but you get the ideea ;)

VimTip 302: Use gvim in kmail http://vim.sf.net/tip_view.php?tip_id=302 To automatically open gvim to edit in kmail, "-f" command line option must be us ed . In kmail configuration go to the composer settings , and write in the "use exter nal editor" field the following command : "gvim -f %f" Without -f option gvim would work in background and editing would not have any e ffect on kmail.

VimTip 303: Statusline Tab Level Function Ruler TVIM http://vim.sf.net/tip_view.php?tip_id=303 I use this function to let me know if my cursor is on a TAB column. The t* on the ruler means I am not. But t3 means the cursor is on tablevel 3 ~vimrc ----------------------- My Ruler ------------------------ r4,c13,t3

~vimrc ----------------------- My Ruler ------------------------ r4,c14,t* If you want to change a tab level you can drag or push the first character of a line to a desired tab level. (more on that later) This ruler replacement will let you know where you are, whether you like to use space tabs (see vimtip #12 ) or regular tabs. My function is set to four space tabs stops and only goes 9 levels but can be easily modified. Actually I just wanted to learn how to use a function in my _vimrc and this was my first attempt. Add this to your _vimrc "--------------------cut-----------------set laststatus=2 "This makes sure the ruler shows. See help laststatus set statusline=%f\ ---------\ My\ Ruler\ ----------\ r%l,c%c,t%{ShowTab()} "See help statusline (I toggle between 12 helpful rulers -- more on that later) fu ShowTab() let TabLev='*' let Col=(col(".")) if Col == 1 let TabLev='0' en if Col == 5 let TabLev='1' en if Col == 9 let TabLev='2' en if Col ==13 let TabLev='3' en if Col ==17 let TabLev='4' en if Col ==21 let TabLev='5' en if Col ==25 let TabLev='6' en if Col ==29 let TabLev='7' en if Col ==33 let TabLev='8' en if Col ==37 let TabLev='9' en return TabLev endf "The ruler (statusline) shows a t* unless you are on col 1,5,9,13,... "-------------------cut------------------This function ShowTab() gets called and updates the ruler with every cursor move but it does not slow things down as I type. Perhaps a speed typist may complain :-) In case I write something else you may search on the key word TVIM Best Wishes TVIM Tamed Vim paradocs@frontiernet.net

VimTip 304: fold braces and javadoc http://vim.sf.net/tip_view.php?tip_id=304 If you'd like to have javadoc folded together with areas in braces try that <pre> set foldmethod=syntax set foldenable syn region foldBraces start=/{/ end=/}/ transparent fold syn region foldJavadoc start=,/\*\*, end=,\*/, transparent fold keepend </pre> and play a bit with: <pre> set foldlevel=0 set foldnestmax=10 </pre> parameters

VimTip 305: Best of VIM Tips (VIM's best Features) http://vim.sf.net/tip_view.php?tip_id=305 Here's a necessarily cryptic list of "MY" Best Vim Tips that I've gleaned from http://vim.sf.net/ & comp.editors http://groups.google.com/groups?safe=off&group=comp.editors updated version at http://www.rayninfo.co.uk/vimtips.html -----------------------------------------------------------------------------# Absolutely essential -----------------------------------------------------------------------------vim.sf.net : Visit frequently comp.editors : "VIM" dominated newsgroup * # g* g# : find word under cursor (forwards/backwards) % : match brackets {}[]() matchit.vim : % now matches tags <tr><td><script> 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 :set ignorecase # you nearly always want this :syntax on : colour syntax in Perl,HTML,PHP etc :h slash<C-D> : type control-D and get a list all help topics containing slash (plus use TAB for Help completion) -----------------------------------------------------------------------------# MAKE IT EASY TO UPDATE/RELOAD_vimrc :nmap ,s :source $VIM/_vimrc :nmap ,v :e $VIM/_vimrc -----------------------------------------------------------------------------#VISUAL MODE Mappings :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 :Ex : file explorer note capital Ex \be : builtin buffer explorer :ls : list of buffers(eg following) :cd .. : move to parent directory -----------------------------------------------------------------------------# Great guu : lowercase line gUU : uppercase line gf : open file name under cursor (SUPER) ga : display hex,ascii value of character under cur sor ggVGg? : rot13 whole file CTRL-A,CTRL-X : increment,decerement number under cursor win32 users must remap CNTRL-A CTRL-R=5*5 : insert 25 into text -----------------------------------------------------------------------------# Makes all other tips superfluous :h 42 :h holy-grail :help! ------------------------------------------------------------------------------

# Markers & moving about '. : jump to last modification line (SUPER) `. : jump to exact spot in last modification line <C-O> : retrace your movements in file (old) <C-I> : retrace your movements in file (new) :ju(mps) :help jump-motions :history : list of all your commands -----------------------------------------------------------------------------# Abbreviations & maps :map <f7> :'a,'bw! c:/aaa/x :map <f8> :r c:/aaa/x :map <f9> :w<CR>:!c:/php/php.exe %<CR> :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 , # For use in Maps <CR> : carriage Return for maps <ESC> : Escape <LEADER> : normally \ <BAR> : pipe -----------------------------------------------------------------------------# List your Registers :reg : display contents of all registers "1p.... : retrieve numeric buffers -----------------------------------------------------------------------------# Useful trick "ayy@a : execute "Vim command" in a text file yy@" : same thing using unnamed register -----------------------------------------------------------------------------# Get output from other commands :r!ls.exe : reads in output of ls !!date : same thing :%!sort -u : use an external program to filter content -----------------------------------------------------------------------------# Multiple Files Management :wn : write file and move to next (SUPER) :bd : remove file from buffer list (SUPER) :sav php.html : Save current file as php.html and "move" to php.html :sp fred.txt : open fred.txt into a split :e! : return to unmodified file :w c:/aaa/% : save file elsewhere :e # : edit alternative file :e % :rew : rewwind to first file in ARGS :bn : next file :bp : next file :brew -----------------------------------------------------------------------------# Recording (BEST TIP of ALL) qq # record to q your commands q @q to execute @@ to Repeat # editing a register/recording "ap <you can now see register contents, edit as required> "add

@a -----------------------------------------------------------------------------# _vimrc essentials :set incsearch : jumps to search word as you type (annoying but excellent) :set wildignore=*.o,*.obj,*.bak,*.exe :set shiftwidth=3 -----------------------------------------------------------------------------# 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> -----------------------------------------------------------------------------#Conventional Shifting :'a,'b>> # visual shifting (builtin-repeat) :vnoremap < <gv :vnoremap > >gv -----------------------------------------------------------------------------# searching /^joe.*fred.*bill/ : normal /^[A-J]\+/ : search for lines beginning A-J followed by at leat 1 A-J /forum\(\_.\)*pent search over possible multiple lines /fred\_s*joe/i : any whitespace including newline /fred\ joe : Search for FRED OR JOE -----------------------------------------------------------------------------#substitution :%s/fred/joe/igc : general substitute command :%s/\r//g : Delete DOS returns ^M :'a,'bg/fred/s/dick/joe/gc : VERY USEFUL :s/\(.*\):\(.*\)/\2 : \1/ : reverse fields separated by : :%s/^.\{-}pdf/new.pdf/ non greedy matching (ie to first pdf) :s/fred/<c-r>a/g substitute "fred" with contents of register "a" :%s/^\(.*\)\n\1/\1$/ delete duplicate lines # non-greedy matching \{-} :%s/^.\{-}pdf/new.pdf/ :help /\{-} :s/fred/<c-r>a/g substitute "fred" with contents of register "a" # multiple commands :%s/\f\+\.gif\>/\r&\r/g v/\.gif$/d %s/gif/jpg/ :%s/suck\ buck/loopy/gc : ORing :s/__date__/\=strftime("%c")/ : insert datestring -----------------------------------------------------------------------------# global command :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

:v/./.,/./-1join : compress empty lines :'a,'b g/^Error/ . w >> errors.txt :g/cmap\ form/p : ORing -----------------------------------------------------------------------------# Paste register * :redir @* : redirect commands to paste :redir END "*yy : yank to paste "*p : insert paste buffer -----------------------------------------------------------------------------# Formatting text gq<CR> gqap (a is motion p paragraph (visual mode)) -----------------------------------------------------------------------------# Operate command over multiple files :argdo %s/foo/bar/ :bufdo %s/foo/bar/ :windo %s/foo/bar/ -----------------------------------------------------------------------------# Command line tricks gvim -h ls gvim - : edit a PIPE!! # vg.ksh (shell script) # vi all files in directory containing keyword $1 and jump to $1 gvim.exe -c "/$1" $(grep -isl "$1" *) & ------------------------------------------------------------------------------

VimTip 306: Open a web-browser with the URL in the current line http://vim.sf.net/tip_view.php?tip_id=306 function! Browser () let line = getline (".") let line = matchstr (line, "http[^ ]*") exec "!netscape ".line endfunction map <Leader>w :call Browser ()<CR>

VimTip 307: annoying "Hit any key to close this window..." http://vim.sf.net/tip_view.php?tip_id=307 i use gvim and bash heavily under win98. i have let $HOME = substitute($HOME, '\\', '/', 'g') set shell=bash\ --rcfile\ \"$HOME\"_bashrc\ -i in my _vimrc, and something like

function br() { if [ $1 ]; then explorer.exe ${1//\//\\} else explorer.exe ${PWD//\//\\} fi } in my _bashrc. when i finish editing one html file, i simply type :!br % everything works fine now. but when :!br % executes, one console window will bump out and wait me to press some key to contiue. i consider this quiet annoying. i want the console window to disappear automatically if no fault has happened. does anyone know how to achieve this? thanks.

VimTip 308: Move through wrapped lines. http://vim.sf.net/tip_view.php?tip_id=308 If you don't like the fact that when you press Up and Down on a wrapped line, yo u get to the next phisical line instead of the next line on the screen, you can do something like this: imap <silent> <Down> <C-o>gj imap <silent> <Up> <C-o>gk nmap <silent> <Down> gj nmap <silent> <Up> gk

VimTip 309: close vim you left open remotely http://vim.sf.net/tip_view.php?tip_id=309 Vim 6 has this cool client-server protocol. I use it all the time to edit a file in an existing gvim, like so $ gvim --remote [filename] Today I left myself logged in at the console at work, and when I got home I real ized I had left vim running with files unsaved. I think I even left it in inser t mode. I wanted to edit these files at home. So I ssh'd to the machine and star ted playing with the --remote commands. :help was a bit cryptic --remote-send {keys} Send {keys} to server and exit.

After a lot of failed attempts, I finally succeeded in getting the remote vim to save its buffers and quit.

$ DISPLAY=:0 vim --servername GVIM --remote-send '<ESC>:wqa<CR>' A couple of notable things. Then environment variable DISPLAY has to be the disp lay of the remote vim, and you have to be able to open that display. The clientserver stuff is done through X. The <CR> is important. This part eluded me for a long time. The {keys} are just like keys you would press if you were editing at the console, and you have to pr ess enter, or vim won't do anything. Check your .swp files to make sure vim really closed the files it was editing. V im provides little feedback as to the success or failure of what you're trying t o do remotely. Nonetheless, it's clearly a useful feature to have available.

VimTip 310: showing ascii value of the current character in decimal, hex, and oc tal http://vim.sf.net/tip_view.php?tip_id=310 dont know if you guys know this or not, but i was trying to make the word "hello " to upper case by trying "gaUw" (= which didnt work but it showed the decimal, hex, and octal of the char under the cursor... ncie to know.

VimTip 311: Open the folder containing the currently open file http://vim.sf.net/tip_view.php?tip_id=311 Occasionally, on windows, I have files open in gvim, that the folder for that fi le is not open. This key map opens the folder that contains the currently open f ile. The expand() is so that we don't try to open the folder of an anonymous buf fer, we would get an explorer error dialog in that case. if has("gui_running") if has("win32") " Open the folder containing the currently open file. Double <CR> at end " is so you don't have to hit return after command. Double quotes are " not necessary in the 'explorer.exe %:p:h' section. :map <silent> <C-F5> :if expand("%:p:h") != ""<CR>:!start explorer.exe %:p:h <CR>:endif<CR><CR> endif endif Tom.

VimTip 312: Copy, Cut, and Paste http://vim.sf.net/tip_view.php?tip_id=312 PS: copy, cut, and paste are the words from (usually) gui editor. Ever try to cut (or copy) some lines and paste to another place? If you need to count the lines first, then try these to eliminate counting task. Cut and Paste: 1. 2. 3. 4. 5. 6. Place the cursor at the beginning of the block you want to CUT. Mark it with md Go to the end of the block. Cut it with d'd Go to the new location that you want to PASTE those text. Press P.

Copy and Paste: 1. 2. 3. 4. 5. 6. Place the cursor at the beginning of the block you want to COPY. Mark it with my Go to the end of the block. Cut it with y'y Go to the new location that you want to PASTE those text. Press P.

The name of the mark used is related to the operation (d:delete or y:yank). I found that those mark names requires minimal movement of my finger. ;)

VimTip 313: printing using kprinter (unix + kde) http://vim.sf.net/tip_view.php?tip_id=313 just add set printexpr=system('kprinter'\ .\ '\ '\ .\ v:fname_in)\ .\ delete(v:fname_in)\ +\ v:shell_error to your ~/.vimrc; further on all your printing will be piped through the nice an d consistent print-dialog of kde. lg, tomte

VimTip 314: Insert and back... http://vim.sf.net/tip_view.php?tip_id=314 this is related to vimtip #289 in terms of programmers (like I) too lazy to move their hands to reach the far far away <esc> key.... joking! :) actually the less your hands move around the faster you type, and the fester y

ou type the more time you have on your hands to think of "what" you type... here is a small snippet from my mappings file, ready to speed things up: // the key overloading might be a somewhat confusing at first.... --cut--imap <S-Space> <esc>l imap <C-CR> <esc>o imap <S-CR> <esc>O nmap <S-Space> i nmap <space><space> i nnoremap <CR> o nmap <S-CR> O ---uncut--Good luck!!

VimTip 315: "Smart <home>" http://vim.sf.net/tip_view.php?tip_id=315 to make it faster to navigate through indented code here is a common way to "go home"... ---cut--fun! s:SmartHome() if col('.') != match(getline('.'), '\S')+1 norm ^ else :call cursor(line('.'),2) norm h endif endfun inoremap <silent><home> <C-O>:call <SID>SmartHome()<CR> nnoremap <silent><home> :call <SID>SmartHome()<CR> vnoremap <silent><home> :call <SID>SmartHome()<CR> ---uncut--what this snippet does is make the <home> key behave as it does in such IDEs as PythonWin or MSVisualStudio, and that is first go to the first non whitespace, a nd then to the first char on the line.

VimTip 316: Using /pattern/ search in a script http://vim.sf.net/tip_view.php?tip_id=316 There are a number of ways you can search for a pattern in a script. The searc h function is the typical way to search for a pattern. But, it has limited opti ons. In particular, there are no options to control the position of the cursor

after it matches the pattern. Instead you can use :normal command. The secret is to add a <CR> (^M) on the en d of the command. For example, to search for "pattern" and move the cursor to the end of the matching pattern issue the command: :normal /pattern/e+1^M where ^M is a real carriage return. It can be entered with <c-v><c-m>. Another use is when you want to enter a bunch of normal commands together. For example, if you were looking to find a '{' to highlight and delete a C block. T he '{' may not be on the same line so you can't use the "f" normal command. :normal V/{/^M%d A drawback to using the normal command is that if the pattern does not match the n it is difficult to detect. Also, you can get in trouble with the wrapscan set ting. For more information about these commands look at :help / :help normal :help search()

VimTip 317: Mozilla Vim Keybindings http://vim.sf.net/tip_view.php?tip_id=317 If you use VIM you like the h, j, k, and l movement keys. I found myself annoye d at not having these movement keys available when browsing web pages. Moving t o the arrow keys on a laptop is annoying to just scroll the page. Locate your mozilla/res/builtin directory (varies by platform). You could search for htmlBindings.xml to find it. (ie. locate htmlBindings.xml. On Mac OS X it's inside the Mozilla application bundle. /Applications/Mozilla/M ozilla.app/Contents/MacOS/res/builtin. Create a new XML file called userHTMLBindings.xml, making it executable for all users and making sure the CRLF format is the same as htmlBindings.xml. i.e. on Mac OS X most files use \r but Vim writes \n instead. You can either save the fi le with Vim as a Mac formatted file or use tr '\n' '\r' < input.xml > output.xml to convert the file. Place the following XML into the userHTMLBindings.xml file. <?xml version="1.0"?> <bindings id="htmlBindings" xmlns="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <binding id="browserUser"> <handlers>

<handler event="keypress" <handler event="keypress" <handler event="keypress" <handler event="keypress" </handlers> </binding> </bindings>

key="h" key="j" key="k" key="l"

command="cmd_scrollLeft"/> command="cmd_scrollLineDown"/> command="cmd_scrollLineUp"/> command="cmd_scrollRight"/>

There are many more bindings one could configure to get Vim like keybindings. Y ou can read http://www.mozilla.org/unix/customizing.html#keys for more informati on. PS. I love the keymaster/gatekeeper xul reference in the xul URL above. It's f rom the original GhostBusters movie. ;-)

VimTip 318: Extended Bracket and Parenthesis + extras for perl http://vim.sf.net/tip_view.php?tip_id=318 This is an extension of vimtip #153 I found this tip useful, but the jump seemed out of place for me, I couldn't ent er just one ' or ", and so I created an improvement Basically, I set it up so that when you're in perl and have a non keyword charct er, (except for @, $ and % for perl) and you type a { you get: { <- cursor } Where as, when I have a keyword I get: word{} With the cursor in the middle, for hashes in perl. I can jump out of any block, except the "" or '' blocks, by typing their closing charcter. So } jumps me ou t past the next } in the file. Warning, this search may wrap around. Finally, I made <Alt-'> inserts <Alt-/> inserts <Alt-[> inserts <Alt-]> inserts <Alt--> inserts <Alt-=> inserts <Alt-,> inserts <Alt-.> inserts it so that, using the alt key, a ' a " a [ a ] a { a } a < a >

"######################################## " File matchMe.vim " Date Wednesday, August 21, 2002 "########################################

" This code fixes my problem with " does the one format for perl and still keeps hashes function! InsertBrackets() let fileType = &ft if fileType == 'perl' let col = col('.') - 1 if !col getline('.')[col - 1] !~ '\k' && getline('.')[col - 1 ] !~ '\$' && getline('.')[col - 1] !~ '@' && getline('.')[col - 1] !~ '%' && ge tline('.')[col - 1] !~ '#' return "{\<cr>\<bs>}\<esc>ko" else return "{}\<esc>i\<c-o>:echo \<cr>" endif else return "{\<cr>\<bs>}\<esc>ko" endif endfunction " This code jumps out of the brackets function! JumpNext(normChar) let ret = "\<space>\<esc>ma\<left>/\\".a:normChar."\<cr>mb`ai\<del>\<esc >`bi\<right>" return ret endfunction " mappings inoremap " ""<esc>i<c-o>:echo <cr> inoremap ' ''<esc>i<c-o>:echo <cr> inoremap < <><esc>i<c-o>:echo <cr> inoremap ( ()<esc>i<c-o>:echo <cr> inoremap [ []<esc>i<c-o>:echo <cr> inoremap { <c-r>=InsertBrackets ()<cr> inoremap > <c-r>=JumpNext(">")<cr> inoremap ) <c-r>=JumpNext(")")<cr> inoremap ] <c-r>=JumpNext("]")<cr> inoremap } <c-r>=JumpNext("}")<cr> inoremap <m-[> [ inoremap <m-]> ] inoremap <m-/> " inoremap <m--> { inoremap <m-=> } inoremap <m-,> < inoremap <m-.> > inoremap <m-'> ' "######################################## " End Of File "######################################## If you have any other suggestions, drop a note...

VimTip 319: text formatting (lining up ='s,('s etc)) http://vim.sf.net/tip_view.php?tip_id=319

some time onw would like to reformat text like a=1; foo=2; longstring=1; c=2 to a =1; foo =2; longstring =1; c =2; Note I am not sure wether the code above is displayed properly in your browsers what is basically shows is all the ='s are lined up in a single column and this is how we achive it 0f=20i<space><esc>020lvf=hx and this is what it does 0 goes to first column f= finds next occurance of = on current line 20i<space><esc> inserts 20 spaces before = 0 goesback to first column 20l forward 20 column vf=hx deletes everything up to the = sign

VimTip 320: Borland pageup/down behavier http://vim.sf.net/tip_view.php?tip_id=320 borlandbehavier = the cursor keeps the same xy position during pageup/down Im new to VIM scripting, im sure it can be done smarter? I read vimtip #105 and it gave me a clue of how BorlandPageUp/Down could be done . " i could'nt find any get_number_of_visible_lines function, so i made my own. function GetNumberOfVisibleLines() let cur_line = line(".") let cur_col = virtcol(".") normal H let top_line = line(".") normal L let bot_line = line(".") execute "normal " . cur_line . "G" execute "normal " . cur_col . " " return bot_line - top_line endfunc " noremap <PageUp> 39<C-U>:set scroll=0<CR> function! MyPageUp() let visible_lines = GetNumberOfVisibleLines() execute "normal " . visible_lines . "\<C-U>:set scroll=0\r"

endfunction " noremap <PageDown> 39<C-D>:set scroll=0<CR> function! MyPageDown() let visible_lines = GetNumberOfVisibleLines() execute "normal " . visible_lines . "\<C-D>:set scroll=0\r" endfunction " BorlandPascal pageup/down behavier! " todo: when hitting top/bottom of file, then restore Y to lastY noremap <PageUp> :call MyPageUp()<CR> noremap <PageDown> :call MyPageDown()<CR>

VimTip 321: Centura swap with upper/lower line behavier http://vim.sf.net/tip_view.php?tip_id=321 I was once forced to use a windows development suite called "Centura". The only good thing i remember was its swap current_line with upper/lower line. function! MySwapUp() let cur_col = virtcol(".") normal ddkkp execute "normal " . cur_col . " " endfunction function! MySwapDown() let cur_col = virtcol(".") normal ddp execute "normal " . cur_col . " " endfunction " swap lines and preserve cursorx " todo: in visual mode, perform swap with line before/after the selection noremap <S-Up> :call MySwapUp()<CR> noremap <S-Down> :call MySwapDown()<CR>

VimTip 322: text template with placeholders http://vim.sf.net/tip_view.php?tip_id=322 Many scripts/ftplugin provide text or code templates. Sadly none of the marks th e places where you are supposed to "fill in the form". My own code templates for C/C++ insert a triple percent (%%%) where you are supp osed to enter something. I mapped ;; to find the next %%% and change them. All the template mappings are insert-mode only, while the "skip to next placehol der" is both insert and normal mode enabled. A complete for-loop template for C++ looks like:

:imap <buffer> ;fo <C-O>mzfor( %%%; %%%; %%%)<CR>{ // %%%<CR>%%%<CR>}<CR><C-O>'z ;; The command to go to the next placeholder is this: :imap <buffer> ;; <C-O>/%%%<CR><C-O>c3l :nmap <buffer> ;; /%%%<CR>c3l Every time I need a for-loop ;fo produces this ( _ is the cursor position) : for( _; %%% ; %%%) { // %%% %%% } Now I enter starting value (i=0): for( i=0_; %%% ; %%%) { // %%% %%% } and go to the condition using ;; for( i=0; _ ; %%%) { // %%% %%% } and so forth. The choice of %%% proved to be almost universal, it even works in MATLAB or LaTe X where % is the comment character. Even if you forget to replace one %%%, that's not a problem as the compiler flag s is as a syntax error (except MATLAB and LaTeX, of course). It made my life easier, maybe it works for you.

VimTip 323: using folders with latex http://vim.sf.net/tip_view.php?tip_id=323 set foldmarker=\\begin,\\end set foldmethod=marker this is useful with big latex document

VimTip 324: Search and replace in files named NAME http://vim.sf.net/tip_view.php?tip_id=324 I'm not sure if there is a simple way to do this from within Vim, but, I wrote t

his simple script that does it. It basically searches for files named NAMED (wha tever name pass) for a given string and replaces that with a given string: find_replace.sh NAMED "string_to_find" "string_to_replace" This is all done from the command line without opening Vim. Of course one could do things like: :let n = 1 :while n <= argc() " loop over all files in arglist : exe "argument " . n : " start at the last char in the file and wrap for the : " first search to find match at start of file : normal G$ : let flags = "w" : while search("foo", flags) > 0 : s/foo/bar/g : let flags = "W" : endwhile : update " write the file if modified : let n = n + 1 :endwhile As suggested in the Vim help files :-) but, I wanted to go and find only these f iles... here is the script: 1 #!/bin/sh 2 # Luis Mondesi < lemsx1@hotmail.com > 3 # DESCRIPTION: 4 # it uses vim to replace a given string for 5 # another in a number of files 6 # 7 # usage: 8 # find_replace.sh file "string" "replace" 9 # 10 if [ $1 -a $2 -a $3 ]; then 11 for i in `find . -name "$1" -type f xargs grep -l $2`; do 12 # how do search and replace 13 # the screen might flicker... vim opening and closing... 14 vim -c ":%s/$2/$3/g" -c ":wq" $i 15 done 16 exit 0 17 fi 18 # I should never reach here 19 echo -e "USAGE: find_replace.sh file 'string' 'replace' \n\n" 20 exit 1

VimTip 325: Errorformat for java/ant/junit/cygwin/bash http://vim.sf.net/tip_view.php?tip_id=325 If you program in Java and use Jakarta ant for builds *and* if you have the bash shell, this tip will make your development experience a little smoother. This tip will result in a working compile/edit/debug system (in Win32

vim/gvim and in Cygwin vim) that takes you to the exact lines where the build fails, whether the failure is a compilation error or a junit test failure. If you use bash on a linux box, you shouldn't have to change very much to get everything to work. There are 1. set up 2. set up 3. set up 4. set up 5. set up 6. set up 6 sections: your build script makeprg shell options path formatting options your errorformat key mappings

Set up build script ------------------Add the following script to your path (I use /usr/local/bin/): mymake: #!/bin/bash cd /work/ ant -emacs $* 2>&1 tr '\\' / ors.sed tee /tmp/errors

tr ^M ' '

sed -u -n -f /usr/local/bin/testerr

Comment: sed -u is non-standard, use the code at: http://mail.gnu.org/pipermail/bug-gnu-utils/2002-May/000192.html to get the -u option for sed (this avoids waiting for the build output to get to the screen) testerrors.sed: # This assumes that all your junit test cases are in a com.* package /^Running com\./ { # duplicate the line s!\(.*\)!\1\ \1! P # turn the test package into a directory path for %D errorformat s!.*\(com\..*\)\.[A-Za-z_][A-Za-z0-9_]*!\1! s!\.!/!g s!.*!Entering: /work/src/&! # print the line and go on p n } # just pass any unmatched lines through p Set up makeprg -------------Add the following lines to your vimrc: autocmd BufNewFile,BufRead /work/*.java set makeprg=mymake autocmd BufNewFile,BufRead ?:/work/*.java set makeprg=mymake Set up shell options -------------------Add the following lines to your vimrc: " in order to have bash as the shell for win32 vi.exe and gvim.exe, you have " to set these options, and also build vimrun.exe in the cygwin environment

" so that the system() call is executed via bash, not cmd.exe -- the command " to build vimrun.exe is "make -f Make_cyg.mak vimrun.exe" set shell=bash.exe set shellcmdflag=-c set shellslash Also to use this environment in Win32 gvim, you must recompile vimrun so that gvim invokes the shell via bash, not via cmd.exe. Set up path formatting options -----------------------------Add the following lines to your vimrc: " allows DOS file names from UNIX (Cygwin) vim set isfname+=\ Set up your errorformat ----------------------Add the following lines to your vimrc: " the "\%DEntering:\ %f," rule relies on a sed script which generates " "Entering: " messages for each test class run (the directory name is " generated from the test class package and a hard-coded src root) " the "%\\C" at the start of the exception matching line tells to match " case-exact (the exception mathching lines rely on the %D rule that sets " up the correct directory from the package structure) " ant/junit/javac errorformat set errorformat= \%-G%.%#build.xml:%.%#, \%-G%.%#warning:\ %.%#, \%-G%\\C%.%#EXPECTED%.%#, \%f:%l:\ %#%m, \C:%f:%l:\ %m, \%DEntering:\ %f\ %\\=, \%ECaused\ by:%[%^:]%#:%\\=\ %\\=%m, \%ERoot\ cause:%[%^:]%#:%\\=\ %\\=%m, \%Ecom.%[%^:]%#:%\\=\ %\\=%m, \%Eorg.%[%^:]%#:%\\=\ %\\=%m, \%Ejava.%[%^:]%#:%\\=\ %\\=%m, \%Ejunit.%[%^:]%#:%\\=\ %\\=%m, \%-Z%\\C\ at\ com.mypkg.%.%#.test%[A-Z]%.%#(%f:%l)\ %\\=, \%-Z%\\C\ at\ com.mypkg.%.%#.setUp(%f:%l)\ %\\=, \%-Z%\\C\ at\ com.mypkg.%.%#.tearDown(%f:%l)\ %\\=, \%-Z%^\ %#%$, \%-C%.%#, \%-G%.%# NOTE: Make sure that the character before "at" is an actual Tab character in the three long -Z lines above Here is an annotated version: set errorformat= " don't treat the build.xml diagnostic as an error \%-G%.%#build.xml:%.%#, " don't treat warning lines as errors \%-G%.%#warning:\ %.%#, " don't treat lines containing "EXPECTED" as errors \%-G%\\C%.%#EXPECTED%.%#,

" look for this standard error format \%f:%l:\ %#%m, " look for this standard error format (with C: on front) \C:%f:%l:\ %m, " look for special sed-generated "Entering" lines while running tests \%DEntering:\ %f\ %\\=, " look for exceptions that were thrown in the tests, use the exception " description as the error message (don't know how to also include the " exception name in the error message) \%ECaused\ by:%[%^:]%#:%\\=\ %\\=%m, \%ERoot\ cause:%[%^:]%#:%\\=\ %\\=%m, \%Ecom.%[%^:]%#:%\\=\ %\\=%m, \%Eorg.%[%^:]%#:%\\=\ %\\=%m, \%Ejava.%[%^:]%#:%\\=\ %\\=%m, \%Ejunit.%[%^:]%#:%\\=\ %\\=%m, " using the "Entering" directory and the filename/line number provided " in the exception trace, go to the test method where the exception " was thrown \%-Z%\\C\ at\ com.mypkg.%.%#.test%[A-Z]%.%#(%f:%l)\ %\\=, \%-Z%\\C\ at\ com.mypkg.%.%#.setUp(%f:%l)\ %\\=, \%-Z%\\C\ at\ com.mypkg.%.%#.tearDown(%f:%l)\ %\\=, " empty lines terminate searching for further exception lines \%-Z%^\ %#%$, " any line can intervene between the start of an exception printout " and the line where it ends (last in list so that it is matched if " none of the other exception trace patterns match) \%-C%.%#, " all other lines are not errors \%-G%.%# Set up key mappings ------------------Add the following lines to your vimrc: nmap <F10> :clist<CR> nmap <F11> :cprev<CR> nmap <F12> :cnext<CR> This allows for quick error navigation. NOTES ----Vim treats the "Entering: /work/src/..." messages in a weird way. If there are any actual errors, then these error lines are ignored by the :cnext and :cprev commands, but if there are no real errors, then :cnext and :cprev roll through these "Entering:" messages as if they were errors, but since they don't include any line numbers, the cursor position is never moved. I thought that this was strange, but even stranger, it is programmed directly into the vim error handling code to function exactly this way. There were no comments, and nobody responded on the vim mailing list, so I just decided to live with it.

The upshot of it all is that if you see an error like "Entering:", chances are that your build succeeded and all the tests ran without a problem. Hope this helps... Mail me with bugs at jdsumsion at earthlink.net.

VimTip 326: Help for VIM Help (VIM QuickRef) http://vim.sf.net/tip_view.php?tip_id=326 Type :help quickref or :h quic And get a VIM Command Quick Reference Page brilliant for beginners & oldtimers a like type :h help to learn how to use help Other Help Tips # help for help :h visual<C-D><tab> :h :h :h :h :h :h :h :h ctrl<C-D> :r CTRL-R \r i_CTRL-R c_CTRL-R v_CTRL-V tutor : obtain list : Then use tab : list help of : help for :ex : normal mode : what's \r in : help for say : help for say : visual mode : VIM Tutor of all visual help topics to step thru them all control keys command a regexp <C-R> in insert mode <C-R> in command mode

These are also listed in my Best Of VIM Tips vimtip #305

VimTip 327: key mappings http://vim.sf.net/tip_view.php?tip_id=327 I use my left thumb for the alt key and right for the space. Using this combo, y ou can get some useful key maps for which you don't have to move your hands. I find I have to turn my hand a little to press the left ctrl key. These are some maps i use for C programming.

map ' ` map <C-f> :w<C-m>:!make<C-m> map <M-]> <C-]> map <M-[> <C-t> map <M-u> :!ctags -R *<C-m> map <M-c> I/*<Esc>A*/<Esc> ent line map <M-d> ^xx$xx ingle line map <M-l> [{zf% brace level map <M-o> zo map <M-i> zc map <M-.> :cn<C-m> list map <M-,> :cp<C-m> st imap <Tab> <C-p> inoremap <S-Tab> <Tab> inoremap { <CR>{<CR> line inoremap } <CR>} . saves one enter stroke

Tags Tags Build Tags Comment curr Delete comment for a s Fold upto the enclosing open fold close fold Go to next error in previous error in li Complete word Tab Brace and brace and line

imap <M-j> <Esc> want to move my hand to esc key. imap <M-k> <C-y> above. imap <M-q> /* */<Esc>hhi d lines

Escape. Don't Copy line from Comment selecte

noremap <M-r> ddko{<C-m>}<Esc>kpko Convert a simple statement to a c ompound statement. And place cursor above prev line. noremap <M-k> ddko{<C-m>}<Esc>kpo Same as above but place cursor bel ow old line. vnoremap <M-j> <Esc> vnoremap <M-c> di/*<C-m>/<C-m><Esc>kkp Commented selected text

nmap <M-n> :noh<CR> Bye, Nithin.

No hilight

VimTip 328: Vim in Microsoft Visual Foxpro http://vim.sf.net/tip_view.php?tip_id=328 You can tell MS VFP to use an external editor for editing project files.

To tell MS VFP to use Vim: start regedit locate [HKEY_CURRENT_USER \Software \Microsoft \VisualFoxPro \5.0 \Options] and create a new item TEDIT with string content "/N C:\Progra~1\vim\vim61\gvim.exe" (or whatever your path to Vim happens to be.) This will not replace the internal VFP editor for such things as modifying the "click method" for a button (unfortunately), but when you modify a program, VFP will fire up gvim. Start MS VFP, start Help and look for TEDIT. ;-)

VimTip 329: A map for swapping words http://vim.sf.net/tip_view.php?tip_id=329 Put the following map into your <.vimrc>: nmap <silent> gw "_yiw:s/\(\%#\w\+\)\(\W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l> Then when you put the cursor on or in a word, press "gw", and the word will be swapped with the next word. The words may even be separated by punctuation (such as "abc = def"). While we're talking swapping, here's a map for swapping characters: nmap <silent> gc xph

This hint was formed in a collaboration between Chip Campbell - Arun Easi - Benji Fisher

VimTip 330: how to stop auto indenting http://vim.sf.net/tip_view.php?tip_id=330 Since VIM 6.0 the indent has been improved so much. But sometimes when we are pasting formated text (source code or HTML etc)

into a buffer, VIM indents again so that lines will be padded with too much spaces. Setting nocindent, noautoindent, nosmartindent still cannot stop this. All you need to do is "set paste", then paste your stuff, and then "set nopaste" again. Ref: indentexpr

VimTip 331: modline magic... http://vim.sf.net/tip_view.php?tip_id=331 One of the things about vim that are both quite simple yet very useful is that you can store by-file settings... that is each file can contain settings specific to it. this thing is called a modline (:help modline). though this is limited to only the 'set' command arguments, you can do allot of local to file things like the indent type, folding method and so on. the syntax is as follows: // vim:set ts=4 sw=4 nowrap: or /* vim:noai:ts=2:sw=4: */ The modlines can be contained in comments so as to not interfere with the file syntax (shown here for C/C++). these lines are read by vim when it loads the file, and they can either be in the first or last 5 lines (by default). refer to ':help modline' //and a happy 20th birthday to the good old smiley!! :-)

VimTip 332: make footnotes in vim http://vim.sf.net/tip_view.php?tip_id=332 I found at http://groups.google.com/groups?q=vim+changing+shell+to+zsh&hl=en&lr= &ie=UTF-8&selm=S_Rh9.716%24a5.124150%40news.uchicago.edu&rnum=4 a macro to insert footnotes in vim, but it doesn't work as of vim6.0. so i wrote my own; this macro requires two differents shortcuts, one for enterin g the first footnote, the other one for all subsequent footnotes. when you hit "K0" (first footnote) or "KK" (all other footnotes) in normal mode, your cursor is positionned at the end of the document, in the footnote & in ins ert mode. The "a" bookmark is set to the place where you entered the footnote in the text. so a "`a" will bring you back to the location of the footnote in the

text. " for now requires entering K0 for the first footnote and then KK nmap K0 i[0]<esc>maG$i<end><enter>[0] nmap KK maG$?\[[0-9]*\]<enter>yt]G$i<end><enter><esc>p<C-a>i<end>]<esc>`aP<C-a>< right>i]<esc>maG$i<end><end>

VimTip 333: Syntax-based folding for c/c++/java http://vim.sf.net/tip_view.php?tip_id=333 Here's a function to toggle the use of syntax-based folding for a c/c++/java fil e. It also handles folding markers. function! OutlineToggle() if (! exists ("b:outline_mode")) let b:outline_mode = 0 endif if (b:outline_mode == 0) syn region myFold start="{" end="}" transparent fold syn sync fromstart set foldmethod=syntax silent! exec "%s/{{{/<<</" silent! exec "%s/}}}/>>>/" let b:outline_mode = 1 else set foldmethod=marker silent! exec "%s/<<</{{{/" silent! exec "%s/>>>/}}}/" let b:outline_mode = 0 endif endfunction

VimTip 334: Loading scripts in .vimrc safely http://vim.sf.net/tip_view.php?tip_id=334 If you copy your .vimrc to many places, you might get a problem: writing a portable .vimrc is sometimes painful. Maybe in some places you have latest VIM6.1, and in some places you have VIM 5.x. And maybe you have some favorite scripts in your own computer while other places does not. Here're some tips and examples on writing portable .vimrc that will not make err or messages when environment changes:

(1) Check version: if version >= 600 set foldcolumn=2 endif (2) Use environment variables: source $VIMRUNTIME/vimrc_example.vim (3) Loading scripts(especially useful for scripts just merged into standard macr os): if filereadable($VIMRUNTIME . "/macros/matchit.vim") source $VIMRUNTIME/macros/matchit.vim endif

VimTip 335: Copy C++ function declaration into implementation file http://vim.sf.net/tip_view.php?tip_id=335 There's a handy plug in for MS Visual Studio called CodeWiz that has a nifty abi lity to copy a function declaration and deposit it into the implementation file on command. I actually missed while using vim, so I wrote an approximation of t hat capability. This isn't foolproof, but it works alright. " Copy Function Declaration from a header file into the implementation file. nmap <F5> "lYml[[kw"cye'l nmap <F6> ma:let @n=@/<cr>"lp==:s/\<virtual\>/\/\*&\*\//e<cr>:s/\<static\>/\/\*& \*\//e<cr>:s/\s*=\s*0\s*//e<cr>:s/(.\{-}\zs=\s*[^,)]\{-1,}\>\ze\(\*\/\)\@!.*)/\/ \*&\*\//e<cr>:s/(.\{-}\zs=\s*[^,)]\{-1,}\>\ze\(\*\/\)\@!.*)/\/\*&\*\//e<cr>:s/(. \{-}\zs=\s*[^,)]\{-1,}\>\ze\(\*\/\)\@!.*)/\/\*&\*\//e<cr>:let @/=@n<cr>'ajf(b"cP a::<esc>f;s<cr>{<cr>}<cr><esc>kk To use this, source it into vim, for example by placing it in your vimrc, press F5 in normal mode with the cursor on the line in the header file that declares t he function you wish to copy. Then go to your implementation file and hit F6 in normal mode with the cursor where you want the function implementation inserted .

VimTip 336: type the line number and press enter to get there http://vim.sf.net/tip_view.php?tip_id=336 an easy way to to get to a line (whose number we know) faster is to combine s ome existing ways that are; :132<ENTER> or 123G or 123gg and the solution is to map in normal mode the enter to G

so with :nmap <ENTER> G we can type the line number and then press enter to get there... it's very small gain ... but it is!!!

VimTip 337: editing remote files via scp in vim http://vim.sf.net/tip_view.php?tip_id=337 VIM 6.x has the netrw plugin installed as a standard plugin. It allows you to ed it files via ftp, rcp, scp, or http. If your username differs on the remote host , however, and you're trying to use scp, things can get a little wierd, particul arly if you're not editing a document under your user tree. To get around this, try opening the file as follows: vim scp://remoteuser@server.tld//path/to/document Notice two things: adding the "remoteuser@" syntax, and the use of two slashes ( //) between the servername and the path. The first sets the remote user so that scp will not grab the $USERNAME environment variable, the second will appropriat ely set the absolute path.

VimTip 338: vim + cscope + cygwin http://vim.sf.net/tip_view.php?tip_id=338 Tip #292 doesn't seem to be true, at least not anymore. I am using cscope 15.4 a nd vim 6.1. With a few hacks, I was able to get cscope to work with vim under cy gwin for Windows 2000. I did not need to change the sprintf line. The hacks incl uded 1. Copying if_cscope.? to the src directory and the if_cscope.pro to the src/pro to directory. These files do not come standard with the Windows source distribut ion of vim. (I think it should - anybody in charge of distribution listening?) 2. Edit if_cscope.c to make the following changes: Add the following includes: #include <sys/unistd.h> #include <sys/signal.h> 3. Edit Make_cyg.mak Add if_cscope.o to OBJ variable. Add a rule for this at the end $(OUTDIR)/if_cscope.o: if_cscope.c $(INCL) $(CC) -c $(CFLAGS) if_cscope.c -o $(OUTDIR)/if_cscope.o

Uncomment the lines following #>>>>> uncomment this block to build a GUI version 4. Edit feature.h Force cscope compilation: # define FEAT_CSCOPE 5. make -f Make_cyg.mak GUI=yes 6. Note that the env variable TMPDIR should be defined in VIM for cscope to work correctly. That should do it. Somebody in charge of distribution please make this standard. It would save a lot of trouble.

VimTip 339: "tabbed windows" http://vim.sf.net/tip_view.php?tip_id=339 This is what I use to emulate the multi-tab environment of certain editors like EditPlus, and easly switch between multiple files being edited (opened with the :split command): " put this in your .vimrc file to rotate windows with Alt-K / Alt-J set winminheight=0 nmap <M-k> <C-W>r<C-W>k:resize<CR> nmap <M-j> <C-W>j<C-W>R:resize<CR> imap <M-k> <ESC><M-k>i imap <M-j> <ESC><M-j>i " end The only problem is that after a :split you have to Alt-K-J to keep the new wind ow "maximized".

VimTip 340: Visual Select And Search http://vim.sf.net/tip_view.php?tip_id=340 The following visual select and search map is a combination of information from Benji's vimrc file (vmap S y/<C-R>=escape(@",'/\')<CR>) and a tip that mentions the "\n" to "\\\\n" substitution. It works for special characters and multiple lines. vmap \s y/\V<C-R>=substitute(escape(@",'/\'),"\n","\\\\n","g")<CR>/<CR> Quick explanation:

vmap \s y / \V <C-R>= substitute escape <CR> /<CR>

visual map your choice yank selected text search delimiter no magic, just text expression substitute "\n" for "\\\\n" escape '/' (delimiter) and '\' in yanked text (@") end expression search

Warning: Folding will not match if the foldexpr expression is using getline() to match against a search pattern that spans multiple lines. Enjoy.

VimTip 341: switch color schemes http://vim.sf.net/tip_view.php?tip_id=341 This function is similar to the vimtip #211. I did not recognize that s.o. already wrote a function for that, but this one has one advantage: It just takes all possible colorschemes in the given directorys and rotates them. Just put the following code in your .vimrc file: let SwitchSchemesFiles = globpath("$VIMRUNTIME,$HOME/.vim","colors/*.vim") let SwitchSchemesIndex = 0 function! SwitchSchemes() let sep="\n" if g:SwitchSchemesIndex == -1 let g:SwitchSchemesIndex=0 endif exe "source " . NextElement(g:SwitchSchemesFiles, sep, g:SwitchSchemesIn dex) let g:SwitchSchemesIndex = NextIndex(g:SwitchSchemesFiles, sep, g:Switch SchemesIndex + 1) endfunction In addition you need the http://www.vim.org/script.php?script_id=109 Put it in the plugin directory. If you use e.g. a map to F12, you can easily switch between all installed themes: map <f12> :call SwitchSchemes()<CR>

VimTip 342: Remap <ESC>

http://vim.sf.net/tip_view.php?tip_id=342 Tired of hunting down <ESC> at upper-left of your keyboard while using a keyboar d with useless Windows keys? Well, remap them -- use xmodmap. I'm using Debian and my xmodmap config file is in /etc/X11/xinit/xmodmap, ymmv. You may have to use xmodmap directly (from ~/.xinitrc in *BSD or whatever). Anyway, here's my xmodmap: [ .. other irrelevant mappings skipped ... ] keycode 115 = braceleft keycode 116 = Escape keycode 117 = braceright Btw, the keys are: * 115 - Windows key, between the left-hand Ctrl and Alt keys * 116 - Windows key, to the right of the AltGr key * 117 - Menu key, to the left of the right-hand Ctrl key Valid for all environments with X, on *BSD as well as on Linux. You get the same mappings under ordinary console by modifying the console keymap file (pretty self-explanatory), in my case it's /usr/share/keymaps/i386/qwerty/et.kmap.gz. I'm using mapping braces to winkeys because of my Estonian keyboard.

VimTip 343: Faster loading of large files http://vim.sf.net/tip_view.php?tip_id=343 In the past I experienced long loading times for large files ( size > 10MB ) These files are normally generated by SQL tracing, XML message based protocols tracing etc. One of the causes of long loading times was syntax parsing, creating swap file e tc. Normally one want to view these files and remove not relevant details by deleting lines, but do not want to have undo capabilities and auto recalculation of syntax highlighting. The code below, I put in my _vimrc to switch off a number of defaults for large files. One can modify the g:LargeFile variable and reload a file to test: :let g:LargeFile=10 :e It would be interesting to know if others have more or better suggestions. " Protect large files from sourcing and other overhead. " Files become read only if !exists("my_auto_commands_loaded") let my_auto_commands_loaded = 1 " Large files are > 10M

" Set options: " eventignore+=FileType (no syntax highlighting etc " assumes FileType always on) " noswapfile (save copy of file) " bufhidden=unload (save memory when other file is viewed) " buftype=nowritefile (is read-only) " undolevels=-1 (no undo possible) let g:LargeFile = 1024 * 1024 * 10 augroup LargeFile autocmd BufReadPre * let f=expand("<afile>") if getfsize(f) > g:LargeFile set eventignore+=FileType setlocal noswapfile bufhidden=unload b uftype=nowrite undolevels=-1 else set eventignore-=FileType endif augroup END endif

VimTip 344: Cut / Copy / Delete / Paste Lines without knowing the number of line s http://vim.sf.net/tip_view.php?tip_id=344 If you ever need to cut / copy / delete / paste lines without knowing the actual number of lines, here is what you should do. 1. In the command Mode, Go to the beginning of the first mark (lets say line 50) . 2. Type: mk 3. Go to the end of your selection (lets say 100), using j's or Ctrl -F or anyth ing. You don't need to count the lines. 4. Type: "ay'k (i.e. Double Quotes, <reg name from a-z>, <y-yank or d-delete>, s ingle quote, k 5. The above command copies those lines into register a. 6. If you do "ad'k , it will delete them from the current location and copies th em into register a. 7. You can paste those lines wherever you want just as you print from registers, i.e. "ap I use this a lot, since I don't need to count the number of lines. -Kdr

VimTip 345: Visual Studio + vim Quickfix mode + cygwin + XFree86 http://vim.sf.net/tip_view.php?tip_id=345 I run gvim inside a cygwin XFree86 session running WindowMaker. Because I'm ins ide cygwin-XFree86, I can't use the useful VisVim plugin to step through Visual Studio compiler errors. To work around this limitation, I wrote a Bash/Perl scr ipt that munges nmake output into something that has cygwin compliant path and i s parseable by the default quickfix errorformat setting . Here's what to do:

1. install the following from cygwin: - perl - cygutils - bash 2. Set up Visual Studio to support command line compiles. Basically this invo lves adding paths to the PATH, INCLUDE, and LIB environment variables. See vcva rs32.bat in the Visual Studio VC98/bin directory for guidelines. 3. Export a makefile for your dsp project file via the Visual Studio "Project E xport Makefile..." 4. Create the cygwin shell script defined below. Put the script in '/bin/dovcm ake' ---begin cut----#!/bin/bash # This script takes output from # Visual Studio's nmake and reformats # it so that it can be parsed by # cygwin's vim default errorformat # setting nmake /F $1 2>&1 perl -n -e \ ' chomp; if(/^([a-z]:[^(]+)\((\d+)\)(.+)$/i) { $f = $1; $l = $2; $m = $3; $f =~ s/\\/\//g; $cyp = `cygpath -au $f`; \ chomp $cyp; print qq{"$cyp",$l:$m\n};} elsif(/error/i) { print qq{$_\n}; }' ---end cut ----5. Add this map to your vimrc: set makeprg=/bin/dovcmake map <f7> :make <c-r>%<cr> 6. Fire up cygwin vim and open the makefile from step 3. If you hit F7, you'll automatically start a Visual Studio build and you'll be able to step through co mpiler errors via the :cp and :cn commands.

VimTip 346: Wrap text in HTML/XML tags after prompting for the tag name http://vim.sf.net/tip_view.php?tip_id=346 Someone else posted this sometime ago on this mailing list, I have enhanced it s lightly and made a tip out of it.

I thought it was pretty clever and very generic. If you have a block of text and you want to wrap it in <TAG_NAME>...</TAG_NAME> then this function will prompt you for the tag name and wrap the text. If there is no text VISUALLY selected, it will wrap the current word in the tag, otherwise it will wrap the visually selected text. It will also strip off any leading spaces. For the end tag, it will use the first word of the tag only. Consider an ANT build file, which has tags like this: <target name="init"> ... </target> When prompted for the tag you would enter: target name="init" And it will wrap the text in: <target name="init"> ... </target> " Tag Select/Wrapper " These mappings and TagSelection function will allow you to place " an XML tag around either the current word, or the current selected " text nmap <Leader>t viw<Leader>t vnoremap <Leader>t <Esc>:call TagSelection()<CR> nmap <Leader>t viw<Leader>t vnoremap <Leader>t <Esc>:call TagSelection()<CR> function! TagSelection() let l:tag = input("Tag name? ") " exec "normal `>a</" . l:tag . ">\e" " Strip off all but the first work in the tag for the end tag exec "normal `>a</" . \ substitute( l:tag, '[ \t"]*\(\<\w*\>\).*', '\1>\e', "" ) exec "normal `<i" \ substitute( l:tag, '[ \t"]*\(\<.*\)', '<\1>\e', "" ) endfunction

VimTip 347: Format paragraph without changing the cursor position http://vim.sf.net/tip_view.php?tip_id=347 map <silent> <C-j> :let line=line(".")<CR>:let col=col(".")<CR>gqap:exec ":".lin e<CR>:exec "normal " . col . "\ "<CR> imap <silent> <C-j> <Esc>:let line=line(".")<CR>:let col=col(".")<CR>gqap:exec " :".line<CR>:exec "normal " . col . "\ "<CR>a

VimTip 348: Quickly insert a single word http://vim.sf.net/tip_view.php?tip_id=348 I've had something like this for a single character for some time, and this may be something that everyone is already doing, but it's really convenient for me. These two mappings make it quick and easy to insert a word. nmap <buffer> <silent> ,w :exec ":imap \<space\> \<space\>\<esc\>,BB"<cr>i nmap <buffer> <silent> ,BB :exec ":iunmap \<space\>"<cr> Given the sentence: The quick fox. To add the word "brown" you would put your curser on the f in fox and type ",w" (or whatever you decide is a good mapping). Type the word brown. As soon as yo u hit space you are out of insert mode. If there's an easier way to do this, please feel free to comment. Thanks.

VimTip 349: Format your xml document using xmllint http://vim.sf.net/tip_view.php?tip_id=349 If you open an xml document that is either totally or partially unindented, you can use the GNU libxml2 libary's xmllint to reformat and align your document. T his is especially good if you want to save your xml documents using as little sp ace as possible (which would be totally unindented). Just add this under the au tocmd section of your .vimrc file au FileType xml exe ":silent 1,$!xmllint --format --recover - 2>/dev/null" This instructs vim to take the entire contents of a *.xml file and pass it throu gh xmllint, using the --format and --recover flags and silencing any errors that may occur. This is generally a very effective process and will only mess up on very poorly typed (a large amout of incorrect syntax) xml documents. Please no te that xmllint only adds and removes structural space. It does not remove spac e from regular text nodes (as doing so would be incorrect).

VimTip 350: when 'formatoptions' has o easily enter a non commented line: go/gO mappings http://vim.sf.net/tip_view.php?tip_id=350 This is relevant when your 'formatoptions' has o.

From :h fo-table, "Automatically insert the current comment leader after hitting 'o' or 'O' in Normal mode." I like this behavior enough to keep the o option, however at times I want to NOT insert the comment chars, and although manually deleting the added chars is not hard I present these simple mappings that delete the added chars automatically. (from my .vimrc) nnoremap go o<esc>S nnoremap gO O<esc>S This makes go open a new line under the cursor and removes inserted chars, while gO opens a new line above the cursor and removes inserted chars. Your mileage will vary of course (: Happy VIMing!

VimTip 351: Using quickfix in a different way http://vim.sf.net/tip_view.php?tip_id=351 I'm a software developer and I find vim's quickfix (:help quickfix) very helpful . You can also use this while debugging your code, in a slightly different way... Usually, you will have some print messages in your code, and after the program runs, you'll look at the output to see the execution trace (e.g which if-constru cts were taken, how many times did a while loop iterate.. ). If you precede these statements with a <filename>:<linenumber>, then, the program output can be parse d with a :cfile, and the execution trace becomes very simple. For instance, in C++ // fdebug is the pointer to the debug file called, debug.txt say. #define DEBUG_MESG( ) fprintf(fdebug, "%0s:%0d\n", __FILE__, __LINE__) ... function( ) { ... if (something) DEBUG_MESG( ); else DEBUG_MESG( ); ... } Open your code in vim and do a ":cfile debug.txt"

VimTip 352: disabling cabbrev http://vim.sf.net/tip_view.php?tip_id=352 Have you ever been annoyed by an over-zealous cabbrev? A simple way to temporari ly disable it is to set invpaste. Very convenient in combination with the pastet oggle key.

VimTip 353: Swap caps-lock and control keys using MS Windows Registry http://vim.sf.net/tip_view.php?tip_id=353 This will allow you to use the caps-lock key as a control key. Makes using vim i n win32 much nicer in my opinion. Place the following text into a text file with the extension *.reg and update yo ur registry by double-clicking the file: REGEDIT4 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout] "Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,1d,00,3a,00,00,00,00,00

VimTip 354: Find in files - recursively (NOT :grep!). Only for unix clones. http://vim.sf.net/tip_view.php?tip_id=354 You probably know about the grep command in vim (:help grep) There is one limitation of this - you can't search for a pattern recursively in files (why doesn't grep have some kind of -R option for searching recursively? H ave looked around enough at the man pages for that..). The script below does thi s. Cut-paste this in to your .vimrc/_vimrc. Type ":Fif" (without arguments) to s ee usage. " Start of script " Location where the temporary file (.fif.tmp) would be stored let g:Fif_tmp_dir = "/tmp" function! Fif_fun(...) if a:0 == 0 " Print usage info and quit echo "Usage: Fif <pattern-to-be-searched> <file-pattern>. E.g:" echo "Fif struct *.c" echo "searches for the word struct in all the c files from the current directory" return endif if a:0 != 2 echohl Error echo "Error! Wrong number of arguments. Type :Fif with no arguments to see usage" echohl None

return endif let tmp_file = g:Fif_tmp_dir . "/.fif.tmp" execute "!touch " . tmp_file . " 2> /dev/null" if ! filewritable(tmp_file) echohl Error echo "No permissions to create " . tmp_file echo "Try setting the g:Fif_tmp_dir variable to the right value" echohl None return endif " Put quotes around the file pattern let com_string = '!find . -name "' . a:2 . '" ' " Do NOT put quotes around the pattern to be searched - leave it to the us er let com_string = com_string . '-exec grep -n ' . a:1 . ' /dev/null {} \; > ' . tmp_file execute com_string if ! filereadable(tmp_file) echohl Error echo "Can't open " . tmp_file . " for reading" echohl None return endif execute "cfile " . tmp_file execute '!rm -f ' . tmp_file . ' 2> /dev/null' endfunction com -nargs=* Fif call Fif_fun(<f-args>) " End of script. No vim magic here, just some shell util usage. Tested on HPUX. Should work on Windows with Cygwin. You'll have to 1. Remove those /dev/null's 2. Make sure that the Cygwin's find and grep utils are used, and not the windows ones 3. Change the default value of g:Fif_tmp_dir 4. Cygwin's grep differs from the version I have on HP. For forcing grep to prin t the filename, you'll have to give it a "-H" option, in addition to "-n" Some more tinkering can be done with this.. for instance, if you want to search in all the text files, irrespective of the extention, you can consider doing som ething like this: " Find all files. let com_string = '!find . -type f -print ' " Get the file type let com_string = com_string . ' xargs file ' " Filter out the text files let com_string = com_string . " awk '/text/ {print $1}' " " Some formatting to remove the trailing ':' let com_string = com_string . " sed 's/://' " " grep for the pattern in all the files let com_string = com_string . ' xargs grep -n ' . a:1 Cheers! Karthick.

VimTip 355: Comment Lines according to a given filetype http://vim.sf.net/tip_view.php?tip_id=355 There is probably an easier way to do this, but, if I cannot find an easy soluti on for a given problem, I just device one that works for the meantime -- which u sually becomes permanent :-) . This function comments out lines according to file type. So if a file is .sh, it uses # to comment lines. And if a file is type .c it will start the comments wi th /* and end them with */. Put this lines in your .vimrc file: " -------- vimrc --------" comment out highlighted lines according to file type " put a line like the following in your ~/.vim/filetype.vim file " and remember to turn on filetype detection: filetype on " au! BufRead,BufNewFile *.sh,*.tcl,*.php,*.pl let Comment="#" " if the comment character for a given filetype happens to be @ " then use let Comment="\@" to avoid problems... fun CommentLines() "let Comment="#" " shell, tcl, php, perl exe ":s@^@".g:Comment."@g" exe ":s@$@".g:EndComment."@g" endfun " map visual mode keycombo 'co' to this function vmap co :call CommentLines()<CR> " ------- end vimrc ------Now create a ~/.vim/filetype.vim file if you don't have one and add things like these to it (remember to put a line filetype on, in your vimrc file ... again if you don't already have one. Vim nee ds to be compiled with filetype detection support for this to work. You have been warned.): -------- filetype.vim --------if exists("did_load_filetypes") finish endif augroup filetypedetect au! BufRead,BufNewFile *.inc,*.ihtml,*.html,*.tpl,*.class set filetype=php let Comment="<!-- " let EndComment=" -->" au! BufRead,BufNewFile *.sh,*.pl,*.tcl let Comment="#" au! BufRead,BufNewFile *.js set filetype=html mment="" let EndComment="" let EndCo

let Comment="//"

au! BufRead,BufNewFile *.cc,*.php,*.cxx let Comment="//" au! BufRead,BufNewFile *.c,*.h let Comment="/*" augroup END ------ end filetype.vim -------

let EndComment=""

let EndComment="*/"

All set, now whenever you are editing a file of those you have defined in your f iletype.vim script, you can just go into Visual mode, highlight what you want to comment out, and type "co". Simple.

VimTip 356: Quick yank and paste http://vim.sf.net/tip_view.php?tip_id=356 Since I didn't want to interfere with the standard Vim mappings I removed all th e <C-c>, <C-v>, etc. mappings found in the default vimrc. But quickly copy-pasti ng text is a must, so I added the following keymaps. This is very simple, but it works like a charm. vmap nmap imap nmap Niels My vimrc if you're interested: http://home.student.utwente.nl/n.h.m.aandebrugh/_ vimrc <C-Space> "ay <C-Space> "aP <C-Space> <C-o>"ap <C-c> "ayiw

VimTip 357: Adding a console to gdbvim http://vim.sf.net/tip_view.php?tip_id=357 This tip shows how to enhance the gdbvim vimscript #84 by making the outputs from gdb appear in a "console buffer" inside vim. "1.a) In gdbvim.vim, one needs to add the following two buffer " manipulation functions: "-------------------------------------------------------" Buffer manipulation functions {{{1 " " function! s:GdbFocusBuf(nameref) {{{2 " move the focus to the buffer nameref -- create " it if it doesn't exist " return the number of the currently focused buffer " function! s:GdbFocusBuf(nameref) let l:oldnr = bufnr("%") let l:win_nu = bufwinnr(a:nameref) if l:win_nu > 0 execute l:win_nu "wincmd w"

else if bufexists(a:nameref) execute "sbuffer" a:nameref else execute "new" a:nameref endif endif return l:oldnr endfunction " function! s:GdbAppendBuf(nameref, stuff) {{{2 " append stuff to buffer nameref " function! s:GdbAppendBuf(nameref, stuff) let l:oldnr = s:GdbFocusBuf(a:nameref) call append("$", a:stuff) execute "normal G\<End>" return l:oldnr endfunction "1.b) And modify the two source file management functions " to be as follows: "-------------------------------------------------------" Source file management functions {{{1 " function! Gdb_Bpt(id, file, linenum) {{{2 " function! Gdb_Bpt(id, file, linenum) let s:nowfile = a:file let l:curnr = s:GdbFocusBuf(a:file) execute "sign unplace ". a:id execute "sign place " . a:id ." name=breakpoint line=".a:linenum." file =".a:file execute a:linenum endfunction " function! Gdb_CurrFileLine(file, line) {{{2 " function! Gdb_CurrFileLine(file, line) if a:file != 0 let s:nowfile=a:file endif let l:curnr = s:GdbFocusBuf(s:nowfile) execute "silent! " . a:line . "foldopen" execute "sign unplace ". 1 execute "sign place " . 1 ." name=current line=".a:line." file=".s:nowf ile execute a:line endf "1.c) And add the following console function: "-------------------------------------------------------" function! Gdb_Console(stuff, set_prompt) {{{2 " function! Gdb_Console(stuff, set_prompt)

let l:fooey = s:GdbAppendBuf("console", a:stuff) if a:set_prompt == 1 " What needs to happen here is to enter command mode " with the partial command ":Gdb " typed out. " The following line shows what doesn't work " call input(":Gdb ") endif endfunction "1.d) And while we are modifying gdbvim.vim, we could also " add a text section to the definitions of the signs: "-------------------------------------------------------sign define breakpoint linehl=DebugBreak text=bb sign define current linehl=DebugStop text=cc #2) The subroutine worker in the perl script gdbvim needs to # be modified as indicated below. The key points to note # are the two calls the vim-script function Gdb_Console(). # this function processes the gdb output, prints it and sends vim commands sub worker # {{{ { vim_call('Gdb_interf_init(\"'.$PIPE.'\", \"'.$ENV{"PWD"}.'\")'); print GDB_WTR "set prompt (gdb)\\n\n"; while (<GDB_RDR>) { if (/^.*?gdb\)/) { print RL_WTR "READ\n"; chomp ; print $_ . " "; vim_call("Gdb_Console(\\\"$_\\\", 1)"); } else { my $stuff = $_; if( s/Breakpoint ([0-9]+) at 0x.*: file ([^,]+), line ([0-9]+)./Gd b_Bpt($1,\\\"$2\\\",$3)/ s/Breakpoint ([0-9]+), 0x.*at ([^,]+):([0-9]+)/Gdb_CurrFileLin e(\\\"$2\\\",$3)/ s/^\s*0x.*\s+at\s+(\S+):([0-9]+)/Gdb_CurrFileLine(\\\"$1\\\",$ 2)/ s/\032\032([^:]*):([0-9]+).*/Gdb_CurrFileLine(\\\"$1\\\", $2)/ s/^\s*0x\S+\s*([0-9]+)\s+.*/Gdb_CurrFileLine(0, $1)/ ) { chomp; vim_call($_); } print $stuff; chomp($stuff); # the next substitution is because I couldn't figure out how to # pass (from perl) double quotes inside string arguments to # vim-script functions $stuff =~ s/"/'/g;

vim_call("Gdb_Console(\\\"$stuff\\\", 0)"); } } vim_call("Gdb_interf_close()"); close GDB_RDR; close GDB_WTR; }; # }}} That's all the modifications -- and now gdbvim will show the output of gdb inside a vim. (Errors from gdb won't show up in the console but still go to the terminal.) Happy gdbVimming! Acknowledgment: I learnt about functions in vim-scripts by the process of tracking down an annoying behavior in cvscommand.vim vimscript #90. Also, the author of cvscommand.vim, Bob Hiestand, graciously improved my earlier versions of the functions GdbFoucBuf and GdbAppendBuf.

VimTip 358: Get a random colorscheme on vim startup http://vim.sf.net/tip_view.php?tip_id=358 This script picks a colorscheme randomly among all available schemes files when vim starts up. This is similar to vimtip #341, but differs in that it is independent of other script liblaries, besides the randomness. Copy & paste the lines below to somewhere appropriate in your .vimrc. " Create the comma-separated list of colorscheme files let s:colors = substitute(globpath(&runtimepath, 'colors/*.vim'), "\n", ',', 'g' ) " Make backward slashes forward if necessary if (has('dos16') has('dos32') has('win16') has('win32') has('os2')) && !&shellslash let s:colors = substitute(s:colors, '\', '/', 'g') endif if strlen(s:colors) " If there are two or more colorschemes if s:colors =~ ',' let s:rnd = matchstr(localtime(), '..$') + 0 let s:loop = 0 " Rotate the list s:rnd times while s:loop < s:rnd let s:colors = substitute(s:colors, '^\([^,]\+\),\(.*\)$', '\2,\1', '') let s:loop = s:loop + 1 endwhile endif " Obtain the filename of the first colorscheme in the list. e.g.: " c:/home/vimfiles/colors/foo.vim " Then, trim unecessary parts to get this: " foo let s:color = substitute(matchstr(s:colors, '^[^,]\+'), '^.*/\(.*\)\.vim$', '\

1', '') execute "colorscheme" s:color endif unlet! s:colors s:color s:rnd s:loop Please be noted that adding this script might slightly slow down the startup time of vim. Enjoy!

VimTip 359: Download RedHat RPMS of the latest and greatest version of VIM. http://vim.sf.net/tip_view.php?tip_id=359 You can now download RedHat RPMS of the latest and greatest version of VIM. Here is the annoucement: http://marc.theaimsgroup.com/?l=vim&m=103629270123503&w =2 Here is the download link: http://nirvani.org/software/vim/

VimTip 360: ':e <dir>' enter files and directories http://vim.sf.net/tip_view.php?tip_id=360 You can directly enter files with ':e filename', but did you know you can 'enter ' directories that way ? e.g. ':e ..' opens a buffer window with the entries of the parent directory. If you then double click on an entry the directory is opened in the same way (if it's a directory) or the file is opened for editing (if it's a file). (Don't ask me, if it's normal vim behaviour or the effect of any script.)

VimTip 361: Use xdvi (or kdvi) in conjunction with gvim (or vim) and converse http://vim.sf.net/tip_view.php?tip_id=361 source: the xdvi man page For recent xdvi versions (>= 22.38), (or recent Unix/Linux versions), xdvi can interact with any editor provided with a client-server mode. We explain here how to use xdvi in conjunction with vim (compiled with the client-server option) or gvim (mostly compiled with this option). I have tested that with Linux Mandrake 9.0. On that system, gvim is compiled with the client-server option and vim is not. 0-Check that your xdvi version provides the "source-special" functions, by typing 'xdvi -version' or 'man xdvi'

1-Configuration of the source file (file.tex) Put the following line at the beginning of the latex file: \usepackage[active]{srcltx} or the following line at the beginning of the tex file \include{srctex} 2-Configuration of xdvi xdvi has to be called with the following options xdvi -editor 'gvim --remote-wait +%l %f' file.dvi & (or with 'xterm -e vim --remote-wait +%l %f' if vim has been compiled with the client-server option). To make it easier to use you can define an environement variable XEDITOR to set the value of 'editor' or add the following line in your .Xdefaults xdvi.editor: gvim --remote-wait +%l %f Launch 'xrdb -load ~/.Xdefaults' to make sure that xdvi.editor is set to the good value. If you have defined such a variable, xdvi will always be launched with the -editor option. To avoid this unsafe behavior, launch 'xdvi -safer'. 3-Conversely, if you call xdvi within gvim with the -sourceposition option, cursor is placed in the dvi file on the corresponding position. Syntax is: xdvi -sourceposition l:cfile.tex file.dvi l is the line number, c is the column number (Be carefull: there is no space between "c" (column number) and file.tex). To make it easier to use, you can do the following First create a file named for example "xdvi_source.vim" with following lines " This script calls xdvi source and puts cursor in xdvi viewer at " the position corresponding to the position in the source file " :exec "silent !xdvi -sourceposition ".line(".").':'.col(".")."%".' '."%:r.dvi" Then launch the following command within gvim editing the .tex source file. Pressing simultaneously <CTRL> and -> will open the dvi file at the right position: :noremap <buffer> <C-Right> :so xdvi_source.vim<CR>

VimTip 362: matchit.vim and coldfusion (and perhaps others) http://vim.sf.net/tip_view.php?tip_id=362 Hi VIMmites I couldn't get any tags to match in Coldfusion files *.cfm either HTML Javascrip t or ColdFusion tags themselves <cfif ..> ... </cfif> Much pain was gone thru before I realised that the Syntax File for ColdFusion (/syntax/cf.vim) was called cf and not cfm Therefore in matchit.cfm I need to add CF in following line and NOT CFM

au FileType html,jsp,php,cf if !exists("b:match_words") zzapper

VimTip 363: Starting up Vim very fast expecially from a telnet session http://vim.sf.net/tip_view.php?tip_id=363 when you telnet to a remote machine and fire Vim on that machine, sometimes it takes a lot of time for Vim to start. instead if you use vim -X it will start vim almost instantaneously. This is because "-X" options tells vim not to connect to the local X server, which can save a lot of startup time. Also vim -X --noplugin will not load any plugins in $VIMRUNTIME/plugin directory, this will again speed up the starting and is very useful especially when running vim from a Disk mounted over NFS. Njoy

VimTip 364: Automatic file type detection with fully qualified ClearCase names http://vim.sf.net/tip_view.php?tip_id=364 I am using the great plugin from Douglas Potts (vimscript #15). When you load a specific ClearCase version of a file, vim cannot find the correc t file type in the full name (ex. filename.c@@/main/foo/1). To improve that, you can create an autocommand in the filetype.vim file in your user runtime directo ry. augroup filetypedetect au BufNewFile,BufRead */*@@* \ if expand("<afile>") =~ '@@' \ exe "doau filetypedetect BufRead " . expand("<afile>:s?@@.*$??") \ endif augroup END The test in the command is for compatibility with path containing '@@' sequence.

VimTip 365: Vim Book Online http://vim.sf.net/tip_view.php?tip_id=365

New Riders has released Steve Oualline book Vi iMproved (VIM) under their Open P ublication License (OPL). View it at http://www.newriders.com/books/opl/ebooks/ 0735710015.html

VimTip 366: really basic RCS interaction from within vim http://vim.sf.net/tip_view.php?tip_id=366 I've looked all around and haven't found RCS functions built into vim (which s urprises me, really), so I looked more and found some almost working RCS scripts for text-mode. Key there is almost. It's still a kludge, but it works without too much hassle. I've chosen F1 and F2, because I never use those keys for what they are inten ded. I use :help for command reference, not for a tutorial style thing. So, us e some discretion. Also, the write command could just as easily have been a :wr ite!, but I decided against that in the case of files that weren't checked out. You should check them out, first, and they should be writable. map <F1> map <F2> :write %<CR>:!ci -l %<CR>:edit!<CR> :!co -l %<CR>:edit!<CR>

New RCS files work just fine with the first mapping. There would be some use to creating the RCS directory, if it's not already the re, but I don't see an "if exists and is directory" function, right now. There's a good menu-driven rcs client for graphical vim, but I hate menus and graphical interfaces.

VimTip 367: What is this $VIMRUNTIME ? http://vim.sf.net/tip_view.php?tip_id=367 $VIMRUNTIME points to a directory where most of the files needed by Vim are kept . As the name suggests these files are needed during "run-time". Though they are n ot necessary for Vim to run, but they help in adding extra functionality to the basic Vim. Here is a brief overview of files and directories in $VIMRUNTIME. bugreport.vim :- Use this file if you think you have discovered a bug in VIM. se e "help bugreport" colors :- Contains various clorschemes. see ":help :colorscheme" compiler :- Contains compilation scripts for various languages. see ":help :comp iler" delmenu.vim :- Deletes all Menu's doc :- Contains Documentation :-) evim.vim :- script for easy vim. see :help evim"

filetype.vim :- Detects filetype of files based on their extensions. see "help f iletype" ftoff.vim :- SOurce this to disable ditection of filetypes. ftplugin :- Contains plugins that are loaded based on the filetype. ftplugin.vim :- Enables flietype plugins ftplugof.vim :- Disables filetype plugins gvimrc_example.vim :- The name says it all, right :-) indent :- contains indentaion scripts for various languages indent.vim :- Enables indentation based on filetype. indoff.vim :- Disables indentation based on filetype. keymap :- Contains keymap files for various encodings. see ":help keymap" lang :- Contains Message files in different language. see ":help language" macros :- Contains variuos cool stuff. read "macros/README.txt" menu.vim :- Default Menus mswin.vim :- sets options for Vim to behave like Windows. optwin.vim :- commands to create option window. plugin :- Contains plugins. All .vim files in this directory are automatically s ourced. scripts.vim :- helps detect filetype in Vim scripts. syntax :- Contains Syntax defination files for various programming languages.see ":help syntax" tools :- Some useful tools. like blink to blink the cursor in xterm. tutor :- Contains tutor.vim. see ":help tutor" vim32x32.xpm :- Vim Logo. vimrc_example.vim :- again name says it all. ~

VimTip 368: Use gvim in VS.Net http://vim.sf.net/tip_view.php?tip_id=368 This tip presumes you have both VS.Net (Developer Studio.Net) and gvim installed , and know where gvim is located on your system. - Create a solution in VS.Net, any project type will do. - In the solution explorer (View->Solution or Ctrl + R) you should see a list of files (click on the "Solution Explorer" tab if you do not see the file list). - Right click on any of the files and choose "Open With...", this brings up the Open With dialog. - Click on "Add..." this brings up the Add Program dialog. - Click on "Browse..." and point the Browse dialog to your gvim location. - You have now added gvim to the list of editors, you may also select gvim to be the default editor for that file type. You may need to do this for all file types you wish to edit with gvim. And yes y ou still have VS.Net open the file in its own editor. Of course if you want to reverse changes simply remove gvim from the list of edi tors and why would you want to do that? :) Enjoy!

Vous aimerez peut-être aussi