*vimtips.txt* from http://www.devious.dk/rss/vimtips.txt For all info on vim see http://vim.sourceforge.net/ Thanks for using vim online. VimTip 1: the super star http://vim.sourceforge.net/tip_view.php?tip_id= When a discussion started about learning vim on the vim list Juergen Salk mentioned 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 earlier... 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.sourceforge.net/tip_view.php?tip_id= 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 taught me a nice way to do this. Add the following snipit to your vimrc: " Edit another file in the same directory as the current file " uses expression to extract path from current file's path " (thanks Douglas Potts) if has("unix") map ,e :e =expand("%:p:h") . "/" else map ,e :e =expand("%:p:h") . "\" endif Then when you type ,e in normal mode you can use tab to complete to the file. You can also expand this to allow for spitting, etc. Very very nice. VimTip 3: use vim to quickly compile java files http://vim.sourceforge.net/tip_view.php?tip_id= 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 was frustrated. I couldn't figure out why. (Beyond my machine crashing twice a day.) Finally I upgraded to windows 2000 (kind of stable!) and started using vim as 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 the Jikes complier first. (Jikes is from ibm, search on google for jikes and you will 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 file 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 your classpath/path setup or use the "let" command to configure it in your vimrc. VimTip 4: Any word completion http://vim.sourceforge.net/tip_view.php?tip_id= Either when programming or writing, I tend to have some identifiers or words that I use all the time. By sheer accident, I noticed the 'ctrl-n' command, that will attempt to complete the word under the cursor. Hit it once, and it will try to 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 the current one. Repeated invocations will cycle through all found matches. VimTip 5: Quickly searching for a word http://vim.sourceforge.net/tip_view.php?tip_id= 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 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 the cursor from the current cursor position to the end of the file, press the shift key and click on the word using the left mouse button. To search in the opposite direction, press the shift key and click on the word using the the right mouse button. To get more help on these, use :help * :help # :help g* :help g# :help :help VimTip 6: Using the % key http://vim.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= '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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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 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.sourceforge.net/tip_view.php?tip_id= 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 i_Ctrl-N :help i_Ctrl-P :help ins-completion :help complete VimTip 12: Converting tabs to spaces http://vim.sourceforge.net/tip_view.php?tip_id= 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 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= From Johannes Zellner on the vim list: You can use vim's makeprg and equalprg to clean up HTML. First download html tidy 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 clean up sections. :help = :help equalprg :help makeprg VimTip 19: line numbers... http://vim.sourceforge.net/tip_view.php?tip_id= I have started doing all my code reviews on a laptop because of the number command. :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.sourceforge.net/tip_view.php?tip_id= 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 backupdir=./.backup,.,/tmp set 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= Check out your .vimrc. If 'set notitle' is an entry, comment it out with a quotation 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 files at the same time. by [jonasbn@wanadoo.dk] VimTip 24: changing the default syntax highlighting http://vim.sourceforge.net/tip_view.php?tip_id= 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 be 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.sourceforge.net/tip_view.php?tip_id= The following settings in .vimrc will enable color highlighting when using SecureCRT 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 "" VimTip 26: Getting rid of ^M - mixing dos and unix http://vim.sourceforge.net/tip_view.php?tip_id= If you work in a mixed environment you will often open files that have ^M's in them. 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 breaks so you end up with some lines that have both a carrage return and a ^M and some lines that have a ^M and no carrage return (and so blend into one). There are 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 expression will replace all the ^M's that have carriage returns after them with nothing. (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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= With Unix-like environment, you can use cat or awk to generate a line number easily, 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.sourceforge.net/tip_view.php?tip_id= :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 search, `v' also perform a search but it match the line not match the canonical expression. 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.sourceforge.net/tip_view.php?tip_id= To increase a number under or nearest to the right of the cursor, go to Normal mode 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.sourceforge.net/tip_view.php?tip_id= 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' without asking for confirmation :%s/foo/bar/gc find each occurance of 'foo' and replace it with 'bar' asking for confirmation first :%s//bar/gc find (match exact word only) and replace each occurance of 'foo' with 'bar' :%s/foo/bar/gci find (case insensitive) and replace each occurance of 'foo' with 'bar' :%s/foo/bar/gcI find (case sensitive) and replace each occurance of 'foo' with 'bar' NB: Without the 'g' flag, replacement occurs only for the first occurrence in each line. For a full description and some more interesting examples of the substitute command refer to :help substitute See also: :help cmdline-ranges :help pattern :help gdefault VimTip 32: Write your own vim function(scripts) http://vim.sourceforge.net/tip_view.php?tip_id= 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 function, 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 //style :g#/*(.{-})*/#//1# /* .... .... ..... */ =====> //...... //...... //...... style: ? Anyone implement it? VimTip 36: Using Gnu-info help in vim http://vim.sourceforge.net/tip_view.php?tip_id= K in normal bring you the man page about the keyword under current cursor. :nnoremap :exe ":!info ".expand("") Now press F1 while the cursor is hold by a keyword such as printf will bring you to Gnu-info help page :h :h nnoremap VimTip 37: The basic operation about vim-boolean optionals http://vim.sourceforge.net/tip_view.php?tip_id= :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.sourceforge.net/tip_view.php?tip_id= If your tierd of the cursor jumping past 5 lines when :set wrap then add these mappings to you vimrc file. nnoremap j gj nnoremap k gk vnoremap j gj vnoremap k gk nnoremap gj nnoremap gk vnoremap gj vnoremap gk inoremap gj inoremap gk What they do is remap the cursor keys to use there `g' equvilant. See :help gj VimTip 39: Undo and Redo http://vim.sourceforge.net/tip_view.php?tip_id= To undo recent changes, use the u[ndo] command: u undo last change (can be repeated to undo preceding commands) U return the line to its original state (undo all changes in current line) CTRL-R 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.sourceforge.net/tip_view.php?tip_id= 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 inserts the file foo.txt below the cursor :0r foo.txt inserts the file foo.txt above the first line :r !ls inserts a listing of your directory below the cursor :$r !pwd 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.sourceforge.net/tip_view.php?tip_id= 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 : exe "let linenum=".v:count:1,$-1dj:exe lin enum."y"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.sourceforge.net/tip_view.php?tip_id= To mark one or more positions in a file, use the m[ark] command. Examples: ma - set current cursor location as mark a 'a - jump to beginning of line of mark a `a - jump to postition of mark a d'a - delete from current line to line of mark a d`a - delete from current cursor position to mark a c'a - change text from current line to line of mark a y`a - yank text to unnamed buffer from cursor to mark a :marks - 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.sourceforge.net/tip_view.php?tip_id= To define abbreviations, use the ab[breviate] command. Examples: :ab rtfm read the fine manual - Whenever you type 'rtfm' followed by a (or or ) vim will expand this to 'read the fine manual'. :ab - list all defined abbreviations :una[bbreviate] rtfm - remove 'rtfm' from the list of abbreviations :abc[lear] - remove all abbreviations NB: To avoid expansion in insert mode, type CTRL-V after the last character of the abbreviation. For a detailed description of the ab[breviate] command and some more examples refer to :help abbreviations VimTip 44: Repeat last changes http://vim.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= You can recall previous command lines from a history table by hitting the and cursor keys in command-line mode. For example, this can be used to find the previous substitute command: Type ":s" and then . 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 - Display command-line history. :his s - 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.sourceforge.net/tip_view.php?tip_id= > 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.sourceforge.net/tip_view.php?tip_id= To swap two characters or lines, use the following commands: xp - delete the character under the cursor and put it afterwards. (In other words, it swaps the characters.) ddp - 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.) dawbP - 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.) VimTip 48: Moving around http://vim.sourceforge.net/tip_view.php?tip_id= You can save a lot of time when navigating through the text by using appropriate movements commands. In most cases the cursor keys, or 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 - move to the end of a word w - move forward to the beginning of a word 3w - move forward three words b - move backward to the beginning of a word 3b - move backward three words $ - move to the end of the line - same as $ 0 - move to the beginning of the line - same as 0 ) - jump forward one sentence ( - jump backward one sentence } - jump forward one paragraph { - jump backward one paragraph H - jump to the top of the display M - jump to the middle of the display L - 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.sourceforge.net/tip_view.php?tip_id= To switch the case of one or more characters use the "~", "gU" or "gu" commands. Examples: ~ - switch case of character under cursor (in visual-mode: switch case of highlighted text) 3~ - switch case of next three characters g~~ - switch case of current line U - in visual-mode: make highlighted text uppercase gUU - make current line uppercase u - in visual-mode: make highlighted text lowercase guu - make current line lowercase gUaw - make current word uppercase guaw - make current word lowercase For some more examples refer to :help ~ See also: :help simple-change VimTip 50: Recovering files http://vim.sourceforge.net/tip_view.php?tip_id= If your computer has crashed while editing a file, you should be able to recover the file by typing vi -r where 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.sourceforge.net/tip_view.php?tip_id= 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 " a ^ 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= One of the keys to vim is buffer management. If I have to use another IDE that makes 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 gets a little unweildly once you have a full project open so you can also use :b to complete to an open buffer. This is really nice because you can type any fragment of a file name and it will complete to the matching file. (i.e. RequestManager.java can be completed using "tma" or "req" or "r.java"). Now for awhile I was also using :bn and :bp which jumps you to the next and previous 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 are 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.sourceforge.net/tip_view.php?tip_id= 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 j, k, etc. At some point you accidently hit 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 o functionality; put this in your .vimrc: nnoremap O :echo "sucker" nnoremap o :echo "sucker" nnoremap :echo "sucker" references: :help :only :help CTRL-W_o That is all. Scott VimTip 62: Applying substitutes to a visual block http://vim.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= Sometimes I think it's helpful if your working directory is always the same as the 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 switch 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.sourceforge.net/tip_view.php?tip_id= Although :set number will add nice line number for you At time you may wish to actually place the line numbers into the file. For example on GNU Unix you can acomplish 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.sourceforge.net/tip_view.php?tip_id= 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 nmap xw :'a,.w! $HOME/.vimxfer vmap xr c:r $HOME/.vimxfer vmap xw :w! $HOME/.vimxfer else nmap xr :r c:/.vimxfer nmap xw :'a,.w! c:/.vimxfer vmap xr c:r c:/.vimxfer vmap xw :w! c:/.vimxfer endif VimTip 67: Ascii Value http://vim.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= Don't worry if your delete key does not work properly. Just press -Backspace. It works under both mode(insert or normal). VimTip 69: dot makes life easier http://vim.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= If you use gvim, you can transfer text from one instance of gvim into another one 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: * VimTip 72: Remove unwanted empty lines http://vim.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= With the addition of folding, Vim6 can function as a high performance outline processor. Simply :set ai and in insert mode use backspace to promote and tab to demote headlines. In command mode, << promotes (n<< to promote multiple lines), and >> demotes. Also, 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/vimoutliner/index.htm. Steve (Litt) slitt@troubleshooters.com VimTip 75: Remap CAPSLOCK key in Windows 2000 Professional and NT4.0 http://vim.sourceforge.net/tip_view.php?tip_id= If you're Windows 2000 Professional user and got tired to move your hands off basic row when hitting key here the solution (not for Windows 9x.): remap CapsLock key as key. It's located in useful position. Put this lines into 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 as : 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.sourceforge.net/tip_view.php?tip_id= 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 through 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 all 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 someone 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 list 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.sourceforge.net/tip_view.php?tip_id= 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 last 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 source 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 method 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 one 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() " View the methods and variables in a java source file." command! Japi Fs public\|protected\|private VimTip 78: rotating mail signatures http://vim.sourceforge.net/tip_view.php?tip_id= For people using mutt and vim for mail, the following script will allow you to insert a new signature (and again and again if you don\'t like the current one) at the bottom of your mail. This is usefull eg when you don\'t want to send a potentially 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 paste another one in. (I put it here in \'tips\' and not in \'scripts\' because it is imo too short to be a \'real\' script) " rotate_sig.vim " Maintainer: Roel Vanhout " Version: 0.1 " Last Change: Tuesday, June 12, 2001 " Mapping I use: " nmap ,r :call RotateSig() " 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 not- " found marker) function! RotateSig() normal mQG execute '?^-- $' execute ':nohl' normal o normal dG normal execute 'r !~/bin/autosig ~/.quotes \%' normal `Q endfunction VimTip 79: How to use :grep to get a clickable list of function names http://vim.sourceforge.net/tip_view.php?tip_id= 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 :call ShowFunc() 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.sourceforge.net/tip_view.php?tip_id= Here's something for your <.vimrc> which will allow you to restore your cursor position in a file over several editing sessions. This technique uses the viminfo 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 help for viminfo to see if you like the settings above). For Windows you'll need to 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 the s and S commands http://vim.sourceforge.net/tip_view.php?tip_id= 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 reference 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 only needed to subsititute the characters foo_bar, I set the cursor on the first character where I'd like the subsitution to begin and type 7s. VIM drops the characters 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 replace them, I just discovered the S command. If you need to subsitute three lines 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.sourceforge.net/tip_view.php?tip_id= this is a simple function i wrote to get the value of a variable from three different places (in that order): the current buffer, the global setting or from the script itself. this allows me to set a default value for a configuration variable inside my script and the user to change it on a global level by setting the same variable with a g: prepended. then, they can further set it on a per-buffer level by the the b: mechanism. one of the examples for this might be my comments script (not uploaded). 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 " vim comments should hug the first column, always " 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 SOME default value. VimTip 83: how to indent (useful for source code) http://vim.sourceforge.net/tip_view.php?tip_id= Here is the most useful vim command that I know of and I'm surprised that it's not yet in the tips list. I use the indent features of vim all the time. Basically, it lets you indent your 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 lines) Tell me that isn't great? VimTip 84: Changing the behaviour of . to include visual mode http://vim.sourceforge.net/tip_view.php?tip_id= 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 . 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 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_"$r" the ^ is because my java code is indented and i don't want to go to column 0 and the 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.sourceforge.net/tip_view.php?tip_id= If you do not have vim 6.0, but would like to mimic the plugins directory feature 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 directory. Now, to add a new plugin, just drop the script in this directory and vim will automatically find it. VimTip 86: Helps undo 1 line when entered many http://vim.sourceforge.net/tip_view.php?tip_id= When U entered text, U cannot undo only 1 line, for example, when U press "u", all entered in last "insert" text removed. If U add this line to .vimrc: inoremap ^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.sourceforge.net/tip_view.php?tip_id= The format of the window title in vim 5.x (well, at least for 5.7,.8, for Win32) used to be VIM - . 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.sourceforge.net/tip_view.php?tip_id= Maybe it's just because I have far too small of a monitor, because I can get distracted 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 startup. au GUIEnter * simalt ~x :he win16-maximized VimTip 89: Get more screen real estate by hidding toolbar and/or menus http://vim.sourceforge.net/tip_view.php?tip_id= 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 toolbar 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= This tip will will explain how to use the dictionary completion facilities provided by vim. This can be useful if you use vim to type your email, edit code, etc. Dictionary completion is one of many search facilites provided by Insert mode completion. It allows the user to get a list of keywords, based off of the current word at the cursor. This is useful if you are typing a long word (e.g. acknowledgeable) 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. See :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 "acknowledgeable" I would do the following in insert mode: acknow 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 through a predetermined set of completion sources. By default, dictionary completion is not a part of this set. This set is defined by the 'complete' option. Therefore, 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 This shortcut may not save a whole lot of typing. However, I find that it requires less hand movement to only worry myself with two key combinations, rather than 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 underscores in them. For more help: help ins-completion help compl-dictionary help 'complete' help 'dictionary' help :set+= VimTip 92: Reducing 'doc' directory size http://vim.sourceforge.net/tip_view.php?tip_id= As everyone knows, the $VIMRUNTIME/doc is increasing rapidly in size. The directory 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 uncompress 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' file 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 can be reffered :) VimTip 93: if you use 'highlight search' feature, map a key to :noh http://vim.sourceforge.net/tip_view.php?tip_id= It is very convenient to use 'hlsearch' option. However it can be annoying to have the highlight stick longer than you want it. In order to run it off you have 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 to do it: nmap :silent noh VimTip 94: Questions & Answers about using tags with Vim http://vim.sourceforge.net/tip_view.php?tip_id= 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 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 will jump to the tag named . 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 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_], , g, :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 key. 4. You can press the g key and then click the right mouse button. Help keyword(s): :pop, Ctrl-T, , g 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. 2. You can position the cursor over the tag and press g Ctrl-]. 3. You can visually select a text and press g Ctrl-] to jump or list the matching tags. 4. You can use the 'stjump' ex command. This will open the matching or selected tag from the tag list in a new window. 5. You can press Ctrl-W g Ctrl-] to do a :stjump. 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 / :stag / :ptag / :tselect / :tjump / :ptselect / :ptjump / 2. If you have the 'wildmenu' option set, then you can press the 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 key to select a tag. 3. If you don't have the 'wildmenu' option set, you can still use the 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 " 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.sourceforge.net/tip_view.php?tip_id= 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 horrible 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 able 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.sourceforge.net/tip_view.php?tip_id= You can - like me :o) - use gvim, like replacement of internal AutoCad MTEXT editor. You need switch variable MTEXTED to "gvim" (or maybe fullpath, something like "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 accustomed vith gvim) or start gvim from gvim.lnk or gvim.bat (I'am using windows95) and 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 &AutoCad.Insert.Space \~ vmenu &AutoCad.Insert.Space `% imenu &AutoCad.Insert.Backslash \\ vmenu &AutoCad.Insert.Backslash `% imenu &AutoCad.Insert.Brackets \{\}F\i vmenu &AutoCad.Insert.Brackets `>a\}`% imenu &AutoCad.Insert.Paragraph \P vmenu &AutoCad.Insert.Paragraph `>a\P% imenu &AutoCad.-SEP1- : imenu &AutoCad.Colour.Red \C1; vmenu &AutoCad.Colour.Red `>a\C7;`% imenu &AutoCad.Colour.Yellow \C2; vmenu &AutoCad.Colour.Yellow `>a\C7;`% imenu &AutoCad.Colour.Green \C3; vmenu &AutoCad.Colour.Green `>a\C7;`% imenu &AutoCad.Colour.Cyan \C4; vmenu &AutoCad.Colour.Cyan `>a\C7;`% imenu &AutoCad.Colour.Blue \C5; vmenu &AutoCad.Colour.Blue `>a\C7;`% imenu &AutoCad.Colour.Violet \C6; vmenu &AutoCad.Colour.Violet `>a\C7;`% imenu &AutoCad.Colour.Black \C7; vmenu &AutoCad.Colour.Black `>a\C7;`% imenu &AutoCad.Colour.D_Grey \C8; vmenu &AutoCad.Colour.D_Grey `>a\C7;`% imenu &AutoCad.Colour.L_Grey \C9; vmenu &AutoCad.Colour.L_Grey `>a\C7;`% imenu &AutoCad.Font.Arial \fArial; vmenu &AutoCad.Font.Arial `% imenu &AutoCad.Font.Symbol \Fsymbol; vmenu &AutoCad.Font.Symbol `% imenu &AutoCad.Font.RomanC \Fromanc; imenu &AutoCad.Font.RomanC `% imenu &AutoCad.Font.RomanS \Fromans; vmenu &AutoCad.Font.RomanS `% imenu &AutoCad.Font.RomanD \Fromand; vmenu &AutoCad.Font.RomanD `% imenu &AutoCad.Font.RomanT \Fromant; vmenu &AutoCad.Font.RomanT `% imenu &AutoCad.Size.0_5x \H0.5x; vmenu &AutoCad.Size.0_5x `% imenu &AutoCad.Size.1_5x \H1.5x; vmenu &AutoCad.Size.1_5x `% imenu &AutoCad.Size.2x \H2x; vmenu &AutoCad.Size.2x `% imenu &AutoCad.Size.3x \H3x; vmenu &AutoCad.Size.3x `% imenu &AutoCad.Effects.Set_Out_1_5 \T1.5; vmenu &AutoCad.Effects.Set_Out_1_5 `>a\T1;`% imenu &AutoCad.Effects.Set_Out_2 \T2; vmenu &AutoCad.Effects.Set_Out_2 `>a\T1;`% imenu &AutoCad.Effects.-SEP3- : imenu &AutoCad.Effects.Tilt_15deg \Q15; vmenu &AutoCad.Effects.Tilt_15deg `>a\Q0;`% imenu &AutoCad.Effects.Tilt_20deg \Q20; vmenu &AutoCad.Effects.Tilt_20deg `>a\Q0;`% imenu &AutoCad.Effects.Tilt_30deg \Q30; vmenu &AutoCad.Effects.Tilt_30deg `>a\Q0;`% imenu &AutoCad.Effects.-SEP4- : imenu &AutoCad.Effects.Change_Width_0_5x \W0.5; vmenu &AutoCad.Effects.Change_Width_0_5x `>a\W1;`% imenu &AutoCad.Effects.Change_Width_2x \W2; vmenu &AutoCad.Effects.Change_Width_2x `>a\W1;`% imenu &AutoCad.Effects.-SEP5- : imenu &AutoCad.Effects.Justify_Down \A0; vmenu &AutoCad.Effects.Justify_Down `% imenu &AutoCad.Effects.Justify_Middle \A1; vmenu &AutoCad.Effects.Justify_Middle `% imenu &AutoCad.Effects.Justify_Up \A2; vmenu &AutoCad.Effects.Justify_Up `% imenu &AutoCad.Effects.Overlined_Characters \O\oF\i vmenu &AutoCad.Effects.Overlined_Characters `>a\O`% imenu &AutoCad.Effects.Underlined_Characters \L\lF\i vmenu &AutoCad.Effects.Underlined_Characters `>a\l`% imenu &AutoCad.Effects.Index_Top \S^; imenu &AutoCad.-SEP6- : imenu &AutoCad.Help ***Quit Editor: press Alt-F4 and 'No' *** star VimTip 97: How do I add a current time string inside Vim? http://vim.sourceforge.net/tip_view.php?tip_id= This is a *request* for a tip. Sometimes (eg. editing HTML pages) I need to add a timestamp string to my editing buffer. On UNIX systems, I can use :r!date to get a localized date time string; but on Windows ('date' on Windows will query 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.sourceforge.net/tip_view.php?tip_id= 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, there 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 traffic 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.com/groups?hl=en&safe=off&group=comp.editors. Using the tips database for asking questions is not likely to work well. For example, 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 search 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.sourceforge.net/tip_view.php?tip_id= 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 :echo "hi<" . synIDattr(synID(line("."),col("."),1),"name") . '> trans<' . synIDattr(synID(line("."),col("."),0),"name") . "> lo<" . synIDattr(synIDtrans(synID(line("."),col("."),1)),"name") . ">" 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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 feature: 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.sourceforge.net/tip_view.php?tip_id= I'm used to complete words with , 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 key in insert mode while still being able to use it when at the start of a line or when the preceding char is not a keyword character. in a script file in a plugin directory or in your .vimrc file: first define a function which returns a or a depending on the context: function InsertTabWrapper() let col = col('.') - 1 if !col || getline('.')[col - 1] !~ '\k' return "\" else return "\" endif endfunction then define the appropriate mapping: inoremap =InsertTabWrapper() the trick here is the use of the = in insert mode to be able to call your function without leaving insert mode. :help i_CTRL-R Benoit VimTip 103: Move to next/previous line with same indentation http://vim.sourceforge.net/tip_view.php?tip_id= 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 line you are currently on. nn k:call search ("^". matchstr (getline (line (".")+ 1), '\(\s*\)') ."\\S", 'b')^ nn :call search ("^". matchstr (getline (line (".")), '\(\s*\)') ."\\S")^ will map Alt-< and Alt-> in Normal mode to upward and downward searching for lines with the same indent as the current line. VimTip 104: using vim to complement Perl's DBI::Shell http://vim.sourceforge.net/tip_view.php?tip_id= 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 give 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 database 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.sourceforge.net/tip_view.php?tip_id= I sometimes found myself moving down a few lines with j, then scrolling down about the same number of lines with to put the cursor in roughly the same place as it started. I decided I wanted to map (and , respectively) to the move-and-scroll operation. First, I did :map j This was pretty good, but behaved funny at the beginning and end of files. Then, I realized that already combined move and scroll, so I figured that giving a count of 1 would do it: :map 1 Unfortunately, this permanently attaches a count to (ugh!), so I have to undo that: :map 1:set scroll=0 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 that did not have the side-affect of changing scroll. Happy vimming, Andrew VimTip 106: Mail signature rotation: Supersimple one-line solution http://vim.sourceforge.net/tip_view.php?tip_id= Hallo, next solution for _most_simple_ signature rotater: You can only put one line to your .vimrc || _vimrc: map ms :e c:\sign.txtggV/--k"*xG$a*:w:bdG$a"*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 insert in your mail. In c:\sign.txt will be first signature pushed to the end of this file. When You want use other signature, only press 'u' and \ms again (Or You can change \ms to e.g. , indeed. ) You can change this and append one part like 'basic' from command and append 'changing' part from .signature file, as you like... Ok, one unpleasant thing is here: your signature must not contain '--' (signature separator)... Anyhow, I find it useful brz* http://brz.d2.cz/ VimTip 107: C/C++: convert enum to string table http://vim.sourceforge.net/tip_view.php?tip_id= 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 following lines to your _GVIMRC file: 31amenu C/C++.transform\ enum2Stringtab :s#[ ]*\\(\\w\\+\\)#/* \\1 */ "\\1"#o};uOstatic const char* const Names[] = {/sdfsdf 31vmenu C/C++.transform\ enum2Stringtab :s#[ ]*\\(\\w\\+\\)#/* \\1 */ "\\1"#o};uOstatic const char* const Names[] = {/sdfsdf 31amenu C/C++.transform\ enum2String :s#[ ]*\\(\\w\\+\\)#/* \\1 */ "\\1"#o}/sdfsdf 31vmenu C/C++.transform\ enum2String :s#[ ]*\\(\\w\\+\\)#/* \\1 */ "\\1"#o}/sdfsdf 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.sourceforge.net/tip_view.php?tip_id= When viewing/editing a folded file, it is often needed to inspect/close some fold. 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 :call ToggleFold() See :help folding for more information about folding. VimTip 109: jump between files http://vim.sourceforge.net/tip_view.php?tip_id= Often I know I'm likely to edit many files. I run 'vim *.pl' and get a whole bunch of open files. To make jumping between files to a pleasure, I defined to mapss: map :previous map :next Press F1 to go back and F2 to go forward. -- Kirill VimTip 110: text->html table converter. http://vim.sourceforge.net/tip_view.php?tip_id= Below are two functions and a mapping which will convert lines of plain text into HTML table code. For example, you have several lines like: ----------------------------------------------- 1 2 3 4 5 6 --------------------------------------------------- by visualizing all the 7 lines and press , you can change the text into
1 2 3
4 5 6
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" else exe "normal IA>>" endif let i=i+1 endwh exe "normal o<<" exe ":" . start exe "normal O<<" endfunc vmap :call Table() 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 highlighting http://vim.sourceforge.net/tip_view.php?tip_id= I have found it undesirable to use :hardcopy directly because it uses the current syntax highlighting to determine how to print the text. For example, I like to print comments in italics, but I don't like italic fonts on the screen. This tip will show you how to set up a colorscheme for printing and use it only when you print. 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 term=italic cterm=italic gui=italic highlight Constant term=bold cterm=bold gui=bold etc.... I then defined the following command in my .vimrc file: command! -nargs=* Hardcopy call DoMyPrint("") 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.sourceforge.net/tip_view.php?tip_id= Paul Wright posted a tip which explained how to jump back and forth between lines with the same indentation level. I do this a lot, so I came up with this slightly 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 versions) in operator pending mode, meaning that you can do a d]l. The motion is specified as being exclusive when in operator pending mode. When might you use this? If you're writing programs in Python, Haskell, or editing XML files, they will be very useful. E.g. in XML you can jump to the outer enclosing 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: Motion is exclusive " false: Motion is inclusive " fwd (bool): true: Go to next line " false: Go to previous line " lowerlevel (bool): true: Go to line with lower indentation level " false: Go to line with the same indentation level " skipblanks (bool): true: Skip blank lines " false: 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 back and forth between lines of same or lower indentation. nnoremap [l :call NextIndent(0, 0, 0, 1) nnoremap ]l :call NextIndent(0, 1, 0, 1) nnoremap [L :call NextIndent(0, 0, 1, 1) nnoremap ]L :call NextIndent(0, 1, 1, 1) vnoremap [l :call NextIndent(0, 0, 0, 1)m'gv'' vnoremap ]l :call NextIndent(0, 1, 0, 1)m'gv'' vnoremap [L :call NextIndent(0, 0, 1, 1)m'gv'' vnoremap ]L :call NextIndent(0, 1, 1, 1)m'gv'' onoremap [l :call NextIndent(0, 0, 0, 1) onoremap ]l :call NextIndent(0, 1, 0, 1) onoremap [L :call NextIndent(1, 0, 1, 1) onoremap ]L :call NextIndent(1, 1, 1, 1) VimTip 113: Translator in vim (Windows solution) http://vim.sourceforge.net/tip_view.php?tip_id= Hallo, today I found script "translate.vim", but on Windows this will be probably 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 under cursor. In 'normal' is only displayed window with translations, in 'insert' is word under cursor deleted and is insert selected form of word from translantion 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/agrep/index.html map b"*yw:! c:/bin/agrep -wih * "c:/dict/an-cs.txt" imap b"*yw:! c:/bin/agrep -wih * "c:/dict/an-cs.txt"dwi * map b"*yw:! c:/bin/agrep -ih * "c:/dict/an-cs.txt" imap b"*yw:! c:/bin/agrep -ih * "c:/dict/an-cs.txt"dwi * brz* VimTip 114: Browsing by paragraph http://vim.sourceforge.net/tip_view.php?tip_id= It can be done by reaching the blank lines in up and down directions just by pressing { ---- 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.sourceforge.net/tip_view.php?tip_id= It can be done by reaching the blank lines in up and down directions just by pressing { ---- 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.sourceforge.net/tip_view.php?tip_id= Sometimes it is useful to know all the occurances of the word under cursor in all 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.sourceforge.net/tip_view.php?tip_id= Searching for a word across the project wastes most of the developres time, which 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 file 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()execute "/\\<" . g:word . "\\>" map _n :nexecute "/\\<" . g:word . "\\>" function ID_search() let g:word = expand("") 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 preference but I use ^K and ^L for this purpose. VimTip 118: Configuring gVim as Internet Explorer 'View Source' editor http://vim.sourceforge.net/tip_view.php?tip_id= Within the registry, you can specify the source editor to be used by Internet Explorer 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 filenames which contain spaces. This will cause problems for Vim because Vim treats each space as an argument separator. If an unquoted filename contains spaces, Vim treats the filename as multiple arguments and will open multiple files instead 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 ' Making variable declaration mandatory option explicit dim oWShell, sArg, sFile ' Create script object set oWShell = CreateObject("wscript.shell") ' Loop through arguments for 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 registry: HKEY_LOCAL_MACHINE |- Software |- Microsoft |- Internet Explorer |- View Source Editor |- Editor Name (Default) = D:\Programs\Vim\gvim.vbs Freddy Vulto http://fvu.myweb.nl/Projects/Vim/Web/vim.htm VimTip 119: Explorer startup and shutdown http://vim.sourceforge.net/tip_view.php?tip_id= 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 explorer is started when vim is started. I also noticed and fixed that the explorers 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 explorer when it's the only window that's left. I'd actually like to take this a step further and close the window if the last _document_ window is closed. I'd prefer 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 easy 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 " this would be useful if you were calling this " 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 explorer 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.sourceforge.net/tip_view.php?tip_id= The $VIMRUNTIME/compiler has 'jikes.vim', but there's nothing for traditional Sun 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.sourceforge.net/tip_view.php?tip_id= 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 " Only in version 6.0 set readonly " 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 nmap q :q " To type the following line, type *two* C-V's followed by two spaces. This " is how you map the spacebar. nmap ^V ---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.sourceforge.net/tip_view.php?tip_id= I love the text folding capabilities of vim. I didn't like that it would display the first line of the range as the "title" for the fold. I like to write my comments 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 finds 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-zA-Z][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 file 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.sourceforge.net/tip_view.php?tip_id= The use of star as in vimtip#1 and vimtip#5 is great, here is how to use this type of search accross a whole directory: Just add the mappings (or choose different letter combinations): map gr :grep * map gr :grep %:p:h/* map gR :grep \b\b * map GR :grep \b\b %:p:h/* mapping one will search for the word under the cursor (like g*) in any of the files in the current directory mapping two will search for the word under the cursor (like g*) in any of the files in the same directory as the current file mapping three will search for the word under the cursor by itself (i.e. surrounded 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. surrounded by word boundary like *) in any of the files in the same directory as the current file Benoit VimTip 124: Number a group of lines http://vim.sourceforge.net/tip_view.php?tip_id= Below is a way to number a set of lines. Here is an exaple before and after snapshot: apple bob pear tree 1 apple 2 bob 3 pear 4 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 ,call Nlist() 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.append/' endfunction VimTip 125: Auto commenting for "}" http://vim.sourceforge.net/tip_view.php?tip_id= 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 matching "{", 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 } :call CurlyBracket()a function CurlyBracket() let l:my_linenum = line(".") iunmap } sil exe "normal i}" imap } :call CurlyBracket() 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.sourceforge.net/tip_view.php?tip_id= 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.sourceforge.net/tip_view.php?tip_id= 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 preview 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 function 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 pt :call PreviewHTML_TextOnly() This will open a new window and display your formatted HTML document in that window. 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 would 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 you 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 pp :call PreviewHTML_External() If you don't use mozilla, you will need to modify the function to use your preferred browser. Happy vimming! VimTip 128: grep, diff, patch, idutils, etc. for Windows systems http://vim.sourceforge.net/tip_view.php?tip_id= If you use Vim on Windows, and you wish you had some of those nifty UNIX command-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.sourceforge.net/tip_view.php?tip_id= If you include the "r" flag in the 'formatoptions' option (:help 'fo' , :help 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 % 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 on 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 "" while in Insert mode. Related point: if you want to adjust the indent while in Insert mode, you can use "" (to Decrease the indent) or "" (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.sourceforge.net/tip_view.php?tip_id= 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, then do NOT include a check for b:did_ftplugin in your ftplugin files, and add the line :autocmd BufEnter * let b:did_ftplugin = 1 to your VIMRC file, BEFORE the ":filetype ftplugin on" line. VimTip 131: Scroll alternate window http://vim.sourceforge.net/tip_view.php?tip_id= This mapping allow you to quickly scroll inactive window when displaying several windows concurrently. nmap :call ScrollOtherWindow("down") nmap :call ScrollOtherWindow("up") fun! ScrollOtherWindow(dir) if a:dir == "down" let move = "\" elseif a:dir == "up" let move = "\" endif exec "normal \p" . move . "\p" endfun PS: Original idea and discussion of this tip appeared on vim@vim.org mailing list, I'm just prettified it a little. VimTip 132: window zooming convenience http://vim.sourceforge.net/tip_view.php?tip_id= i frequently have multiple windows open in vim -- this reduces the number of lines each window displays -- i almost always have my windows either all the same size or the current one as big as possible. the following function can be toggled on or off by typing 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 window causes that one to become big) and all the others get very small. i actually use this ALL the time. turning it off (by typing the hotkey sequence again) will 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 \=" unlet g:windowMax else augroup maxCurrWin " au BufEnter * exe "normal \_\\" " " only max it vertically au! BufEnter * exe "normal \_" augroup END do maxCurrWin BufEnter let g:windowMax=1 endif endfunction map max :call ToggleMaxWins () VimTip 133: Windo and Bufdo http://vim.sourceforge.net/tip_view.php?tip_id= i like bufdo and windo but i don't like the fact that the commands end in a different window/buffer than from where i executed them. these versions (starts with 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 set nu does the trick also but leaves me in a different window than where i started. " 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() " 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() VimTip 134: View Source in IE6 using VIM http://vim.sourceforge.net/tip_view.php?tip_id= You can change the "View Source" editor of IE6 by adding the following to the Windows Registry. Change the path in case you installed VIM in another location. [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\View Source Editor\Editor Name] @="C:\\vim\\vim60\\gvim.exe" VimTip 135: Vim buffer FAQ http://vim.sourceforge.net/tip_view.php?tip_id= 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 " 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 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 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 the ":bfirst" or ":brewind" ex command. 2. To jump to the first buffer in the buffer list in a new window, use the ":sbfirst" or ":sbrewind" ex command. 3. To edit the next buffer in the buffer list, use the ":bnext" ex command. 4. To open the next buffer in the buffer list in a new window, use the ":sbnext" ex command. 5. To edit the previous buffer in the buffer list, use the ":bprevious" or ":bNext" ex command. 6. To open the previous buffer in the buffer list in a new window, use the ":sbprevious" or ":sbNext" ex command. 7. To open the last buffer in the buffer list, use the ":blast" ex command. 8. To open the last buffer in the buffer list in a new window, use the ":sblast" ex command. 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 "" in the map command. For example, :map ,w /[.,;] 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 "" in the :abbreviate command. For example, :abb FF for (i = 0; i < ; ++i) Help keyword(s): :abbreviate-local VimTip 136: Remapping Alt, Ctrl and Caps in Win2k http://vim.sourceforge.net/tip_view.php?tip_id= Since I installed Win2K on my laptop, I had been unable to locate a utilitie that would simply enable me to remap my Crtl Alt and Caps the way I think they should 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 Caps 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,1D,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 remapping 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 remappings. What I do not know is how far you can extend this instruction without getting 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 since it is easy to confuse this instruction with the Keyboard LayoutS (S for emphasis) which must not be deleted. Again, thanks to Juano@mindspring.com who got me going and suggested I post my tip. 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.sourceforge.net/tip_view.php?tip_id= 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 help with that. I'm pretty sure that if you remove the , then it will work in 5.x... nnoremap :call WrapLeft() nnoremap :call WrapRight() nnoremap h :call WrapLeft() nnoremap l :call WrapRight() 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 VimTip 138: Getting name of the function http://vim.sourceforge.net/tip_view.php?tip_id= Hi All, While browsing code one always needs to know which function you are currently looking. Getting the name is very painful when the functions are lengthy and you are currently browsing NOT near to the start of the function. You can get the function's name by using this simple mapping. Just place this in your .vimrc. map _F ma[[k"xyy`a:echo @x 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 previous '{' in the first column, go one line up, yank the line in register x, return to the mark a, echo the value of register x, which is the wanted function name. VimTip 139: Alignment: =, LaTeX tables, declarations, etc http://vim.sourceforge.net/tip_view.php?tip_id= 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.vim). The textab program coupled with 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
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.sourceforge.net/tip_view.php?tip_id= When writing scripts using the embedded interpreter available if vim has the +perl 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 recompiled 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 message 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 stub methods which will allow you to use the command line perl interpretor to at least 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.sourceforge.net/tip_view.php?tip_id= Below is a tip that the C/C++ Newbies may find interesting and handy to use. The 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 mz:execute FileHeading()`zjA Where stands for ^V+ESC and for ^V+ENTER VimTip 142: Automatic function end commenting for C++ and Java http://vim.sourceforge.net/tip_view.php?tip_id= 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: 10h%$?\w\+\s*("xy/\s*(/{:nohl%$"xpa If you now end the function with '}//', the follwoing string will be automatically generated: '} //END: functionname' VimTip 143: Use of Vim folds for javadocs http://vim.sourceforge.net/tip_view.php?tip_id= Hi, The fold-method marker can be effectively use to set the folds in your Java source. Define some marker and place it inside HTML comments . This way, it does not affect the Javadocs generated without the necessity of a seprate comment line. e.g. /** * * The class description. * ... */ public class AbcClass { /** * * 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.sourceforge.net/tip_view.php?tip_id= The most useful feature that I find in VIM is the "recording" feature (:help recording). I have used this to automatically insert function headers, re-indent lines, and convert some 34 source files into HTML. This feature is most useful when you want to do some repeated jobs, which you cant 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 see the word "recording" in the status(?) line. You can start the key sequences that 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. Pressing "@@" will repeat the same again. Sameer. VimTip 145: Changing DOS style end of line to UNIX, or vise-versa http://vim.sourceforge.net/tip_view.php?tip_id= Those of us doomed to work in both the Unix and Windows world have many times encountered files that were create/editted on systems other that the one we are on at the time 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 (DOS) to just (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.sourceforge.net/tip_view.php?tip_id= i use the :split command a lot -- both to open a second window containing the currently edited file and to edit a new file altogether (with the :split option). however, i also like to be able to edit more than one file and calling :sp multiple times is inconvenient. so, i created the following command, function 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() 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' everywhere, 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.sourceforge.net/tip_view.php?tip_id= 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('AppFunction') map PickAMap AppFunction endif # Global Maps: # map \ \ \ \\:set ai\gg" VimTip 376: A totally useless tip...or is it ? http://vim.sourceforge.net/tip_view.php?tip_id= Would it not be cool to have your Name listed as part of a Vim command. Well If you build your VIM from source , you can do that. CD to the source directory and do ./configure --with-compiledby="" After building and installing Vim, Whenever you issue :version You will see your Name in the "compiled by" line. NJoy. VimTip 377: Microsoft Natural Multimedia Keyboard Scancodes http://vim.sourceforge.net/tip_view.php?tip_id= I have collected most of the special keys' scancodes on the Microsoft Natural Multimedia Keyboard. This might be helpful for those of you that do lots of key-bindings. http://nirvani.org/docs/Microsoft_natural_multimedia_keyboard_scancodes.html -- Jeremy Brand http://nirvani.org/software/vim/ VimTip 378: Auto insert Java class template when editing a new Java file http://vim.sourceforge.net/tip_view.php?tip_id= If you are lazy like me, tend to use lengthy and verbose Java class names, then this tip is for you. When creating a new Java class file, the first thing that I do after creating it is to add the following block of text: public class ClassName { } Rather than have to type the ClassName twice (once when you first opened the new file, and then again for this block), you can use this autocmd to insert that text for you automatically: autocmd BufNewFile *.java \ exe "normal Opublic class " . expand('%:t:r') . "\n{\n}\1G" VimTip 379: 1,$ s/^M//g gets rid of control-Ms (windows carriage returns) http://vim.sourceforge.net/tip_view.php?tip_id= This has got to be in the tips somewhere else, but darned if I could find it. I had been bothered by the pesky ^M characters that appeared at the end of lines in files that were generated in MS Windows -- particulary appserver log files for me. My new best friend showed me this regex substitution that gets rid of them: :1,$ s/^M//g Note - If I don't have this in the command buffer, I usually wind up copying and pasting the ^M into the regex if I'm in windows, since I'm not sure how to type it from the keyboard (shift 6 followed by capital M doesn't work). In unix, I can ususally type ctrl-V followed by Enter to get the ^M. VimTip 380: Using gvim as frontend for dbx http://vim.sourceforge.net/tip_view.php?tip_id= There is a easy, fast way to use gvim as somewhat like a frontend for the solaris dbx - debugger. Add the following to your .dbxrc: alias sc=" gvim --remote +$vlineno $vfile" when stop { gvim --remote +$vlineno $vfile ;} Allways the debugger stops it shows you the current positon in the gvim. My gvim does'nt take the focus, I dont know why, but so I just can walk through the code. The sc alias shows the current position and is helpful after loading the executable to show the start (we have'nt stopped at this point). Unfortunately it doesn't work at the first stop after attaching to a process. VimTip 381: Running the win32-version of Vim from cygwin http://vim.sourceforge.net/tip_view.php?tip_id= This tip does not only concern Vim, but any native win32 application (NWA) we may want to run from cygwin. Note: I call a "native win32 application", any program that has not been specifically compiled to run on cygwin. Typical examples are internet explorer, yap, acrobat reader, ... and of course the win32 version of Vim available on this site or on http://cream.sourceforge.net. The problem with running NWAs from cygwin comes from the fact that paths in cygwin can be expressed in ways that NWAs can't understand. Indeed from cygwin, we can also: - express paths as *nix-like paths ; e.g. /etc/profile - use paths that, as a matter of fact, are symbolic links. So, to come around this issue, here is a shell script that can be used to define aliases: http://hermitte.free.fr/cygwin/cyg-wrapper.sh [More help available on: http://hermitte.free.fr/cygwin#Win32] All you have to do is to drop it into one directory from your $PATH, and define into your .profile something like: alias gvim='cyg-wrapper.sh "C:/Progra~1/Edition/vim/vim61/gvim.exe" -c' Notes: - under MsWindows 9x, I had to writte the path to gvim.exe in the windows short form - the '-c' is here to tell cyg-wrapper.sh that: when calling VIM, the parameter following '-c' is not a path. This enables to write: gvim -c '/^$/' foo.xxx Regarding the use of *nix-like paths from win32-VIM, check Johannes Zellner's plugin (cygwin.vim) that will convert *nix paths into MsWindows paths on file-opening -- there are different autocommand to add, but it will give you the main idea. Last point, the win32 version of Vim can not expand paths expressed in the *nix way ; e.g. ':sp /etc/pr' won't expand. VimTip 382: Search and replace in all open buffers http://vim.sourceforge.net/tip_view.php?tip_id= Useful for doing simple refactoring i.e. changing a method or variable name. Prompts for a word and then replaces all instances of in open buffers with the word. "--------------------------------------------------------------------------- " Search for and replace with input() in all open buffers "--------------------------------------------------------------------------- fun! Replace() let s:word = input("Replace " . expand('') . " with:") :exe 'bufdo! %s/' . expand('') . '/' . s:word . '/ge' :unlet! s:word endfun map \r :call Replace() Thanks to Jurgen Kraemer for showing me how to use the :exe command :) Sean VimTip 383: a Map to jump to a subroutine/function from where it is called http://vim.sourceforge.net/tip_view.php?tip_id= Hi When writing/debugging code you often want to jump from where a subroutine/function is called to where it actually is . Hitting the "*" key is frustrating if the sub/func is called many times. The following mapping solves the problem. (Notice how it can be altered for other lanaguages) nmap gx yiw/^\(sub\function\)\s\+" Instructions: place cursor over called function (normal mode) and type gx How it works: yiw : Yank inner work to un-named register /^\(sub\function\)\s\+ : search for sub or function followed by 1 or more spaces " : Retrieve un-named register : Start Search (also included in vimtip #305 ) VimTip 384: Easily switch between source and header file http://vim.sourceforge.net/tip_view.php?tip_id= To switch between header and source files very quickly, all you need to do is add a few key mappings in your filetype plugin files. Let me explain with an example: Let's say that you're editing C files, so all you would have to do is edit your ftplugin/c_extra.vim file and include nmap ,s :find %:t:r.c nmap ,S :sf %:t:r.c to switch to the corresponding source file, and nmap ,h :find %:t:r.h nmap ,H :sf %:t:r.h to switch to the corresponding header file. The built-in 'find' command will search (recursively or not) for the specified file anywhere in your vim 'path' setting. The 'sf' is short for split-find, meaning that if vim finds your file it will open it in a split window. Simply add the 'vert' keyword before 'sf' if you want a vertical split. See these help pages for a full description of these built-in features: help expand # for a description of the %, :t, :r expansion help find # for a description of the 'find' and 'sf' features help ftplugin # for a description of how filetype plugins work help path # for a description of how the path setting works This method is also highly configurable. All you have to do is change the 'path' setting when switching to different projects, and modify the corresponding filetype plugin to support other languages. This tip is very similar to vimscript #31 by Mike Sharpe, however this method only takes a few lines, and his script spans several pages! VimTip 385: some java & vim tips http://vim.sourceforge.net/tip_view.php?tip_id= i started to aggregate some java & vim tips (in part because i easily forget stuff). they're the kind of tips that are a little elusive but deliver a big bang for their effort; like actually getting quickfix to work with java, using ctags with java, etc.... http://www.ophinity.com/papers/jim/index.html ...on that note, i wonder if vim.org should start organizing tips and scripts into areas of interest or perhaps cross-indexing? some things that come to mind are document generation (tex/ latex), oracle/ db integration, java development, c/ c++ coding, win32 issues, etc... VimTip 386: Cut/copy and paste using visual selection http://vim.sourceforge.net/tip_view.php?tip_id= Visual selection, although common in applications today, is a key feature that differentiates vim from traditional vi. To cut (or copy) and paste using visual selection: 1. Position the cursor at the beginning of the text you want to cut/copy. 2. Press v to begin character-based visual selection (or upper case V to select whole lines, or Ctrl-V for a vertical block). 3. Move the cursor to the end of the text to be cut/copied. (While selecting text, you can perform searches and other advanced movement, a feature that sets vim apart from most other editors.) 4. Press d (as in "delete") to cut, or y (as in "yank", which I imagine meaning "yank so hard and fast that it leaves a copy behind") to copy. 5. Move the cursor to the desired paste location. 6. Press p to paste after the cursor, or P to paste before. In gvim, visual marking (steps 1-3) can be replaced by selecting text using a mouse or similar pointing device, although I strongly prefer to navigate using the keyboard. Bonus tip: To replace the selected text with new text (to be entered by you), press 'c' instead of 'd' or 'p' on step 4. This deletes the selection and leaves you in insert mode. Then, instead of (or prior to) steps 5-6, type your replacement text. VimTip 387: A way to quickly prefix a char(or chars) to a parameter list, via :s http://vim.sourceforge.net/tip_view.php?tip_id= This is a way to quickly prefix a char(or chars) to a parameter list, via :s In the thought that others may like the same preferred style as I, here is an easy way to prefix each param with an underscore. The command: :s/\<\(\I\i*\s\{-}[,)]\)/_\1/g A sample menu entry: amenu Fe&ral's.Prefix\ underscores\ to\ params :s/\<\(\I\i*\s\{-}[,)]\)/_\1/g :noh An Example: Before: BOOL CSomeView::Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID) After: BOOL CSomeView::Create(DWORD _dwStyle, const RECT& _rect, CWnd* _pParentWnd, UINT _nID) Happy VIMing :) VimTip 388: Insert C++, LaTeX, and other comments easily http://vim.sourceforge.net/tip_view.php?tip_id= Visual selection combined with powerful replace (:s) command can be used for fast inserting C++ (//), LaTeX (%), and other comments at the beginning of a block of lines. If you have, for example, paragraph in a LaTeX file and you want to comment it (so that it does not appear in the output anymore), then you have to insert the percent sign '%' at the beginning of every line. An easy way to do this is to select visually the block of text, press ':' for entering a vim command (which automatically expands to :'<,'>) and to use substitute s/^/%/ The whole command then looks like :'<,'>s/^// So just press enter and the comment will be inserted at the beginning of all the selected lines. If you want to delete it later, just use column blocks (Control-V starts blockwise visual selection) to select first column(s) and d to delete them. VimTip 389: search only in unfold text(intend to work with diff) http://vim.sourceforge.net/tip_view.php?tip_id= hi, sometimes I would like to search/replace the code in the latest version. That is when I show diff between two version of code, I would like to only search the unfold. The following function may do the replace job: function Foldrepl(spattern, tpattern) normal gg "go to top of the file if &diff "need to change fold option for diff exec "set diffopt=context:0" endif "echo a:spattern "echo a:tpattern let mycount =0 while search(a:spattern, "W") > 0 "find the search pattern if foldlevel(line(".")) < 1 "not in flod exec "s/".a:spattern."/".a:tpattern."/g" let mycount = mycount + 1 endif endwhile if &diff "need to restore fold option, mine is 4 set diffopt=context:4 endif echo mycount ." lines are changed" endfunction It can be changed to do the search job or both Demai VimTip 390: combining vimdiff with cvs diff http://vim.sourceforge.net/tip_view.php?tip_id= i like using vim's diff mode for comparing different revisions of source code files. usually older versions do not live in the directory structure with the current versions, but in a cvs repository. the command below, CVSdiff, can compare the current file to any given revision number in the cvs repository. please note that in case a revision number does not exist, empty files will be displayed, as the below script does not do any error checking (yep, i'm lazy, and this works for me). a vertical split is performed on the current file and its given previous revision. command -nargs=1 CVSdiff silent call CVSdiff("%", "") function! CVSdiff(filename, cvsversion) " append a:filename to keep extension and therefore highlighting mode let patchname = tempname() . a:filename let tempname = tempname() . a:filename let newname = tempname() . a:filename execute "!cvs diff -a -r " . a:cvsversion . " " . a:filename . " > " . patch execute "!cp " . a:filename . " " . tempname execute "!patch -R -o " . newname . " " . tempname . " < " . patchname execute "vertical diffsplit " . newname call delete(patchname) call delete(tempname) call delete(newname) endfunction VimTip 391: Simple programmers TODO list using grep and quickfix http://vim.sourceforge.net/tip_view.php?tip_id= I use this to maintain a TODO list for projects I am working on. All my projects are pretty small scale with each project stored in it's own directory so this tip was writtten with that in mind. Basically it is two keymappings one which inserts //TODO_ITEM leaving Vim in insert mode so you can add a note to help you remember what you wanted to do ;) The other mapping uses :grep to search for all occurrences of TODO_ITEM in files in the current directory excluding ~ files and then opens the error window displaying the list of TODO_ITEMs. imap \q i//TODO_ITEM map \q i//TODO_ITEM imap \w :grep --exclude=*~ TODO_ITEM * :copen map \w :grep --exclude=*~ TODO_ITEM * :copen Change the comment style to suit your language and the lame keymappings to something better. Sean VimTip 393: PCRE search and replace (Perl Compatible Regular Expressions) http://vim.sourceforge.net/tip_view.php?tip_id= 1. Verify in :ver that +perl or +perl/dyn is compiled in. 2. Install Perl if necessary. On Windows, ActivePerl is required. 3. Type :perldo s/searchme/replaceme/g VimTip 394: pop up menu for checking the meaning of the word from internet http://vim.sourceforge.net/tip_view.php?tip_id= To check the meaning of the word under the cursor, right click mouse, and choose Dic. Either IE or mozilla will be opened and dictionary service offered by www.m-w.com will be ready. Following is the map: To open mozilla nme PopUp.&Dic :sil! !start C:/Progra~1/mozilla.org/Mozilla/mozilla -nosplash "http://www.m-w.com/cgi-bin/dictionary?book=Dictionary&va=" To open internet explorer: nme PopUp.&Dic :sil! !start iexplore -nohome "http://www.m-w.com/cgi-bin/dictionary?book=Dictionary&va=" This is tested for gvim.exe on windows 2000 professional. VimTip 395: visual marks http://vim.sourceforge.net/tip_view.php?tip_id= Hi, Setting visual bookmarks in a file / buffer can be done in a simple way by using VIM's 'sign' feature. This solution just sets the background of the current line to light blue. Also see ':help sign'. Add these lines to your gvimrc: " define a highlight colour group for bookmarks hi default BookmarkCol ctermfg=blue ctermbg=lightblue cterm=bold guifg=DarkBlue guibg=#d0d0ff gui=bold " define a bookmark / sign: just highlight the line sign define MyBookmark linehl=BookmarkCol " add something to the context menue (right mouse) amenu 1.200 PopUp.-SEP3- : amenu 1.200 PopUp.&mark.set\ bookmark :exe 'sign place 1000 name=MyBookmark line='.line(".").' buffer='.winbufnr(0) amenu 1.200 PopUp.&mark.del\ bookmarks :sign unplace 1000 amenu 1.200 PopUp.&mark.list\ bookmarks :sign list Happy VIMming Thomas VimTip 396: Highlighting whitespaces at end of line http://vim.sourceforge.net/tip_view.php?tip_id= Whitespace characters (tabs, spaces, etc) at end of line are rarely meant to be there; they are usually there by accident. If you don't want them, maybe it pays to highlight them with an alarming color. (After all, GNU Emacs has it (show-trailing-whitespace), so why not in vim :-) ) Put this in your ~/.vimrc to highlight the whitespace characters at end of line: highlight WhitespaceEOL ctermbg=red guibg=red match WhitespaceEOL /\s\+$/ VimTip 397: mapping for better browsing of :help docs http://vim.sourceforge.net/tip_view.php?tip_id= I personally find it very akward and un-intuitive to browse the documentation using Ctrl-] for following the link and Ctrl-Shift-t to go back. I have had an idea to to remap those commands to Enter and Backspace, since I do not use those keys in help in normal mode. The command :nnoremap can remap the key only in the given buffer without affecting the other buffers. just create file $VIMRUNTIME/ftplugin/help.vim with following contens """""""""""""""""""""""""""""""""""""""""""""""" """" begining of the file " Only do this when not done yet for this buffer if exists("b:did_ftplugin") finish endif " map ctrl-] to enter in normal mode only for this buffer nnoremap " map ctrl-T to backspace in normal mode only for this buffer nnoremap """" End of the file """""""""""""""""""""""""""""""""""""""""""""""" VimTip 398: Mapping for quicker access to macros http://vim.sourceforge.net/tip_view.php?tip_id= :nnoremap @q Start recording keystrokes by hitting 'qq'. End recording with 'q' ( q if you're in insert mode). Play keystrokes by hitting space. --- Refs: :help register :help record VimTip 399: fold away empty lines http://vim.sourceforge.net/tip_view.php?tip_id= You can fold sequences of at least two empty lines (may contain blanks) with these settings: " fold empty lines with white spaces: syn match MyEmptyLines "\(^[ ^I]*\n\)\+" fold You probably can substitute '[ ^I]' with '\s'. If you have set 'foldcolumn' to more than 0 you can just open/close these empty lines block by clicking the '+' or '-' with the mouse in the folder column. VimTip 400: Fast scroll mappings (incl. insert mode) http://vim.sourceforge.net/tip_view.php?tip_id= " allow Alt-[movement keys] to scroll window if !has("gui_running") nmap ^[l nmap ^[h nmap ^[k nmap ^[j vmap ^[l vmap ^[h vmap ^[k vmap ^[j imap ^[l imap ^[h imap ^[k imap ^[j endif " To have available for the mappings below, search menu.vim for the " first instance of &Help and change it to Hel&p so that isn't used " for the GUI Help menu nmap 4zl nmap 4zh nmap nmap vmap 4zl vmap 4zh vmap vmap imap 4zl imap 4zh imap imap VimTip 401: A mapping for easy switching between buffers http://vim.sourceforge.net/tip_view.php?tip_id= Instead of using a buffer-explorer I looked for a simpler method for fast switching between buffers. So on a rainy day I invented a simple mapping: map :bn map :bp This works very well for an intermediate amount of buffers. Of course you can take other keys (instead of the up and down arrows) for the mapping. Chris. VimTip 402: Just using space-bar: jump between splitted windows and open them wide http://vim.sourceforge.net/tip_view.php?tip_id= Jump between splitted windows and open them wide. Use only the space-bar for this. Press space-bar once and you jump to the next window. Press it twice and the window opens wide for better reading - this works for horizontal and vertically open windows. Put this in your vimrc: "Jump between windows map w "Open window wide map :call OpenSplittedWindowWide() function OpenSplittedWindowWide() normal ^W| normal ^W20+ endfunction Note: ^W must be generated by vim (must be one character). ------------------------------- The first tip is not new I know it - to jump between windows using the space-bar. But the combination jumping and opening wide with just using the space-bar this is new. If not, please apologize, I cannot know all the tips and possibilites published. VimTip 403: Request for tip - interleaving '.' and '@:' http://vim.sourceforge.net/tip_view.php?tip_id= I'm looking for a way to repeat the last command, whether it is an ex command or not. '.' repeats the last non-ex command, while '@:' repeats the last ex command. Can anyone think of a way to interleave the two? It may not seem very useful, but since you can map a keystroke to an ex command (or a sequence of them), isn't it reasonable to expect a uniform way to repeat the last keystroke, without having to remember how it's implemented? As a random note, it occurs to me that the undo command probably maintains sufficient information to do this - if only we could get at it. VimTip 404: Tags for Mixed Assembly and C http://vim.sourceforge.net/tip_view.php?tip_id= Probably this is a no-brainer, but thought would share it just the same. While accessing C functions/variables from assembly (esp for those DSP/low level guys out there) the usual exhuberant ctags doesn't work. The solution a) Make a copy of 'tags' file b) Search and replace all variables & functions of C files with _variables & _functions in the copy file, say 'Tags' (ex in Vim ":g/\.c\>/s/^\(\l.\)/_\1/") c) In Vim :set tags=tags,Tags d) Use Ctrl-] to sail through. Tried to find an elegant (read complicated) solution, but then gave up :). Of course if you need to be doing ctags all the time write a perl scripts or something to do this. Cheers VimTip 405: ShowBlockName one-liner equivalent for one coding style http://vim.sourceforge.net/tip_view.php?tip_id= I use [[ and its look-alikes a lot for browsing my C++ code. You can use ShowLine() and the following mapping to obtain something close to ShowBlockName (and it's pretty fast): map z[ [[k:call ShowLine()`` Thanks for your scripts, Gary Holloway. I look forward to using z[ heavily! Cheers, William VimTip 406: Alternate delimiters for the replace command http://vim.sourceforge.net/tip_view.php?tip_id= This text is from http://www.troubleshooters.com/lpm/200212/200212.htm -- pasted text -- In many VI implementations you don't need to use the slash character as the expression delimiter. You can use most non-alphanumeric characters (but not \, " or |). This is very handy when working with UNIX filenames, as in the following example: :s+/usr/local/+/opt/+Whatever character follows the :s is defined to be the delimiter character. If your implementation doesn't support this, you can represent slashes in search and replace expressions by escaping them with backslashes, as follows: :s/\/usr\/local\//\/opt\//As you can see, the escaping method is much less readable, so if you can use alternative delimiter characters, it's a good idea. VimTip 407: PHPdoc: Use JCommenter.vim for php-scripts http://vim.sourceforge.net/tip_view.php?tip_id= Use JCommenter.vim for php-scripts: jcommenter.vim : A script for automatically generating JavaDoc comments http://vim.sourceforge.net/script.php?script_id=20 PHPdoc is an imitation of JAVAdoc. The syntax between the two languages is very close, see the examples below: Example 1: You have the PHP-function: function serialize_it($something) { $person = serialize($something); return $person; } Put the cursor on the first line and call :call JCommentWriter() You get /** * * * @param $something * @return */ function serialize_it($something) { $personen = serialize($something); return $personen; } Example 2: You have the PHP-class: class submenu { ... } Put the cursor on the first line and call :call JCommentWriter() You get /** * * * @author * @version */ class submenu { ... } Example 3: For a class-variable you get: /** * */ var $urls; Note: It does not work if you have = '' like in function serialize_it($something = '') {} But I think jscript.vim can be adapted for the use with PHP. Klaus VimTip 408: Enhance Calendar (script 52) with special dates http://vim.sourceforge.net/tip_view.php?tip_id= To enhance Calendar (vimscript #52) with display of special dates: Step 1) Create a file called "holidays" in the directory assigned to g:calendar_diary (Default value for g:calendar_diary is ~/diary). This file will contain the special dates. Essence of contents of the holidays file is the special dates encoded as (10000+(month*100)+day). ____example_contents_of_file_g:calendar_diary/holidays_________ List of holidays: ^(10000 + ((month * 100)+day)) Encoded Sign Color Description Date 10101 n blue Jan 01 (Wed) - New Year's Day 10217 p blue Feb 17 (Mon) - President's Day 10214 v red Feb 14 (Fri) - Valentine's Day 10414 s green Apr 14 (Mon) - Spring Break 10526 m blue May 26 (Mon) - Memorial Day 10703 i gold 10704 i gold Jul 3&4 (Thu & Fri)- Independence Day + 1 day 10901 l blue Sep 01 (Mon) - Labor Day 11127 t blue Nov 27&28(Thu & Fri)- Thanksgiving Day + 1 day 11128 t blue 11225 c silver Dec 25&26(Thu & Fri)- Christmas Day + 1 day 11226 c silver Dec 25&26(Thu & Fri)- Christmas Day + 1 day Step 2) Add the following to your vimrc file: let calendar_sign = 'MyGetSpecialDay' function! MyGetSpecialDay(day, month, year) let l:m100d = 10000 + (a:month * 100 ) + a:day let l:holidays = expand(g:calendar_diary) . "/holidays" exe "split " . l:holidays let l:found = search(l:m100d) if l:found let l:found = 'h' endif quit return l:found endfunction That's all. Note: The preceding constitutes basic support for display of special dates. With this basic support, all special dates are shown with the same sign (viz. +) and the same highlight color. An enhancement would be to pick up the sign and the highlight color from the holidays file. (Also, I suspect management of buffer for the holidays file can be speeded up, perhaps by opening it only once, keeping it in the background and searching with warp-around flag ('w').) VimTip 409: Using selected text as part of a command? http://vim.sourceforge.net/tip_view.php?tip_id= I wish to use selected text as part of a command - say, to substitute instances of a very long variable with a shorter name: :%s//ShorterName/g How would I do this? (Hope its OK to ask a question, as opposed to presenting an answer). VimTip 410: Allow Inform header files to be distinguished from C headers http://vim.sourceforge.net/tip_view.php?tip_id= Inform is an Interactive Fiction authoring language. It's header files often use a '.h' extension, which causes VIM to think they are C files, or do not have any extension at all, leaving VIM unable to determine what kind of file they are. This is irritating to Inform developers using VIM with syntax highlighting. The solution is to use a custom 'filetype.vim' and 'scripts.vim'. Create a '$HOME/.vim/filetype.vim': if exists("did_load_filetypes") finish endif augroup filetypedetect au BufNewFile,BufRead *.h call FTCheck_inform() augroup END " function to detect inform code (any extension) fun! FTCheck_inform() if getline(1) =~ "^!" setfiletype inform elseif getline(2) =~ "^!" setfiletype inform else let s:colnum = col('.') let s:linenum = line('.') call cursor(500, 1) if search('\[\(\s*\I\i*\)*\s*;', 'bW') > 0 setfiletype inform endif call cursor(s:linenum, s:colnum) endif endfun On loading a file with a '.h' extension, a function is called to examine the file for certain Inform-specific constructs. If it finds any, it sets the filetype as inform, otherwise it leaves the filetype unset, allowing the global 'filetype.vim' to determine the filetype. For files with no extension, create a '$HOME/.vim/scripts.vim': " local scripts.vim gets called when " all autocommands have failed to identify file type, " but before global scripts.vim " call FTCheck_inform() See also the site http://www.stephenthomas.uklinux.net/informvim VimTip 411: How to initialize plugins http://vim.sourceforge.net/tip_view.php?tip_id= Plugins have two basic ways of being initialized: a) via some variable that the plugin script uses; the initialization here is obvious -- set the desired variables in your <.vimrc> (or use an appropriate autocmd to do so). b) via a map or function call. The problem here is that <.vimrc> is sourced prior to plugin sourcing, so the map or function call isn't available yet. Solution: put in .vim/after/plugin a file of the same name as the plugin you're initializing. In that file put call TheInitializationFunction() -or- norm TheInitializationMap For example, the script which supports the highlighting of matching brackets as you move onto a bracket is not on by default. Normally it requires one to type "\[i" to start it. However, if you'd like to have the script to start enabled, then put norm \[i into the file <.vim/after/plugin/HiMtchBrkt.vim> (see tip vimtip#177). (Windows users: mentally change .vim to _vimfiles and / to \ in the tip above) VimTip 412: Easy menu-style switch between files with a simple map http://vim.sourceforge.net/tip_view.php?tip_id= When there are several files opened in a vim session, it becomes difficult to keep track of the files and their respective buffer numbers. Switching to a different file is made easier using a simple map: :map :buffers:e # When F5 is pressed, a numbered list of file names is printed, and the user needs to type a single number based on the "menu". Another good thing is that the "menu" disappears after choosing the number and hitting enter. So it appears only when you need it. VimTip 413: Drag and Drop file names into VIM's command line http://vim.sourceforge.net/tip_view.php?tip_id= You can open files in VIM by Drag&Drop of selected file names from Windows Explorer. (not very surprising). This also works by dropping into the VIM command line, so you can e.g. type ':split ' then drag&drop a selected file to VIM window and hit The complete path and filename is transferred to commandline and the file is opened in a new VIM buffer/window. VimTip 414: Change guifont to see more of your file. http://vim.sourceforge.net/tip_view.php?tip_id= Sometimes, its nice to be able to quickly jump to a smaller font to see more of the file you're editing at once, and jump back again to make the text more readable. I use these mapping: :map :set guifont=Lucida_Console:h9:cANSI :map :set guifont=Lucida_Console:h11:cANSI :map :set guifont=Courier_New:h9:cANSI :map :set guifont=Courier_New:h11:cANSI 9 and 11 are my mnemonics for the font size. wouldn't work for me because it activates the menu. Of course, this only works in gvim. Ben VimTip 415: easy way to edit two files using split window http://vim.sourceforge.net/tip_view.php?tip_id= In my rc ($HOME/.exrc) file, I have the following lines: map K ESC:split map k ^K ^W^W where the 'ESC', '^K', and '^W^W' are escape sequences. This allows the user to split the screen using 'K', then switch between the two screens using 'k'. This in conjuction with the :e to edit a different file can be powerful. Useful for pulling lines (or blocks) from one file into another without having to cut/paste or use the :r command. Personally I use this alot so I find it useful. I got the syntax from the O'Reilly book 'Learning the vi editor' in the section about 'ex commands'. VimTip 416: Fix error "E97: Cannot create diffs" on VIM for Windows http://vim.sourceforge.net/tip_view.php?tip_id= I read a couple postings of people having this issue, even if they have a diff program in their path when running on Windows platforms. Check out your _vimrc file, function "MyDiff". If the path to the diff file contains ANY spaces, enclose the path in double quotes. Alternatively you can remove the path and just leave the diff file and check. This is the line that if fixed in my _vimrc: Changed silent execute '!C:\Program Files\Vim\vim61\diff -a ' . opt . v:fname_in . ' ' . v:fname_new . ' > ' . v:fname_out To be: silent execute '!"C:\Program Files\Vim\vim61\diff" -a ' . opt . v:fname_in . ' ' . v:fname_new . ' > ' . v:fname_out I am running the diff program that comes with CygWin and it works just fine. VimTip 417: combining move and scroll [IMPROVED] http://vim.sourceforge.net/tip_view.php?tip_id= A long time ago, I entered vimtip #105. I used that mapping for a long time, but it always had a couple problems. One, it reset the scroll parameter. Two, it didn't work in visual mode, because :set scroll exits visual mode. I was reviewing my vim configuration and learning some new tricks, and in the process I improved this mapping. Now, Ctrl-J and Ctrl-K will move the cursor one line down or up, and scroll one line down or up--so the cursor remains on the same screen line (except near the beginning and end of the file)--in both normal and visual modes. And the scroll parameter is unaffected. " N and N idiotically change the scroll setting function! s:Saving_scroll(cmd) let save_scroll = &scroll execute "normal" a:cmd let &scroll = save_scroll endfunction " move and scroll nmap :call Saving_scroll("1") vmap :call Saving_scroll("gv1") nmap :call Saving_scroll("1") vmap :call Saving_scroll("gv1") This is an example of several terrible vim hacks, to boot. VimTip 418: Stop the beeping in gvim. http://vim.sourceforge.net/tip_view.php?tip_id= How do you stop gvim from beeping on error? VimTip 419: Auto-fold perl subs (and possibly other languages) http://vim.sourceforge.net/tip_view.php?tip_id= Add this to your .vimrc file and it'll automatically fold perl functions (and possibly other languages that define a subroutine with "sub ...") Once you open a perl file, you'll see all functions are folded. You can then move to a function and (space) or "zo" to open it, "zc" to close it, "zR" to open all folds (normal file) and "zM" to re-fold all folds. It makes skimming over a file a breeze. See ":help folding" for more info on folding in general. function GetPerlFold() if getline(v:lnum) =~ '^\s*sub' return ">1" elseif getline(v:lnum + 2) =~ '^\s*sub' && getline(v:lnum + 1) =~ '^\s*$' return "<1" else return "=" endif endfunction setlocal foldexpr=GetPerlFold() setlocal foldmethod=expr VimTip 420: get rid of annoying menu/tool bar http://vim.sourceforge.net/tip_view.php?tip_id= if you also get annoyed by the menu bar and/or tool bar in the gui version of vim, you can get rid of them with the following: set guioptions-=m " to get rid of the menu bar set go-=T " to get rid of the tool bar and then you're back to the look and feel of how vim should always be =] -your friendly neighbourhood garbage man. VimTip 421: the simplest map to highlight the current line http://vim.sourceforge.net/tip_view.php?tip_id= This is the simplest map to highlight the current line nn K mk:exe 'match Search /\\%'.line(".").'l/' Note: abstract from http://vim.sourceforge.net/tips/tip.php?tip_id=411 http://vim.sourceforge.net/tips/tip.php?tip_id=177 To turn off highlight, type :match VimTip 422: A Quick Reference http://vim.sourceforge.net/tip_view.php?tip_id= After using vi and similar for a few years, I have accumulated a list of commands I use most often, and pass it on to people starting with vi. The available quick reference tends to be verbose, but is useful for people with more vi experience (type ":help quickref" or go to http://vim.sourceforge.net/htmldoc/quickref.html). For beginners, here is my file: VI is a text editor. Its idea is that you manipulate text (as opposed to enter it all the time). Almost all commands can be "repeated" a number of times, which you specify before typing the command itself (to delete a line, type dd; to repeat the deletion of a line 55 times, type 55dd). At almost any time, "u" means "undo", and "Esc" stops all command or text entering. For help, type :help. There is a difference between what I call direct and indirect commands: "u" is a direct command, ":h" is an indirect one (it uses an underlying program). :q to quit, :q! to quit without saving Entering and manipulating text: Command Interpretation . repeat the last command iEsc enter on current line, at current position IEsc enter on current line, at beginning of line aEsc enter on current line, at next character position AEsc enter on current line, at the end of the line oEsc enter on a new line below OEsc enter on a new line above r replace characters by repeated times, starting from cursor towards end of line sEsc substitute characters by , starting from cursor towards end of line REsc substitute characters by , starting from cursor towards end of line ~ change the case d delete (combine with a movement: dl deletes to the right, d0 deletes to beginning of line, 5dw deletes 5 words forward) dd delete line D delete to the end of the line (like d$) c change (same combinations as with d) cc change line C change to the end of the line (like c$) S change line, like cc x delete the character at the current position X delete the character at the left (backspace) J join the next line to the current line y yank (copy, same combinations as with d) p, ]p paste the result of the last deletion or yanking command after the cursor P, [p paste the result of the last deletion or yanking command before the cursor /, ? find forward, backward (then, n means next in the same direction, N means next in the opposite direction) Ctrl-a, Ctrl-x increase, decrease by 1 the number under the cursor (5Ctrl-a increases by 5) :,g// on all lines within , range and matching , execute . :3,$g/^ table/d deletes all lines from 3 to end of buffer that start with " table" :%g/[a-z0-9]$/s/boo/table/ on all lines in buffer that end with a lowercase letter or a digit, replace "boo" with "table" :%g/[^RT]umble.*cran[0-6]/m'a move all lines in buffer of the kind "Aumble...cran4" or "Gumble...cran6" (NOT Tumble or Rumble) underneath line marked as a. :,v// on all lines within , range and not matching , execute . :,! execute shell on lines to Moving around: Command Interpretation 0, $ jump to the beginning, end of the line h, j, k, l left, down, up, right (you can also use the arrow keys) H, M, L jump to the highest, middle, lowest line on screen {, } move up, down to the next empty line % jump to the corresponding parenthesis, square bracket or curly brace [[, ]] jump to the beginning, end of the file :1, :$ jump to the beginning, end of the file G jump to line (without the number, jumps to the end of the file) Ctrl-f, Ctrl-b next page down, up Ctrl-d, Ctrl-u next half-page down, up Ctrl-e, Ctrl-y shift all the text by one line down, up w, b go forward, backward to the next word e, ge go to the end of the word, backwared to the end of the previous word f goes to the next in the current line t goes to the character just before the next m, ' set mark , go to mark '' go to the line that was last modified Manipulating files: Command Interpretation :r read file in :w write current buffer to (default: write current buffer to current file, if defined) :w! same as write file, overriding permissions :wq, ZZ write to file and quit :wq! write to file and quit, no matter what :sp split window and edit file :e edit :n edit next file in list :ls list buffers :buf edit buffer number Executing a command easily several times: Mapped keys: To map a key to a command to execute, type: :map Then, type to execute . Macros: To enter a macro, type: qq To execute the macro (default: 1) times, type: @ Important note: macros can contain calls to mapped keys. Registers: To use a register named , type " before your command. Example: copying the word under the cursor and saving into register z: "zyw Example: pasting the result of register c before this word or line: "cP Important note 1: register characters are independent of marks ('a is not affected by "a) Important note 2: a macro named is actually stored in the register of same name. To edit the macro f, just create a new line (o), paste the contents of register f ("fp), edit the commands (...), go to the beginning of the line and delete/store the line into register f (0"fD), and remove the temporary line (dd). Additions to this file are welcome, but make sure it's concise... William VimTip 423: Finding more available keys to map http://vim.sourceforge.net/tip_view.php?tip_id= One of my ongoing problem with VIM is finding more keys on my keyboard onto which I can map functions without losing some other functionality. I finally went on a search of terminal emulations that maximize the programability of the keyboard when accessing Linux servers from a Windows 2000 client. I am in no way associated with the author or the company, but I wanted to give other VIM users a pointer to check out the ZOC terminal emulator from Emtec at http://www.emtec.com/zoc. Not only does this support full use of the Alt key, but it also supports compete remapping based on the NumLock and ScrollLock keys. Keys can be mapped to send any string including binary codings. ZOC also supports a Linux console terminal mode. Again I'm not advertising for a particular product; I'm just passing on my solution to a particularly onerous problem when attempting to use the full potential of VIM. VimTip 424: Copy, cut, and paste macros that also work in old vi http://vim.sourceforge.net/tip_view.php?tip_id= The following three mappings implement a useful, quick line-oriented copy, cut, and paste scheme that not only works in VIM but also standard old vi. These macros use yank or delete commands to either copy or delete lines to named register m where those lines are defined by the motion command to mark m. The put command is then used to insert the contents of register m at the desired location. There's nothing special about mark m or register m, thery're just somewhere in the middle. Meta-g is mnemonic for "get". Meta-v looks like an insertion mark. Meta-q looks like Meta-g but with a twist. Of course any other keys, registers, or marks could be used. map mn"my'm`n map "md'm map "mp To copy some lines ( only in command mode ): 1. Put the cursor on the first or last line and press "mm" 2. Move to the other end of the line range, last or first, and press meta-g 3. Move to the line above where you wish to insert the lines and press meta-v To cut some lines and move them to a new location use the same procedure but replace meta-g in step 2 with meta-q. I find that in programming I constantly use these simple functions to position code in the proper place. I started using this scheme years ago and find it useful now because not all systems have vim, and because it is so quick and easy that it has become part of my finger habits. Some day I will have to learn the visual mode of VIM better. VimTip 425: Forcing Syntax Coloring for files with odd extensions http://vim.sourceforge.net/tip_view.php?tip_id= If you are editting a file containing PHP script (for example) but the file doesn't have the extension .php you can force the desired syntax coloring with :set syntax=php similarly :set syntax=perl :set syntax=html Alternatively if the extension causes an undesired coloring, switch off coloring with :set syntax=off look in the directory *vim/vim61/colors/ for supported languages VimTip 426: Protecting a file you're referencing http://vim.sourceforge.net/tip_view.php?tip_id= A common programmimg situation, you are comparing two versions of the same file. One is the "reference file" which you DONT WANT to update. However they look so similar that you can get confused. Solution: :set ro (readonly) in the master file additionally change it's color scheme (peachpuff is quite a benign one!) :colorscheme peachpuff look in vim/vim61/colors for available colorschemes VimTip 427: Fast window resizing with +/- keys http://vim.sourceforge.net/tip_view.php?tip_id= Depending on your willingness to occasionally consume the + and - keys, here's a fast way to resize the active window if you have more than one window open: if bufwinnr(1) map + + map - - endif I normally use the scrollpad + and - keys. The map eliminates the need for time-consuming chording and if you liked chording, you'd be using Emacs instead of Vim anyway... VimTip 428: Wordwise Ctrl-Y in insert mode http://vim.sourceforge.net/tip_view.php?tip_id= Ctrl-Y in insert mode is one of Vim's handy extensions that inserts character which is above cursor (see :help i_CTRL-Y). However, sometimes this is not very useful when a user wants to insert many characters. In this case it's better to get a *word* above cursor. Put this in ~/.vimrc: " Wordwise Ctrl-Y in insert mode noremap! klyWjpa You might want to substitute 'W' with 'w', 'E', or 'e'. Try them and choose one that works best for you. Unfortunately, this simple map doesn't work at the beginning or end of line. Improvements are welcome. VimTip 429: Using '< and '> marks http://vim.sourceforge.net/tip_view.php?tip_id= Today I discovered that '< and '> persists even after the selection is gone. Thus, to repeat an Ex command over a previously selected (via V command) block just use : history -- no need to reselect block again. VimTip 430: Fast switching between buffers http://vim.sourceforge.net/tip_view.php?tip_id= This is one for Tab key fans. I use these mapping to quickly cycle between buffers using Tab and Shift-Tab. I use them in normal more as I use tab for word completion when in editing more. Put these in your .vimrc or gvimrc. The buffer will be written before switching to the next one. The test makes sure that the file can be written to and is modified. nmap :if &modifiable && !&readonly && &modified :w :endif :bn nmap :if &modifiable && !&readonly && &modified :w :endif :bp VimTip 431: map to toggle between backslash and forwardslash http://vim.sourceforge.net/tip_view.php?tip_id= Microsoft is backward, ie, using C:\Progra~1\Outloo~1\ To get it back forward, we can do :s#\\#/#g Now, life turns back to normal: C:/Progra~1/Outloo~1/ However, to copy and paste this normal path to Windows' applications, we have to substitute slash to backslash: :s#/#\\#g Here came a small map to toggle between "/" and "\" within one line. Usage: Put the cursor on "/", and type v\, all "/" becomes "\". Put the cursor on "\", and type v\, all "\" becomes "/". Map: vn y:let c=getline(line("."))[col(".")-1] \:if(c=='/')s#/#\\elseif(c=='\\') \s#\\\\#/endif`< VimTip 432: Putting the current file on the Windows clipboard http://vim.sourceforge.net/tip_view.php?tip_id= Sometimes I want to use the file I'm editing in Vim (on Windows) in another application; I created the following command: com! Copyfile let @*=substitute(expand("%:p"), '/', '\\', 'g') This simply copies the entire path and filename of the current file -- substituting backslashes for slashes (in case there are any) -- onto the Windows clipboard. I can then just go and paste the value wherever I want (such as a File -> Open dialog). For example, for my _vimrc file, I get c:\vim\_vimrc in the clipboard. VimTip 433: a rough mapping to spellcheck the buffer http://vim.sourceforge.net/tip_view.php?tip_id= well, certainly well, certainly there are plugins to do this much better, but, if you like to have most of the stuff placed on your vimrc file, the following must help: map ,SS :exec system("ispell -l -t -d br < ".expand("%")." \| sort -u \| sed 's/\\(.*\\)/syntax match Underlined \"\\\\<\\1\\\\>\" contains=TOP /'") basically, i use 'ispell' to collect all misspelled words, and assign each one to the 'Underlined' syntax group (seems better than 'Error') =] improvements aren't so hard to do; actually, I use another mappings for another 'spell' functions, but the essential can fit in just one line; leorosa VimTip 434: Autogroup commands for C/C++ editing - inserting skeletons etc (long post!) http://vim.sourceforge.net/tip_view.php?tip_id= Hi all, When you start editing a *.h file, you'd need some format like this: CODE STARTS: /***************************************************************** * Filename: abc.h * Description: * Created: Mar 5 03 09:00:00 * Last modified: Mar 6 03 09:00:00 * * * Revision History * Date Author Remarks * Mar 5 2003 KG File Created *******************************************************************/ #ifndef _ABC_H_ #define _ABC_H_ #endif // vim:ts=3:sw=3:ft=c CODE ENDS I wanted my gvim to do the following things at various stages of editing a abc.h file: 1. Upon opening a new file, insert the skeleton like the one above, and leave me in insert mode after "Description" 2. When writing a file, update the "Last Modified" timestamp 3. On opening a existing file, modify the "Revision History" to add a new line, and leave me in insert mode below "Remarks" The following autogroup (:help au) commands let you do these (put these in your .vimrc): CODE STARTS: if !exists("autocommands_loaded") let autocommands_loaded = 1 au BufNewFile *.h call InsertCHHeader() au BufWrite *.h call ModifyTime() " You might want to comment-out the line below - see note 6 at the end of the post. au BufReadPost *.h call ModifyHeader() endif function! InsertCHHeader() call InsertSkeleton("skeleton.h") " CHANGE this! call InsertFname() 1 " Search for Description call search("Description:") normal $ startinsert endfunction function! InsertSkeleton(fname) let path_to_skeletons = $HOME . "/etc/skeletons/" " CHANGE this! " Save cpoptions let cpoptions = &cpoptions " Remove the 'a' option - prevents the name of the " alternate file being overwritten with a :read command exe "set cpoptions=" . substitute(cpoptions, "a", "", "g") exe "read " . path_to_skeletons . a:fname " Restore cpoptions exe "set cpoptions=" . cpoptions " Delete the first line into the black-hole register 1, 1 delete _ " Search for Filename: call search("Filename:") exe "normal A " . expand("%:t") " Search for Created: let current_time = strftime("%b %d %Y %T") "CHANGE this! call search("Created:") exe "normal A " . current_time " Search for Last modified: call search("Last modified:") exe "normal A " . current_time " Search for Date let date_line_no = search("Date") let rev_history = getline(line(".")) let rev_history = substitute(rev_history, "Date ", strftime("%b %d %Y"), "") " CHANGE this! let rev_history = substitute(rev_history, "Author", "KG ", "") "CHANGE this! let rev_history = substitute(rev_history, "Remarks", "File created.", "") call append(date_line_no, rev_history) endfunction function! InsertFname() " Convert newname.h to _NEWNAME_H_ let fname = expand("%:t") let fname = toupper(fname) let fname = substitute(fname, "\\.", "_", "g") " Search for #ifndef call search("#ifndef") exe "normal A " . "_" . fname . "_" " Search for #define call search("#define") exe "normal A " . "_" . fname . "_" endfunction function! ModifyHeader() " Modify header only if we have write permissions if &readonly == 0 " Search for Date let date_line_no = search("Date") if date_line_no != 0 let rev_history = getline(line(".")) " Substitute Date, and Author fields let rev_history = substitute(rev_history, "Date ", strftime("%b %d %Y"), "") " CHANGE this! let rev_history = substitute(rev_history, "Author", "KG ", "") " CHANGE this! let rev_history = substitute(rev_history, "Remarks", "", "") " echo "Modified = " . rev_history call append(date_line_no, rev_history) normal j$ startinsert endif endif endfunction function! ModifyTime() " Do the updation only if the current buffer is modified if &modified == 1 let current_time = strftime("%b %d %Y %X") " CHANGE this! " Save current position at mark i normal mi " Search for Last modified: let modified_line_no = search("Last modified:") if modified_line_no != 0 && modified_line_no < 10 " There is a match in first 10 lines " Go to the : in modified: exe "normal f:2l" . strlen(current_time) . "s" . current_time echo "Modified date stamp to " . current_time sleep 500m " Restore position normal `i endif endif endfunction CODE ENDS Notes: 1. The strftime( ) function is not-portable. You might need to change the format specifier for your system 2. The autogroup commands assumes that there is a file called skeleton.h at the location ~/etc/skeletons. You might have to modify the path and file name. In my case, the skeleton.h file looks like: /****************************************************************************** * Filename: * Description: * * Version: 1.0 * Created: * Last modified: * Revision: None * * Author: Karthick Gururaj * Company: [Removed] * e-mail: [Removed] * * Revision history * Date Author Remarks * ******************************************************************************/ #ifndef #define #endif // vim:sw=3:ts=3 Search the script for the pattern "CHANGE" to see where you might have to make changes.. 3. I have not tried to make the script super-portable (that looks obvious eh?). The reasoning is, any changes are a one time effort. 4. The scripts don't modify search history or register values. I have used one letter for marking thou' 5. If you open a new header file, and quit it without writing, no file is created. 6. I found having an autogroup command for modifing the revision history everytime the file is opened to be irritating. So I have disabled this in my system. Note on note: I also had some problems when trying to open the file thro' the quickfix window. 7. You can define more such skeletons for other extentions. 8. Feedback is welcome! Cheers! VimTip 435: remarks to script c.vim : statement oriented editing of C / C++ programs http://vim.sourceforge.net/tip_view.php?tip_id= Seems to be a nice, powerful addition for C-programmers. The screenshots show a really dangerous C++ trap: NEVER add C++ comments after a '#define' statement ! The Preprocessor will substitute the defined text literally, so all of your code behind the defined text will be commented out. I used abbreviations for C-constructs like 'cfor' for empty for loops, 'cif' for if then elses, etc., so typing in insert mode has not to be interupted. The cursor will be positioned for entering the following code. Another thing is standard C-comments for file/function headers. I used a command line tool (perl script) to get a personalized version from a standard template and read in the output with ':r ! '. This is a solution for workgroups where no one HAS to use VIM. I had autocommands for automatically read in the comment headers when opening new header or source files. Thomas VimTip 436: Accidently typed control-u and lost your input? http://vim.sourceforge.net/tip_view.php?tip_id= If you've accidently typed control-U to delete a line then accidently typed ESC straight after that because you've been using web forms and ESC in IE forms is like undo and basically you really didn't want to do that then you should do this: :let @a = @. "aP The . register is basically everything you've just typed in input mode including the control-U. When you paste this buffer it acts like you're typing it again and deletes the line. You need to reassign it to another register with the let command before you can paste it properly and get at your nice input. VimTip 437: extending keywords http://vim.sourceforge.net/tip_view.php?tip_id= sometime when you are working with an extended language (such as uC++) there exist keywords that are not included as keywords in the vim release, so you can easily update keywords in two ways. 1. edit your c.vim file [if you are coding c/c++] try 'vim61/runtime/syntax/' for location of these files, and add the keywords in the correct groups, 2. the second way is you can put them all in a separate file, and source it, eg: say i had some new c types, called uTask or uMutex i could get them highlighted as types using the following command: :syn keyword type uTask uMutex uNoMutex [etc..] enjoy. .. hzp. VimTip 438: Search/replace "within selection" in gvim using '< '> http://vim.sourceforge.net/tip_view.php?tip_id= In other editors I've always used the search/replace "within selection" features a lot but never knew how to do that in gvim. I finally found the '< and '> marks '< goes to the start of the last graphical selection (in gvim) '> goes to the end of the last graphical selection so you can use these to simulate the search "within selection" option that other programs have. eg: :'<,'>s/fred/joe/g will replace fred with joe in the last graphical selection VimTip 439: Replace text in highlighted search http://vim.sourceforge.net/tip_view.php?tip_id= you can search for text and highlight it, using /pattern usually you want to replace the exact found occourences with another string, because the common trick to e.g. repeadetly pressing: 1. cw = change till end of word, or ct( = change till first occourence of character ( 2. n = next found pattern 3. . = do command 1. again 3. goto 2. is too cumbersome, besides, you already specified what you want to replace with /pattern. solution: use c//e as 1. (it replaces till end of highlight). you will NEED to bind: nnoremap n // nnoremap N ?? in your vimrc, or step 2. will end up with the cursorposition on the last character of your match, because it will remember the pseudo-search-command in step 1. VimTip 440: Automatic formatting of paragraphs http://vim.sourceforge.net/tip_view.php?tip_id= When I use Vim to create plain-text files (like mail messages) I like the feature that automatically makes lines XY characters long. I simply type ':set tw=60' on the command line, and as I type lines are broken (autorwapped) before they reach 60 characters length. The problem is, when I latter decide to edit the paragraph. When I delete or add some words, the paragraph looks broken. The solution is to type 'gqap' to format a paragraph or make a mapping for this command. However, it annoys me to do it repeatedly. There is a better solution. 1. Go to http://cream.sourceforge.net/vim.html and download the latest patched Vim 2. Install the program. 3. See :help auto-format. I will not repeat the docs here. For the impatient, set fotmatoptions to aw2tq ':set fo=aw2tq' and start typing. The text flows automagically between lines as you type text inside the paragraph. GREAT!!! VimTip 441: Toggle auto-wrap using txtwidth in INSERT mode http://vim.sourceforge.net/tip_view.php?tip_id= In INSERT mode, I would like to 1. keep tying without auto-wrap (good for editing vimrc and c) 2. wrap long line at will (good for email and text) Following is the map I figured out, using in this example: set sr fo=roqm1 tw=64 im :setl sr! fo=strpart("-+",&sr,1)=tc_ By default, it goes without auto-wrap. If I want, I can type to triggle auto-wrap. Another toggles back. Basically it toggles two settings: a) :set fo+=tc b) :set fo-=tc strpart() is used for toggling; "sr" is choosing for no good reason; "_" can be any char; is needed to *triggle" this action. It works for me on W2K. Please tell me if you have better ideas to get this job done. Note: We may use 'linebreak', but that still leaves a really long line. I would like to keep my &tw. Thanks VimTip 442: Show all lines that contain keyword under cursor http://vim.sourceforge.net/tip_view.php?tip_id= Started finding this one pretty useful. If you want to view a list of all the lines in the current buffer that contain a word, place your cursor over the word and press [I Handy to see where you last used variables, functions, etc. VimTip 443: A better interfacing of (La)TeX with the quickfix mode http://vim.sourceforge.net/tip_view.php?tip_id= VIM's quickfix mode is a very nice feature. Nevertheless, I was not completely satisfied when I used it together with (La)TeX. Here are the main reasons: * The default error format pattern is able to extract the line number and the error message, but not the column number. * This pattern is of course unable to deal with BibTeX's or MakeIndex's error messages. * TeX's messages are quite verbose. Having them displayed at each run, even when no error occurs is sometimes annoying. Thus I implemented TeXwrapper, a small program which silently runs TeX and optionally some associated tool like BibTeX, MakeIndex, eukleides or Dvips. When an error occurs, TeXwrapper scans the transcript files and prints to stderr "compiler style" error messages, i.e.: ::: This allows very simple settings on VIM's side, that is: set makeprg=texwrapper set errorformat=%f:%l:%c:%m Someone writing an article with LaTeX containing cross references and a bibliography may then use: "make -lb2 %". Option -l stands for "run LaTeX" (instead of TeX), -b for "run BibTeX", -2 for "run twice" (to get correct cross references). Another feature is the --window option (short: -w). When something goes wrong, a GTK+ window pops up, displaying a summary of the encountered errors. Hence, one may use: "silent make -w %" which enables to avoid the "Hit ENTER or type command to continue" message at each run. TeXwrapper has been developed on a GNU/Linux system, but it should build on any system where flex has been ported. The pop up window is opened by a separate program, named texwrapper_window, which of course requires the GTK+ library. TeXwrapper has been released under the GPL and is available at: http://perso.wanadoo.fr/obrecht/texwrapper Happy Vimming & TeXing! Christian Obrecht VimTip 444: quickfix show entire contents of multiline error in cwindow on cn, cp and cc http://vim.sourceforge.net/tip_view.php?tip_id= put this in your .vimrc if you use the cwindow " \cc map cc :cwindow:ccb " \cn map cn :cwindow:cnb " \cp map cp :cwindow:cpb and when you use \cc (or whatever your leader character is + cc), \cn or \cp, it will do what :cc, :cn and :cp usually did, with the added bonus of showing the entire contents of multiline errors. this is especially useful for javac via ant, and it's obnoxious to keep typing b every time i do a :cn, so i mapped this. detailed explaination: ":cwindow" ensures that the quickfix window is show. ":cc" (:cn, and :cp) actually do the operation "b" go to the bottom window (which cwindow will be if it's shown) which will magically center on the error "" carriage-return on the error line, taking you back to the code with the error i know it probably seems superfluous if you haven't been personally affected by this particular annoyance. thanks to freenode #vim for inspiration. VimTip 445: Formatting stuff http://vim.sourceforge.net/tip_view.php?tip_id= Hello all, Im new to VIM, but I wanted to post some of my ideas for everyone here. Mark T, a friend of mine, just reciently got me in to VIM and I havent looked back yet! I really like this program, and I feel it's a valuable tool. Mark and I program in Lisp and Visual lisp for AutoCAD. (Its a program for drafting) and I have been adding stuff to my 'rc' file for lisp programing for abbout a month now. Mark has convinced me to post some tips here. So here they are: ********************************************************************** imap " this will allow me to always use the backspace key in insert mode imap Ji " this will allow me to join a line while still in insert mode map .f v%zf " fold an entire block of code nnmap ,y y " This will select a whole line of text or it will select " everything in a fold. map .; v%:s/^/;;;/:noh " comments out and entire block of code from paren to paren :au BufRead *.lsp :loadview 1 :au BufRead *.LSP :loadview 1 " load the first fold view file for the current file map st :set tw=70vgq " this will allow you to format an entire block of text ********************************************************************** John VimTip 446: Quick and dirty Postgres query http://vim.sourceforge.net/tip_view.php?tip_id= Here is a simple and usefull mapping for anyone who can't stand developing queries on the psql prompt or messing around with the single \e psql edit buffer. map :!psql -d yourdb < % less VimTip 447: Use the upper-lower case ~, also on Windows (ita) http://vim.sourceforge.net/tip_view.php?tip_id= For who know to change the case of key typed, otherwise see before the Tip #49 :^) I had find usefull use ~ ( on linux :^) to change the case of word, but also a my friend want this option on windows. So i told him to use the ~ for this. But italian keyboard have not the ~ on board. So i have mapped this to a key, let read the code: map ~ Thats all. I have used this on windows and italian keyboard, but i believe that is possible also on other keyboard yhat not have the tilde like us-keyboard. NOTE: Make attention to key that you use for mapping ~, some key ar used by vim, so for this don't work. Have a nice day :^) VimTip 448: Yank (copy) decimal numbers from hex numbers. http://vim.sourceforge.net/tip_view.php?tip_id= Here is a mapping that will copy a hexadecimal number in a register after converting it to the decimal equivalent. The tip is pretty useful if you are a programmer. :map \y g*:let @*=@/ + 0 Usage: 1. Place the cursor on any hexadecimal number (eg 0xff, 0xfefe, 0x3434) and press \y. 2. Place the cursor at the location where you want to paste the number in decimal and press "*p 3. The number is also copied to the clipboard (windows) so you can paste it in other applications. Example: If the hexadecimal number is 0xff, then 255 will be copied to the clipboard. Configuring the tip. If you do not like the above key combinations or the register being used, you can configure the tip to use other mappings as explained below: 1. Change \y in the above mapping to any key combination of your choice. 2. Change @* to @ to copy the contents to another register. If you do this, pasting will require the command "p Side effects: 1. The tip uses the search register for the conversion. Therefore any last search will be lost. 2. The tip also uses a register to yank the result. The earlier contents of that register (in our case the * register) will be lost. -mohit VimTip 449: FORTRAN highlighting problems http://vim.sourceforge.net/tip_view.php?tip_id= Sometimes the FORTRAN syntax file doesn't set the correct source form. So if you want to choose it by yourself, add the following line in your vimrc file: au BufNew *.for let b:fortran_fixed_source=1 " set the correct value The other way to do this is to change the file extension (F77/F90/F95), but it might be a long and/or hazardous work for big projects... VimTip 450: Working with multiple sessions http://vim.sourceforge.net/tip_view.php?tip_id= The problem I'm trying to solve: I usually need to work on different projects (let us call them: PROJ1 and PROJ2). These are in different directories, have different files.. etc. It would be nice if I can instruct my editor to take me back to the exact session (see :help sessions) for each of these projects - open the required files and buffers, window layout etc... Solution 1. Append the following code to your .vimrc - Change the variable g:PathToSessions to your desired place, if needed (make sure that this directory exists and is writable) 2. Open all/some files in a particular project (as if you are working on that) in gvim. Say I open all my PROJ1 related files. You can split windows etc.. and make it look as if you are really working! :-) Do a :SetSession PROJ1 3. Quit gvim 4. Restart gvim without any filenames at the command line. 5. You ought to get a popup-entry asking you which session to restore. Choose PROJ1.vim to see the effect. 6. Repeat with other projects. Note: 1. You don't have to :SetSession everytime you open gvim as in step 5. Only once. 2. If you start vim with no files at the command line, you have an option of going back to the last saved session (this is available in the gui if you choose LastSession.vim) CODE STARTS au VimLeave * call VimLeave() au VimEnter * call VimEnter() let g:PathToSessions = $HOME . "/.vim/sessions/" function! VimEnter() if argc() == 0 " gvim started with no files if has("browse") == 1 let g:SessionFileName = browse(0, "Select Session", g:PathToSessions, g:PathToSessions . "LastSession.vim") if g:SessionFileName != "" exe "source " . g:SessionFileName endif else " For non-gui vim let LoadLastSession = confirm("Restore last session?", "&Yes\n&No") if LoadLastSession == 1 exe "source " . g:PathToSessions . "LastSession.vim" endif endif endif endfunction function! VimLeave() exe "mksession! " . g:PathToSessions . "LastSession.vim" if exists("g:SessionFileName") == 1 if g:SessionFileName != "" exe "mksession! " . g:SessionFileName endif endif endfunction " A command for setting the session name com -nargs=1 SetSession :let g:SessionFileName = g:PathToSessions . . ".vim" " .. and a command to unset it com -nargs=0 UnsetSession :let g:SessionFileName = "" CODE ENDS VimTip 451: KDE Konsole renameSession to edited file name http://vim.sourceforge.net/tip_view.php?tip_id= In Kde the renameSession will set the Konsole name. Add this to your .vimrc file to name the session after the edited file. autocmd BufReadPost * :silent !dcop $KONSOLE_DCOP_SESSION renameSession % VimTip 452: Unix: Editing multiple files, listed in a file, one per line, from the command-line http://vim.sourceforge.net/tip_view.php?tip_id= I needed to edit about 300 files in a directory tree that all contained a specific line. I used -w {scriptout} on the first file to write my macro, and then used this command line to execute the rest: vim -s scriptin `cat file-containing-files` This cats the file containing the multiple files, one per line, to the command line, allowing you to edit tens, hundreds or even thousands of files using the same script. Of course, I had to use a recursive macro to get it done. Here's what I used: qq/\.\.\.\.\.\.Complete^Mdd:wn^M^M@qq@q Basically recording the macro, searching for my string, deleting that line, writing the file and going to the next, then executing itself (@q), ending the macro and then executing itself. This way one script could be used to edit all 300 of my files. VimTip 453: Use Taglist with LaTeX files http://vim.sourceforge.net/tip_view.php?tip_id= First, you have to add a new language to ctags in ~/.ctags add : <.ctags> --langdef=tex --langmap=tex:.tex --regex-tex=/\\subsubsection[ \t]*\*?\{[ \t]*([^}]*)\}/- \1/s,subsubsection/ --regex-tex=/\\subsection[ \t]*\*?\{[ \t]*([^}]*)\}/+\1/s,subsection/ --regex-tex=/\\section[ \t]*\*?\{[ \t]*([^}]*)\}/\1/s,section/ --regex-tex=/\\chapter[ \t]*\*?\{[ \t]*([^}]*)\}/\1/c,chapter/ --regex-tex=/\\label[ \t]*\*?\{[ \t]*([^}]*)\}/\1/l,label/ --regex-tex=/\\ref[ \t]*\*?\{[ \t]*([^}]*)\}/\1/r,ref/ I think this good for me but if someone found something better, i will be happy :) Edit taglist.vim (my patch for version 2.4) : --- taglist.vim 2003-04-14 16:47:25.000000000 +0200 +++ .vim/plugin/taglist.vim 2003-04-14 15:00:04.000000000 +0200 @@ -509,6 +509,9 @@ " vim language let s:tlist_def_vim_settings = 'vim;a:autocmds;v:variable;f:function' +" tex language +let s:tlist_def_tex_settings = 'tex;s:section;c:chapter;l:label;r:ref' + " yacc language let s:tlist_def_yacc_settings = 'yacc;l:label' in vim, type : :Tlist or see taglist doc references : Taglist : http://www.vim.org/scripts/script.php?script_id=273 ctags : http://ctags.sourceforge.net Vim-LaTeX : http://vim-latex.sf.net/ VimTip 454: Syntax Highlighting Keeps Breaking (and how to fix it!) http://vim.sourceforge.net/tip_view.php?tip_id= If you vim syntax highlight keeps breaking as you move around your document this is the tip for you! :) First of all, how to fix it: put the following in your .vimrc (_vimrc on windows): "autocmd BufEnter * :syntax sync fromstart" now, you might say, "Robert, I already put 'syntax sync fromstart' in my .vimrc, and it doesn't work!" -- and in saying that, you would be correct, because of a few factors coming together to cause you pain. Factors: 1. Vim syntax files should define the best syntax sync method for that langauge 2. Many vim syntax files do not do #1 3. Almost all syntax files do a :syntax clear which removes _your_ sync setting Notes: The syntax files that tend to have the most trouble keeping sane highlighting are multilangauge files (html/javascript -- html/php/javascript ...), yet the all work perfectly with :syntax sync fromstart. This is not a vim bug, but a problem with the syntax files, yet, it has been argued that maybe vim should NOT clear out the sync setting when doing a syntax clear -- and just wait for it to be overwritten... like everything else -- that is debatable :) Hope this helps you... join #vim on irc.freenode.net for all your vim help needs :) VimTip 455: Map a function key to toggle line wrapping http://vim.sourceforge.net/tip_view.php?tip_id= Most of the time I want to have line wrapping on. But, there are some times that I want to toggle it off, to check structures or something... here's a function key for toggling line wrapping: :set wrap :let g:toggleWrap = 0 map :if g:toggleWrap == 1:set wrap:let g:toggleWrap = 0:else:set nowrap:let g:toggleWrap = 1:endif Tom. VimTip 456: escape select mode in a map command (used to map indent in select mode) http://vim.sourceforge.net/tip_view.php?tip_id= When using mswin behaviour, the select mode is activated each time you select some text with shit+arrows or with the mouse. Then entering '>' to ident the text will just replace selected text with >. To offer a behaviour similar to visual text editor, I use the following mappings : vmap ^0 > vmap ^0 < then in select mode, tab will go to to visual mode, shift one block and then return to select mode ! Shit-Tab will just do the same thing, going backward. VimTip 457: Follow tag in new window http://vim.sourceforge.net/tip_view.php?tip_id= If you use tags, you might want to follow a tag, but leave the current window open. The following mapping allows you to do this easily with Ctrl-\. :map :sp_ VimTip 458: How to use quickfix mode to see all errors in one window (:cwindow). http://vim.sourceforge.net/tip_view.php?tip_id= Uptil vim 5.8, I was using the cfile, clist...etc for quickfix mode. In vim6.x, I found out that :cw will boost my productivity as a programmer. To make, type :make as we do in older versions of vim (<6.0). Instead of clist,cfile...etc, type :cw you get one split window, in which errors are listsed. Current error line will be highlighted and cursor will move to the corresponding source file line. Doing an on any error line in the error window will take the cursor to the corresponding source line. This eliminates the need for the process described in vimtip #345.(Now you can get rid of Visual studio altogether !) Details: Help is available in vim 6.x onwards by entering :help cw VimTip 459: Use Ctrl-O instead of Esc in insert mode mappings http://vim.sourceforge.net/tip_view.php?tip_id= Theory: Ctrl-O in insert mode switches to normal mode for one command and then switches back to insert mode. Practice: Mappings like :imap :set number!a move the cursor one character right when it's in the first column. Use :imap :set number! instead, it has no side-effects. If you have mapped in normal mode too (to do the same thing), :imap is even better. When you need to do more than one thing in the mapping, you can - use more Ctrl-O, one before each command, or - use | to run more commands at once, or - define a command (or function) doing everything and map to it. - ... (TMTOWTDI) VimTip 460: how to implement vertical lines showing tab groups.. http://vim.sourceforge.net/tip_view.php?tip_id= When browsing the jEdit screenshots page, I saw a feature I wanted and didn't have in vim. It was a vertical line showing tab groups. if (this) { | if (that) { | | do stuff; | } } http://www.jedit.org/index.php?page=screenshot&image=10 <-- show a much better example that my little example did... I was wondering how todo this in vim.. turns out it is simple :set list :set listchars=tab:\|\ :h listchars for help Hope this helps you... join #vim on irc.freenode.net for all your vim help needs :) VimTip 461: Open a Perl module based on it's module name http://vim.sourceforge.net/tip_view.php?tip_id= This may be of interest to Perl programmers using vim. Sometimes I want to open up the source code of a system Perl module that's installed. Here's one way to do that: :e `perldoc -l Module::Name` I find that useful. VimTip 462: G's of Vim http://vim.sourceforge.net/tip_view.php?tip_id= Hi Guys !! You can play with THE "g" in VIM editor. Try this Place the cursor on any variable in your program. gd will take you to the local declaration gD will take you to the global declaration. g* search for the word under the cursor. It's just like * but don't put < or > around words so here you can search word which contains word under your cursor Confused ???? try it NOW :-) g# same as g* but in backward direction Now time for gssssss ggdG takes out all your hard work ;-) I mean deletes the content of the file .. Happy viming ... VimTip 463: XSLT Mappings I use to speed up developing XSLT files. http://vim.sourceforge.net/tip_view.php?tip_id= I recently added these mapping to speed up typing XSLT elements. As this is my first tip, I hope these might be useful to someone else. I added these mappings to my copy of Devin Weaver's xmledit script. imap pi ^M imap ap imap ap`s ^[F"i imap ap`sm ^[3F"i imap at ^[F"i imap el ^[F"i imap if >^[kf"a imap im ^[F"i imap in ^[F"i imap ou ^[F"i imap pa ^[F"i imap pa`ns ^[3F"i imap st > imap te >^[kf"a imap te`n >^[kf"a imap te`mm >^[kf"a imap va ^[F"i imap wi ^[F"i imap wi`ns ^[3F" For more information: vimscript #301 help: imap VimTip 464: search & replace the word under the cursor http://vim.sourceforge.net/tip_view.php?tip_id= I have this usefull mapping in my vimrc: nmap ; :%s/\<=expand("")\>/ Now, if you see a word 'foo' which should be replaced, you only have to put the cursor on it and type ';'. Then the command-prompt has already the annoying :%s/\/ and you just have to enter your new word. For information: :help :help expand VimTip 465: generic xml imap to make an element of any word you type http://vim.sourceforge.net/tip_view.php?tip_id= Hi all. We're doing a lot of xml work, in docbook and custom xml files. I'd just like to share one macro I've developed, that I really can't live without. imap ,,, bdwa<pa>pa>kA If in isert mode I type programlisting,,, the text immediately get's modified to with the cursor in between, still in Insert mode. The same happens with any other word i type followed by three commas. It saves me a lot of work, and I'd like to share it. Hope you can use it Bart van Deenen. (bart@vandeenensupport.com) VimTip 466: Insert one character only http://vim.sourceforge.net/tip_view.php?tip_id= I have not yet seen this idea yet. But early in my use and love of Vim, I got frustrated in command mode when I wanted to insert just one character of text. So I put this in _vimrc: "insert one character noremap ir I think it has been one of the most time saving mappings -- and I have remapped most of my keyboard. VimTip 467: vim windows displaying output inside vim window http://vim.sourceforge.net/tip_view.php?tip_id= In vim for *nix or cygwin, the command :!cmd displays the output inside vim windows, but for vim windows, the output is displayed in the console window. To make the output displayed inside vim or gvim window, can use :echo system("command") references: :help system() :help echo VimTip 468: display date-and-time on status line http://vim.sourceforge.net/tip_view.php?tip_id= It didn't seem like an existing tip mentioned this, so: The following lines in .vimrc or a plugin file will display the time of day and calender date (some of us need that reminder) on the editor status line: set ruler set rulerformat=%55(%{strftime('%a\ %b\ %e\ %I:%M\ %p')}\ %5l,%-6(%c%V%)\ %P%) It doesn't update time if you issue no keystrokes, but as soon as you do anything at all in the editor, you will get the current time. VimTip 469: The use of %< instead of % http://vim.sourceforge.net/tip_view.php?tip_id= This tips is for vim or gvim user. We know the following map map! /' ^[:w^M:! latex %^Mi is doing the following. By typing "/'" in insert mode, this will save the current tex file, and compile it. The reader understand that one can change "/'" by anything he want, as long as it does not bug its own configuration, I like this map 'cause on an english keyboard both / and ' are close to eachother. We may wonder what to do if we wish to open the associated dvi file?! Indeed one has to replace % by %<.dvi and then we get map! ^[:! xdvi %<.dvi ^Mi or map! ^[:! kdvi %<.dvi ^M if you are using K environement. The same thing apply indeed for any other extension i.e., the map map! ^[:! gv %<.ps ^Mi will open the associated ps file with gv. VimTip 470: Map to quickly swap/exchange arbitrary text http://vim.sourceforge.net/tip_view.php?tip_id= When editing text, it's not uncommon to need to swap two bits of text. In Vim, it's easy to swap adjacent characters, words and lines (see vimtip #47), but to swap non-adjacent text (such as comma-separated words, variable assignments, and function parameters), you usually have to resort to a tedious delete/move/put/delete/move/put sequence. Mappings such as the one in vimtip #329 can help in some cases, but for a more general solution, try this mapping: vnoremap `.``gvP``P To use it: First, delete some text (using any normal Vim command, such as daw, {Visual}x, or dt,). Then, visually select some other text, and press CTRL-X. The two pieces of text should now be swapped. For example, to swap "apple" and "orange" in the line below: int apple, lemon, orange; 1. Delete "apple", using (for example) diw or d 2. Visually select "orange" 3. Press CTRL-X The mapping is not limited to single words, though, and will work with anything you can delete/select (even lines and blockwise selections). VimTip 471: Bridging the worlds: putting your rodent to work for vim in xterms http://vim.sourceforge.net/tip_view.php?tip_id= If, like me, you don't want to use the GUI vim because you work in an xterm most of the time anyway, you may be annoyed at the shortcomings this presents. For example, during my webbrowsing, I'll often fire up vim in one of the already lying around xterms to conveniently write a long text (such as this one), and then paste from vim into a textfield on a HTML form in the browser. The first problem is caused by line numbering, which I keep enabled at all times. :set number :help number Normally, if you try to copy text out of the xterm that vim is running in, you'll get the text as well as the numbers. The GUI version gets this right: it only selects the text, keeping the line numbers out of the picture. But I don't want the GUI version. So instead, I added this to my vimrc: :set mouse=a Much better. You can also selectively enable mouse support for specific modes only by using something other than 'a' (for 'all'). :help mouse Now although I'm more of a keyboarder, when I juggle text between X apps (or maybe between xterms), it's just more convenient and efficient to keep my hands on my mouse, since they're there anyway. Now, if you own a moderately recent model, you'll know this lovely little wheel they have (which usually also doubles as mouse button 2). Rolling it scrolls the window in GUI vim, which simplifies life when selecting several, distant passages to paste one after the other. But I don't want to use the GUI vim - you can imagine my delight when I ran across this in the vim documentation: :help wheel It involves adding a couple mappings to your vimrc and corresponding VT100 translations to your .Xresources file as a prerequisite. Don't forget $ xrdb -load .Xresources after you edit the file. The running xterm will not heed the changes; you need to open a new one to see the effect. The wheel may not work with the mappings as described in the helpfile. They worked without a hitch for me at first (using Xfree 4.1 then), but broke after I upgraded my distro. Whether it was the switch to 4.3 on this binary has been built with different options, I don't know. At any rate, I had to experiment a bit with the list from :help keycodes After a bit of trial and error, I finally fixed them by substituting for : :map [62~ " etc " ... Done. Load a large text file and marvel at mousewheel scrolling. VimTip 472: Handy option flag toggler http://vim.sourceforge.net/tip_view.php?tip_id= Here's a little function I put together to make some of my mappings easier to read, understand and change. function ToggleFlag(option,flag) exec ('let lopt = &' . a:option) if lopt =~ (".*" . a:flag . ".*") exec ('set ' . a:option . '-=' . a:flag) else exec ('set ' . a:option . '+=' . a:flag) endif endfunction Examples of use: map :call ToggleFlag("guioptions","m") map :call ToggleFlag("guioptions","T") Can anyone see anyway to improve it? e.g. remove the leading exec... "if &{a:option}..." doesn't work. e.g. a regex match doesn't seem the cleanest of checks, though I prefer it to setting a variable for each possible flag. VimTip 473: "compiler" for perl http://vim.sourceforge.net/tip_view.php?tip_id= At on stage I was writing a lot of perl scripts/modules with Vim and found it useful to be able to run the perl syntax-checker (perl -c) from within Vim via the "make" function. To be able to do this you'll need to add the following Module (VimCompile.pm) to your @INC ------------------------------ #!/usr/bin/perl -w #$Id: VimCompile.pm,v 1.2 2002/02/16 01:07:03 forkin Exp $ # reformat "perl -c" syntax-check error-/warning-messages for Vim package VimCompile; use strict; sub _die { my ($msg)=@_; $msg=~s/^((.* at )((.*) line )([0-9]+)(\.|, near .*))$/$4:$5: $1/mg; die qq/$msg/; } sub _warn { my ($msg)=@_; $msg=~s/^((.* at )((.*) line )([0-9]+)(\.|, near .*))$/$4:$5: $1/mg; warn qq/$msg/; } $SIG{'__DIE__'}=\&_die; $SIG{'__WARN__'}=\&_warn; # return OK 1; __END__ --------------------------- This Module will reformat the warnings/errors so that Vim can parse them (to allow you to jump to the location/source-code of the error). You will also need to deposit the following (perl.vim) in your ~/.vim/runtime/compiler directory. --------------------------- " Vim compiler file " Compiler: perl (output of "die" massaged) " Maintainer: Chris Forkin, chris@forkin.com if exists("current_compiler") finish endif let current_compiler = "perl" " A workable errorformat for "perl -c" setlocal errorformat=%f:%l:\ %m " default make setlocal makeprg=perl\ -MVimCompile\ -c\ % --------------------------- VimTip 474: have . restore the cursor position a la emacs in viper mode http://vim.sourceforge.net/tip_view.php?tip_id= Before making the switch to vim, I spent time in limbo using EMACS in viper mode (which is EMACS with vi emulation). Despite the vast improvements in most areas, there were a few things I missed from EMACS. One thing I really missed was the behavior of the . command, which always restored the cursor position. For example, let's say I had the following: foo.some_method.each do { |x| puts x } foo.some_other_method(Time.now) foo.close() and I wanted to change foo to bar. I would always use a cw and then the . command: cwbarj.j. rather than making a substitute command which would make me worry about the range over which it should take place etc. When making the switch to vim, I was disconcerted because after the first . my cursor was at the end of the second 'bar'. In fact I pretty much always wanted this behavior from '.', so this mapping helped me out: "make . not move the cursor noremap . mz.`z I've since noticed this is just a special case of the tip *restore-position* in the help manual, but it took me a while to find out how to do this. One other former emacs/viper user also was searching for this. Hopefully this tip makes it easier for the next person to find who finally finds their way out of EMACS. VimTip 475: wrap visual selection with fold markers http://vim.sourceforge.net/tip_view.php?tip_id= Use this vmap to enclose a block with fold markers: vmap fold mz:''>o// }}}`z?{{{A VimTip 476: multime errorformat & makeprgs http://vim.sourceforge.net/tip_view.php?tip_id= I was fiddling around with the errorformat and makeprg opts, and as I code in different languages, i was wondering if there was a way of specifiing a special makeprg and errorformat parameter for each language.... and THERE IS!! just edit the $VIM/ftplugin/[syntaxfile].vim i.e.: perl.vim added at the end : set makeprg=$HOME/bin/vimparse.pl\ -c\ %\ $* set errorformat=%f:%l:%m c.vim set makeprg=g++\ % well, and you get the pattern. It works delightfully with the :Make tip vimtip #203 Ah! I mapped F-5 to :Make, and made it go back to the main window: map :Make VimTip 477: How to put the indentation level on the status line http://vim.sourceforge.net/tip_view.php?tip_id= related to vimtip #303 in .vimrc set statusline=\t%{ShowTab()}\ %P fu ShowTab() let TabLevel = (indent('.') / &ts ) if TabLevel == 0 let TabLevel='*' endif return TabLevel endf VimTip 478: Copy the search results into clipboard http://vim.sourceforge.net/tip_view.php?tip_id= " previous clear the clipboard with this command :normal "*y0 " Usage: :g//call CopyPattern() function CopyPattern() let idx = 0 let xEnd = 0 while idx >= 0 let @* = @* . matchstr(getline("."), '' . histget("/", -1), idx) . "\n" let xEnd = matchend(getline("."), '' . histget("/", -1), idx) let idx = match(getline("."), '' . histget("/", -1), xEnd) endwhile unlet idx unlet xEnd endfunction VimTip 479: Replace with NO Typing http://vim.sourceforge.net/tip_view.php?tip_id= Often I replace one word with another. This is much faster than the substitute command and requires no typing. For example, to change badName(...) to goodName(...) (with the mappings below): 1. Put the cursor anywhere on goodName and type: gy 2. Move the cursor to badName and type: gp That's it! If there are more than one badNames, type *N before typing go, then n gp to change the next one. I mapped go to put a space after the word, but someone clever might be able to combine them. Here is how I mapped the commands: "replace word with register b WITH SPACE AFTER word noremap go lb"bPldwi hbye "replace word with reg b WITHOUT SPACE after word "(lb so no move to previous word, but gives error at end of line) noremap gp lb"bPldwhbyw "copy this word to register b for replacing with go and gp noremap gy lb"bye VimTip 480: editing files on an ftp server listening on a non-standard port http://vim.sourceforge.net/tip_view.php?tip_id= Vim will edit files on an FTP server with the command: e ftp://ftp.server/path/to/file/filename But if you are using a virtual FTP server as in Bricolage to edit templates, the FTP server is listening on a non-standard port (typically 2121, but it can be something different). In that case, the command would be e ftp://ftp.server\#2121/path/to/file/filename. Note the "\#". The standard syntax for specifying a port number is to append #2121 to the server name, where "2121" is the port to connect to. But Vim treats an unescaped "#2121" as an alternate file reference and fails with the message "No alternate file name to substitue for '#'". Escaping the "#" causes Vim to treat is an another character in the string, and the connection works. help edit and then search for "count" to find the syntax for editing alternate files This works on Red Hat and on WindowsNT. VimTip 481: abbreviations only on shortcut http://vim.sourceforge.net/tip_view.php?tip_id= Actually, this is just a more flexible completion. I made the following (example) to have a unique abbreviation: iabbrev date^A =strftime("%F") Note that ^A is Control-A (insert with ). This is to avoid the completion if you really want to write 'date'. And now this mapping: inoremap a Now type date in insert-mode and you will get the date. VimTip 482: Use VIM as an organizer of Memos, bookmarks, todo, etc. http://vim.sourceforge.net/tip_view.php?tip_id= No one has perfect memory. I know this when I saw clever person often key in notes in his computer. He uses a number of small files with ".txt" extension and "grep" through them. To me this is not good because you still need to give a different name to different things and as time goes by, you will useup common words and starts "name1", "name2", ... to enumerate. Have you ever thought of having one single Memo at hand that can put things down as normal editor, still very easy to search and navigate through? HTML would be perfect for hypertext navigation, but it is not as perfect for writting notes. Who knows what

means level 3 headings when i just want to use to highlight my text, ... A lot inconvenience. I use VIM! For many years it helps me remember almost everything and still enjoy it. Let me share the experience with you. Of course I expect you be a VIMMER as me first. VIM as an organizing tool? The help system of VIM is so well organized that we can think of reusing the same for our everyday purpose. For example, here is my own Memo (abridged): <> *memo.txt* My Memo - extending my poor memories |guide| ------------------------------------------------------------------------------------------------------------- *subjects* *toc* |cmd| command tips |def| definitions |dev| developments |ed| editors |friends| friends |lang| languages |misc| others |private| personal info |sys| system ------------------------------------------------------------------------------------------------------------- Commands *cmd* *General http://www.cslab.vt.edu/manuals ...... |doskey| DOS key utility : expand history |man| Unix manual man foo nroff -man foo.1 | less nroff -man foo.1 | a2ps -m |unix| http://gd.tuwien.ac.at/linuxcommand.org/ |winhelp| ..... ------------------------------------------------------------------------------------------------------------- Development *develop* *dev* ... ------------------------------------------------------------------------------------------------------------- vim:tw=78:fo=tcq2:isk=!-~,^*,^\|,^\":ts=8:ft=help:norl: <> Some explainations: 1) The last line instructs VIM with a number of editing settings. The most important one here is "ft=help", which says file-type is "help"! So the VIM will highlight thing for us. 2) You can use *foo* to indicate an anchor to the "help" system of VIM. If you press Ctrl + ] on a word "foo", the cursor will jump to the first *foo*. You can also see |foo| as a way to highlight it as implicit keywords. 3) This is not magic. The mechanism behind is the tag system. VIM needs to have the following tag file to go to where you want it to go: =================================== %userprofile% memo.txt /*%userprofile%* .htaccess meo.txt /*.htaccess* access memo.txt /*access* access.conf memo.txt /*access.conf* addressbook memo.txt /*addressbook* anchor_keyword memo.txt /*anchor_keyword* apache memo.txt /*apache* as index.txt /*as* at index.txt /*at* awk index.txt /*awk* =================================== Each line defines a tag, the first element is the keyword, the second is the file where the tag belongs (yes, you can use multiple files as long as you know what they are), and the last element is the command which as VIM to perform at the keyword (you can as well do something wield here, but that's your own business). 4) But that's tedious! How to write these tags? God save you and thanks VIM, you can find this utility to do it: cc doctags.c -o doctags doctags memo.txt | sort -f | awk -f cases.awk >tags uniq -d -2 tags ------------------------------------------------------------------------------ <> doctags.c /* vim:set ts=4 sw=4: * this program makes a tags file for vim_ref.txt * * Usage: doctags vim_ref.txt vim_win.txt ... >tags * * A tag in this context is an identifier between stars, e.g. *c_files* */ #include #include #include #include #define LINELEN 200 int main(argc, argv) int argc; char **argv; { char line[LINELEN]; char *p1, *p2; char *p; FILE *fd; if (argc <= 1) { fprintf(stderr, "Usage: doctags docfile ... >tags\n"); exit(1); } printf("help-tags\ttags\t1\n"); while (--argc > 0) { ++argv; fd = fopen(argv[0], "r"); if (fd == NULL) { fprintf(stderr, "Unable to open %s for reading\n", argv[0]); continue; } while (fgets(line, LINELEN, fd) != NULL) { p1 = strchr(line, '*'); /* find first '*' */ while (p1 != NULL) { p2 = strchr(p1 + 1, '*'); /* find second '*' */ if (p2 != NULL && p2 > p1 + 1) /* skip "*" and "**" */ { for (p = p1 + 1; p < p2; ++p) if (*p == ' ' || *p == '\t' || *p == '|') break; /* * Only accept a *tag* when it consists of valid * characters and is followed by a white character or * end-of-line. */ if (p == p2 && (p1 == line || p1[-1] != '-') && (strchr(" \t\n\r", p[1]) != NULL || p[1] == '\0')) { *p2 = '\0'; ++p1; printf("%s\t%s\t/*", p1, argv[0]); while (*p1) { /* insert backslash before '\\' and '/' */ if (*p1 == '\\' || *p1 == '/') putchar('\\'); putchar(*p1); ++p1; } printf("*\n"); p2 = strchr(p2 + 1, '*'); /* find next '*' */ } } p1 = p2; } } fclose(fd); } return 0; } <> cases.awk { print tolower($1) "\t" $2 "\t" tolower($3); } <> That's it. Good luck VIMMER. VimTip 483: Using GREP for a ‘list occurrences’ and quickfix help command. http://vim.sourceforge.net/tip_view.php?tip_id= This is inspired by VIMTIP#391: Simple programmers TODO list using grep and quickfix taglist.vim is VIMSCRIPT#273 This is a little tip on shortcuts to make :grep just a little bit more handy. :GREP is simply a front end to :grep which uses the current word under the cursor and the current file. Use this for the times when you want a ‘list occurrences’ type search. (See also :h :ilist another method) " [Feral:158/03@07:02] Easily GREP current word in current file. command GREP :execute 'grep '.expand('').' '.expand('%') | :copen | :cc Certainly nothing fancy here. Now given that continually typing :cnext, :cprev and :cc can get a bit cumbersome to type one might consider mappings to speed up the process. When such mappings call a user function we can get somewhat fancy as illustrated below. "[Feral:314/02@19:33] Assign some keys for handy quickfix window commands. if has("win32") nnoremap :call Fancy_Quickfix_Cmd(':cnext') nnoremap :call Fancy_Quickfix_Cmd(':cprev') nnoremap :call Fancy_Quickfix_Cmd(':cc') nnoremap :clast nnoremap :cfirst nnoremap :cnewer nnoremap :colder endif " [Feral:158/03@08:02] Very simple wrapper: do quickfix cmd, center line and " if taglist.vim's window is open sync function s:Fancy_Quickfix_Cmd(Cmd) :try execute a:Cmd :catch /^Vim(\a\+):E553:/ :echohl ErrorMsg | echo v:exception | echohl None :endtry :norm! zz " If the taglist window is open then :TlistSync " Tag list window name: '__Tag_List__' if bufwinnr('__Tag_List__') != -1 :TlistSync endif endfunction NOTE that s:Fancy_Quickfix_Cmd() uses VIM 6.2’s new try/catch commands; For previous versions just omit the try/catch … endtry lines. The function works well enough just is not as graceful when you reach the first or last of the error list. I.e. PRE 6.2 version: function s:Fancy_Quickfix_Cmd(Cmd) execute a:Cmd :norm! zz " If the taglist window is open then :TlistSync " Tag list window name: '__Tag_List__' if bufwinnr('__Tag_List__') != -1 :TlistSync endif endfunction Just as an asside, if you did not want to use a user command for something like this you can do something like this: nnoremap :cnext :norm! zz :TlistSync nnoremap :cprev :norm! zz :TlistSync nnoremap :cc :norm! zz Of course if you do not have/want the syncing with taglist.vim simplly remove :TlistSync. Now, the advantage of having s:Fancy_Quickfix_Cmd() is that we can conditionally do something based on the command, or some other attribute. In this case we function the same for all commands (and just blindly execute them). We do check to see if the taglist window is open and if so ask it to Sync, if it is not, we don't. One other (minor, cosmetic) advantage to this is we see the user command in the echo area and not the last command executed (as with just the pure mapping method directly above). You may need to modify the :GREP command so that your grep has the proper flags, etc. On win32 I have my grepprg set to "set grepprg=C:\Dev\bin\grep.exe\ -niH", fwiw. Happy VIMing! VimTip 484: Console-like fonts for Windows GVim http://vim.sourceforge.net/tip_view.php?tip_id= For some excellent "DOS"-like fonts in multiple sizes (.fon format) check out http://www.uwe-sieber.de/dosfon_e.html. Very cool for GVim and console windows! VimTip 485: Open a new window and read in the man page for the word under the cursor http://vim.sourceforge.net/tip_view.php?tip_id= This short function opens a new window and reads in the Unix man page for the word under the cursor. To use it add the following to your ~/.vimrc file: fun! ReadMan() " Assign current word under cursor to a script variable: let s:man_word = expand('') " Open a new window: :exe ":wincmd n" " Read in the manpage for man_word (col -b is for formatting): :exe ":r!man " . s:man_word . " | col -b" " Goto first line... :exe ":goto" " and delete it: :exe ":delete" endfun " Map the K key to the ReadMan function: map K :call ReadMan() cf: :help windows :help wincmd etc The col command may differ on your version of Unix, see col(1) for details. VimTip 486: Search for word under cursor, but don't move. http://vim.sourceforge.net/tip_view.php?tip_id= This is very, very simple: :noremap #* I find this helpful when editing multiple files and I want to search for the word under the cursor in *another* file. I then type F1, C-^, n. VimTip 487: jump to a file to a certain line number http://vim.sourceforge.net/tip_view.php?tip_id= Dear VIMMERS: It is useful to have cn, cl for locating errors. however, when the compilation was done off-line, gcc ... >& compile.log how to use the compile.log to locate the errors? for example, vim.h:1506 if i use "gf" when the cursor is over "vim.h", it just jumps to the begining of the file. here may be one solution by combining several steps: nmap gt mAT f:l"aywbbgf:^Ra^M "mA" --- marks the current position to global register A so that i can return the log file by 'A "T " --- goes to the begining of the tag, so in any characters of "vim.h:1506", it first places the cursor to "v". "f:" --- goes to the ":" separator "l" --- goes to the starting of line number "ayw --- try to use register a to remember the line number "bb" --- move cursor back to the filename "gf" --- now jump to the file ":^Ra^M" --- jump to the line number remembered in register a nmap gt ... place the above steps into key combinations "g" "t" so next time use "gt" instead of "gf" on the error tag! VimTip 488: vimrc setting for wider vim diff window (gVim) http://vim.sourceforge.net/tip_view.php?tip_id= The Vim diff feature (fantastic as it is) opens with the default window width (gVim), and the two files each get a half width buffer windows with a vertical split between them. When you resize, only one buffer window changes. We might write function to automatically center the split and possibly trigger it automatically with an autocmd (advanced). However, we can still have Vim open with a wider window when performing a diff. The following code can be added to the vimrc file. Be sure to adjust the numbers for the available screen real-estate and the other settings to taste. "=============================================================== " Window settings set lines=60 " Set window height set columns=98 " Set window width 'co' set guioptions+=b " Add bottom scroll bar 'go' " If comparing files side-by-side, then ... if &diff " double the width up to a reasonable maximum let &columns = ((&columns*2 > 172)? 172: &columns*2) endif "=============================================================== Remember, the default for the columns setting is either 80 or the terminal width. I wouldn't expect consistant results for non-gVim usage. By the way, I still need to add a test to detect vim vs. gVim in my own vimrc (perhaps greping $VIM for gvim) so that I can adjust colors and other settings accordingly. Note that the expression in the let statement can be replaced with a constant. But, that expression may prove usefull if the columns setting is to vary (e.g. a filetype plugin). For a general function (intermediate), someone would want to come up with some global names like MaxScreenColumns or MaxBufferColumns. VimTip 489: Section jump in Latex http://vim.sourceforge.net/tip_view.php?tip_id= This is a small mapping that can be used for jumping sections in a latex file (just like ]m and [m for Java methods) map ]s :/\\\(sub\)\{,2}section\s*{ :noh map [s :?\\\(sub\)\{,2}section\s*{ :noh I want to extend it to recognize something like 2]s to move two sections forward. How to do it. Aditya VimTip 490: Paste vim registers in search or colon command-line instead of using the system clipboard http://vim.sourceforge.net/tip_view.php?tip_id= To paste something into a search or the colon command-line without using the system clipboard, press Ctrl-R" (including the quote, which represents the unnamed register), or replace the quote with another register. For more information about registers, see ":help resisters". VimTip 491: can anyone tell me how to get rid of the F1 mapping ? http://vim.sourceforge.net/tip_view.php?tip_id= owkay i have been googeling for 2 hours now and i cant find how to remove that really anoying map i keep hitting it as i go for esc, and its really starting to piss me off ^^; can anyone tell me how to get rid of the F1 mapping ? VimTip 492: jump to file from :CVSDiff output http://vim.sourceforge.net/tip_view.php?tip_id= I use :CVSDiff from cvscommand.vim quite often to get an overview of the changes i made to a file. I always want to jump from the diff to the corresponding line in the original file. So I wrote a small script that does that, and put it in $VIM/after/syntax/diff.vim Pressing will execute that script. function! DiffJumpToFile() let a=line(".") " current line number let b=search("^\\(---\\|\\*\\*\\*\\) ", "b") " search for line like *** 478,489 *** let c=getline(b) " get this line as string let d=strpart(c, 4, match(c, ",")-4) " get the first line number (478) from that string let f=search("^\\(---\\|\\*\\*\\*\\) .*\\t", "b") " search for line like *** fileincvs.c .... let g=getline(f) " get this line as string let h=match (g, "\\t", 4) " look for end of filename (terminated by tab) in string let i=strpart(g, 4, h-4) " get the filename execute ":b " . i | " change to that file execute "normal " . (d+a-b-1) . "G" | " go to right line number endfunction nmap :call DiffJumpToFile() I didn't put that script in the script section because it doesn't have any error checking at all. VimTip 493: Open the directory for the current file in Windows http://vim.sourceforge.net/tip_view.php?tip_id= It's often handy to open the folder that corresponds to a file I'm editing (as much as I hate to leave Vim!) I've added this mapping: map :silent !explorer %:p:h:gs?\/?\\\\\\? So that typing ctrl-e in any buffer opens the folder that the file lives in in Windows. See :help filename-modifiers for more. VimTip 494: maximize or restore window http://vim.sourceforge.net/tip_view.php?tip_id= I used to define 2 different mapping for maximize and restore window. But I wanted a map that can toggle between them. So, I came up with this function. This function assumes you are using win32 version of gvim. If you are using different version, then substitute :simlat ~[rx] by the key combination for your window manager. Add following lines on your [._]g*vimrc let w:windowmaximized = 0 function! MaxRestoreWindow() if w:windowmaximized == 1 let w:windowmaximized = 0 " restore the window :simalt ~r else let w:windowmaximized = 1 " maximize the window :simalt ~x endif endfunction map :call MaxRestoreWindow() VimTip 495: Backspace key using puTTY to RH9 box http://vim.sourceforge.net/tip_view.php?tip_id= I connect to a RedHat9 server via the free software "puTTY" from a Windows computer. On the shell (tcsh), the was working as it should, but in VIM it was not. No matter what I did in the .vimrc file, it always acted like a key. Very annoying. I've discovered that one must use the keyboard setting of "linux" in the puTTY settings in order for the key to work properly in VIM. The "linux" keyboard is not the default. If one does not do this, VIM always is sent the key command when pressing on the . VimTip 496: This is the hyperlinked html format of the Vim Reference Manual. http://vim.sourceforge.net/tip_view.php?tip_id= DESCRIPTION ---------- This is the hyperlinked html format of the Vim Reference Manual. Vim is much more than just a text editor; it's a cross-platform working environment, but quite counter-intuitive to use. A Greek translation of the Vim Tutor and Menu is on the drawing board at LynxX.org. If you have a Web browser, the official hypertext version is currently at . This unofficial version looks much nicer than the official hypertext versions that exist at vim.org or can readily be converted to html from the RefMan documents, but is an exact copy of the source docs. You can downloaded it from here: -- FTP -- HTTP DISCLAIMER ---------- This document is freely redistributable, but I take no liability for the correctness and safety of any procedures or advice given here. This document is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, explicit or implied for the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS ---- If you find any mistakes or dead links, please contact: Vangelis Eustratius VimTip 497: Replacing a string with default buffer contents http://vim.sourceforge.net/tip_view.php?tip_id= It's common to replace a given string in a file with something that appears elsewhere in the file. Often I don't think to put the replacement string in a named register, so it's hard to delete the text I'm replacing without replacing what's in the default (@") copy register -- :let is too cumbersome for this. (BTW, is there a way to issue a command like 'd' or 'c' *without* replacing what's in @"?) Anyway, I've been using this map vmap R ::let @9=@"gvx"9P which replaces what's highlighted in visual mode the contents of "" It's ugly though (all the backspaces are necessary to delete the default :'<,'> that shows up when you start a command in visual mode.) I find this useful enough that I use it, but what I really want is something similar where I could type say R3w (where R is remapped to my special command) that replaces the next three words the contents of @" VimTip 498: Completation using the syntax file http://vim.sourceforge.net/tip_view.php?tip_id= To use the vim completion you can use a dictionary. :set complete=k As a dictionary you can use a syntax file (which are in the /syntax/ directory), so you can complete the reserved words. Inserting in your .vimrc a line like that autocmd Syntax * exec('set dict=/usr/share/vim/syntax/' .expand('') .'.vim') you can avoid to select the dictionary for each filetype. (Don't forget to use your correct syntax directory for this). To get more info: :help autocmd :help complete VimTip 499: View character class http://vim.sourceforge.net/tip_view.php?tip_id= This one shows the definition of a predefined character class. ([:alpha:], [:graph:] etc.) The cursor is assumed to point to the name of the character class one wants to examine. Press "cc" ... fun! s:Show() norm! viwy echo 'class [:' . @" . ':]' . "\n" let pat = '[[:' . @" . ':]]' let i = 0 while i < 256 let ch = nr2char(i) if ch =~ pat | echon ch . '(' . i . ')' . "\t" | endif let i = i + 1 endwhile endfun nn cc :call Show() VimTip 500: View character class http://vim.sourceforge.net/tip_view.php?tip_id= This one shows the definition of a predefined character class. ([:alpha:], [:graph:] etc.) The cursor is assumed to point to the name of the character class one wants to examine. Press "cc" ... fun! s:Show() norm! viwy echo 'class [:' . @" . ':]' . "\n" let pat = '[[:' . @" . ':]]' let i = 0 while i < 256 let ch = nr2char(i) if ch =~ pat | echon ch . '(' . i . ')' . "\t" | endif let i = i + 1 endwhile endfun nn cc :call Show() VimTip 501: View character class http://vim.sourceforge.net/tip_view.php?tip_id= This one shows the definition of a predefined character class. ([:alpha:], [:graph:] etc.) The cursor is assumed to point to the name of the character class one wants to examine. Press "cc" ... fun! s:Show() norm! viwy echo 'class [:' . @" . ':]' . "\n" let pat = '[[:' . @" . ':]]' let i = 0 while i < 256 let ch = nr2char(i) if ch =~ pat | echon ch . '(' . i . ')' . "\t" | endif let i = i + 1 endwhile endfun nn cc :call Show() VimTip 502: View character class http://vim.sourceforge.net/tip_view.php?tip_id= This one shows the definition of a predefined character class. ([:alpha:], [:graph:] etc.) The cursor is assumed to point to the name of the character class one wants to examine. Press "cc" ... fun! s:Show() norm! viwy echo 'class [:' . @" . ':]' . "\n" let pat = '[[:' . @" . ':]]' let i = 0 while i < 256 let ch = nr2char(i) if ch =~ pat | echon ch . '(' . i . ')' . "\t" | endif let i = i + 1 endwhile endfun nn cc :call Show() VimTip 503: PuTTY numeric keypad mappings http://vim.sourceforge.net/tip_view.php?tip_id= Purpose: Add support for {rhs} of keyboard numeric keypad while in vim insert mode and using PuTTY as a SSH terminal connection. What to do: Add these mappings to your _vimrc or _gvimrc. PuTTY's default terminal type is xterm. Check your settings or just echo $TERM at the command prompt on most unix systems to verify xterm type. Code to add to _vimrc: :imap ^[Oq 1 :imap ^[Or 2 :imap ^[Os 3 :imap ^[Ot 4 :imap ^[Ou 5 :imap ^[Ov 6 :imap ^[Ow 7 :imap ^[Ox 8 :imap ^[Oy 9 :imap ^[Op 0 :imap ^[On . :imap ^[OQ / :imap ^[OR * :imap ^[Ol + :imap ^[OS - Any questions about vim and PuTTY please send to mmetzger@mv-research.com. Michael Metzger VimTip 505: email from vim! http://vim.sourceforge.net/tip_view.php?tip_id= I always found myself typing into my email editor and wishing that it had the nice features of Vim. There are a bunch of hacky ways to email from Vim, but there's actually an elegant solution: Pine! The University of Washington has turned what was once a lame console program into a sopohisticated IMAP email client with server-based address books and configuration files. Among its many options is one that allows you to use your favorite text editor to edit emails. There's even a very good port for Windows called PC-Pine. Here's the link: http://www.washington.edu/pine/ VimTip 506: Open windows Help files (chm) using or selected area http://vim.sourceforge.net/tip_view.php?tip_id= If you want to open a CHM (HTML Help) file and force the index to go to a specific entry you can do the following (on WinXP or any windows platform that has keyhh.exe). " Create mappings to launch the ASA9 Help file with context nnoremap :silent!!cmd.exe /cstart keyhh.exe -\#klink "" "$ASANY9\docs\dbmaen9.chm" vnoremap :let old_reg=@"gvy:silent!!cmd.exe /cstart keyhh.exe -\#klink """ "$ASANY9\docs\dbmaen9.chm":let @"=old_reg:echo "" Each of these are on one line. nnoremap opens the help file using the that the cursor is on. vnoremap allows you to visually select a block of text and open the search window with that text. It also restores what ever was previously visually selected after the launch. If you use the map repeatedly, the same HTML Help window will be used. VimTip 507: Quick window resizing http://vim.sourceforge.net/tip_view.php?tip_id= These key mappings (placed in your _vimrc) let you use the F8 and F9 keys to make a window wider or taller. The shift key reverses the effect, and the Ctrl and Alt modifiers go to a choice of standard settings. Mappings to change the font size.(which work slightly differently) are also included. Obviously you can change F8 and F9 to keys of your choice. " Window size appearance augroup guiappearance au! set guifont=Andale_Mono:h12 :map :set guifont=Andale_Mono:h12 :map :set guifont=Andale_Mono:h10 :map :set guifont=Andale_Mono:h14 :map :set lines+=5 :map :set lines-=5 :map :set lines=60 :map :set lines=30 :map :set columns+=10 :map :set columns-=10 :map :set columns=132 :map :set columns=80 augroup END VimTip 509: Commands that don't clobber the search register http://vim.sourceforge.net/tip_view.php?tip_id= I frequently execute commands (mappings, usually) that perform operations that change the value of the search register for the sake of the mapping. They might do a :s or some such that affects the search register. I don't always want this side effect, so I use the following command/function: " Executes a command (across a given range) and restores the search register " when done. function! SafeSearchCommand(line1, line2, theCommand) let search = @/ execute a:line1 . "," . a:line2 . a:theCommand let @/ = search endfunction com! -range -nargs=+ SS call SafeSearchCommand(, , ) " A nicer version of :s that doesn't clobber the search register com! -range -nargs=* S call SafeSearchCommand(, , 's' . ) Basically, :SS followed by any command will execute that command (to simulate keystrokes, use :normal as the command) and restore the search register when it's done. :S is a replacement for :s which works EXACTLY the same way (without or without range, flags etc. etc.) but doesn't clobber the search register in the process. VimTip 510: one way to set $VIMRUNTIME within vimrc http://vim.sourceforge.net/tip_view.php?tip_id= In general, $VIMRUNTIME cannot be set within vimrc. (:set helpfile is not so useful) Bram prefers to let vim figures it out. This tip is for those who want to avoid setting $VIMRUNTIME as an enviromental variable (either rc file on UNIX or enviroment on Windows). I found the following steps worked on my PC and unix: 1. find out your $VIM (On Windows, it is the directory where gvim.exe lives) 2. create a directory called doc under $VIM (now, we have $VIM/doc) 3. copy help.txt from official $VIMRUNTIME/doc (now, we have $VIM/doc/help.txt) Now, we can set $VIMRUNTIME within vimrc, for example let $VIMRUNTIME='C:/usr/share/vim/vim62' I find it is useful on PC especially when I have cygwin installed, thus a single copy of VIMRUNTIME can be shared for both vi (cygwin version) and gvim.exe (win32 version). VimTip 511: key mapping for goto the absolute line number http://vim.sourceforge.net/tip_view.php?tip_id= It's quite simple, nmap G Now, you can keep the original [count] function and have an easier way to goto the abolute line number. Have a nice day! VimTip 512: Automatic insertion of C/C++ header gates http://vim.sourceforge.net/tip_view.php?tip_id= C/C++ header files should be guarded against multiple inclusions using preprocessor directives, e.g.: #ifndef FOO_H #define FOO_H /* Declarations. */ #endif Placing the following snippet in your .vimrc file makes vim insert these preprocessor gates automatically: function! s:insert_gates() let gatename = substitute(toupper(expand("%:t")), "\\.", "_", "g") execute "normal i#ifndef " . gatename execute "normal o#define " . gatename . " " execute "normal Go#endif /* " . gatename . " */" normal kk endfunction autocmd BufNewFile *.{h,hpp} call insert_gates() VimTip 513: Automatic insertion of C/C++ header gates http://vim.sourceforge.net/tip_view.php?tip_id= C/C++ header files should be guarded against multiple inclusions using preprocessor directives, e.g.: #ifndef FOO_H #define FOO_H /* Declarations. */ #endif Placing the following snippet in your .vimrc file, makes vim insert these preprocessor gates automatically, when a new header file is created: function! s:insert_gates() let gatename = substitute(toupper(expand("%:t")), "\\.", "_", "g") execute "normal i#ifndef " . gatename execute "normal o#define " . gatename . " " execute "normal Go#endif /* " . gatename . " */" normal kk endfunction autocmd BufNewFile *.{h,hpp} call insert_gates() VimTip 514: Automatic insertion of C/C++ header gates http://vim.sourceforge.net/tip_view.php?tip_id= C/C++ header files should be guarded against multiple inclusions using preprocessor directives, e.g.: #ifndef FOO_H #define FOO_H /* Declarations. */ #endif Placing the following snippet in your .vimrc file, makes vim insert these preprocessor gates automatically, when a new header file is created: function! s:insert_gates() let gatename = substitute(toupper(expand("%:t")), "\\.", "_", "g") execute "normal i#ifndef " . gatename execute "normal o#define " . gatename . " " execute "normal Go#endif /* " . gatename . " */" normal kk endfunction autocmd BufNewFile *.{h,hpp} call insert_gates() VimTip 515: see filenames of all scripts that vim loaded or tried to load http://vim.sourceforge.net/tip_view.php?tip_id= To see filenames of all scripts that vim loaded, including those loaded implicitly at startup: :scriptnames This does not show names of 'would-be scripts' -- that is, scripts that vim tried to open, did not find and was silent about it. To see the 'would-be' scripts -- that is, scripts that vim tried to open, did not find and was silent about it -- add '-V' option when starting vim: vim -V Also: vim --version # shows system-dependent location of rc-files # but does not show location of system/personal # plugins :help startup VimTip 516: find two words in either order http://vim.sourceforge.net/tip_view.php?tip_id= The shortest regular expression to find two words in either order (on the same line): .*alice\&.*bob (Thanks to Piet Delport and Matthew Winn) Other solutions: \(alice.*bob\)\|\(bob.*alice\) -- "old-style" regexp ^\(.*Alice\)\@=\(.*Bob\)\@= Keywords: find, match, search, words in either order, regular expression VimTip 517: Rejustification of *roff style markup. http://vim.sourceforge.net/tip_view.php?tip_id= Normally, I bind F4 to gqap, which suffices nicely to rejustify plain text, and most of my latex and HTML stuff (with due care taken to have plenty of blank lines for delimiting. However, if you're dealing with *roff style markup, such as man-pages or (in my case) documents using the -ms groff macros, it won't work, as the tags are on the line just above, such as the following example. .IP Boggart Magical being that transforms into whatever the viewer most fairs. Proffessor Lupin used a boggart to teach Harry how to repel Dementors, as (at that time) Harry most faired Dementors. Ideally, I'd just position the cursor on the body of the text (this a definition list entry, if anyone is wondering), and just press F4. But that would also rejustify the argument to the IP macro, which would be bad. So instead of using gqap, I use gq an a selected range of lines. I search upwards something that might be a macro, or a blank line, move down a line into the body, start to select, search forward for the next macro or blank line, then gq to rejustify. The regex I use to search for the extents is \(^\.[A-Za-z]\{2\}\\|^$\) Since the document I'm working with has an extension of .groff, I bind, on BufferEnter, the following macro. au BufEnter *.groff nmap ?\(^\.[A-Za-z]\{2\}\\|^$\)jV/\(^\.[A-Za-z]\{2\}\\|^$\)kgq And it works. I'm using vim 6.1.320, although I believe it should work on most versions. VimTip 518: errorformat for icc7 http://vim.sourceforge.net/tip_view.php?tip_id= This is a errorformat for Intel icc7 compiler: errorformat=%E%f(%l): %m,%-C,%-C%p,%Z VimTip 519: Folding like in Visual Basic .NET http://vim.sourceforge.net/tip_view.php?tip_id= If your are using Microsoft Visual Studio .NET for editing Visual Basic .NET files, the Window Form Designer Generated Code is folded by default. If you want to have the same nice feature when editing the same file in Vim, put this code in your _vimrc file so you can switch between the folded and unfolded mode: function! NetFold() set foldmethod=syntax syn region myFold start="#Region" end="#End Region" transparent fold keepend extend syn sync fromstart set foldcolumn=2 endfunction function! NetUnFold() set foldmethod=manual set foldcolumn=0 norm zE endfunction So when your are editing a *.vb file, you simply have to call the function like this: :call NetFold() or :call NetUnFold() Also, if you want that little function to be called automatically when you edit a *.vb file, put these two lines in your _vimrc file: autocmd BufNewFile,BufRead *.vb setfiletype vb autocmd BufNewFile,BufRead *.vb call NetFold() Hope this will help. If you have any other suggestion, don't be shy to add them! VimTip 520: Searching for Identifiers http://vim.sourceforge.net/tip_view.php?tip_id= The problem: It's always annoying trying to do a search and replace for identifiers in C when the identifier that you are searching for is a substring of other identifiers or keywords in the program. For instance, let's say you want to search for every place you access the ubiquitous loop variable 'i'. If you do a search, you'll hit all the i's in the "if" and "while" keywords and any other identifiers that contain the letter i. For awhile I have been looking for some way to do this in vim. Other IDE's that I have seen have a "whole word" option where the text must be the whole word. Vim has the "]CTRL-I" command, but that is useless for search and replace because when you replace one instance, you won't have the original identifier under your cursor any more. Until recently, I didn't know how to do it in vim without manually typing the whole regular expression for C identifiers. The solution: Use the "\<" and "\>" in your search. Evidently, these respresent the start and end of words. So, to search for all occurrences of the variable 'i', you would use the following command: /\ If you want all identifiers that start with 'i', you use "/\". If anyone knows a better solution, I would love to know about it. VimTip 521: Something in GVIM for fun http://vim.sourceforge.net/tip_view.php?tip_id= Try these for fun Open gvim with some text in it and try set rl to come back to where u were try set norl In Gvim type ggvGg? --- This encrypts the whole of text Happy vimiiiing !!!! VimTip 522: Fix an autoindent error http://vim.sourceforge.net/tip_view.php?tip_id= When splitting a line in two, I sometimes insert a return before a space. Unfortunately, this mangles the autoindentation: the last tab turns into spaces. The following map fixes that problem: "Fixes a rare autoindent error inoremap =ReturnWrapper() function ReturnWrapper() if strpart(getline('.'), col('.') - 1) =~ '^\s*\S' return "\wi\" else return "\" endif endf Thanks to vimtip #102 for the tip on using with a wrapper function. VimTip 523: Folding functions with the prototype included http://vim.sourceforge.net/tip_view.php?tip_id= I used to use folding to fold functions in C/C++ from the "{" to the "}", but I wanted a way to fold the prototype as well. Using foldexpr allows this. " ----------- CUT function FoldBrace() if getline(v:lnum+1)[0] == '{' return '>1' endif if getline(v:lnum)[0] == '}' return '<1' endif return foldlevel(v:lnum-1) endfunction set foldexpr=FoldBrace() set foldmethod=foldexpr " ---------- END CUT Note that this will only work if you put the braces on lines by themselves in the very first column, ie: void func() { .... } VimTip 524: evaluate expression in any mode, including normal mode, using = http://vim.sourceforge.net/tip_view.php?tip_id= The = things evaluates the expression. For example: =12+34 = works in insert mode and in command mode.I felt it more convenient if = did the same thing in normal mode too. I have this in my .vimrc: map = :echo Now =123*456 evaluates expressions for me in all 3 modes: normal mode, insert mode, and command mode. In fact I found it much more convenient to do casual calculations using = in normal mode than in any other mode. Be warned: when typing = in normal mode, don't make long pause before '='. alone means 'redo' in normal mode. Vim is very smart, and figures the difference between single (which is 'redo') and the mapped sequence = (which is remapped). The 'timeoutlen' option controls this difference. The default value of 'timeoutlen' option is very convenient. This is expansion of vimtip #73 "using vim as calculator" References: :he c_CTRL-R :he i_CTRL-R :he 'timeoutlen' :he 'ttimeoutlen' Keywords: calculator, expression evaluation, normal mode VimTip 525: JavaBeans helper function http://vim.sourceforge.net/tip_view.php?tip_id= This one helps creating beans. Nothing serious actually, but might come in handy. It's pretty fresh, cuz I just got annoyed with Netbeans - I haven't tested it fully. Perhaps we could create some bigger Java Struts thing, huh? nnoremap dc :call AddBean() function! s:AddBean() let line = line('.') let name = inputdialog('Enter the name of the variable: ') let type = inputdialog('Enter the type of the variable: ') let upperName = substitute(name, '^\(\w\)\(.*\)$', '\u\1\2', '') call append(line, "\t}") call append(line, "\t\tthis.".name." = ".name.";") call append(line, "\tpublic void set".upperName."(".type." ".name.") {") call append(line, "") call append(line, "\t}") call append(line, "\t\treturn (this.".name.");") call append(line, "\tpublic ".type." get"."".upperName."() { ") call append(line, "") call append(line, "\tprivate ".type." ".name.";") call append(line, "\t//".name) return line endfunction VimTip 526: enhancing Benji Fisher's word_complete.vim script http://vim.sourceforge.net/tip_view.php?tip_id= I suggest you first look at the script itself: http://www.vim.org/scripts/script.php?script_id=73 Since the script has some problems (at least for me) when I paste text in X11 with the mouse, and since I need to switch to paste more anyway, I now use this in my .vimrc: " the word_complete.vim plugin just *rocks* autocmd VimEnter * call DoWordComplete() fun! SetComplete() call DoWordComplete() set nopaste nunmap iunmap nmap :call UnsetComplete() imap :call UnsetComplete()a echo endfun fun! UnsetComplete() call EndWordComplete() set paste nunmap iunmap nmap :call SetComplete() imap :call SetComplete()a echo endfun nmap :call UnsetComplete() imap :call UnsetComplete()a Issues: (i) I'm sure this can be done better (ii) in insert mode, F12 switches to paste mode, but not back again. In normal mode, it works. I'm sure this is going to be something really, really silly. VimTip 527: vim (console/xterm) colors in gvim http://vim.sourceforge.net/tip_view.php?tip_id= You might have noticed that gvim uses slightly different colors compared to the console version. If you like the console colors more than the gvim default colors (as I do), you can add the following to your .vimrc: set background=dark hi SpecialKey guifg=Blue hi MoreMsg guifg=Green hi Visual guifg=NONE guibg=NONE hi Folded ctermbg=4 guibg=Blue hi FoldColumn ctermbg=7 hi DiffAdd guibg=Blue hi DiffChange guibg=Magenta hi DiffDelete guibg=Cyan hi Normal guifg=Gray guibg=Black hi Cursor guibg=White hi lCursor guibg=White hi Comment guifg=Cyan hi Constant guifg=Magenta hi Special guifg=Red hi Identifier guifg=Cyan hi Statement guifg=Yellow hi PreProc guifg=Blue hi Type guifg=Green hi Underlined guifg=Blue hi Todo guifg=Black There's one little difference: Folded is changed to something better for console *and* gui and FoldColumn is left as is in gvim and changed for console vim to match the gvim version. VimTip 528: Make search results appear in the middle of the screen. http://vim.sourceforge.net/tip_view.php?tip_id= Some useful mapping to make search results appear in the middle of the screen. nmap n nmzz.`z nmap N Nmzz.`z nmap * *mzz.`z nmap # #mzz.`z nmap g* g*mzz.`z nmap g# g#mzz.`z VimTip 529: Making (shift-tab) work http://vim.sourceforge.net/tip_view.php?tip_id= Shift Tab is a useful key combination to be able to use. I wanted to use it for tab completion: vimtip #102 Many people also use it for unindenting: vimtip #456 But shift tab seemed not to work on my system (slackware 8.1) but I managed to find a solution, and a workaround. Diagnosis: Make sure you are getting something from the keypress. Go into insert mode: and press then You should get a tab. and press then You should get ^[[Z If this happens, it is good, you can skip the next part of the diagnosis. Diagnosis Part 2: If you get nothing when you do then go to a command line prompt (#) and type: # xmodmap -pke | grep 'Tab' It should either show: keycode 23 = Tab or keycode 23 = Tab ISO_Left_Tab Now, which one is the 'right' one seems to depend on what terminal program you are using its various settings. (I need to use the 'ISO_Left_Tab' one with 'xterm' but the 'Tab' one with Eterm) I suggest you try changing to the mapping to the other one and test what you get from the keypresses again. If it doesn't work, you can just change it back. To change the mapping: # xmodmap -e 'keycode 23 = Tab ISO_Left_Tab' or # xmodmap -e 'keycode 23 = Tab' If changing the xmodmap setting worked, you'll probably need to put it somewhere where it will load on X startup or login. (.xinitrc or .bashrc or somewhere else depending on your system config.) If it didn't work see the other things to try below. Interpreting shift-tab correctly: Once you have the shift-tab key combo generating the correct string ^[[Z you just need to make sure that is then interpreted by vim as As of version 6.2 vim does this, so upgrading to 6.2 would be good. If you cannot upgrade for whatever reason try this workaround: :map [Z :ounmap [Z This will map the key you get when you press shift tab to which you can then use in other maps/scripts I suggest adding these lines (minus the leading : of course) to your .vimrc Other things to try: If none of the above worked, here are some other things to investigate. Make sure your window manager is not eating the keystrokes. - You don't have it mapped there to change desktop, or switch between windows or something do you? Use 'xev' to check that shift-tab is registering as a keypress and what it is returning. Good Luck. VimTip 530: How do I get the name of the current file http://vim.sourceforge.net/tip_view.php?tip_id= To get the name of the file you are currently editing use: @% If you want to make sure of the path as well use: expand("%:p") see also: help @ help expand vimtip #296 for why it might be a useful thing to do. VimTip 531: 1-2-3, let's make gvim.exe for free http://vim.sourceforge.net/tip_view.php?tip_id= This tip is for those who is interested to make gvim.exe on Windows without using MSVC or BCC. The condition is that cygwin is installed. (Another tip for Windows users: cygwin makes Windows really useful!) Following is three steps (under any shell and any directory) step 1: cvs -z3 -d:pserver:anonymous@cvs.vim.sf.net:/cvsroot/vim co vim step 2: cd vim/src step 3: make -f Make_cyg.mak IME=yes I have tested under Windows 2000 and have used my own gvim.exe for months without any problem. Special thanks to Dan Sharp to develop/debug Make_cyg.mak, which make it possible. VimTip 532: usefule keymaps -- for comment out,etc.. http://vim.sourceforge.net/tip_view.php?tip_id= -->a key map for commenting out lines -- use f12 key append this line into your .vimrc/.gvim rc file map ^i#j -->key maps to avoid a long shift press nmap :X :x nmap :W :w nmap :Q :q VimTip 533: Page 1 of 123 in header of :hardcopy http://vim.sourceforge.net/tip_view.php?tip_id= To get this to work you have to know how many lines per page :hardcopy is normally making. Open empty document and in Normal mode "100o". Then make ":%s/^/\=line('.')". Now ":hardcopy > nu.ps". Open nu.ps in PostScript viewer. You will see how many lines per page Vim is printing. In my case this is 73. Now set 'printheader' option: :set printheader=%<%f%h%m%=Page\ %N\ of\ %{line('$')/73+1} Explanations of % items in option are here |'statusline'|. line('$') - number of lines in buffer 73 - number of lines per page +1 - Vim don't know floating point math and everything rounds down. VimTip 534: for verilog users only http://vim.sourceforge.net/tip_view.php?tip_id= for all verilog users dealing with netlists,this an easier way to find out in which module you are really working in.add this map to your .vimrc/.gvimrc file.use `(tick) key to find out in which module u are actually residing in. map ` ma?moduleWyiw'a:echo "module -->" @0 note: this map works only when u are whithin the module.placing it on module/endmodule does not make any sense. VimTip 535: Working with only one term/console? http://vim.sourceforge.net/tip_view.php?tip_id= Sometimes you can only work with a single terminal/console, or you hate having too many windows open and need to switch between them, or QuickFix does not work on your favourite languages? This simple, yet powerful key stroke (Ctrl-Z) might be very useful to you. For example, let's say you are composing an email using vim on mutt, or you want to compile your file, you can simply press Ctrl-Z, gives you the prompt back, do multiple commands and whatever you want, and goes back to vim editing by typing "fg" again. If you need to admin some machine that only have vi instead of vim on some reason, you can edit multiple files by suspend them, using "jobs" to list them and "fg %n" (n is the job number) to load them back. So by using the simple Ctrl-Z, not only that you can edit multiple files in the same vim, you can edit multiple groups of files in different vim. Although it is a shell feature, but it goes together nicely with vim. Just in case for people that do not know, if all you want is to run a single external command, use ":!cmd", or "!" to filter text throught the command. For example, if you have a line "1 + 1 * 2", position cursor on it, and type "!}bc", you got "3" for you answer back. Or another example, position your cursor at the first line of your paragraph and type "!}fmt", now the paragraph is nicely formatted. With all these in hand, you don't need to waste key strokes to switch between different windows anymore, the only drawback is it only works in *nix. VimTip 536: Automaticly quit Vim if quickfix window (buffer) is the last http://vim.sourceforge.net/tip_view.php?tip_id= I was confused when I do some development job. Usually I have open one window with source code and one with error codes (command :copen). When I quit the source code quickfix window stay open. I'm lazy man so I must close this window with additional typing. I make simple autocmd which this difficult work in my stead. If you like it (or are lazy too) include this code in your .vimrc and use your spared time somewhere else :-). au BufEnter * call MyLastWindow() function! MyLastWindow() " if the window is quickfix go on if &buftype=="quickfix" " if this window is last on screen quit without warning if winbufnr(2) == -1 quit! endif endif endfunction VimTip 537: mimicking the shift-arrows (mark block) in terminals that don't understand shift-arrow (e.g. putty) http://vim.sourceforge.net/tip_view.php?tip_id= I like the MS-windows default behavior (ctrl-c for copy, ctrl-v for paste, etc) even when I'm running vimon a unix terminal. However, using mswin doesn't give the right "mark block" behavior in the terminal I use (putty). This may hold true for other Xterm emulators: the shift-arrows (mark block) don't work because shift-arrow sends exactly the same signal as just arrows. I have some maps that fix this by assinging some imaps and vmaps to the combination of ctrl-arrows (thanks to Antoine J. Mechelynck) " make arrow keys work in visual mode vmap OA k vmap OB j vmap OC l vmap OD h " simulate shift-arrows (select block in windows) with control-arrows inoremap [A vk vnoremap [A k inoremap [B vj vnoremap [B j inoremap [C vl vnoremap [C l inoremap [D vh vnoremap [D h VimTip 538: e-mail archive http://vim.sourceforge.net/tip_view.php?tip_id= This is a small archive of all the email sent to the Vim mailing list (vim_at_vim.org). This archive covers 2-1/2 years, they are gzipped text files that contain six months each. http://www.theswamp.org/vim/ VimTip 539: Quick access to vim tips and scripts with konqueror / kde http://vim.sourceforge.net/tip_view.php?tip_id= For those of you using KDE and Konqueror to browse the vim.sf.net, you can add it to the so called "Web Shortcuts" in konqueror: 1. In Konqueror choose "Settings/Configure Konqueror" 2. Goto "Web Shortcuts", choose "Add..." 3. Now configure the shortcut: * Search Name Provider: "VIM Tips" * Search URI: "http://vim.sourceforge.net/tips/tip.php?tip_id=\{@}" * URI shortcuts: "vt,vimt,vimtip" 4. Click OK and Apply the changes to Konqueror You can now use: "vt:4" in Konqueror's location bar to jump directly to Vim Tip #4. Feel free to do the same for VIM scripts using "http://vim.sourceforge.net/scripts/script.php?script_id=\{@}" as the Search URI. VimTip 541: How to get help using VIM http://vim.sourceforge.net/tip_view.php?tip_id= If you need help with vim and do not know where to go. Check out the Community link on the left. Or click this link http://vim.sourceforge.net/community.php VimTip 542: Edit remote files locally via SCP/RCP/FTP http://vim.sourceforge.net/tip_view.php?tip_id= I'm frequently editing files remotely, but if the network traffic is tight, then a normal VIM session turns into a tortuous event. The solution to that was right under my nose: VIM's Network-Oriented File Transfers (:help netrw). Instead of editing the file remotely, it can be transfered from the host server, to a local copy, edited and then sent back when done. I know that you can do this manually, but it's a hassle, besides, if it can be done automatically, why not go for that? :) Assuming you have the following installed and properly configured: 1. VIM 2. netrw.vim (afaik comes in all recent vim installs) 3. scp, rcp, ftp or ftp+ Then to use, all you need to go is specify the protocol, user, host and path to the file you want to edit: vim scp://konimi@vim.org//var/www/html/rtc_functions.php gvim scp://konimi@vim.org//var/www/html/tips/add_tip.php Every time you write the file (:w etc.) the file will get copied over to the source and you will be brought back to your session for further editing. If you already have an open session, then just issue the following commands: To read/load up a file: :Nread scp://konimi@vim.org//var/www/html/rtc_functions.php To write the file back: :Nwrite scp://konimi@vim.org//var/www/html/rtc_functions.php That's it! You'll be editing at local speed. VimTip 543: vim.po - Internationalizing the Vim editor http://vim.sourceforge.net/tip_view.php?tip_id= vim.po - Internationalizing the Vim editor +++++++++++++++++++++++++++++++++++++++++++ For a given vim-###-src#.tar.gz release there is only one vim.po file that can be created for translation purposes. However, this vim.po is not unique since several options may be set while extracting with `xgettext', depending mostly on the format of comments. For your convenience you can download a standard vim.pot to use as a translation template for vim-6.1 to most any language(s): http://lynxx.org/misc/download/vim-6.1-pot.tgz This is the general template for translating messages in Vim 6.1 using the Xgettext format. It contains all English messages in the (untranslated) form: msgid "ABC" - English text msgstr "" - canditate language To translate Vim 6.1 messages, proceed line-by-line, taking care not to translate commands and options specific to the editor. See the GNU `gettext' man-page for more info and details on this. This vim.pot should be used only with v. 6.1 to translate to any language. When Vim versions advance, a standard vim.po must be created from the newer sources, as delineated in the next VimTip "Vim goes INTL - Translating Vim Editor Messages, Menus, and Encodings' (VimTip#). You may also want to download a complete set in Greek to use as an example of full support for a specific language: http://lynxx.org/misc/download/vim-6.1-menu_el.zip http://lynxx.org/misc/download/vim-6.1-menu_el.tgz Happy Intl-ing! Vangelis Eustratius vangelise@lynxx.org VimTip 544: Vim goes Greek - Greek language support for Vim 6.1 http://vim.sourceforge.net/tip_view.php?tip_id= Vim goes Greek - Complete set of Greek language support for Vim 6.1 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ENGLISH TEXT ------------ This is the full set of messages, menus and encodings to be used to support Greek language. This set contains: vim.pot -- dummy portable object template for vim-6.1 (can be used with any language) vim.po -- the above vim.pot file with strings translated in Greek lang/el/LC_MESSAGES/vim.mo -- the Greek vim.po file formatted in machine object mode (vim.mo) lang/menu_gr_gr.greek.vim -- Greek used as the default encoding lang/menu_gr_gr.latin1.vimq -- Greek for Latin lang/menu_gr_gr.iso_8859-1.vim -- Latin-based ISO encoding sourceing from iso_8859-7 spec lang/menu_gr_gr.iso_8859-7.vim -- Greek-Latin-based ISO encoding lang/menu_greece_greek.737.vim -- MS-DOS/wINDOWS codepage for Greek (737) lang/menu_greek_greece.1253.vim -- MS-DOS/wINDOWS codepage for Greek (1253) lang/menu_greek_greece.cp437.vim-- Unix CodePage for Greek (nl_cp437) lang/menu_gr_gr.utf-8.vim -- UTF-8 for Greek tutor/tutor.gr -- Vim TUTOR in Greek README.TXT -- this file These compressed archives can be downloaded from: http://lynxx.org/misc/download/vim-6.1-menu_el.zip http://lynxx.org/misc/download/vim-6.1-menu_el.tgz To use Vim to edit in Greek (or any) language, we first enable the language option for the keyboard (Control Panel|Keyboard|Languages|Greek) and enable a key sequence (e.g. Ctrl-Shift) to toggle between the default language and Greek. In Vim the Greek language is displayed correcty. Finally, we unzip vim-6.1-menu_el to the vim61 directory. This ensures that the above files are place in the correct path. If you don't know how to extract to $VIMRUNTIME, unzip to any temporary folder. Then drag&drop or copy-and-paste each of the above files to its place after creating the container folders (/path/to/vim61/lang/el). This is what one may call manual extraction, so please wash your hands beforehand. For help on setting up Vim to support Greek -- from Vim do: :help language :help messages :help encoding For messages you'll have to set at least: let $LANG='el' / let $LANG='gr' :lan mes el / :lan mes gr For menus: :menut English Greek / let menut=Greek from the cmdline or in the _vimrc file. For more information see VimTip # "Vim goes INTL - Translating Vim Editor Messages, Menus, Encodings". The present document was posted as VimTip # and can be viewed online at: http://www.vim.org/tips/tip.php?tip_id= Enjoy Vim a la Greek! GREEK TEXT ---------- Vim στα Ελληνικά - Πλήρες σετ υποστήριξης ελληνικών για το Vim 6.1 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Αυτό είναι το πλήρες σετ μυνημάτων, μενού και κωδικοποίησης για χρήση σε υποστήριξη της ελληνικής γλώσσας με το Vim 6.1. Περιεχόμενα: ++++++++++++ vim.pot -- κενό πρότυπο ΡΟ για το vim-6.1 (μπορεί να χρησιμοποιηθεί με οποιαδήποτε γλώσσα vim.po -- το παραπάνω αρχείο vim.pot με συμβολοσειρές μεταφρ. στα ελληνικα lang/el/LC_MESSAGES/vim.mo -- το ελληνικό αρχείο vim.po μορφοποιημένο σε κατάσταση ΜΟ (vim.mo) lang/menu_gr_gr.greek.vim -- Greek χρησιμοποιείται σαν κωδικοποίηση προεπιλογής lang/menu_gr_gr.latin1.vimq -- Ελληνικά για Latin lang/menu_gr_gr.iso_8859-1.vim -- κωδικοποίηση ISO με βάση τη Λατινική, εκπηγάζει από τη προδιαγραφή iso_8859-7 lang/menu_gr_gr.iso_8859-7.vim -- κωδικοποίηση ISO με βάση τη Λατινική-Ελληνική lang/menu_greece_greek.737.vim -- κωδικοσελίδα MS-DOS/wINDOWS για ελληνικά (737) lang/menu_greek_greece.1253.vim -- κωδικοσελίδα MS-DOS/wINDOWS για ελληνικά (1253) lang/menu_greek_greece.cp437.vim -- Κωδικοσελίδα Unix για ελληνικά (nl_cp437) lang/menu_gr_gr.utf-8.vim -- UTF-8 για Ελληνικά tutor/tutor.gr -- ΦΡΟΝΤΙΣΤΗΣ Vim στα Ελληνικά README.TXT -- αυτό το αρχείο Αυτά τα συμπιεσμένα αρχεία μπορούν να μεταφορτωθούν από: http://lynxx.org/misc/download/vim-6.1-menu_el.zip http://lynxx.org/misc/download/vim-6.1-menu_el.tgz Για να χρησιμοποιήσετ το Vim σαν επεξεργαστή κειμένου στα ελληνικά (ή οποιαδήποτε άλλη γλώσσα, πρώτα ενεργοποιήστε την επιλογή για το πληκτρολόγιο (Πίνακας Ελέγχου|Πληκτρολόγιο| Γλώσσες|Ελληνικά) και διαλέξτε μια διαδοχή πλήκτρων (π.χ. ) για να αλλάζετε μεταξύ της προεπιλεγμένης γλώσσας και των ελληνικών. Στο Vim τα ελληνικα προβάλλονται σωστά. Τέλος, αποσυμπιέετε το vim-6.1-menu_el στον κατάλογο vim61. Αυτό εξασφαλίζει ότι ταπαραπάνω αρχεία τοποθετούνται στη σωστή διαδρομή. Αν δεν ξέρετε να εξάγετε στο $VIMRUNTIME, ξεζιπάρετε σε οποιοδήποτε προσωρινό φάκελο. Κατόπιν σύρετε-κ-αφήσετε ή αντιγράψτε-κ-επικολλήστε τα παραπάνω αρχεια στη θέση τους μετά τη δημιουργία των καταλόγων που θα τα περιέχουν (/διαδρομη/προς/vim61/lang/el). Αυτή είναι η λεγόμενη χειροκίνητη εξαγωγή, γι΄αυτό παρακαλούμε να πλύνετε τα χέρια σας προηγουμένως. Για βοήθεια στη ρύθμιση των παραμέτων του Vim για υποστήριξη ελληνικών, από τη γραμμή εντολών του Vim, δώστε: :help language :help messages :help encoding από τη γραμμή εντολών του Vim. Τουλάχιστον πρέπει να τεθούν για μυνήματα: let $LANG='el' / let $LANG='gr' :lan mes el / :lan mes gr για μενού: :menut English Greek / let menut=Greek από τη γραμμή εντολών ή στο αρχείο _vimrc. Για περισσότερες πληροφορίες, δες VimTip # ("Vim goes INTL - Translating Vim Editor Messages, Menus, Encodings"). Το παρόν έγγραφο δημοσιεύτηκε σαν VimTip # και μπορεί να ξεφυλιστεί σε απευθείας σύνδεση στην ιστοσελίδα: http://www.vim.org/tips/tip.php?tip_id= Kales epejergasies keimenou! Vaggelis Efstratiou vangelise@lynxx.org VimTip 545: Vim goes Greek - Greek language support for Vim 6.1 http://vim.sourceforge.net/tip_view.php?tip_id= Vim goes Greek - Complete set of Greek language support for Vim 6.1 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ENGLISH TEXT ------------ This is the full set of messages, menus and encodings to be used to support Greek language. This set contains: vim.pot -- dummy portable object template for vim-6.1 (can be used with any language) vim.po -- the above vim.pot file with strings translated in Greek lang/el/LC_MESSAGES/vim.mo -- the Greek vim.po file formatted in machine object mode (vim.mo) lang/menu_gr_gr.greek.vim -- Greek used as the default encoding lang/menu_gr_gr.latin1.vimq -- Greek for Latin lang/menu_gr_gr.iso_8859-1.vim -- Latin-based ISO encoding sourceing from iso_8859-7 spec lang/menu_gr_gr.iso_8859-7.vim -- Greek-Latin-based ISO encoding lang/menu_greece_greek.737.vim -- MS-DOS/wINDOWS codepage for Greek (737) lang/menu_greek_greece.1253.vim -- MS-DOS/wINDOWS codepage for Greek (1253) lang/menu_greek_greece.cp437.vim -- Unix CodePage for Greek (nl_cp437) lang/menu_gr_gr.utf-8.vim -- UTF-8 for Greek tutor/tutor.gr -- Vim TUTOR in Greek README.TXT -- this file These compressed archives can be downloaded from: http://lynxx.org/misc/download/vim-6.1-menu_el.zip http://lynxx.org/misc/download/vim-6.1-menu_el.tgz To use Vim to edit in Greek (or any) language, we first enable the language option for the keyboard (Control Panel|Keyboard|Languages|Greek) and enable a key sequence (e.g. Ctrl-Shift) to toggle between the default language and Greek. In Vim the Greek language is displayed correcty. Finally, we unzip vim-6.1-menu_el to the vim61 directory. This ensures that the above files are place in the correct path. If you don't know how to extract to $VIMRUNTIME, unzip to any temporary folder. Then drag&drop or copy-and-paste each of the above files to its place after creating the container folders (/path/to/vim61/lang/el). This is what one may call manual extraction, so please wash your hands beforehand. For help on setting up Vim to support Greek -- from Vim do: :help language :help messages :help encoding For messages you'll have to set at least: let $LANG='el' / let $LANG='gr' :lan mes el / :lan mes gr For menus: :menut English Greek / let menut=Greek from the cmdline or in the _vimrc file. For more information see VimTip # "Vim goes INTL - Translating Vim Editor Messages, Menus, Encodings". Enjoy Vim a la Greek! GREEK TEXT ---------- Vim στα Ελληνικά - Πλήρες σετ υποστήριξης ελληνικών για το Vim 6.1 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Αυτό είναι το πλήρες σετ μυνημάτων, μενού και κωδικοποίησης για χρήση σε υποστήριξη της ελληνικής γλώσσας με το Vim 6.1. Περιεχόμενα: ++++++++++++ vim.pot -- κενό πρότυπο ΡΟ για το vim-6.1 (μπορεί να χρησιμοποιηθεί με οποιαδήποτε γλώσσα vim.po -- το παραπάνω αρχείο vim.pot με συμβολοσειρές μεταφρ. στα ελληνικα lang/el/LC_MESSAGES/vim.mo -- το ελληνικό αρχείο vim.po μορφοποιημένο σε κατάσταση ΜΟ (vim.mo) lang/menu_gr_gr.greek.vim -- Greek χρησιμοποιείται σαν κωδικοποίηση προεπιλογής lang/menu_gr_gr.latin1.vimq -- Ελληνικά για Latin lang/menu_gr_gr.iso_8859-1.vim -- κωδικοποίηση ISO με βάση τη Λατινική, εκπηγάζει από τη προδιαγραφή iso_8859-7 lang/menu_gr_gr.iso_8859-7.vim -- κωδικοποίηση ISO με βάση τη Λατινική-Ελληνική lang/menu_greece_greek.737.vim -- κωδικοσελίδα MS-DOS/wINDOWS για ελληνικά (737) lang/menu_greek_greece.1253.vim -- κωδικοσελίδα MS-DOS/wINDOWS για ελληνικά (1253) lang/menu_greek_greece.cp437.vim -- Κωδικοσελίδα Unix για ελληνικά (nl_cp437) lang/menu_gr_gr.utf-8.vim -- UTF-8 για Ελληνικά tutor/tutor.gr -- ΦΡΟΝΤΙΣΤΗΣ Vim στα Ελληνικά README.TXT -- αυτό το αρχείο Αυτά τα συμπιεσμένα αρχεία μπορούν να μεταφορτωθούν από: http://lynxx.org/misc/download/vim-6.1-menu_el.zip http://lynxx.org/misc/download/vim-6.1-menu_el.tgz Για να χρησιμοποιήσετ το Vim σαν επεξεργαστή κειμένου στα ελληνικά (ή οποιαδήποτε άλλη γλώσσα, πρώτα ενεργοποιήστε την επιλογή για το πληκτρολόγιο (Πίνακας Ελέγχου|Πληκτρολόγιο| Γλώσσες|Ελληνικά) και διαλέξτε μια διαδοχή πλήκτρων (π.χ. ) για να αλλάζετε μεταξύ της προεπιλεγμένης γλώσσας και των ελληνικών. Στο Vim τα ελληνικα προβάλλονται σωστά. Τέλος, αποσυμπιέετε το vim-6.1-menu_el στον κατάλογο vim61. Αυτό εξασφαλίζει ότι ταπαραπάνω αρχεία τοποθετούνται στη σωστή διαδρομή. Αν δεν ξέρετε να εξάγετε στο $VIMRUNTIME, ξεζιπάρετε σε οποιοδήποτε προσωρινό φάκελο. Κατόπιν σύρετε-κ-αφήσετε ή αντιγράψτε-κ-επικολλήστε τα παραπάνω αρχεια στη θέση τους μετά τη δημιουργία των καταλόγων που θα τα περιέχουν (/διαδρομη/προς/vim61/lang/el). Αυτή είναι η λεγόμενη χειροκίνητη εξαγωγή, γι΄αυτό παρακαλούμε να πλύνετε τα χέρια σας προηγουμένως. Για βοήθεια στη ρύθμιση των παραμέτων του Vim για υποστήριξη ελληνικών, από τη γραμμή εντολών του Vim, δώστε: :help language :help messages :help encoding από τη γραμμή εντολών του Vim. Τουλάχιστον πρέπει να τεθούν για μυνήματα: let $LANG='el' / let $LANG='gr' :lan mes el / :lan mes gr για μενού: :menut English Greek / let menut=Greek από τη γραμμή εντολών ή στο αρχείο _vimrc. Για περισσότερες πληροφορίες, δες VimTip # ("Vim goes INTL - Translating Vim Editor Messages, Menus, Encodings"). Kales epejergasies keimenou! Vaggelis Efstratiou vangelise@lynxx.org VimTip 546: Vim goes INTL - Translating Messages, Menus, Encodings http://vim.sourceforge.net/tip_view.php?tip_id= Vim goes INTL - Translating Vim Editor Messages, Menus, Encodings +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Message Translation =================== The program used for internationalizing sources is the GNU `gettext' utility. It is discussed in detail by its creators so we won't go into it here. Instead, we'll follow the GNU `gettext' diagram to the letter so that we can visualize the process of creating our vim.po and vim.mo files using the program. Numbers in parentheses represent the steps we'll actually carry out (1 through 5): ~~~~~~~~~~~~~~~~ QUOTE ~~~~~~~~~~~~~~~~ (#1) [1.1] Original C Sources ---> PO mode ---> Marked C Sources ---. | .---------<--- GNU gettext Library | .--- make <---+ | | `---------<--------------------+-----------' (#2) | | | .-----<--- PACKAGE.pot <--- xgettext <---' .---<--- PO Compendium | | | ^ | | `---. | [2.1] | `---. +---> PO mode ---. | +----> tupdate -------> LANG.pox --->--------' | | .---' | | | | | `-------------<---------------. | (#3) | +--- LANG.po <--- New LANG.pox <----' | .--- LANG.gmo <--- msgfmt <---' | | (#4) (#5) | `---> install ---> /.../LANG/PACKAGE.mo ---. | +---> "Hello world!" `-------> install ---> /.../bin/PROGRAM -------' ~~~~~~~~~~~~~~ END QUOTE ~~~~~~~~~~~~~~ (drwng got distorted in textarea) STEP #1 ------- Get the most recent of the vim sources (vim-6.1-src1.tar.gz, vim-6.1-src2.tar.gz) from http://www.vim.org/download.php # create a temporary folder - let's call it "vim_tmp" - # anywhere on your disk: mkdir /path/to/vim_tmp # copy the vim source tarball(s) in the temporary directory: cp /original/location/vim???.tar.gz /path/to/vim_tmp # change to that directory: cd /path/to/vim_tmp # and decompress them (currently there are only two source # archives): tar xvfz vim-6.1-src1.tar.gz ; tar xvfz vim-6.1-src2.tar.gz NOTE: Several subdirectories are created, but only the `src' directory contains really translatable strings. [1.1] ------- We bypass this step since all canditate strings for translation in C sources are already marked with `N_()' or `_()' in vim source files. For a full discussion of how to mark strings as translatable in C source files, please refer to the GNU `gettext' utilities manpage. We'll return later to this step as the keywords in vim source files (`N_' and `_') are needed as an argument to the `xgettext' command. IMPORTANT: Before proceeding to make the PO file, we'll have to tag the sources, i.e. create the `tags' file: # since the `src' directory is the only one containing # translatable strings, and because only *.c files plus # two more fileS (globals.h, if_perl.xs) have them, # we switch to the `src' directory and issue: etags *.[ch] *.xs # to make sure all files get tagged # we could just as well have issued: etags src/*/*.* STEP #2 ------- The command-line options we'll use are fully described in the gettext manpage. NOTE: (i) We'll add the `join' option in the second instance of the command line so that the strings for the second keyword (`_') be extracted and appended to the same vim.po file; otherwise a second file vim.po would have to be created. (ii) We use INPUTFILE=*.[ch] because we know where the strings are to be exctracted from; else we must use INPUTFILE=* to exctract from all files. # We are ready to issue the `xgettext' command - once for each # keyword, and only for the files we know they contain # # translatable strings (i.e. *.c, globals.h and if_perl.xs): xgettext -a -d vim -k N_ -s *.c *.h *.xs xgettext -a -j -d vim -k _ -s *.c *.h *.xs # It can also be invoked in full: xgettext --extract-all --default-domain=vim \ --keyword=N_ --sort-output *.c *.h *.xs xgettext --extract-all --join-existing --default-domain=vim \ --keyword=_ --sort-output *.c *.h *.xs CAUTION: Don't be surprised when opening a vim.po file in a text editor. It looks something like this: ... #: ex_cmds.c:4421 msgid "E149: Sorry, no help for %s" msgstr "" #: globals.h:1053 msgid "E14: Invalid address" msgstr "" ... Now before proceeding to get the binary text we're after (vim.mo), we'll have to translate _all_and_each_messages_ listed in the vim.po file. The translator must insert the translated sting as the value of the `msgstr' variable (between quotation marks). To stay with the previous quotation, the Italian translation of the excerpt above is: ... #: ex_cmds.c:4421 msgid "E149: Sorry, no help for %s" msgstr "E149: Spiacente, nessun aiuto per %s" #: globals.h:1053 msgid "E14: Invalid address" msgstr "E14: Indirizzo invalido" ... [2.1] ------- We currently have no use for the `tupdate' command since there's no vim.po file yet; however, this program comes handy when we already have a *.po file and must update it based on a new release of sources. The command is simple enough. After unpacking the new tarballs to our "vim_tmp" directory (step 1), we issue: # change to tmp directory cd /path/to/vim_tmp # rename "vim.po" to "OLD_vim.po" assuming it's placed here: mv vim.po OLD_vim.po # update OLD_vim.po: tupdate NEW_vim.po OLD_vim.po # rename "NEW_vim.po" back to its usable filename: mv NEW_vim.po vim.po In case we don't want to go through the whole process of creating a vim.po file after a new vim-###-src#.tar.gz release, this program will take care of recreating our updated vim.po file (NEW_vim.po) from OLD_vim.po, including the old translations which will be taken over to the newly created file as long as they still match. However, it is recommended that, after a new vim_src### release, we actually start over. Just in case! STEP #3 ------- Next step is simplicity itself--assuming all messages have already been translated in vim.po. We'll only use one option out of several that the `msgfmt' program supports; they are fully described in the `msgfmt' manpage. For hints on internationalizing Vim see the previous VimTip (VimTip#). # change to tmp directory where our vim.po is placed: cd /path/to/vim_tmp # create vim.mo from vim.po: msgfmt -o vim.mo vim.po # or in full-text: msgfmt --output-file=vim.mo vim.po STEP #4 ------- Installing the vim.mo file requires that a directory in $VIMRUNTIME$ (i.e. currently /path/to/vim61) exists or is created express for the language you'll be supporting. Let's suppose the language we support is Greek (abbreviated as `gr' or `el'). We do: # create directory named `el' in $VIMRUNTIME$/path/to/lang # with a standard subdirectory `LC_MESSAGES': mkdir /path/to/vim61/lang/el mkdir /path/to/vim61/lang/el/LC_MESSAGES # copy our vim.mo file for Greek language supported: cp /path/to/vim_tmp/vim.mo /path/to/vim61/lang/el/LC_MESSAGES STEP #5 ------- Vim detects the system's local language settings when starting and--if supported--loads it automatically; else you'll have to change default message language from within Vim using: " lan[guage] {name} e.g.: lan el " now let's test if it's working by issuing an erroneous vim command--like: :HELP " and you'll get the message: Δεν είναι εντολή κειμενογράφου: HELP " that's all Greek to me: HELP Not an editor command: HELP Summary ------- - Download and unpack the vim sources in a temporary directory. - Use GNU `gettext' to get your template (untranslated) file. - Translate all entries in the template in your language. - Convert the translated PO file into a MO file using `msgfmt'. - Place MO file in /vim##/lang/your_language/LC_MESSAGES folder. - Set the 'language', 'messages', 'menu' options in Vim. - Test Vim and use it with your newly installed language. Menu Translation ================ BASICS ------ For Latin-based languages, menu translation is fairly painless. Open a `menu_xx_xx.latin1.vim' and use it as a template to create the menu after translating the relevant strings into the Latin-based language you intend to support. You only have to pay attention that unique letter identifiers in a given submenu don't repeat (e.g. &Open binds the letter `O' uniquely so that the keyboard responds to Alt-O, and cannot be repeated in the "File" menu. For Latin-based languages, at least one encoding must be defined as the default encoding for a given system; Latin1 is used on all OS'. If your canditate language is non-Latin but Latin-based, --as a rough rule--do menu translations in at least one of the following encodings: o utf-8 o iso-####-# o an MS-DOS/wINDOWS code page --consult old MS-DOS (v.5 or 6.2) online help for codepage and/or country setting details). HOW-TO ------ To create the menu file, we use one or several word processors that supports one or several of the encodings for the language we intend to support. If we can find the above encodings in the SaveAs option of our word processor(s), it's already sufficient -- depending on the number of OS' you wish to support. We can use, for example, an existing menu_xx_xx.latin1.vim template and translate the translatable strings pretty much like the gettext program prepares them by distinguishing between `msgid "ABC"' and `msgstr "XYZ"'. Instead we'll do it manually. Save only the translated strings of the supported language (i.e. `msgstr "XYZ"' in our example) into a separate file using the Save As option of a word processor (e.g. MS-Word). Now we have, for example, a file containing the translated stings, say in iso-####-x with filename `msgstr_iso-####-x'. Here's the Hungarian menu for the iso_8859-2 specification (lang/menu_hu_hu.iso_8859-2.vim): msgid "ABC" msgstr "XYZ" ~~~~~~~~~~~~~~~~~~~~~~ QUOTE ~~~~~~~~~~~~~~~~~~~~~~ ... scriptencoding iso-8859-2 " Help menu menutrans &Help &Sϊgσ menutrans &Overview Α&ttekintιs menutrans &How-to\ links &HOGYAN\ linkek menutrans &User\ Manual &Kιzikφnyv" ... ~~~~~~~~~~~~~~~~~~~~ END QUOTE ~~~~~~~~~~~~~~~~~~~~ We would create two plain text files, one with filename `msgid_iso-####-y', containing the left-most part of menu_hu_hu.iso_8859-2.vim: ... menutrans &Help menutrans &Overview menutrans &How-to\ links menutrans &User\ Manual ... and one with filename `msgstr_iso-####-z' we got with the SaveAs option of our word processor, containing the right-side part of menu_hu_hu.iso_8859-2.vim: ... &Sϊgσ Α&ttekintιs &HOGYAN\ linkek &Kιzikφnyv" ... CAUTION: Do not use a spreadsheet to do the job as these apps add/remove bytes to encodings and reset counters when saved and distort them. Only use your wordprocessor's SaveAs option and make sure it's a good one at that. Then we open both files in a simple text editor (Windows Notepad or vim) and paste line by line the left-side-file to the right-side-file so that the we get the joined file. Now them as a simple text. This is, say, our save menu_aa_bb.iso_8859-cc.vim CAUTION TOO: Do not use a legacy word processessing program for this last Save-As-Text-Only file operation. Do not use the word processor that helped with the encoding; else you might get the wrong bytes in encodings when the left-most part of the file is saved along with the rest. We can repeat the same (painstaking, yet menus are short) process with utf-8 encoding, MS-wINDOWS codepage, and any other encoding we need to support. Encodings ========= To create the language encodings files for Vim in any language, we first jot down the full specification of the encodings in the most common OS' for the language we intend to support. Next we create a corresponding menu_xx_yy.ABC_mn-zz.vim file for each of these supported encondings (making sure they exist!). We may use only one or several menu translations (we suggested three basic ones above, sect. 2); one of these -- the one with the translated strings -- can be used as the default encoding to reference other ones. We reference the encodings we cannot create with a word processor to the default encoding using any menu_xx_yy.ABC_mn-zz.vim as a template. Here's the Spanish menu for the MS-wINDOWS codepage 850 specification (lang/menu_spanish_spain.850.vim): ~~~~~~~~~~~~~~~~~~~~~~ QUOTE ~~~~~~~~~~~~~~~~~~~~~~ source :p:h/menu_es_es.iso_8859-1.vim ~~~~~~~~~~~~~~~~~~~~ END QUOTE ~~~~~~~~~~~~~~~~~~~~ As you can see, it contains only one line and sources this spec here from another one (i.e. es_es.iso_8859-1 in this case). Examples ======== As an example for fully supporting a specific language you may download the Greek tarball: http://lynxx.org/misc/download/vim-6.1-menu_el.zip http://lynxx.org/misc/download/vim-6.1-menu_el.tgz See also VimTip "Vim goes Greek - Complete set of Greek language support for Vim 6.1" (VimTip#). Disclaimer ========== This document is freely redistributable, but I take no liability for the correctness and safety of any procedures or advice given here. This document is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, explicit or implied for the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Happy PO-MO-ing! Vangelis Eustratius vangelise@lynxx.org VimTip 547: Smarter Table Editing http://vim.sourceforge.net/tip_view.php?tip_id= Smarter Table Editing I frequently need to edit tables where the fields are of varying lengths. Switching between fields is a pain as the fields can contain multiple words and using the w key is impractical. Moreover adding a new row to the table is most troublesome. The new fields need to be aligned with the old entries and tabs don't work very well. Below is an example of such a table that I pulled from the vim user's guide: USAGE RESULT DESCRIPTION append( {lnum}, {string}) Number append {string} below line {lnum} argc() Number number of files in the argument list argidx() Number current index in the argument list argv( {nr}) String {nr} entry of the argument list * The table above might not be aligned vertically because of the font vim-online is using I wrote the NextField function (given below) to automatically check the fields on the line directly above and move the cursor to the beginning of the next field. The function pads the line if required. I am using 2 or more spaces as the field separator but the field separator is an argument to the function and can be changed easily. I have mapped (Shift-Tab) to invoke the function. In the case of the above table hitting anywhere on the lines after the line that starts with "append" will cause the cursor to move to the next field position or just before it depending on the context. The function will not work on the line starting with "append" as there is an empty line with no fields above it. It will work on the empty line below the table titles as there are fields on the line above it. Same is the case with the empty line below the last line of the table. The function takes the following arguments: fieldsep: A pattern that specifies the field separator between table columns minlensep: Minimum length of field separator. It is used to make the function move to the next field even when the cursor is positioned less than the length of a field separator from the next table column. Set this to 0 if you are not sure what this argument is for. padstr: The string to be used for padding when the current line needs to be padded in order to reach the next table column. offset: The offset at which you want the cursor to be positioned in the next table column. Set it to 0 if you want the cursor positioned at the start of the next table column. (The above table is another case where the function is helpful) To use the function, place the code below in vimrc and add the following lines after it: map :call NextField(' \{2,}',2,' ',0) map! :call NextField(' \{2,}',2,' ',0) Note: If the whitespace between the fields consists of anything other than spaces, the function will not work correctly without changing the field separator. Use expandtab option if you must use tabs. Many variations of the above idea are possible. One variation would be to have a plugin that when invoked on a specific line, extracts the field information on that line and maps the tab key to move to the next field then onwards. That way there won't be any dependence on the line directly above the cursor. If you have any suggestions of your own let me know. If enough people show interest in enhancing this feature I most likely will code an enhanced version. --------------------------------Cut Here---------------------------------------- " function: NextField " Args: fieldsep,minlensep,padstr,offset " " NextField checks the line above for field separators and moves the cursor on " the current line to the next field. The default field separator is two or more " spaces. NextField also needs the minimum length of the field separator, " which is two in this case. If NextField is called on the first line or on a " line that does not have any field separators above it the function echoes an " error message and does nothing. func! NextField(fieldsep,minlensep,padstr,offset) let curposn = col(".") let linenum = line(".") let prevline = getline(linenum-1) let curline = getline(linenum) let nextposn = matchend(prevline,a:fieldsep,curposn-a:minlensep)+1 let padding = "" if nextposn > strlen(prevline) || linenum == 1 || nextposn == 0 echo "last field or no fields on line above" return endif echo "" if nextposn > strlen(curline) if &modifiable == 0 return endif let i = strlen(curline) while i < nextposn - 1 let i = i + 1 let padding = padding . a:padstr endwhile call setline(linenum,substitute(curline,"$",padding,"")) endif call cursor(linenum,nextposn+a:offset) return endfunc --------------------------------Cut Here---------------------------------------- VimTip 548: Using H and L keys as context sensitive pagedown/pageup http://vim.sourceforge.net/tip_view.php?tip_id= The H and L keys move the cursor to the top or bottom of the window respectively. They can be a real time saver, instead of hitting j/k many times, a single H/L can move the cursor to the proper place. However, when you are already at the top of the window the H key does nothing and similarly at the bottom of the window the L key does nothing. I started using the H/L keys a few days ago and quickly discovered that after getting to the top using H, I often want to scroll up. Hitting H again does nothing, so I wrote a function Hcontext which makes the H key context sensitive. I then mapped Hcontext to the H key. Now hitting the H key anywhere other than at the top of the window leads to the usual behavior but hitting H at the first line of the window causes the window to scroll one page back and positions the cursor at the top of the window. Similar behavior is implemented by the Lcontext function but in the other direction. Hitting L on the last line of the window now acts like the pagedown key. Even if you have never used the H/L keys before you can now start using them as replacement pagedown/pageup keys. Just cut and paste the code at the end into your vimrc and put the following maps after that. noremap H :call Hcontext() noremap L :call Lcontext() The unmapped H and L keys take a numeric count as well. Unfortunately, I am not aware of a way to make that count available to the user functions I wrote. The typical vim behavior in case of user functions is to supply the count as a range to the user function. This works most of the time but sometimes the count gets rejected because of range checking. If you are aware of a workaround please let me know. You can contact me by writing to latif@techuser.net. If you have suggestions as to other keys that can be made context sensitive without affecting their original function, email me. I also maintain a webpage where you can ask help for your text processing problems. The webpage is at http://www.techuser.net ---------------------------------Cut Here---------------------------------------- func! Hcontext() if (winline() == 1 && line(".") != 1) exe "normal! \H" else exe "normal! H" endif echo '' endfunc func! Lcontext() if (winline() == winheight(0) && line(".") != line("$")) exe "normal! \L" else exe "normal! L" endif echo '' endfunc ---------------------------------Cut Here---------------------------------------- VimTip 550: FreeBSD Fix: Arrow keys/cursor movement prints A B C D letters on remote shell: xterm, vt100. http://vim.sourceforge.net/tip_view.php?tip_id= Hi, I wonder how many of you are pissed of with arrow keys behavior during INSERT mode in Vim. So was I. Leave all the key mappings default, do not change your TERM environment. Here's a simple tip, :set term=cons25 and save the settings for Vim usage. It was tested with Vim 5.8 and 6.1 editions on; FreeBSD 4.X-STABLE; xterm(-color),VT100 remote terminals; (t)csh shells. Greets. Peace. Legalize it. VimTip 551: automatic indenting XML file in VIM with the help of XSLT http://vim.sourceforge.net/tip_view.php?tip_id= Do you want to indent an XML file? Try the following XSLT: ---------------------------------------- name it indent.xsl ---------------------------------------- In VIM, whenever a file with the ".xml" extension is loaded into the buffer, you can try the following in your ~/.vimrc to trigger the XSLT for filtering on the buffer contents: ---------------------------------------- if version >= 540 augroup filetype autocmd FileType xml '[,']!xsltproc indent.xsl % augroup END endif " other autocmds if version>540 autocmd! endif ---------------------------------------- Voila! Next time when you load an XML file in VIM, it will be indented automatically. Cheers, VimTip 552: replace buffer list when switching http://vim.sourceforge.net/tip_view.php?tip_id= I use vim's session file feature a lot to switch between projects. Preserving all that context is nice. Usually my process goes like this: 1. Save the current session: :mks! ~/v/project1.vim 2. Quit vim :xa 3. Restart with different session file: vim -S ~/v/project2.vim I was exiting and re-opening vim because if I just loaded the second project file, a list of /both/ projects buffers would appear in my buffer list. This was not what I wanted-- I wanted to replace the first buffer list completely wtih the second. There is a simple way to do this. At the top of a session file, add this: 1,999bdelete That will delete the first 999 existing buffers, effectively allowing any new buffer definitions in the rest of the session file to replace what is currently there. Now you can switch directly to a new session without exiting. Just use: :so ~/v/project2.vim VimTip 553: Prev and Next http://vim.sourceforge.net/tip_view.php?tip_id= One of the most useful key combinatins that remain unknown to the masses are and . They work like the "back" and "next" arrows in your HTTP user agent, meaning you can jump back and back again between files/locations within the same file very very easily and comfortable. :jumplist for a list of possible locations. Try it. Use it. Have a nice day. VimTip 554: Smarter Table Editing II http://vim.sourceforge.net/tip_view.php?tip_id= In vimtip #547 I described some functions that enable easier navigation and editing of tables. I have considerably enhanced the functionality and placed all the relevant code in a script file vimscript #769. The idea of the script is to automatically extract fields from a table row and use that information to create maps that aid in editing and navigation of the table. The user first marks a table row as table heading. The line does not literally have to be the table heading, but it should be representative of the typical row of the table in question. After this step the script maps tab and shift-tab keys to move between fields. These mappings work in both insert and normal modes. The tab mapping is especially useful in insert mode as it inserts the correct amount of padding to reach the start of the next field. The script also has an alignment feature that aligns the fields of the row with that of the heading. Editing a pre-existing table frequently leads to misaligned rows and this feature alleviates the need to manually add/remove padding. To better illustrate the functionality of the script, I have created the table below: ==================================================================== This table illustrates the use of table.vim script ==================================================================== th marks a line as table heading and activates maps for and keys th must be invoked on a well formed line with the right number of columns This means that the above line does not qualify Also notice that the field separator is atleast two spaces -------------------------------------------------------------------- when the maps are active, pressing here <-- moves here here <-- moves here <== moves back to "<==" <** here moves to "<**" above -------------------------------------------------------------------- The maps for and work in insert and normal modes, and can be deactivated by pressing tt pressing tt again, re-enables the maps -------------------------------------------------------------------- The script has some very basic support for field alignment It is very easy to get out of alignment when editing ta on the line above will fix the line to: It is very easy to get out of alignment when editing -------------------------------------------------------------------- ta can be very handy if the user wants to expand or contract fields, just change the width of the fields on the heading line and press th to mark the new heading and then numta on the top line of the table. num is the number of lines in the table -------------------------------------------------------------------- The alignment command fails when a row has more fields than the heading or when the contents of a field don't fit inside the field, as specified by the heading row case1 is this row case2 is this row ... ... this is another example of case2, there is no space for field separator on the first field on above line ==================================================================== If you don't like the default mappings change them to whatever you like. The mappings are defined on top of the table.vim script file. To install the script, place table.vim in the vim macros directory and source it in your vimrc using: source $VIMRUNTIME/macros/table.vim If you simply want to check the functionality of the script, place the script file in your current directory, open vim in the same directory and use :so table.vim If you have questions/comments or bug-reports to submit, send them to latif@techuser.net or visit my website http://www.techuser.net The script can also be downloaded from http://www.techuser.net/files VimTip 555: Vim as bookmark manager http://vim.sourceforge.net/tip_view.php?tip_id= Vim as bookmarks manager Sometimes you are collecting bookmarks from various sources, not only web, mail client, usenet even newspapers. Sometimes it is not possible, easy etc. to insert them in your favorite web browser bookmark manager. But nothing is lost - you can use your Editor :) Keep all URLs in one file called eg. url. One URL per line. Put this in your .vimrc: autocmd BufRead ~/url map :call BrowserURL() let g:web_browser = "konqueror" function! BrowserURL() if getline('.') !~ '^\s*\#' if g:web_browser == "konqueror" exe ":!dcop `dcopfind -a 'konqueror*'` konqueror-mainwindow\\#1 newTab ".getline('.') elseif g:web_browser == "mozilla" exe ":!mozilla -remote \"openurl(".getline('.').", new-tab)\"" endif endif endfunction Note: you can select in Visual mode few lines and open in one keypress few tabs. Comment lines with # at the beginning. This lines won't be precessed with function. I am sure such operation are possible also with other webbrowsers with tabs. Konqueror from KDE3.2-Alpha1 (but this dcop commands should work also with older versions) Mozilla 1.4 VimTip 556: Help on for Python with pydoc http://vim.sourceforge.net/tip_view.php?tip_id= Add the following 2 lines to your ~/.vim/ftplugin/python.vim, open an pythonscript place the cursor over an keyword and press F2 and be happy. map :exec "!xterm -e 'pydoc ".expand("")."'" imap :exec "!xterm -e 'pydoc ".expand("")."'"i VimTip 557: Opening several files in vim via ListFile http://vim.sourceforge.net/tip_view.php?tip_id= Suppose You want to open several files in vim, but the names of the files to open are stored in a file, each file name on separate line. This is the case with Total Commander, when You open a program and pass it %L as a parameter. It is possible to do it like that: gvim "+gl/^/exec 'badd '.getline('.')" +bdel +nohls +"cd %:h" LISTFILE where LISTFILE contains list of file names to open. For abovementioned Total Commander, I create new item in "start menu", and assign a shortcut, let's say CTRL+ALT+F4 to it. Set path\gvim.exe as a command. This is what i put in a "parameters" section: "+gl/^/exec 'badd '.getline('.')" +bdel +nohls +"cd %%:h" %L Then I can select several files, press CTRL+ALT+F4 and load all of them into my favourite text editor :) VimTip 558: Using TagList for ANT build files http://vim.sourceforge.net/tip_view.php?tip_id= ANT is a XML based make utility (mainly for Java, http://ant.apache.org). A build file can have several projects, and each project can have many targets. Here is a simple example: ant clean ant compile ant run Editing an ANT file can be tiresome looking for the appropriate target entry. Using the taglist plugin at least version 2.02 (http://vim.sourceforge.net/script.php?script_id=273) you can easily navigate an ANT file by creating these entries: In your _vimrc file: let g:tlist_ant_settings = 'ant;p:Project;t:Target' And either add to or create a ctags.cnf file: --langdef=ant --langmap=ant:.xml --regex-ant=/^[ \t]*<[ \t]*project.*name="([a-zA-Z0-9 ]+)".*>/\1/p,project/i --regex-ant=/^[ \t]*<[ \t]*target.*name="([a-zA-Z0-9 ]+)".*>/\1/t,target/i To determine where to create the ctags.cnf file see the ctags documentation (http://ctags.sourceforge.net/ctags.html, on WinXP this file goes into C:\Documents and Settings\local_user_name\ctags.cnf). When this is used in conjuction with the Vim compiler for ANT and a Vim Menu for ANT (http://www.vim.org/script.php?script_id=155), it can be very powerful. VimTip 559: Use Vim to Expire your Mail (So that Mutt can delete them later) http://vim.sourceforge.net/tip_view.php?tip_id= Mutt has a feature to list expired mails (~E). Sadly, there's no built in way to set the expiry date of a certain mail so I came up with a vim mapping to manually insert the "Expiry:" field of the mail header. It will ask for the date the email should expire (default is 'today') and then run the date command to produce the rfc-822 compliant date. Here's the mapping and related function: " Set expire date for the currently edited mail nmap ,e gg/^Date: :call GetExpiryDate():exe "normal! oExpires:\ndate --rfc-822 -d '". ExpiryDate."'"!!shkJ function GetExpiryDate() call inputsave() let g:ExpiryDate = input("Enter expiry date: ", "today") call inputrestore() endfunction VimTip 560: Generate calendar file http://vim.sourceforge.net/tip_view.php?tip_id= Since I work on different machines, I prefer all my calendar items to be available in one single ASCII file, which is easily handable with vim. The function Calendar() below generates the following output (extract) ............... ----- Week 1 ----- Mo 30 Tu 31 ==================== 2003 ======================================== ==================== Q 1 ======================================== -------------------- Jan 2003 ---------------------------------------- We 01 Th 02 Fr 03 Sa 04 Su 05 ----- Week 2 ----- Mo 06 Tu 07 ............... This may be stored in a file accessible by a single key stroke from vim. Here is the function: function! Calendar(year, month, day, weekday, week, daycount) " output daycount calendar days starting from given date " into new buffer new set buftype=nofile bufhidden=hide noswapfile let year = a:year let month = a:month let day = a:day let wd = a:weekday let week = a:week let index = 0 let date = '' let diy = 777 " day in year, wrong before next year while (index < a:daycount) " no of days to output let diy = diy + 1 if (wd > 7) let wd = 1 let week = week + 1 if (week >= 53) if (week >= 54) let week = 1 elseif (day >= 28 || day <= 3) let week = 1 endif endif endif if (wd == 1) " day name let dn = "Mo" elseif (wd == 2) let dn = "Tu" elseif (wd == 3) let dn = "We" elseif (wd == 4) let dn = "Th" elseif (wd == 5) let dn = "Fr" elseif (wd == 6) let dn = "Sa" elseif (wd == 7) let dn = "Su" else let dn = "** ERROR: Unknown day name ** " endif if ((day > 31) || (month == 2 && (day > 29 || day > 28 && year % 4)) \ || (month == 4 && day > 30) || (month == 6 && day > 30) \ || (month == 9 && day > 30) || (month == 11 && day > 30)) let day = 1 let month = month + 1 if (month > 12) let month = 1 let diy = 1 let year = year + 1 if (wd <= 3) let week = 1 endif endif if (month == 1) let yline = "====================" call append(line("$"), yline . " " . year . " " . yline . yline ) call append(line("$"), yline . " Q 1 " . yline . yline ) let monthn = "Jan" " month name elseif (month == 2) let monthn = "Feb" elseif (month == 3) let monthn = "Mar" elseif (month == 4) let monthn = "Apr" call append(line("$"), yline . " Q 2 " . yline . yline ) elseif (month == 5) let monthn = "May" elseif (month == 6) let monthn = "Jun" elseif (month == 7) let monthn = "Jul" call append(line("$"), yline . " Q 3 " . yline . yline ) elseif (month == 8) let monthn = "Aug" elseif (month == 9) let monthn = "Sep" elseif (month == 10) let monthn = "Oct" call append(line("$"), yline . " Q 4 " . yline . yline ) elseif (month == 11) let monthn = "Nov" elseif (month == 12) let monthn = "Dec" else let monthn = "** ERROR: Unknown month ** " endif let mline = "--------------------" call append(line("$"), mline . " " . monthn . " " . year . " " . mline . mline ) endif if (wd == 1) "call append(line("$"), "----- Week " . week . " (" . diy . "..) -----") call append(line("$"), "----- Week " . week . " -----") endif let date = dn . " " " beginn with name of day of week if (month < 10) let date = date . year . '-0' . month else let date = date . year . '-' . month endif " skip month, year let date = dn . " " " not interested in year, month if (day < 10) let date = date . '0' . day else let date = date . day endif " let date = date . " (" . diy . ")" call append(line("$"), date) let index = index + 1 let day = day + 1 let wd = wd + 1 endwhile endfunction map :call Calendar(2002, 12, 30, 1, 1, 1000) " Dec 30, 2003 is Monday (day 1 in week), week 1 in 2003 Put the above code in your vimrc and call the function, here it is shown with entries for 1000 days. Of course, if you do not use correct arguments matching and existing day, all output will be mess. VimTip 561: Context Sensitive h and l http://vim.sourceforge.net/tip_view.php?tip_id= While writing an email I noticed that the h key does nothing when pressed at the start of the line. It occurred to me that it would be very natural behavior for the h key to move to the end of the previous line under the above situation. Similarly, it would be fairly useful behavior for the l key to move to the start of the next line when the cursor is at the end of the line. The following illustration should clarify the behavior I am talking about: pressing l at the end of this line --> <-- should move to the beginning of this line pressing h at the start of the next line, should move to end of this line --> <-- I have coded two functions that implement the desired behavior. Putting the code given at the end of this tip in your vimrc will map the h and l keys to behave in a context sensitive manner. The only caveat is that under "virtualedit=all" h/l keys will revert to their usual vim behavior. This tip is similar in spirit to vimtim# 548, which concerned the H and L keys. Robert Kelly created vimscript# 763 for the code in vimtip# 548. I suggest that he adds the code below to that script. You can also retrieve a script with mappings for all the above mentioned keys on my download page http://www.techuser.net?content=5 ------------------------------------cut here----------------------------------- nmap h :call ContextLeft() nmap l :call ContextRight() func! ContextLeft() let cnt = v:count == 0 ? 1 : v:count if col('.') == 1 && line('.') != 1 && &ve != "all" exe "normal! " . cnt. "k$" else exe "normal! " . cnt. "h" endif endfunc func! ContextRight() let cnt = v:count == 0 ? 1 : v:count if col('.') >= strlen(getline('.')) && line('.') != line('$') && &ve != "all" exe "normal! " . cnt . "j^" else exe "normal! " . cnt . "l" endif endfunc ------------------------------------cut here----------------------------------- VimTip 562: modeline sets vimrc options on a per file basis http://vim.sourceforge.net/tip_view.php?tip_id= Sometimes I want vi to treat a file different than the .vimrc file. For example, I have a file that has fixed length text records, tabs in this file would mess it up. Setting the option expandtab will force tabs to be converted to spaces. Near the top of the file I put a line that says: # vim: set expandtab: When I open the file after that it will replace ^I (tab characters) with the correct number of spaces. VimTip 563: useful Occurences under cursor and with prompt http://vim.sourceforge.net/tip_view.php?tip_id= [I is very useful display all lines that contain the keyword under the cursor so following are two function for selection contain in two way under cursor or prompt find a big thanx Yegappan give me the hint for ijump function! s:UnderOccurences() exe "normal [I" let nr = input("Which one: ") if nr == "" return endif exe "normal " . nr . "[\t" endfunction! function! s:FindOccurences() let pattern = input("Prompt Find: ") if pattern == "" return endif exe "ilist " . pattern let nr = input("Which one: ") if nr == "" return endif exe "ijump " . nr . pattern endfunction VimTip 564: mouse wheel for scroll only - disable paste on middle button press. http://vim.sourceforge.net/tip_view.php?tip_id= I have had a problem when using the mousewheel for scrolling. I occasionaly press the wheel and it pastes text in the clipboard's "*" register at the place where the scroll wheel was pressed accidentally. This has been a constant irritation. The workaround is documented in VIM help - :help From change.txt (VIM help): "If you have a scrollwheel and often accidentally paste text, you can use these mappings to disable the pasting with the middle mouse button: > :map :imap " Also, to revert to the original setting for middle button click, simply unmap the previous setting. :unmap :iunmap Enjoy! VimTip 565: never see ^M again http://vim.sourceforge.net/tip_view.php?tip_id= There have been plenty of tips dealing with ridding of ^M characters appended to dos text files. However, all of the previous tips involve some typing. With the following command in your vimrc, you won't have to type anything. Moreover, you are not likely to see ^M characters again at all, they get removed before you get to view the file. The only exception being readonly files. autocmd BufRead * silent! %s/^M$// Note: Use to enter ^M and not caret followed by M VimTip 566: Autocomplete with TAB when typing words http://vim.sourceforge.net/tip_view.php?tip_id= "-- Use TAB to complete when typing words, else inserts TABs as usual. "-- Uses dictionary and source files to find matching words to complete. "-- See help completion for source, "-- Note: usual completion is on but more trouble to press all the time. "-- Never type the same word twice and maybe learn a new spellings! "-- Use the Linux dictionary when spelling is in doubt. "-- Window users can copy the file to their machine. "-- http://www.cs.albany.edu/~mosh - Mohsin Ahmed function! Mosh_Tab_Or_Complete() if col('.')>1 && strpart( getline('.'), col('.')-2, 3 ) =~ '^\w' return "\" else return "\" endfunction :inoremap =Mosh_Tab_Or_Complete() :set dictionary="/usr/dict/words" VimTip 567: Edit a temporary copy of the current file http://vim.sourceforge.net/tip_view.php?tip_id= " Edit a copy of the current file as $TMP/file-$DATE by pressing 'zs' :map zs :exe "sav $TMP/" . expand("%:t") . strftime("-%Y-%m-%d_%H%M%S") VimTip 568: Use temporary tags file when browsing new source. http://vim.sourceforge.net/tip_view.php?tip_id= " Create and Use $TMP/tags for local source dir (which may be unwriteable) " Unix users can change c:/tmp to ~/tmp/ (I use $TMP with sh). :map t :!(cd %:p:h;ctags -o c:/tmp/tags -R .)&:set tags^=c:/tmp/tags VimTip 569: Insert line numbers or filter thru perl. http://vim.sourceforge.net/tip_view.php?tip_id= " Create a menu item to call perl on the file " Edit the -e "script" before pressing return to filter thru perl " Script below works shell=sh, and add line numbers to the file. :amenu Mo1.Format.NumberLines:!perl :1,$!perl -ne \"printf(\\"\%3d:\%s\\",\$.,\$_);\" " " http://www.cs.albany.edu/~mosh Mohsin VimTip 570: Align badly formatted text region into table. http://vim.sourceforge.net/tip_view.php?tip_id= " What: Aligns badly formatted text into a table. " How: Select region and press , " in this case aligns the '=', you decide the centering string " before pressing return " You need the perl script "align" from " http://www.cs.albany.edu/~mosh/Perl/align " Inspired by Emacs align.el " Works on Windows and Unix. " Default key Mapping is: :vmap !perl ~/perl/align -c:= " Example input: " x = 1; " xyz = 245; " a=1; " Example Output: " x = 1; " xyz = 245; " a = 1; " " I know not what; but format in apparel, " In gait and countenance surely like a father. " -- BIONDELLO in Taming of Shrew by Shakespeare. VimTip 571: source ..../vimrc and use ..../tags in an ancestor directory. http://vim.sourceforge.net/tip_view.php?tip_id= " Source .../.vimrc and use .../tags in ancestor of source directory. " useful when you have source tree eight fathom deep, " an exercise in vim loops. let parent=1 let local_vimrc = ".vimrc" let local_tags = "tags" while parent <= 8 if filewritable(local_vimrc) echomsg "sourcing " . local_vimrc exe ":so " . local_vimrc endif let local_vimrc = "../". local_vimrc let local_tags = "../". local_tags exe ":set tags+=".local_tags let parent = parent+1 " ToDo: stop at the root on windows and ~ on unix. endwhile unlet parent local_vimrc " Vat be all you, one, two, tree, four, come for? " -- DOCTOR CAIUS, Windsor, Shakespeare. " http://www.cs.albany.edu/~mosh - Mohsin. VimTip 572: auto highlight word under cursor (when reading new code) http://vim.sourceforge.net/tip_view.php?tip_id= " Highlight all instances of word under cursor, when idle. " Useful when studying strange source code. " Turn on/off with z/ (or key of your choice) :map z/ :call Mosh_Auto_Highlight_Toggle() :function! Mosh_Auto_Highlight_Cword() :exe "let @/='\\<".expand("")."\\>'" :endfunction function! Mosh_Auto_Highlight_Toggle() :if exists("#CursorHold#*") : au! CursorHold * : let @/='' :else : set hlsearch : set updatetime=500 : au! CursorHold * nested call Mosh_Auto_Highlight_Cword() :endif endfunction " There is cold meat i' the cave; we'll browse on that, " -- GUIDERIUS, in Cymbeline by Shakespeare. " No occupation; all men idle, all; " -- GONZALO, Tempest by ShakesPear. " http://www.cs.albany.edu/~mosh - Mohsin. VimTip 573: Repeating a substitute from current cursor position http://vim.sourceforge.net/tip_view.php?tip_id= The :RS /pattern/subpattern/{flags} command+function as shown below allows one to repeat a RS-substitute after the current cursor position. Ex. cursor starts... one two three one two three one two three o^here :RS /two/TWO/ one TWO three one two three one two three one TWO^cursor ends up here move cursor: one TWO three one two three one two three one TWO three one two ^ cursor ends up: one TWO three one two three one TWO three one TWO three one two three one TWO^ (normally I'd have left the characters preceding the ^ as blanks but I'm trying to avoid problems with proportional fonts) Put the following into your <.vimrc> if you'd like to be able to do this: " --------------------------------------------------------------------- " RS: repeat substitution command com! -range -nargs=* RS call RepeatSubst() " RepatSubst: fun! RepeatSubst(subexpr) if a:subexpr != "" let g:repeatsubst= a:subexpr endif let curcol= col(".") let sep = strpart(g:repeatsubst,0,1) let pat = substitute(g:repeatsubst,'^.\(.\{-}\)'.sep.'.*$','\1','') s/\%#./\r&/ let curcol= curcol + matchend(getline("."),pat) exe "s".g:repeatsubst norm! k j! exe 'norm! '.curcol.'|' endfun " --------------------------------------------------------------------- VimTip 574: delete/move matching paragraphs/lines http://vim.sourceforge.net/tip_view.php?tip_id= " Put these in .vimrc, and these four items will become menu items. " You can of course just type these one liners, if you don't have menus. " Edit /word/ before pressing return, " Note: /word/ can be any perl expression to select paras. :amenu Mo1./.Delete-Matching-Paras:1,$!perl :1,$! perl -0000lne 'print if m/word/' :amenu Mo1./.Delete-Matching-Lines:g//d :g//d :amenu Mo1./.Delete-Non-Matching-Lines:v//d :v//d :amenu Mo1./.Move-Matching-Lines-Topg//\.m0 ma:g// .m0`a :amenu Mo1./.Move-Non-Matching-Lines-Lastv//\.m$ ma:v// .m$`a " - Mohsin Ahmed http://www.cs.albany.edu/~mosh " > To match thy goodness? My life will be too short, " > And every measure fail me. -- Cordelia, King Lear 4.7 VimTip 575: chop long lines. http://vim.sourceforge.net/tip_view.php?tip_id= " Some regexp substitutions for your menus from .vimrc :amenu Mo1.Format.ChopLongLines :%s!\(.\{-80,}\)\s!\1\r!gc :amenu Mo1.Format.JoinHypenatedLines :%s,\v\s+(\w+)-\n(\s*)(\S+)\s*, \1\3^M\2,gc :amenu Mo1.Format.JoinBackSlashLines :%s,\\\n,,gc " - Mohsin Ahmed http://www.cs.albany.edu/~mosh " > How now, how now, chop-logic! What is this? - Capulet, R & Juliet 3.5, WS. VimTip 576: one call to generate all unicode "characters" from within vim http://vim.sourceforge.net/tip_view.php?tip_id= This is a small function to generate all unicode "characters". It might be interesting to those who are familiar with CJK. I modified Frank's idea, http://groups.yahoo.com/group/vim/message/43907, with a neat format. (Thank you, Frank) Tony Mechelynck offered a great tip as how to work with utf-8 in http://vim.sourceforge.net/tip_view.php?tip_id=246 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" function! GenerateUnicode() let i = 0 while i <= 16*16*16*16 let n = i let j = 0 let h = "" while n let h = '0123456789ABCDEF'[n%16].h let n = n/16 endwhile let c = h.' ' while j<16 let u = i+j let c = c.nr2char(u).' ' let j = j+1 endwhile $put = c let i = i+16 if (i%(16*16) == 0) $put='----------------------------------------------------' $put=' 0 1 2 3 4 5 6 7 8 9 A B C D E F ' $put='----------------------------------------------------' endif endwhile endfunction """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" VimTip 577: Access vim@vim.org using Newsgroup Reader http://vim.sourceforge.net/tip_view.php?tip_id= For some reason one may not prefer mailling lists over usenet newsgroups (like me). IMHO Newsgroup reader is a lot more versatile and easy to use. So, find a newsgroup equivalent for vim@vim.org is improtant for newsgreoup users. Unfortunately, the comp.editors on USENET is not as active as vim@vim.org. The non-official news server news.gmane.org, have a mirror to vim@vim.org, named gmane.editors.vim, the maillist vim@vim.org and newsgroup gmane.editors.vim seemed to be syncronised together. To access the gmane news, just new an account with the NNTP server news.gmane.org, then find the newsgroup gmane.editors.vim, then you can enjoy vim@vim.org with your favorate news reader program, and without messing up mailling list messages with your private e-mail client (which is what the newsgroup designed for). I think gmane.editors.vim should be highly recommended for newsgoup users. VimTip 578: Specify Range with search patterns http://vim.sourceforge.net/tip_view.php?tip_id= I was recently using sed to pull out multi-line fields with sed when I wondered if I could specify a range using two search patterns in vim as I can in sed. Sure enough it works. I am using 6.1 and do not know if this feature is new but I suspect it has probably been around. Here is a contrived example. Suppose I had a vim script I was editing and I want to comment out the function declaration of a function named My_func. Instead of searching for it, marking the range and then adding a comment to the start of the line, the following command will work: :/^ *function *My_funct\>/,/^ *endfunction/s/^/" / The range is specified by two patterns. For the start of the range I look for the line which contains function My_funct. I added the \> end of word delimeter to the pattern in case I had other functions that had names beginning with My_func. The end of the range will be the first occurance of the second pattern, /^ *endfunction/ starting from where the first pattern was matched. The two patterns are separated with a comma as any range would be and the command to perform on the range follows. In this case a substitution, s/^/: / but it could be any command. This has become useful and even though I have used vim for several years this was a new discovery for me. VimTip 579: Cut&Paste without too much newlines, eg. into WORD http://vim.sourceforge.net/tip_view.php?tip_id= Sometimes I am forced to enter text into MS Word. Since this tool is not reliable and fast enough for me, I often prefer to create the text in VIM before and cut&paste it into Word. Unfortunately, Word creates newlines of its own and regards entered newlines as paragraphs. So I created a mapping that deletes all single newlines from a selected area but keeps multiple ones. Here it is: vmap "+y:let @+ = substitute(@+, "\n\n\n*", "±", "g") \\|:let @+ = substitute(@+, "\n", " ", "g") \\|:let @+ = substitute(@+, "±", "\\n", "g") \\|'< Just shortly what is does: Copy the visual area into the selection register +, subsitute two and more newlines but a strange symbol hopefully not contained in the area (±), substitute single newlines by a blank and resubstitute the strange symbol by one newline, then go back to the beginning of the selected area. If you select now text in VIM with V, it is copied with as described and can be pasted normally into another application. Siegfried VimTip 580: Switching back and forth between ViM and Visual Studio .NET http://vim.sourceforge.net/tip_view.php?tip_id= This tip is for when you work on a devstudio project and need the debugger heavily and/or can't stay in ViM all the time. But when it comes time to make changes you want to do them in ViM and don't want to relocate the file and line number. After you have made the change and perhaps opened another file or navigated your way to a new section of the code you want to switch back to devstudio at the spot you were in ViM. It may be because you want to set a breakpoint or any reason. The easy part: Launching ViM from DevStudio.NET is easy. From the DevStudio menu item Tools|External Tools... add a new entry where: The "Command Line" field is set to the path of the ViM executable The "Arguments" field contains: --servername gmain --remote-silent +$(CurLine) +"normal zz" $(ItemPath) The "Initial Directory" may optionally contain: $(ItemDir) This will start a ViM session or connect to an already existing one (--remote-silent) named gmain (--servername gmain). This will use only one instance of ViM for all devstudio editing. It will open the file specified by $(ItemPath) and set the cursor pos to $(CurLine). It will also execute the normal command zz to center the cursor. You can then create a keyboard shorcut to map to this tool (Tools|Options||Environment|Keyboard, select Tools.ExternalCommandX) and you will be able to switch to ViM quickly. The hard part: Opening a file in an existing DevStudio.NET instance is a pain and setting the cursor to a line number is even more so. DevStudio cannot be controlled by the command line. To open a file in an existing instance a DDE call must be initiated. Its an old and obsolete technology called Dynamic Data Exchange used for interprocess communication. When you click on a .cpp file in the Windows Explorer it calls devenv.exe with the /DDE switch (its undocumented) and sends it an Open DDE command. You can see it for yourself if you look at the file type mapping of .cpp in the Windows Explorer (if you haven't already changed them to open ViM :-)). The Explorer shell is DDE enabled but I found no way to send DDE from the command line (I didn't really look for it either ;-)). So I wrote a small C++ console app from the code I got from an Experts Exchange question. I formatted the code, renamed references from DevStudio to DevEnv and put it in a project. Setting the line number is a different problem. I wrote a Perl script using the Win32::GuiTest module. This module allows interacting with the Windows GUI and provides a very useful function called SendKeys. The script finds the Visual C++ window (if you are using a different language change the script) and sends it: a CTRL-G, the current line number as specified on the command line and ENTER. It is integrated in ViM by a function (in _vimrc) that gets the current file name and line number and silently executes the script: function! DevEnvDDE() let cmd = '!devenvdden.pl %:p ' . line(".") silent execute cmd endfunction All that is left is to map the function to a key. You can get the source files for the Perl script and DDE project at http://dunderxiii.tripod.com/vimtips/devenvdde.zip The original DDE code was taken at http://www.experts-exchange.com/Programming/Programming_Platforms/Win_Prog/Q_20489782.html Win32::GUITest is located at http://groups.yahoo.com/group/perlguitest/ VimTip 581: Using vim to view source and edit textarea in mozilla/firebird http://vim.sourceforge.net/tip_view.php?tip_id= This is the feature I have dreamed for months, please refer to http://mozex.mozdev.org VimTip 582: Quick way to write to your file. http://vim.sourceforge.net/tip_view.php?tip_id= Put this in your .vimrc map , :w^M When you need to save your file instead of typing :w and hitting enter, just hit the comma (,) Note that with vim you may need to type CTRL-Q first to get the verbose CTRL-M character in your file. For those who have earlier versions or non-PC compatible, CTRL-V before CTRL-M will get that character in there. Has been life-changing for me :-). I can't take the credit as I found this one years back when scanning info about building html pages. The author had a little script that checked the update of the file and sent a message to the browser to re-read the file when the file was written. He's the one who suggested mapping an unmapped button to do this. VimTip 583: Vim as XML Editor http://vim.sourceforge.net/tip_view.php?tip_id= If Vim is your main text editor, and if you do a lot of XML editing, then this mini howto might help you to make that even more fun: Vim as XML Editor http://www.pinkjuice.com/howto/vimxml/ VimTip 584: Awesome text formatter http://vim.sourceforge.net/tip_view.php?tip_id= The berkeley program 'par' can format/justify text/c-comments (examples below) better (and much more) than the default unix formatters. Download from: http://www.cs.berkeley.edu/~amc/Par/ Usage: Select region and press to format. In ~/_vimrc put (-j is for justify lines) :set formatprg=par\ -w60 : map {v}!par -jw60 :vmap !par -jw60 Examples from par.man Before: /* We the people of the United States, */ /* in order to form a more perfect union, */ /* establish justice, */ /* insure domestic tranquility, */ /* provide for the common defense, */ /* promote the general welfare, */ /* and secure the blessing of liberty */ /* to ourselves and our posterity, */ /* do ordain and establish the Constitution */ /* of the United States of America. */ After "par -59": /* We the people of the United States, in */ /* order to form a more perfect union, establish */ /* justice, insure domestic tranquility, provide */ /* for the common defense, promote the general */ /* welfare, and secure the blessing of liberty */ /* to ourselves and our posterity, do ordain */ /* and establish the Constitution of the United */ /* States of America. */ Or after "par -59f": /* We the people of the United States, */ /* in order to form a more perfect union, */ /* establish justice, insure domestic */ /* tranquility, provide for the common */ /* defense, promote the general welfare, */ /* and secure the blessing of liberty to */ /* ourselves and our posterity, do ordain */ /* and establish the Constitution of the */ /* United States of America. */ Or after "par -59l": /* We the people of the United States, in */ /* order to form a more perfect union, establish */ /* justice, insure domestic tranquility, */ /* provide for the common defense, promote */ /* the general welfare, and secure the */ /* blessing of liberty to ourselves and our */ /* posterity, do ordain and establish the */ /* Constitution of the United States of America. */ Or after "par -59lf": /* We the people of the United States, */ /* in order to form a more perfect union, */ /* establish justice, insure domestic */ /* tranquility, provide for the common */ /* defense, promote the general welfare, */ /* and secure the blessing of liberty */ /* to ourselves and our posterity, do */ /* ordain and establish the Constitution */ /* of the United States of America. */ Or after "par -59lft0": /* We the people of the United States, */ /* in order to form a more perfect union, */ /* establish justice, insure domestic */ /* tranquility, provide for the common */ /* defense, promote the general welfare, */ /* and secure the blessing of liberty */ /* to ourselves and our posterity, do */ /* ordain and establish the Constitution */ /* of the United States of America. */ Or after "par -59j": /* We the people of the United States, in */ /* order to form a more perfect union, establish */ /* justice, insure domestic tranquility, provide */ /* for the common defense, promote the general */ /* welfare, and secure the blessing of liberty */ /* to ourselves and our posterity, do ordain and */ /* establish the Constitution of the United */ /* States of America. */ Or after "par -59jl": /* We the people of the United States, */ /* in order to form a more perfect */ /* union, establish justice, insure domestic */ /* tranquility, provide for the common defense, */ /* promote the general welfare, and secure */ /* the blessing of liberty to ourselves and */ /* our posterity, do ordain and establish the */ /* Constitution of the United States of America. */ Before: Preamble We the people of the United States, to the US in order to form Constitution a more perfect union, establish justice, insure domestic tranquility, provide for the common defense, promote the general welfare, and secure the blessing of liberty to ourselves and our posterity, do ordain and establish the Constitution of the United States of America. After "par -52h3": Preamble We the people of the United to the US States, in order to form a Constitution more perfect union, establish justice, insure domestic tranquility, provide for the common defense, promote the general welfare, and secure the blessing of liberty to ourselves and our posterity, do ordain and establish the Constitution of the United States of America. Before: 1 We the people of the United States, 2 in order to form a more perfect union, 3 establish justice, 4 insure domestic tranquility, 5 provide for the common defense, 6 promote the general welfare, 7 and secure the blessing of liberty 8 to ourselves and our posterity, 9 do ordain and establish the Constitution 10 of the United States of America. After "par -59p12l": 1 We the people of the United States, in order to 2 form a more perfect union, establish justice, 3 insure domestic tranquility, provide for the 4 common defense, promote the general welfare, 5 and secure the blessing of liberty to ourselves 6 and our posterity, do ordain and establish the 7 Constitution of the United States of America. Before: > > We the people > > of the United States, > > in order to form a more perfect union, > > establish justice, > > ensure domestic tranquility, > > provide for the common defense, > > Promote the general welfare, > and secure the blessing of liberty > to ourselves and our posterity, > do ordain and establish > the Constitution of the United States of America. After "par -52": > > We the people of the United States, in > > order to form a more perfect union, > > establish justice, ensure domestic > > tranquility, provide for the common > > defense, > > Promote the general welfare, and secure > the blessing of liberty to ourselves and > our posterity, do ordain and establish > the Constitution of the United States of > America. Before: > We the people > of the United States, > in order to form a more perfect union, > establish justice, > ensure domestic tranquility, > provide for the common defense, > Promote the general welfare, > and secure the blessing of liberty > to ourselves and our posterity, > do ordain and establish > the Constitution of the United States of America. After "par -52d": > We the people of the United States, > in order to form a more perfect union, > establish justice, ensure domestic > tranquility, provide for the common > defense, > Promote the general welfare, and secure > the blessing of liberty to ourselves and > our posterity, do ordain and establish > the Constitution of the United States of > America. Before: # 1. We the people of the United States. # 2. In order to form a more perfect union. # 3. Establish justice, ensure domestic # tranquility. # 4. Provide for the common defense # 5. Promote the general welfare. # 6. And secure the blessing of liberty # to ourselves and our posterity. # 7. Do ordain and establish the Constitution. # 8. Of the United States of America. After "par -37p13dh": # 1. We the people of the # United States. # 2. In order to form a more # perfect union. # 3. Establish justice, # ensure domestic # tranquility. # 4. Provide for the common # defense # 5. Promote the general # welfare. # 6. And secure the blessing # of liberty to ourselves # and our posterity. # 7. Do ordain and establish # the Constitution. # 8. Of the United States of # America. Before: /*****************************************/ /* We the people of the United States, */ /* in order to form a more perfect union, */ /* establish justice, insure domestic */ /* tranquility, */ /* */ /* */ /* [ provide for the common defense, ] */ /* [ promote the general welfare, ] */ /* [ and secure the blessing of liberty ] */ /* [ to ourselves and our posterity, ] */ /* [ ] */ /* */ /* do ordain and establish the Constitution */ /* of the United States of America. */ /******************************************/ After "par -42r": /********************************/ /* We the people of the */ /* United States, in order to */ /* form a more perfect union, */ /* establish justice, insure */ /* domestic tranquility, */ /* */ /* */ /* [ provide for the common ] */ /* [ defense, promote the ] */ /* [ general welfare, and ] */ /* [ secure the blessing of ] */ /* [ liberty to ourselves ] */ /* [ and our posterity, ] */ /* [ ] */ /* */ /* do ordain and establish the */ /* Constitution of the United */ /* States of America. */ /********************************/ Or after "par -42re": /********************************/ /* We the people of the */ /* United States, in order to */ /* form a more perfect union, */ /* establish justice, insure */ /* domestic tranquility, */ /* */ /* [ provide for the common ] */ /* [ defense, promote the ] */ /* [ general welfare, and ] */ /* [ secure the blessing of ] */ /* [ liberty to ourselves ] */ /* [ and our posterity, ] */ /* */ /* do ordain and establish the */ /* Constitution of the United */ /* States of America. */ /********************************/ Before: Joe Public writes: > Jane Doe writes: > > > > > > I can't find the source for uncompress. > Oh no, not again!!! > > > Isn't there a FAQ for this? > > That wasn't very helpful, Joe. Jane, just make a link from uncompress to compress. After "par -40q": Joe Public writes: > Jane Doe writes: > > > > I can't find the source for > > uncompress. > > Oh no, not again!!! > > > Isn't there a FAQ for this? > That wasn't very helpful, Joe. Jane, just make a link from uncompress to compress. Or after "par 40qe": Joe Public writes: > Jane Doe writes: > > > I can't find the source for > > uncompress. > > Oh no, not again!!! > > Isn't there a FAQ for this? That wasn't very helpful, Joe. Jane, just make a link from uncompress to compress. Or after "par -40qi": Joe Public writes: > Jane Doe writes: > > > > > > I can't find the source for > > uncompress. > Oh no, not again!!! > > > Isn't there a FAQ for this? > > That wasn't very helpful, Joe. Jane, just make a link from uncompress to compress. Or after "par -40qie": Joe Public writes: > Jane Doe writes: > > I can't find the source for > > uncompress. > Oh no, not again!!! > > Isn't there a FAQ for this? That wasn't very helpful, Joe. Jane, just make a link from uncompress to compress. Before: I sure hope there's still room in Dr. Jones' section of archaeology. I've heard he's the bestest. [sic] After "par -50g": I sure hope there's still room in Dr. Jones' section of archaeology. I've heard he's the bestest. [sic] Or after "par -50gc": I sure hope there's still room in Dr. Jones' section of archaeology. I've heard he's the bestest. [sic] Before: John writes: : Mary writes: : + Anastasia writes: : + > Hi all! : + Hi Ana! : Hi Ana & Mary! Please unsubscribe me from alt.hello. After "par Q+:+ q": John writes: : Mary writes: : : + Anastasia writes: : + : + > Hi all! : + : + Hi Ana! : : Hi Ana & Mary! Please unsubscribe me from alt.hello. Before: amc> The b option was added primarily to deal with amc> this new style of quotation amc> which became popular after Par 1.41 was released. amc> amc> Par still pays attention to body characters. amc> Par should not mistake "Par" for part of the prefix. amc> Par should not mistake "." for a suffix. After "par B=._A_a 50bg": amc> The b option was added primarily to amc> deal with this new style of quotation amc> which became popular after Par 1.41 amc> was released. amc> amc> Par still pays attention to body amc> characters. Par should not mistake amc> "Par" for part of the prefix. Par amc> should not mistake "." for a suffix. VimTip 585: Keymap for normal mode http://vim.sourceforge.net/tip_view.php?tip_id= I generated a keymap for the vim 6.X normal mode on a german keyboard layout. Keymaps for other layouts may follow, if someone tells me about how they look. The keymap is here: http://michaelsen.kicks-ass.net/bjoern/keymap.pdf The author may be contacted here: bjoern@michaelsen.kicks-ass.net VimTip 586: Smarter Pasting http://vim.sourceforge.net/tip_view.php?tip_id= Frequently I yank a few words or part of a line and like to have them pasted on a separate line. Vim provides the put and put! commands for that purpose but they are not mapped by default to anything. Typing the commands is much slower than inserting a line and pasting to it so I have created the following maps: nnoremap ,p :pu " nnoremap ,P :pu! " VimTip 587: Preview current file in Mozilla through localhost http://vim.sourceforge.net/tip_view.php?tip_id= This is something I 'discovered' whilst trying to preview html or php files in mozilla using the apache server locally. Put the path as the first line of a file wrapped in the appropriate comments. eg: php: eg html: Place the following mappings in your .vimrc file " Typing will open the file in moz through the server. nmap :sil! !start mozilla "" imap :sil! !start mozilla ""i As I'm working through Wellings PHP and MySQL Web Development I can use my tokens plugin to speed creating the first line as follows: Add these as the string parts of the array: (for php) "phpf " (for html) "htmlf " then on the first line of the file if I type phpf et I'll only have to enter the chapter number and the filename without the extension. eg 04 orders This will insert: Place the cursor anywhere on the file path, and the file will load (through apache) in moz. Hope someone finds this useful, Mark VimTip 588: How to sort using visual blocks http://vim.sourceforge.net/tip_view.php?tip_id= 1. To sort lines based on a visually-selected column: Check out http://www.erols.com/astronaut/vim/index.html#VimFuncs ; look under "Visual Block Sorting". It uses Piet Delport's vim-based binary insertion sort and some vim-glue to provide visual-block sorts! To enable it, put into your <.vim/plugin> directory. To then perform sorting based on a visual-block selection (ctrl-v): :'<,'>Vissort 2. To sort a visually-selected block (and leave the text outside the block in place): Check out http://www.erols.com/astronaut/vim/index.html#VimFuncs ; look under "Visual Block Commands". The plugin provides a command which allows other commands to be applied only to the visually selected block. To then perform sorting of just a visual-block (ctrl-v): :'<,'>B !sort Or, using Piet Delport's binary insertion sort: :'<,'>B Bisort Examples: Original, visual-block select the central column one two three four five six seven eight nine ten eleven twelve :'<,'>Vissort seven eight nine ten eleven twelve four five six one two three :'<,'>B !sort one eight three four eleven six seven five nine ten two twelve :'<,'>B Bisort one eight three four eleven six seven five nine ten two twelve VimTip 589: Vim as refactoring tool (with examples in C#) http://vim.sourceforge.net/tip_view.php?tip_id= You can use vim as a refactoring tool. The advantages are: 1. You automatisate repetitive writing tasks 2. You learn refactoring You can expect much from a refactoring tool but if you have a look at the commercial refactoring tools there is much (not all!) vim can do too. Whatever your opinion is, my experience is that vim helps to refactor. I give you three examples, all in C#. Example 1: Anti-sphagetti code weapon or the "Extract Method" refactoring. Sphagetti code example: public string CreateMenu(string startMenu,string file) { string strOutput = ""; int i = 0; ArrayList startArray = new ArrayList(); string strVariable = ""; string strTemp = ""; XmlDocument XMLDoc = new XmlDocument(); try { XMLDoc.Load(file); } catch (Exception e) { strOutput = e.GetBaseException().ToString(); return strOutput; } XmlNodeList nodeList = XMLDoc.DocumentElement.ChildNodes; ... Imagine 50 lines of code here. Use the "extract method refactoring" to make a "composed method". I use a vim function (see below) to build the exracted method. I highlight the code part I want to extract and press \em (for e-xtract m-ethod). A dialog appears and asks me how to name the new method. I type in "GetXmlDocumentFrom" and do get this: // = GetXmlDocumentFrom(); private GetXmlDocumentFrom() { XmlDocument XMLDoc = new XmlDocument(); try { XMLDoc.Load(file); } catch (Exception e) { strOutput = e.GetBaseException().ToString(); return strOutput; } // return ; } Now I have time to think what parameters the method needs and what to return. I end up with the following function and remove it from the original function: private XmlDocument GetXmlDocumentFrom(string XmlFile) { XmlDocument XMLDoc = new XmlDocument(); string strOutput = ""; try { XMLDoc.Load(XmlFile); } catch (Exception e) { strOutput = e.GetBaseException().ToString(); ErrorMessage(strOutput); } return XMLDoc; } In the original code I put two lines. XmlDocument XMLDoc = new XmlDocument(); XMLDoc = GetXmlDocumentFrom(XmlFile); So I reduced the original code for 8 lines and made it clearer what the code does. I do this with the rest of the code again and again. Since the class gets bloated because of the many new methods I later will use the "Extract Class" refactoring to put this method in an own XmlDocument-class. This has the advantage that our new function is also available for other similar purposes. I will create the new class also with the help of vim, the actual extracting of the method into the new class is just a matter of copy & paste. Here is the vim-code: vmap \em :call ExtractMethod() function! ExtractMethod() range let name = inputdialog("Name of new method:") '< exe "normal O\private " . name ."()\{\" '> exe "normal oreturn ;\}\k" s/return/\/\/ return/ge normal j% normal kf( exe "normal yyPi// = \wdwA;\" normal == normal j0w endfunction Example 2: The "Self Encapsulate Field" refactoring. I have heard a programmer who just uses Visual Studio (nothing against Visual Studio, it's a great tool!) say: "I do not use properties. It's too much work." He just uses fields instead. With vim it is no problem to write a property, id est to use the "Self Encapsulate Field" refactoring. I write a name e.g. "Name" press CTRL-C CTRL-P CTRL-S (c-reate p-roperty with s-tring). Voila, the new property appears in just a second: private string m_Name; public string Name { get { return m_Name; } set { m_Name = value; } } Here are the vim mappings and the underlying function: "Create property imap :call CreateProperty("string")a imap :call CreateProperty("int")a function! CreateProperty(type) exe "normal bim_\b\"yywiprivate ".a:type." \A;\public ".a:type." \\"ypb2xea\{\oget\{\return \\"ypa;\}\set\{\\\\"yPa = value;\}\}\\" normal 12k2wi endfunction You can combine Visual Studio and vim. You can work in Visual Studio and load the file in vim for refactoring. I have made a menu entry in Visual Studio that loads the actual file I am writing in vim (cf. Tip #580 http://vim.sourceforge.net/tips/tip.php?tip_id=580). Example 3: The "Replace Conditional with Polymorphism" refactoring. Imagine a switch and you want to replace it with an abstract class and some concrete classes which inherit from this parent class. You may think "Why should I replace this switch? It's too much work. Writing all these classes ..." With vim it's just a question of a few seconds. To build the abstract class I type, say "Fruit". Then I press CTRL-C CTRL-A CTRL-C (c-reate a-bstract c-lass) and get public abstract class Fruit { public abstract void |(); } | means the Cursor position. Now I fill in the methods. public abstract class Fruit { public abstract void Taste(); public abstract void Color(); public abstract string GetSize(); } Now I go on the first letter of "Fruit" and type CTRL-C CTRL-C CTRL-C (c-reate c-oncrete c-lass). A dialog appears and asks me for the new name of the concrete class. I type in Apple and get public class Apple : Fruit { public override void Taste() { } public override void Color() { } public override string GetSize() { } } I continue doing so with all the child classes of the abstract class. In this way I get code templates that I can implement now. Here are my mappings and the underlying funtion. "Create abstract class imap bipublic abstract class A{public abstract void X();}:?X0fXs "Create concrete class map :silent! call ImplementAbstractClass() function! ImplementAbstractClass() range exe "normal \\"yyw" /{ normal "xy% normal %o exe "normal \o" let name = inputdialog("Name of new method:") exe "normal ipublic class " .name." : \\"yp\"xp" exe "normal }O}\==" normal %v% normal gv '<,'>s/abstract/override/g normal gv '<,'>s/;/\r{\r}\r/g normal == normal %kdd%k endfunction Happy vimming ... and happy refactoring! Klaus VimTip 590: Using vim to send mail on windows http://vim.sourceforge.net/tip_view.php?tip_id= The question of using Vim for writing email messages with Vim on windows was raised many times. Finally there *is* an elegant solution. go to http://sylpheed-claws.sourceforge.net/win32/ and download sylpheed-0.9.6claws.exe Install an application go to menu configuration -> Common preferences go to tab Other and fill something like c:\Progra~1\Vim\vim62b\gvim.exe -f "%s" (depending on where your Vim is installed) as the the editor option The -f option is very important so Vim does not fork. You might also go to Compose tab and select Automatically launch an external editor. Tada....... Beware Sylphed-Claws is a bleeding edge software. Have a nice time Stano VimTip 591: Have a nice and easy use of plugins http://vim.sourceforge.net/tip_view.php?tip_id= Are you tired of hundreds of mappings and functions that pollute your .vimrc ? Do you want to nicely organize your customization to quickly find what you search ? Perhaps is it time for you to consider the use of plugins (if it is not already done). Plugins are really easy to do and provide a simple way to organize functions and mappings. They are automaticaly loaded Here is an example of simple and very short plugin that provides a command MyCommand that saves the selected text in the file passed in parameter. I don't know if the function is useful but the example show the parameter passing, the autocompletion and the use of ranges in a function. Autocompletion is very practical to help to remember the commands you defined. It is often a problem to remember all the mappings you've done so it may be faster to type your command than to remember the mapping you've chosen. Using user-commands allows you to use mappings only when it is absolutely pertinent ------------------ file MyPlugin.vim ----------------------- " save 'cpo' let s:cpo_save = &cpo set cpo&vim " To Edit the Plugin nnoremap :e $VIMRUNTIME/plugins/MyPlugin.vim " To reload the plugin if you modify it nnoremap :so $VIMRUNTIME/plugins/MyPlugin.vim " It is very interesting to define commands to call your functions because you can then use " autocompletion and other features you cannot use for usual functions if !exists(':MyCommand') command -range=% -nargs=1 -complete=file MyCommand ,call s:MyCommandFunction() endif " the ! allows you to modify the function and reload the plugin. It will be your new version that " will be considered function! s:MyCommandFunction(...) range split execute "norm " . a:firstline . "GV" execute "norm " . a:lastline . 'G"ay' enew norm "ap exe "sav! " . a:1 q endfunction " restore 'cpo' let &cpo = s:cpo_save unlet s:cpo_save ---------------------End of file -------------------------- commented version of the function : function! s:MyCommandFunction(...) range " create a temporary window split " select and copy the lines in the range passed (a:firstline and a:lastline are the vim " variables for the first and the last lien of the range execute "norm " . a:firstline . "GV" execute "norm " . a:lastline . 'G"ay' " create a new file and paste enew norm "ap " saves the file with the name passed in parameter " exe executes the string passed as a command " a:1 is the first parameter (if you have more, a:2, a:3. a:0 gives you the number of parameter " passed exe "sav! " . a:1 " quit the temporary window q endfunction Of course you can separate your functions in different plugins (one for the mapping, one for the functions... You can use prefix to classify your functions and use the autocompletion more efficiently. Where to find help on these subjects General considerations on plugins :help plugins How to create a user-command and how to use the parameters (-range, -nargs, -complete...) :help user-commands How to program vim :help eval.txt all the buildin functions :help functions How to define a function :help user-functions VimTip 592: Smart and keymaps http://vim.sourceforge.net/tip_view.php?tip_id= I found interesting the way and keys act in some editors and I wondered why try not carry it out with Vim. Put the following lines in your ~/.vimrc and so will move the cursor between the first column and the first non-blank character. is similar but work at the end of the line. I think this should be very useful to the indented code and trailing characters. let g:home_key = '0' let g:end_key = '$' function ToggleHome() exe "normal! \".g:home_key let g:home_key = g:home_key == '0'? '^' : '0' endfunction function ToggleEnd() exe "normal! \".g:end_key let g:end_key = g:end_key == '$'? 'g_' : '$' endfunction inoremap :call ToggleHome()i nnoremap :call ToggleHome() inoremap :call ToggleEnd()a nnoremap :call ToggleEnd() VimTip 593: basic postfix abbreviations http://vim.sourceforge.net/tip_view.php?tip_id= I'm learning VIM in order to be more competitive in online programming competitions where speed of accurate typing is a factor. This may be a basic tip for some more advanced VIM users out there. I'm very used to editors that provide prefix abbreviation expansion; for example, in jEdit I'd type FA,array, in order to make a basic for loop that scanned the array. I wanted this in VIm as well, but found that it was harder to program. When I discovered that I could use a postfix abbreviation instead of a prefix one, I realized that I really didn't need any programming, but rather a long :ab statement like this: "this is for java, c++,c# can reshape as necessary :ab ff ^d$ifor(int i=0;i<pi.length;i++){}//end for loop over array pi[i]==k==k==ji this way, if I need a loop over the array lines[] then I would type linesff and vim would transform this into (with proper indentation) for(int i=0;i }//end for loop over array lines[i] similar abreviations with multiple arguments could be delimited by spaces and could be yanked into multiple registers and plunked down as necessary. You could even use a similar structure to writing abbreviations in jEdit. But, this opens up possibilities for many different things, because VIM allows you to map real commands into the abbreviations, instead of just vanilla text like in jEdit. VimTip 595: suppressing file changed warnings in a specific buffer http://vim.sourceforge.net/tip_view.php?tip_id= I generally liked the warnings that VIM gives when a file changes outside of the editor. However, there are times when I want to run a shell command that changes the buffer, and I don't want to hear about it. I've come up with the following convoluted method to do this, but if there's a better way, I'd love to know. function ChangeThisBuffer "set an environment variable to current buffer name let $aucfile = expand( "%" ) "add autocmd which only applies to this buffer which removes itself once it runs once autocmd FileChangedShell $aucfile autocmd! FileChangedShell $aucfile execute( 'silent !mycommand' ) endfunction One problem with this approach is that if the shell command fails, or doesn't really change the file, then you won't be notified the next time it changes. VimTip 596: Insert location of the currently edited file http://vim.sourceforge.net/tip_view.php?tip_id= With :imap @ =expand("%:p:h") VimTip 597: indet a code block - >i{ http://vim.sourceforge.net/tip_view.php?tip_id= Let's say we have: // some code { // start block //some other code // HERE IS THE CURSOR // other code } // end block The command ">i{" will indent the current block of lines, inside {}. The { and } are unmodified. The ">a{" will modify also the { } lines. " nmap ,cl :let @*=expand("%:p") VimTip 601: Tag with line:column http://vim.sourceforge.net/tip_view.php?tip_id= Tags allow us to jump to a particular line, but I needed to get to the exact column also, eg. when I have many tags on one long line. This is not possible with the tag format, however with Vim's regexp extensions, I am able to generate and use such tags, eg: > tail -1 ./tags main mohsin.c /^\%89l\%12c/ ;" Goto line 89, column 12. VimTip 602: How to remove one mark or all marks at once http://vim.sourceforge.net/tip_view.php?tip_id= To remove a mark you can use \mh in normal mode. Go to the mark and type \mh. If you are using marks in a script you can use the function below. Then you would write e.g. function! MyFunction() ... kl "set mark l ... "do something ... call RemoveMark("l") "Mark l is no longer used, remove it ... endfunction Here is the function: function! RemoveMark(mark) try exe "normal '" . a:mark "go to the mark normal \mh "remove it catch endtry endfunction If you want to remove all your marks in normal mode you can use the mapping map \rm :call RemoveMarks() It calls the function: function! RemoveMarks() try call RemoveMark("a") call RemoveMark("b") call RemoveMark("c") call RemoveMark("d") call RemoveMark("e") call RemoveMark("f") call RemoveMark("g") call RemoveMark("h") call RemoveMark("i") call RemoveMark("j") call RemoveMark("k") call RemoveMark("l") call RemoveMark("m") call RemoveMark("n") call RemoveMark("o") call RemoveMark("p") call RemoveMark("q") call RemoveMark("r") call RemoveMark("s") call RemoveMark("t") call RemoveMark("u") call RemoveMark("v") call RemoveMark("w") call RemoveMark("x") call RemoveMark("y") call RemoveMark("z") catch endtry endfunction Could you think of other possibilities? Please share it with us. Note: I am using the try-catch clause so the following works only for >= vim 6.2. If you want to use the functions for an older version remove the try-catch clauses. Happy vimming Klaus VimTip 603: Bookmarks as menu item http://vim.sourceforge.net/tip_view.php?tip_id= I like to save location of files I am editing in a bookmark file. Each bookmark shows up as a menu item. Add the attached lines to ~/_vimrc, and the Bookmark->Add menu items will appeare in gvim (I use it on Windows/NT). Note: I used cmd.exe,sh.exe,echo.exe to write the bookmark to a file, it is tricky to get the quotes right. It would be whole lot easier if vim had a function append-register-or-string-to-file. Maybe someone can find a way to do this without external shells? - Mohsin (mosh.cs.albany.edu) :set shell=sh shellslash shellcmdflag=-c shellxquote=\" shellpipe=\|\ tee :amenu Mo2.BookMarks.Add \ :let @b='\\042 Bookmark: '. \ " DATE=".strftime("%Y-%b-%d_%X"). \ " PWD=".escape(getcwd(),'\'). \ escape("\\n",'\'). \ ":amenu Mo2.BookMarks.". \ escape(escape(expand("%:t"),'.\'),'\'). \ ' :sp +'.line(".").' '. \ escape(expand("%:p"),' \') \ :exe ':!(echo '.@b.' >> $HOME/bookmark.vim)' \ :so $HOME/bookmark.vim :amenu Mo2.BookMarks.Edit :sp $HOME/bookmark.vim :amenu Mo2.BookMarks.Load :so $HOME/bookmark.vim if filereadable(expand("$HOME/bookmark.vim")) :amenu Mo2.BookMarks.-Sep- : :so $HOME/bookmark.vim endif VimTip 604: Doing in nmode http://vim.sourceforge.net/tip_view.php?tip_id= Although very simple, I think this is nifty: :nmap _i Now one can press enter in normal mode to insert an empty line. This spares me from alot of typing. VimTip 605: replace a word with the yanked text http://vim.sourceforge.net/tip_view.php?tip_id= I often need to replace a word with the yanked text when programming, so I add this map: map S diw"0P I rarely use S command, because it's equal to cc. VimTip 606: Seeing the man pages while being in VIM http://vim.sourceforge.net/tip_view.php?tip_id= You can see the man pages of anything you want from VIM. No need to exit VIM. Just put the cursor under the word.and press shift+k (Capital K) and you will be in the man page section. when you are through just press 'q' and you will be out of VIM. Press enter to come back to VIM. VimTip 607: Opening gvim atop a console window http://vim.sourceforge.net/tip_view.php?tip_id= I like to have gvim open atop the current xterm I'm using, rather like a vim console would. Here's some Korn shell script for setting up a function "gv" which queries X for the current window's geometry and adjusts the window for the current fontsize, borders, and menu region. Admittedly the adjustments for that vary with border sizes, etc, so you'll likely need to adjust x,y,w,h in the Adjustments section. Usage: gv files, options, etc # ======================================= # gv: gvim covers starting console window function gv { if [[ "${WINDOWID}" = "" ]]; then echo "***error*** unknown window id!" return fi xwi=$(xwininfo -id $WINDOWID) xyposn=${xwi##*Corners: } xyposn=${xyposn%% -*} wh=${xwi##*geometry } wh=${wh%+0+0} integer x y w h x=${xyposn%+[0-9]*} y=${xyposn#+[0-9]*} w=${wh%x*} hh=${wh#*x} h=${hh%[-+]*} # ---------------------------- # Adjustments: # x,y in pixels # w,h in characters # ---------------------------- # for RH8 Linux, GTK, courier-12-r h=h-4 x=4 y=y-18 # ---------------------------- # invoke gvim gvim -geometry "${w}x${h}+${x}+${y}" $* } # ======================================= VimTip 608: Evaluate current line (or pease of line) using Python http://vim.sourceforge.net/tip_view.php?tip_id= Pyhton language has more powerfull evaluation functions than vim editor. If you have need to evaluate some by python you can use command :py print 2*2 (see :help :if_pyth.txt) But I can tell you more pleasant example. Write in your .vimrc file followings: === begin paste ======== python << EOL import vim # do not say from vim import * beacuse this instraction # delete builtins function eval def EvaluateCurrentLine(*args): cur_str = vim.current.line action, symb = None, None for i in args: if i in ["r","p"]: action = i else: symb = i try: start = cur_str.rindex(symb)+len(symb) except: start = 0 result = eval(cur_str[start:],globals()) if action == "r": vim.current.line = cur_str[:start]+str(result) else: print result EOL command -narg=* PyEv python EvaluateCurrentLine() === end paste ============ Be carefull about identation in python part. This text provide command :PyEv This command evaluate expression in line under cursor and print result in echo area. With r argument :PyEv r evaluate expression and replased it by resalt of evaluation. And other arg in argument searching the arg backword from the end of current line and evaluate followed expression. For example: let we have string \setlength{\textwidth}{450-63 :PyEv r { \setlength{\textwidth}{387 VimTip 609: Execute python from within current file http://vim.sourceforge.net/tip_view.php?tip_id= Inspired by vimtip #608. To execute python from a range within the current text file and write the output to that file (replacing the python), add the snippet below to .vimrc (or other suitable *rc file). Requires a 'proper' python setup so that the imported modules can be found. I find it a handy intermediate step between using the python interpreter on command line and running a complete script. Can be used for easy buffer manipulation, filtering input, preprocessing text and templating-like tasks. def PyExecReplace(line1,line2): r = vim.current.buffer.range(int(line1),int(line2)) redirected = cStringIO.StringIO() sys.stdout = redirected exec('\n'.join(r[:]) + '\n') sys.stdout = sys.__stdout__ output = redirected.getvalue().split('\n') r[:] = output[:-1] # the -1 is to remove the final blank line redirected.close() EOL command -range Pyer python PyExecReplace(,) Some examples of use: Simple ------ print 2 + 2 :Pyer (if cursor is on the 'print' line, replaces line with 4) Filter ------ for line in vim.current.buffer: if line[0] != '\t': print line :%Pyer (filters out lines beginning with a tab in the current buffer) Inserting time -------------- import time print time.ctime() :%Pyer (replaces line with date/time) Getting web content without tags ------------------------------- import urllib2,htmllib,formatter h = htmllib.HTMLParser(formatter.AbstractFormatter(formatter.DumbWriter())) h.feed(urllib2.urlopen('http://www.somesite.com').read()) :%Pyer (inserts the web page text, but not the html tags, for a given site) I also use a slightly modified version that appends the output, leaving the python intact. VimTip 610: Saves you frequent typings of certain words. http://vim.sourceforge.net/tip_view.php?tip_id= You can use VIM's autocomplete feature in insert mode. Just edit the .vimrc file and add this lines iab is the letter which should be expanded to Example: iab #i #include ( typing "#i" and space will be expanded to "#include") iab #d #define ( typing "#d" and spacet will be expanded to "#define") iab s struct (typing "s" and space will be expanded to "struct") iab t typedef ( typing "t" and space will be expanded to "typedef") You can add your custon expansion words. PITFALLS: In some cases VIM expands a letter automatically you dont want. You have to take care of that. But this is a good utility. VimTip 611: Open big files and work fast http://vim.sourceforge.net/tip_view.php?tip_id= When opening big files, having no swap file and no undo levels speeds up Vim dramatically. Here are lines to set that up automatically beyond a given file size threshold (BufSizeThreshold): let g:SaveUndoLevels = &undolevels let g:BufSizeThreshold = 1000000 if has("autocmd") " Store preferred undo levels au VimEnter * let g:SaveUndoLevels = &undolevels " Don't use a swap file for big files au BufReadPre * if getfsize(expand()) >= g:BufSizeThreshold | setlocal noswapfile | endif " Upon entering a buffer, set or restore the number of undo levels au BufEnter * if getfsize(expand()) < g:BufSizeThreshold | let &undolevels=g:SaveUndoLevels | hi Cursor term=reverse ctermbg=black guibg=black | else | set undolevels=-1 | hi Cursor term=underline ctermbg=red guibg=red | endif endif Many thanks to Antoine and Chip, and to Ron who triggered the thread on vim@vim.org. William PS: I have not done a search for big file handling tips... PPS: we could also disable syntax highlighting and restore it for small files, but I just thought about it now. VimTip 612: save a nanosecond with marks http://vim.sourceforge.net/tip_view.php?tip_id= Instead of marking all the time with "ma", mark with "ml". When you need to return to the mark, `l is a little quicker to type than `a. If you save a fraction of a second many times, you'll have saved as much time as it took to read this tip! VimTip 613: open last edited file, AKA lvim for bash http://vim.sourceforge.net/tip_view.php?tip_id= The starting.txt help file (http://vim.org/htmldoc/starting.html) tells you how to open the last edited file in csh. In bash, do it like so: alias lvim='vim -c "normal '\''0"' VimTip 614: perldoc function and module keyboard mappings http://vim.sourceforge.net/tip_view.php?tip_id= " put the cursor over a perl function and try backslash-pf to see perldoc :nmap pf :!perldoc -f " put the cursor over a perl module name and try backslash-pd to see perldoc :nmap pd :e `perldoc -ml ` " see ':help mapleader' for more info... default is backslash. VimTip 615: Moving to the next word in insert mode http://vim.sourceforge.net/tip_view.php?tip_id= You can move to the next word in insert mode using You can move to the next word in command mode using w You can move to the previous word in insert mode using VimTip 616: Have Vim check automatically if the file has changed externally http://vim.sourceforge.net/tip_view.php?tip_id= You can place this in your vimrc file, and then run: :CheckForUpdates This will toggle the behaviour for the given buffer. " If you are using a console version of Vim, or dealing " with a file that changes externally (ie a web server log) " then Vim does not always check to see if the file has been changed. " The GUI version of Vim will check more often (for example on Focus change), " and prompt you if you want to reload the file. " " There can be cases where you can be working away, and Vim does not " realize the file has changed. " " This function will force Vim to check more often. " " The function will turn on the :checktime command so that the " file is checked based on the CursorHold event. " " Thanks to Jürgen Krämer, Antoine J. Mechelynck for the help. " " CheckForUpdates will toggle the behaviour on the current buffer. function! CheckForUpdates() " Save the current default register let saveB=@" " Check to see if the checkforupdates autocommand exists redir @" silent! exec 'au checkforupdates' redir END if @" =~ 'E216' augroup checkforupdates if has("win32") " will do this except for file paths that contain spaces -- and if " you are on Windows, backslashes should be converted to slashes, " too: exec "au Cursorhold " . escape( \ substitute(expand("%:p"), '\', '/', 'g') \ , ' ') . " :checktime" else exec "au Cursorhold " . expand("%:p") . " :checktime" endif augroup END else " Using a autogroup allows us to remove it easily with the following " command. If we do not use an autogroup, we cannot remove this " single :checktime command " augroup! checkforupdates au! checkforupdates augroup! checkforupdates endif let @"=saveB endfunction command! CheckForUpdates :call CheckForUpdates() VimTip 617: Fun with case twiddling http://vim.sourceforge.net/tip_view.php?tip_id= Someone came on #vim asking about "sentence case", meaning Capitalization Of Every Word. I came up with some bad solutions before learning this: :s/\(^\|\s\)\([a-z]\)/\1\U\2/g This inspired me to come up with a silly script for rotating between ALL CAPS, all lower, and Sentence Case. MiXed Case is set to UPPER. Then I mapped it (in visual mode) to ~, thus breaking the wonderful tilde :) Here's the script: fun! TwiddleCase(str) if a:str == toupper(a:str) let ans = tolower(a:str) elseif a:str == tolower(a:str) let ans = substitute(a:str,"\\(^\\|\\s\\)\\([a-z]\\)","\\1\\U\\2","g") else let ans = toupper(a:str) endif return ans endfun And the mapping: vmap ~ x:call setreg('"', TwiddleCase(getreg('"')))^MP VimTip 618: how to make and submit a patch http://vim.sourceforge.net/tip_view.php?tip_id= Vim is developed using an open-source model, and users are encouraged to contribute to its development. Users with programming experience should have a look at the to-do list from time to time (:help todo), and even beginners can help by asking and answering questions on the mailing lists, adding tips to this database, and suggesting improvements to the documentation. (IMHO, if you get a question answered on one of the lists, a good way to repay the Vim community is by posting the answer as a tip here.) Even rating tips and scripts on the vim web site helps others, by pointing them to the most useful ones. Another way to give back to the community is to support vim's charity: :help uganda Here is how to make a patch. Make a local copy of the file you are going to change, and edit it. Then, change to the directory (such as vim62/) containing the src/ source directory. If you are editing one of the help files and do not have the vim source files, change to your $VIMRUNTIME directory (usually /usr/local/share/vim/vimxx/ on *NIX systems). Use the diff program to make the patch like this: $ diff -c /src/eval.c path/to/my/eval.c > /tmp/eval.c.diff for a patch to the source or (assuming you do not have the sources) $ diff -c doc/help.txt path/to/my/help.txt > /tmp/help.txt.diff The directory and file name for the patches are just suggestions. If you change more than one file, you can concatenate the patches or read the man page for diff to create one big patch. If you are on a Windows system that does not have the diff program, you may be able to get one from http://gnuwin32.sourceforge.net/ . (I have not used Windows for a while now, so I have not tried this.) If the usage is substantially different from the above, perhaps someine will be kind enough to add a comment below explaining this. The -c option produces a "context diff." This is fairly easy for both humans and machines to read, and all official patches for vim are released in this form. Once you have your patch, you can submit it to the vim-dev mailing list. :help vim-dev or http://www.vim.org/maillist.php#vim-dev VimTip 619: HowTo make a keymap http://vim.sourceforge.net/tip_view.php?tip_id= The present tip explains how to make a keymap for yourself. It is based on what is said under :help mbyte-keymap :help keymap-file-format and you'll also find relevant information under :help 'keymap' :help 'iminsert' :help language-mapping :help *1* How to name the file and where to place it. Keymaps reside in the "keymap" subdirectory of the directories named in 'runtimepath'. Their names are of one of the forms .vim _.vim so if you need keymaps for Czech and Norwegian, and want to use them under UTF-8, you will probably create two keymaps, named, for instance, "czech_utf8.vim" and "norwegian_utf8.vim". If those names collide with names already present in $VIMRUNTIME/keymap/, then either use slightly different names before the underline, or put them in the "keymap" subdirectory of a directory named earlier than $VIMRUNTIME in 'runtimepath', so yours will be found first (but in the latter case you won't be able to use the default keymap of the same name). Create the needed directory if it doesn't exist yet. *2* What a keymap consists of. A keymap consists of three parts: a) a Vim script b) a line containing only the word "loadkeymap" (without quotes) c) the key mappings themselves. *3* First part of a keymap: the Vim script. This may contain any Ex-commands and Vim comments germane to the use of the keymap. In particular, the following Ex-commands are useful: a) If this keymap is only a slight modification of another, preexisting one: a "source" statement for the keymap on which this one is based. Then you will only have to code the changes. b) A short name, for instance in a keymap for Czech let b:keymap_name="cz" This will appear as near the right end of the standard status line for any window where the keymap in question is enabled (by having its long name set ot setlocal'ed in 'keymap' and 'iminsert' setlocal'ed to 1). c) A cursor color for when keymaps are in use. This one is more controversial (Bram comments it out in published keymaps) but I find it useful in my "private" ones. highlight lCursor ctermbg=red guibg=red Use any color that pleases you, and beware that highlight groups are global for the whole of Vim, so it is possible to use different keymaps in split windows of a single Vim instance, but not different language cursor colors, unless you set up an autocommand to change the lCursor highlight at the WinEnter event. (How to make that work is outside the scope of this HowTo.) *4* Second part: the "loadkeymap" command. This is just to tell Vim that whatever comes after, to the end of the file, is a series of language-mappings, in a special format which will be described hereafter. *5* Third part: The mappings themselves. Each key mapping line consists of three parts; the optional third one may contain spaces but not the first two: {lhs} {rhs} [comment] Vim interprets this line as if (in a standard Vim script) there had been lmap {lhs} {rhs} The {lhs} is what you press, as interpreted by your default (English) keyboard. It is usually a single character, but it may be more than one: in that case all of them but the last act as "dead keys". For instance, in a German keymap, you may want to use the colon as a prefix to tell that the following vowel gets an umlaut (so that :A maps to Ä, :a to ä etc.) Any key or key combination which does not appear as an {lhs} keeps its "English" meaning in the target language. (This will usually be the case for the space bar :-) and for any punctuation, or even letters, that you don't want to move about on the keyboard.) This means that if, for instance, you map the sz letter pair to the German eszet, you'll still be able to use the small-s letter with its usual meaning whenever it is not followed by z. Similarly, if you map the colon as above, a colon remains a colon if followed by anything other than a vowel, for instance a space or a digit. In all cases, you can force the initial key(s) of a mapping to keep their original meaning, either by waiting for the mapping to time out, or by moving the cursor about, for instance with . The {rhs} is what it translates to, in the target language. For UTF-8 the {rhs} may be of the form to (decimal), or to (hex), or to (octal) -- see ":help ". For other encoding targets, the notation may also be used, but of course only as far as the target permits: e.g. in 8-bit encodings, only till 255 / 0xFF / 0377. The [comment] is the easiest: it's for the human reader of the keymap, not for Vim. VimTip 620: getting to know the function prototypes http://vim.sourceforge.net/tip_view.php?tip_id= Use "[ i" for display of function prototypes at bottom or "[ ctl i" for jumping to the file containing the prototype. also can use " I" for listing of proto. VimTip 621: Vim as a syntax highlighting engine for web publishing http://vim.sourceforge.net/tip_view.php?tip_id= Geoff Richards has written a Perl module to turn Vim into a highlighting engine for the web. Text::VimColor (http://search.cpan.org/perldoc?Text::VimColor). See some basic usage at http://www.perlmonks.org/index.pl?node_id=314528 where I also show a caching module to improve Text::VimColor performance. Enjoy gmax VimTip 622: Deleting a buffer without changing your window layout http://vim.sourceforge.net/tip_view.php?tip_id= Here's a small command for your <.vimrc>: com! Kwbd let kwbd_bn= bufnr("%")|enew|exe "bdel ".kwbd_bn|unlet kwbd_bn To use it, type :Kwbd Kwbd stands for: Keep window (layout) and delete the associated buffer. VimTip 623: External Paste Buffer http://vim.sourceforge.net/tip_view.php?tip_id= We are forever using copy and paste to copy information from application to application. Inevitably however we need to edit/reformat the buffer contents . This tip allows you to quickly open a separate VIM containing just the paste contents. You may then edit these contents as required, writing or closing VIM automatically causes the changed contents to be rewritten to the paste buffer. The following is a CygWin script (could just as easily be a Win32 batch file) function vxp { # description : Edit paste contents gvim -c 'normal ggdG"*p' c:/aaa/xp } Such that I just type vxp and it opens a new Vim just containing the current paste buffer. To automatically cause the rewriting of the paste buffer add the following to your .vimrc autocmd bufWritePost c:/aaa/xp normal ggVG"*y (Thanks to Bob Chan et al from comp.editors) VimTip 624: Insert template files into buffer ( HTML editing for example) http://vim.sourceforge.net/tip_view.php?tip_id= While editing HTML I want to use template files to be expanded on my html pages. Say for example I have something like this on my html file:

html code here

more html code here...

I want the files "header.html" and "footer.html" to be inserted on my page, you can do this with the following global command: :g%First, find these lines: " Batch file for MSDOS (*.cmd is close enough) au BufNewFile,BufRead *.bat,*.cmd,*.sys setf dosbatch --->Then change them to this: " Batch file for MSDOS (*.cmd is close enough) au BufNewFile,BufRead *.bat,*.cmd,*.sys call FTCheck_bat() " Perl scripts converted to bat by pl2bat have a unique string that " identifies the file. It should be the first line. fun! FTCheck_bat() if exists("g:filetype_bat") exe "setf " . g:filetype_bat else let l = getline(nextnonblank(1)) if l =~ '--\*-Perl-\*--' setf perl else setf dosbatch endif endif endfun --->That's it! This is very specific to look for the string pl2bat adds to the file, but can be easily modified to your needs. VimTip 639: Comment highlight #ifdef DEBUG for code-read ease (C/C++) http://vim.sourceforge.net/tip_view.php?tip_id= Hi all, If your C/C++ code is scattered with statements like #ifdef DEBUG // Some code.. cout << "Debug output: blah" << endl; #endif and you would like to highlight these segments in a different colour (so that you can skip them visually), add the following code in your .vimrc (colouring follows that of comments) CODE STARTS syn region MySkip contained start="^\s*#\s*\(if\>\|ifdef\>\|ifndef\>\)" skip="\\$" end="^\s*#\s*endif\>" contains=MySkip let g:CommentDefines = "" hi link MyCommentOut2 MyCommentOut hi link MySkip MyCommentOut hi link MyCommentOut Comment map ,a :call AddCommentDefine() map ,x :call ClearCommentDefine() function! AddCommentDefine() let g:CommentDefines = "\\(" . expand("") . "\\)" syn clear MyCommentOut syn clear MyCommentOut2 exe 'syn region MyCommentOut start="^\s*#\s*ifdef\s\+' . g:CommentDefines . '\>" end=".\|$" contains=MyCommentOut2' exe 'syn region MyCommentOut2 contained start="' . g:CommentDefines . '" end="^\s*#\s*\(endif\>\|else\>\|elif\>\)" contains=MySkip' endfunction function! ClearCommentDefine() let g:ClearCommentDefine = "" syn clear MyCommentOut syn clear MyCommentOut2 endfunction CODE ENDS To see the effect, position the cursor on the word DEBUG in the C code snippet above and type ,a VimTip 640: See your vim templates in Windows Explorer's New context menu http://vim.sourceforge.net/tip_view.php?tip_id= Do you wish you had your own vim settings for a file appear automatically when you right click in Windows Explorer? If so then read on, following these steps sequentially: - Create a template file where the last few lines control vim. See below for a sample: -[sample template file begins below this line]- --------------------------------End of Text---------------------------------- The line below controls vim, which you can get free from: http://www.vim.org/ vim:tw=80:ai:ft=txt:norl: -[sample template file ends above this line]- - Call the above sample template file GVIM.vtd and save it in "C:\Windows\ShellNew\" directory. You may use another extension, but I played it safe and used one that wasn't being used on my system. Moreover, I did not change the default location of Windows installation, but you may need to do so if your system does not match mine. - Open Explorer and click on Tools->Folder Options... in the dialog box that appears, click on File Types and then scroll the file types until you reach VTD. Click on the file extension VTD and click on Change; now associate gvim.exe with this file extension. - Next, open the registry with regedit by clicking on Start->Run and typing regedit in the Run dialog box - In the registry, scroll HKEY_CLASSES_ROOT until you get to Vim.Application - then add a key; call it "shell" - next scroll into: [HKEY_CLASSES_ROOT\Vim.Application\shell] - and add a key; call it "open" - once more scroll into: [HKEY_CLASSES_ROOT\Vim.Application\shell\open] - and add yet another key; call it "command" - now change, by double clicking on, the "(Default)" value of "command" to point it to the location of gvim.exe on your hard drive. On my system, I entered the following in the text field "Value data" C:\PROGRA~1\Vim\vim62\gvim.exe "%1" - Finally open up Explorer and navigate to any directory on your hard drive. Now, right click on, the pane displaying the files, to see "Vim" as one of your options. When you choose Vim, you will create a file called "New Vim.vtd" in that directory. When you open "New Vim.vtd" you should see the above sample text and Vim uses the settings used in the last line of the file. - Any changes made to the original template in C:\Windows\ShellNew appear in the new files that you create. I tried to get this to work with using TweakUI but that did not help in Windows XP, so I had to do it the long way. So, I hope this tip helps at least a few of you, Enjoy! VimTip 641: Highlighting of method names in the definition (C++) http://vim.sourceforge.net/tip_view.php?tip_id= When editing big cpp files, it can be very convenient to highlight the method name (the part after "::") in a method definition. --> I use the following function in my .vimrc: " Add highlighting for function definition in C++ function! EnhanceCppSyntax() syn match cppFuncDef "::\~\?\zs\h\w*\ze([^)]*\()\s*\(const\)\?\)\?$" hi def link cppFuncDef Special endfunction --> I have another line to call this function automatically when editing a C++ file: autocmd Syntax cpp call EnhanceCppSyntax() --> That's it! This doesn't work in all cases (for instance, it doesn't highlight constructors using an initialization list on the same line) but it shouldn't highlight function calls (such as "MyClass::MyStaticMethod( int foo );" ) Don't hesitate to extend the regular expression for a more accurate matching... VimTip 642: Windows: Get K to not display a DOS box that needs closing http://vim.sourceforge.net/tip_view.php?tip_id= To get the K command to open a Windows program without creating DOS box that needs to be closed you can do the following: In your _vimrc add the following: map K yiw:exec "silent !".&kp." ".@0 You can then set the keywordprg (abbreviated kp above) to the program you want to run. Thanks to Jacob Lerner, Tim Chase, and Suresh Govindachar for coming up with this. VimTip 643: Disable built-in command http://vim.sourceforge.net/tip_view.php?tip_id= If there's a built-in key command in vim that you just can't stand, find annoying, and/or often hit by accident(for me it's "K", with ">" a close second), then you can disable it using ":map". You can't use ":unmap", as you might think. Instead, you can map it to nothing, like: :map K ( is not the "Nop" key on your keyboards, but literal letters inside literal pointy brackets.) Of course, you can always :unmap K if you start doing C programming and want to instantly "man" things under the cursor again. VimTip 644: restoring indent for '#' http://vim.sourceforge.net/tip_view.php?tip_id= In 'smatrindent' mode '#' removes the indent if it is the first char on the line. Very annoying for me. From Vim's help: When typing '#' as the first character in a new line, the indent for that line is removed, the '#' is put in the first column. The indent is restored for the next line. If you don't want this, use this mapping: ":inoremap # X^H#", where ^H is entered with CTRL-V CTRL-H. This helps, but it failes to work when placed in ~/.vimrc. The fillowing mapping work in any case: :inoremap # a#^Oh^Ox^OA, where ^O is entered with CTRL-V CTRL-O. VimTip 645: Enabling Windows shortcuts (eg alt+space, F10 etc) for gvim window http://vim.sourceforge.net/tip_view.php?tip_id= I was trying to figure out why Alt+space would not work, as i would have to use the mouse to maximize/restore/minimize my gvim window (on Win32) which was a pain and found that i needed to set winaltkeys=yes to make this work. Now I can use Alt+Space followed by 'x to maximize Alt+Space followed by 'n' to minimize Alt+Space followed by 'r' to restore! See help winaltkeys Also see this: vimtip #494 VimTip 646: moving lines up/down in a file http://vim.sourceforge.net/tip_view.php?tip_id= The following mappings in .vimrc provide a quick way to move a line of text up or down within a file: map dd-P map ddp Hold down the Control key, and the and arrow keys move the line. Check it out! This is particularly useful when editing a file consisting of single-line items in a particular order (such as priority) - it makes it easy to change the relative position of items in the list. VimTip 647: Single letter insert http://vim.sourceforge.net/tip_view.php?tip_id= Often I have to insert only one character ( typically a paren) :map ylpr VimTip 648: Uniq - Removing duplicate lines http://vim.sourceforge.net/tip_view.php?tip_id= There are two versions, the first leaves only the last line, the second leaves only the first line. g/^\(.*\)$\n\1$/d g/\%(^\1$\n\)\@<=\(.*\)$/d Breakdown of the second version: g//d <-- Delete the lines matching the regexp \@<= <-- If the bit following matches, make sure the bit preceding this symbol directly precedes the match \(.*\)$ <-- Match the line into subst register 1 \%( ) <--- Group without placing in a subst register. ^\1$\n <--- Match subst register 1 followed by end of line and the new line between the 2 lines In this simple format (matching the whole line), it's not going to make much difference, but it will start to matter if you want to do stuff like match the first word only This does a uniq on the first word in the line, and deletes all but the first line: g/\%(^\1\>.*$\n\)\@<=\(\k\+\).*$/d VimTip 649: expand existing abbreviation http://vim.sourceforge.net/tip_view.php?tip_id= This mapping expands existing abbreviation map diw:exe "normal i".@" VimTip 650: abbreviation that prompts whether to expand it or not http://vim.sourceforge.net/tip_view.php?tip_id= You can define abbreviation in such a way that it will ask whether to expand it or not. The trick is to define it as insert-mode mapping with special body, not as abbreviation. Here is how to define it: function! MyExpand(abbr,expansion) let answer=confirm("Expand '".a:abbr."' [y] ", "&Yes\n&No") if answer==2 exec "normal! a".a:abbr else exec "normal! a".a:expansion endif endfunction imap ABC :call AskExpand("ABC","...expansion for ABC ...")a imap XYZ :call AskExpand("XYZ","...expansion for XYZ ...")a VimTip 651: Edit gnupg-encrypted files. http://vim.sourceforge.net/tip_view.php?tip_id= It can be somewhat laborious to edit a file which you have encrypted: first you have to decrypt to plaintext, then use vim and save; then encrypt again. The method below lets vim take care of some of the dirty work. First, be sure you have gnupg setup to the point where you can ascii-armor encrypt a file using your own public key, and decrypt it again. Then put this into your .vimrc (don't duplicate the 'if has("autocmd")' part if it is already there): if has("autocmd") augroup GPGASCII au! au BufReadPost *.asc :%!gpg -q -d au BufReadPost *.asc |redraw au BufWritePre *.asc :%!gpg -q -e -a au BufWritePost *.asc u au VimLeave *.asc :!clear augroup END endif " has ("autocmd") you might also want to add these options to your ~/.gnupg/options file to decrease the messages gnupg outputs: no-greeting quiet default-recipient-self #to always encrypt for yourself. Now vim a new file, the name of which ends with .asc: vim important.asc and edit. When you save and quit, gnupg may prompt for gnupg ids to encrypt for (if you don't have default-recipient-self set). Enter your own. To edit, just vim it again and you'll be prompted for your passphrase. This isn't perfect -- in particular, you occasionally have to tell vim to redraw with ctrl-L to get rid of gnupg crud -- but it works pretty well for me. I'd love to hear about improvements! VimTip 652: save all open buffers at once http://vim.sourceforge.net/tip_view.php?tip_id= Since i like to work with more than one buffer, i always have had the problem that i left one of them unsaved by mistake. For this purpose i wrote this small function which saves all open buffers (only if changes were made). If you map the function to a key (e.g. F12), this is quite a convenient way. add this to your .vimrc: function! SaveBuffers() if !buflisted(bufnr('%')) return end let myBufferNumber = bufnr('%') exec("bufdo update") exec("b".myBufferNumber) endfunction nmap :call SaveBuffers() VimTip 653: doxygen '///' :comments setting http://vim.sourceforge.net/tip_view.php?tip_id= This will continue lines of '///' doxygen comments when you reach the end of a line while typing a comment. It also works if you use 'o' to open a new line while on a comment starting with '///'. It only works if there is a space between the last '/' and the first letter of the comment, that is no big deal, since it lends itself to readability. So for example: /// This will work. ///This won't. Here is the magic line. Make sure you put it somewhere that will get sourced whenever you open a file you want to use with doxygen. I have it in ~/.vim/after/ftplugin/c/c.vim, so it gets sourced for all C and C++ files. set comments=sO:*\ -,mO:*\ \ ,exO:*/,s1:/*,mb:*,ex:*/,bO:///,O:// All other comments will continue to work as expected. - Michael VimTip 654: special characters in VIM substitution http://vim.sourceforge.net/tip_view.php?tip_id= Let's think about the code below void howdy(void) { M00 = M01 = M10 = M11 = M20 = M21 = 0; } Now you want to change the code like void howdy(void) { M[0][0] = M[0][1] = M[1][0] = M[1][1] = M[2][0] = M[2][1] = 0; } You can easily do that with :g/\(M\)\([0-9]\)\([0-9]\)/s//\1[\2][\3]/g Here, \1 is a special substitute character meaning first pair of the search pattern. To specify a pair in your search pattern, simply enclose your search pattern with "\(" and "\)". Thus, in the above example \(M\) corresponds to \1, and \([0-9]\) to \2 and etc... And substitute pattern "\1[\2][\3]" means "1st pair" + "[" + "2nd pair" + "]" + "[" + "3rd pair" + "]", which is what we want here. For more information on special substitute characters, simply do :help substitute. Happy Vim-ing! VimTip 655: search with one key http://vim.sourceforge.net/tip_view.php?tip_id= * is 2 keys (shift and press 8) I found it simpler to map these to a single key. put these mappings in your _vimrc file :nmap :execute ":normal #" :nmap :execute ":normal *" Now you can search for the word under the cursor in normal mode with the F8 key backwards and the F9 key forwards. Can this be done in insert mode? VimTip 656: Recursive mappings - (2 examples to learn from) http://vim.sourceforge.net/tip_view.php?tip_id= Recursive mappings are fun to learn and really handy when you want to do repetitive tasks. One way to do this is Tip#144 (recording). This is another way when you find that you are using the same **editing pattern** again and again. Recursion may seem a bit complicated at first but it is very intuitive once you get the hang of it. Here are two examples for you to learn from. For example, you have a file with the following contents - aaa.txt bbbbbb.txt ccc.txt You want to change the file as follows - wc aaa.txt> aaa.log echo "HelloWorld" wc bbbbbb.txt > bbbbbb.log echo "HelloWorld" wc ccc.txt> ccc.log echo "HelloWorld" A simple recursive mapping that will do the job is :map z Iwc lyawA>pa.logecho "HelloWorld"jz Now type z in the first line and everything else is magic. Here is the breakup where {} contain the vim commands. 1. Goto the beginning of the line and type "wc " and then come back to normal mode {Iwc } 2. Copy the word aaa (or bbbb or ccc). We do this by going right one character and copying the word under it. {lyaw} 3. Goto the end of the line and append > and then come back to normal mode. {A>} 4. Paste what we had copied {p} 5. Append .logecho "HelloWorld" to the line. {a.logecho "HelloWorld"} 6. Goto the next line but first we switch to the normal mode. {j} 7. Do steps 1 to 7 all overagain {z} The recursion terminates when the j cannot take you one more line further. If you manually execute a command for one line, you will find it very intuitive to create recursive mappings. Here is another example. Say you want to change #define myid 199 #define myid2 200 #define myid3 201 To #define myid 201 #define myid2 202 #define myid3 203 The simple mapping would be - :map z 2^Ajz Where ^A is CTRL_V+A 1. Add 2 to the number in the line 2. Go down one line. 3. Do steps 1 to 3 again. Also see :help recursive_mapping :help CTRL-A :help nowrapscan // when using recursion with searching. There may be many ways to solve the above problems... this is just another way which I like to use. Recursion is very powerful espcially when I manipulate many open windows where the content of one is to be used in another. VimTip 658: Switching to unit test module for python http://vim.sourceforge.net/tip_view.php?tip_id= Doing a lot of programming in Python, I need to switch quickly between Python module and corresponding unit-test module. Often there is one unit-testing module for multiple python modules. This function allows you to switch to correct unit testing module quickly, using the filename hardcoded at the end of the file. Idea is stolen from Twisted sources. Put this to your ftplugin/python.vim: nmap :call JumpToTestFile() fun! JumpToTestFile() let line = getline("$") if line =~ "^### testfile: " let filename = strpart(line, 14) execute ":e " . filename else echo "TEST PATTERN ### testfile: NOT FOUND!" endif endfun VimTip 659: Collect filenames of current subtree http://vim.sourceforge.net/tip_view.php?tip_id= In vim you can edit directories, but sometimes for me it is more convenienant to have the names of all files in the complete subtree listed in one buffer. The below function does just this. In essential, it globs the file names of the current directory and iterates throught all the names, globbing it again if it is a directory. The following mapping abbreviates the invocation to pressing '_L': map _L :call ListTree('.') function! ListTree(dir) new set buftype=nofile set bufhidden=hide set noswapfile normal i. while 1 let file = expand("") if (file == '') normal dd elseif (isdirectory(file)) normal dd let @" = glob(file . "/*") normal O normal P let @" = glob(file . "/.[^.]*") if (@" != '') normal O normal P endif else if (line('.') == line('$')) return else normal j endif endif endwhile endfunction VimTip 660: Comment lines in different filetypes http://vim.sourceforge.net/tip_view.php?tip_id= This code snippet is a part of .vimrc (_vimrc 4 Win) file to set comments in various filetypes. The funtion CommentIt() decides itself, according to the current file's type which variant of comments to use. --> IMPORTANT this function should be started with "autocmd BufEnter * call CommentIt ()" some where after its declaration to be involved every time user enters a new buffer. function CommentIt () if &filetype == "vim" vmap +# :s/^/"/ vmap -# :s/^"// elseif &filetype == "tcl" vmap +# :s/^/#/ vmap -# :s/^#// elseif &filetype == "c" vmap +# I/*gva*/ vmap -# I2xgv$h2x elseif &filetype == "cpp" vmap +# Agv:s/^/ *gvIko/*gvAji */ vmap -# :s/^..//gvIddgvAdd elseif &filetype == "dosbatch" vmap +# :s/^/rem / vmap -# :s/^rem // endif endfunction ... autocmd BufEnter * call CommentIt () VimTip 661: LaTeX: Addition to latex-suite: folds the preamble http://vim.sourceforge.net/tip_view.php?tip_id= In /ftplugin/latex-suite/folding.vim I added the lines you see below, so that the latex-suite folding \rf also folds the preamble (the part between \documentclass and \begin{document}. " {{{ Preamble call AddSyntaxFoldItem ( \ '^\s*\\documentclass', \ '^\s*\\begin{document}', \ 0, \ 0 \ ) " }}} happy LaTeXing chris VimTip 662: Quote unquoted HTML attributes http://vim.sourceforge.net/tip_view.php?tip_id= This is a simple regex that can be used to search an HTML file and replace all unquoted attributes with their quoted version. map :%s/\([^&^?]\)\(\<[[:alnum:]-]\{-}\)=\([[:alnum:]-#%]\+\)/\1\2="\3"/g VimTip 663: Annoyed that some stuff is reset during GUI init? http://vim.sourceforge.net/tip_view.php?tip_id= I've always been. t_vb is one of those things that forced me to have a separate .vimrc and .gvimrc or to fudge around with $GVIMINIT. And while not documented as such, guioptions seems to get reset as well. Be annoyed no longer: if has("gui_running") autocmd GUIEnter * source ~/.vimrc endif Make sure your .vimrc is safe for multiple sourcings. autocmds should be cleared, in particular. autocmd! There may also be more things to take into account I'm not aware of. Now you can keep all your settings neatly in a single place. VimTip 664: Vim Easter Egg?? http://vim.sourceforge.net/tip_view.php?tip_id= I could not successfully verify this on my 6.2 win32 Install. Maybe, I should not believe everything I read! Or does it work for you?? From http://linuxgazette.net/issue89/vinayak.html ------- Easter Egg # 3 (Credit Listing in VIM) This is a easter egg I recently discovered in the popular editor VIM. Follow the steps and you are in for a surprise. 1. On the command line edit a file programmers.txt 2. Get into insert mode by pressing i 3. Press enter 11 times 4. Now that you are on the 12th line, type the name Bram Moolenaar 5. Open a new buffer using the key sequence CTRL+W followed by N 6. In the new buffer you will see the names of all the people who have contributed to VIM VimTip 665: Hide & Toggle GUI widgets http://vim.sourceforge.net/tip_view.php?tip_id= If you like your GUI clean, but want the option to access all its power, then you might like this tip. The variable "guioptions" determines what GUI widgets are visible (see :help guioptions). I personally prefer to have as few widgets visible as possible, until I need them. To that end, I have the following in my vimrc (thanks to Tim Chase): " Turn off useless toolbar set guioptions-=T " Turn off menu bar (toggle with CTRL+F11) set guioptions-=m " Turn off right-hand scroll-bar (toggle with CTRL+F7) set guioptions-=r " CTRL+F11 to toggle the menu bar nmap :if &guioptions=~'m' \| set guioptions-=m \| else \| set guioptions+=m \| endif " CTRL+F7 to toggle the right-hand scroll bar nmap :if &guioptions=~'r' \| set guioptions-=r \| else \| set guioptions+=r \| endif Opera browser fans will find the bindings familiar. VimTip 666: switch between a *.cpp and matching .h file http://vim.sourceforge.net/tip_view.php?tip_id= For programmers, that want to switch from foo.cpp to foo.h (or vice versa) on a single key stroke, this might help: map :e %:p:s,.h$,.X123X,:s,.cpp$,.h,:s,.X123X$,.cpp, it maps (on F4) the change of the current filename. The endings ".h" and ".cpp" are exchanged (via the magic ending ".X123X"). You could use ".hpp" or ".c" filename endings by changing it in the replacement statemtents. comments are welcome Joerg (j.beyer@web.de) VimTip 667: Navigate large CSV files more easily http://vim.sourceforge.net/tip_view.php?tip_id= I often work with csv files that have dozens or hundreds of items on a line. Scrolling around to find the 34th item is very hard, specially when the items are of varying lengths -- but this small script makes it a bit easier. function! CSVH(x) execute 'match Keyword /^\([^,]*,\)\{'.a:x.'}\zs[^,]*/' execute 'normal ^'.a:x.'f,' endfunction command! -nargs=1 Csv :call CSVH() Now you can do ':Csv 23' to hilite the 23rd entry in each line and go to the 23rd entry in the current line. There's also a great tip at http://www.rayninfo.co.uk/vimtips.html about how to make the columns in csv files line up. VimTip 668: Re-indenting sections : ={motion} http://vim.sourceforge.net/tip_view.php?tip_id= It's simple and documented, but I needed some time to find it: when the right indenting (:he indenting) is chosen, ={motion} re-indents the block. Maybe this could be mentioned in indenting. VimTip 669: nice window resizing http://vim.sourceforge.net/tip_view.php?tip_id= " Map F1 for gvim window resizing " Put this snippet of code in you .vimrc for nice window resizing. " Press F1 key to toggle between the three settings . nmap :call ResizeWindow() imap a " for insert mode function! ResizeWindow() if (has("gui")) if s:selectedsize == 1 let s:selectedsize = 2 set number set columns=88 " 88 is exactly 80 with :set number set lines=35 elseif s:selectedsize == 2 set number let s:selectedsize = 3 set columns=98 set lines=45 else " old school console goodness let s:selectedsize = 1 set nonumber set columns=80 set lines=25 endif endif endfunction let s:selectedsize=1 call ResizeWindow() VimTip 670: Filtering: deleting some lines with some exeptions http://vim.sourceforge.net/tip_view.php?tip_id= I have several hundred file path names in a buffer, each filling a line, e.g. created with vim tip # 659. About half of them are help files, starting with './help/' which I want to delete, but I want to keep the german ones, starting with './help/de/'. Here comes how I do it with VIM: :global:^./help/:if (match(getline(line(".")), '^./help/de/') == -1) | delete | endif VimTip 671: Add a newline after given pattern(s) http://vim.sourceforge.net/tip_view.php?tip_id= After having gone numb when trying to de parse HTML source code w/ very long lines, i created the following function, thus macro and command. It takes a list of one or more patterns/strings, and adds a newline after each. (Wrapping/Indentation is controlled by your own settings.) " Intentionally left incomplete to be complete as needed nnoremap ,nl :NewLine " Add line breaks in after given strings/regex com! -nargs=+ -range -bar NewLine ,call AddNewLine() function! AddNewLine(...) range let str_no = 1 while str_no <= a:0 exec 'let var = a:' . str_no " ` (backquote) is used as delimiters for s///, which is hard " to distinguish but also is much rarer than delimiters. " " And, "No Match found" messages are suppressed (s///e) " " (The "exec..." is one long line.) exec a:firstline . "," . a:lastline . 's`\(' . var . '\)\($\)\@!`\1\r`ge' let str_no = str_no +1 endwhile unlet! var unlet str_no endfunction VimTip 672: Buffer Bar http://vim.sourceforge.net/tip_view.php?tip_id= Hello, GVim does not have a buffer bar (i.e. a toolbar with buffer names listed), but we can make a simple one by using (GUI only) :tearoff Buffers this will float (:help tearoff) the Buffers menu, giving an easier access to switching buffers. The advantage of using this floating menu is that we does not have to switch mode and giving commands everytime we want to switch buffer also it gives the list of files currently being edited. The problem is that when you switch buffer, the floating menu disappear. To make it always appear, we can put this command in the .vimrc autocmd VimEnter * tearoff Buffers The floating menu will become quite lenghty if we open many buffers, to make it somehow smaller, we can edit the file menu.vim in $VIMRUNTIME to make it (1) show only the filename, not with the path and (2) not showing the delete, refresh, etc, since these command can easily done from command mode (:help buffer). For the first one, we can set this variable to 0 :let g:bmenu_max_pathlen=0 in our .vimrc and for the second one, we can use this command (assuming the commands are around lines 563-573, in my menu.vim -> may differ to yours) :563-573s/"/'/g :563-573s/exe/"exe/ the order of these commands does matter. You should check if the command are really located in those lines, the commands to be commented are exe 'an ' . g:bmenu_priority . ".2 &Buffers.&Refresh\\ menu :call BMShow()" exe 'an ' . g:bmenu_priority . ".4 &Buffers.&Delete :bd" exe 'an ' . g:bmenu_priority . ".6 &Buffers.&Alternate :b #" exe 'an ' . g:bmenu_priority . ".7 &Buffers.&Next :bnext" exe 'an ' . g:bmenu_priority . ".8 &Buffers.&Previous :bprev" exe 'an ' . g:bmenu_priority . ".9 &Buffers.-SEP- :" After that, restart gVim. Thanks. VimTip 673: dealing with typing ":wq" in insert-mode http://vim.sourceforge.net/tip_view.php?tip_id= \" I find myself typing \":wq\" in insert-mode many a time. \" Add this to your .vimrc. function WQHelper() let x = confirm(\"Current Mode == Insert-Mode!\\n Would you like \':wq\'?\",\" &Yes \\n &No\",1,1) if x == 1 silent! :wq else \"??? endif endfunction iab wq :call WQHelper() VimTip 674: One-liner Replacement for ':sb(uffer) | e(dit) somefile' http://vim.sourceforge.net/tip_view.php?tip_id= I prefer to use buffers and split windows [unlike a coworker who shall remain nameless (Bob) who insists on having many, many gvim instances open ;) ]. While rather tedious and error-prone, I was satisfied with the built-in method of splitting the buffer and editing a file... Until today, that is. Critical mass was achieved after I fat-fingered ':sb | e somefile' four times in a row, leading to these, my first user commands: "Put this in your .vimrc command! -nargs=1 -complete=file Sedit sbuffer | edit command! -nargs=1 -complete=file Vedit vsplit | edit --------------- Help References --------------- "User Commands :help user-commands "Argument Handling :help E175 "Command Completion :help command-completion Enjoy! VimTip 675: How to turn off all colors http://vim.sourceforge.net/tip_view.php?tip_id= If you're like me, you don't want a colorful editor. I spent hours looking for a "turn off all those colors right now!!" command and I couldn't find any help. After some poking around for a while, I found the commands you need. Just put these at the end of your .vimrc file. syntax off set nohlsearch set t_Co=0 If you don't have a .vimrc file, simply create one in your home directory. The commands I have described will work for version 6.1. If you have some other version, try them and see if they work. -mdmiller VimTip 676: Shortcut key for gvim in Windows XP http://vim.sourceforge.net/tip_view.php?tip_id= Purpose: I want to open gvim, in Windows XP, using a shortcut key. HowTo: I made a shortcut to gvim, and I assigned a shortcut key in the "ProperTies" menu. Issue: I can start the first instance of gvim, but the same combination will not allow me to start the second instance; it will just display the first one. HowToFixIssue: I created a shortcut in the Start Menu. Now, I press and release the "WIN" key, and after that, I press "g" once. It can launch an unlimited number of instances of vim. Sometimes, I need to write a script in one instance and to see the output in another. VimTip 677: quick way to insert opening and closing braces for programmers http://vim.sourceforge.net/tip_view.php?tip_id= This insert-mode map is fairly easy. I will save a lot of keystrokes for opening and closing braces when programming. It works best with cindent on (:set cindent) since vim will automatically indent to the right tabstop. I mapped it to insert-mode Ctrl-F. (The few unmapped left.) Example: int main() Ctrl-F will produce: int main() { | } insert the following in your .vimrc file ============================ " Opening and closing braces imap {}O VimTip 678: Get Diff to Work with SFU 3.5 on Windows XP http://vim.sourceforge.net/tip_view.php?tip_id= I was having problems getting the diff utility to work running version 6.2 of VIM from within windows. I loaded SFU 3.5, Services for Unix, onto Windows XP SP1, to try and take advantage of the included diff utility. Basically what I have found is that it works out of the box, so long as you DO NOT specify the "icase" parameter with diffopt. That is, if you have: diffopt=filler,context:2,icase,iwhite you will receive E97: Cannot create diffs. However, if you simply remove the icase parameter and have: diffopt=filler,context:2,iwhite Diff will work just fine with SFU 3.5, no special functions or scripts required. Unless, of cource, you want to ignore case. VimTip 679: Findlast occurrence of an item http://vim.sourceforge.net/tip_view.php?tip_id= Find the last occurrence of an item. com! -nargs=1 Findlast :execute'normal G' | :execute':normal ?' . . '?' Put that in your vimrc file. Usage: :Findlast item e.g. :Findlast 123 with a regular expression, put the regex inside single quotes e.g. :Findlast '\d\d\d' Explanation: G = Goto line [count], default last line, on the first non-blank character (linewise) ? = Search backward for the [count]'th previous occurrence of {pattern} (exclusive) . = string concatenation VimTip 680: 'Verbose' vs. "File not found" http://vim.sourceforge.net/tip_view.php?tip_id= Problem ------- I want to run vim with 'verbose' set, but then it gives out a lot of "file not found" messages at startup and at closedown. I'd like to avoid those messages, while still seeing where an option was set whenever I interrogate its value. Solution -------- Instead of setting 'verbose' in your vimrc, use autocommands, as follows (for instance) if &cmdheight == 1 set cmdheight=2 endif if &verbose == 0 augroup late-verbose autocmd VimEnter * set verbose=1 autocmd VimLeave * set verbose=0 augroup END endif Notes ----- - The idea of the "if" statement is to avoid interfering with a -V argument which might be set in the command-line for debugging. - The command-line is widened to at least two lines to avoid Hit-Enter prompts on ":set option?" ":edit existing/filename" etc. VimTip 681: Enhanced Command Window (ECW) http://vim.sourceforge.net/tip_view.php?tip_id= " "Enhanced Command Window " Suresh Govindachar March 18, 2004 " "If you are comfortable " " 1) with Vim's modes and " 2) with using the key (meaning " you rarely hit unnecessarily) " "and you " " 3) would prefer entering : commands in a modal " command window rather than on the command line " "Then this tip is for you. "_____________________________________________________ "Some key features of the command window (see ;help cmdwin) "that would lead one to be interested in it are: " " - One can edit the buffer any way one wants " - Hitting results in the line one was one being executed " - (editing in the command window is much nicer than editing " on the command line) "_____________________________________________________ "Begin with some mappings: nmap q:_ nmap q/ q/_ nmap q? q?_ augroup ECW_au au! au CmdwinEnter * nmap :q au CmdwinLeave * nmap q:_ augroup END "Simple observation: with these mappings, one can go "from normal-mode to cmdwin and back via escape ()! "_____________________________________________________ "Some nice things about the command line that are not present "in the usual command window are: " " - The and arrow find all the commands that match " the text entered to the left of the cursor " - Hitting shows the ways in which the typed text can be " completed (see :help cmdline-completion) " "It is possible to have similar features in the command-window too. "For the feature, add the following au-command event "triggered maps: augroup ECW_au " musn't do au! again au CmdwinEnter : imap y0:let@/='^'.@0? au CmdwinLeave : iunmap au CmdwinEnter : imap y0:let@/='^'.@0/ au CmdwinLeave : iunmap au CmdwinLeave : :let @/="" augroup END "Now, while in the command window, going to insert mode and hitting "the arrow followed by the n key results in one visiting all "the commands that match the text to the left of the cursor when "the key was hit -- then hitting while on any line causes "it to be executed. Likewise, for the arrow. "_____________________________________________________ "Next for the feature. This is slightly more complex. "Begin by adding the following autocommand event triggered maps: augroup ECW_au " musn't do au! again au CmdwinEnter : imap y0:ECWCtrlD au CmdwinLeave : iunmap augroup END "Then provide this function: function! s:ECWCtrlD() "With this function, hitting while in insert mode in the "command window results in more information about the text to "the left of the cursor appearing on the lines below the cursor. "This information can left on the command window or removed "by typing u (undo). " "The nature of the information provided by depends on what "is to the left of the cursor: " " If the stuff to the left of the cursor looks, essentially " like "map " or "map foo" then the information provided by " is the same as the information that appears when the " the same stuff is typed on the command line and return is hit. " " If the stuff to the left of the cursor begins, essentially " like "sf " or like "find " then what is displayed on is " the glob of the remaining stuff (after appending the remaining " stuff with a *) " " If the stuff to the left of the cursor looks like neither of " the above two cases then what is displayed is the glob of the " very last non-space separated "word" (after appending that "word" " with a *) " function! s:ECWCtrlD() if (match(@", '^ *[a-z]\?map\s\s*\(\S\S*\)\?\s*$') >=0 ) let s:foo = @" let save_more=&more set nomore execute ':redir @" |'.s:foo.'|redir END' let &more = save_more put=@" "Keep this next command even though Vim comlains -- it is "a work-around for some "unknown bad thing" silent normal return endif "sf and find can have space separated arguments if (match(@", '^ *\(\(sf\)\|\(find\)\)\ *') >=0 ) let s:foo = substitute(@", '^ *\(\(sf\)\|\(find\)\)\ *', '', '') else "pick the trailing non-space separated stuff let s:foo = substitute(@", '\(.\{-}\)\(\S\S*\s*\)$', '\2', '') endif let s:foo = substitute(s:foo, '\s*$', '*', '') "OK if ending has two wild-cards let @"=glob(s:foo) if(@" == "") | let @"='no match' | endif put=@" endfunction if !exists(":ECWCtrlD") command -nargs=0 ECWCtrlD call s:ECWCtrlD() endif "If one wants to get even more fancy, one can start with the map " " nmap :ECWtobedefined " " wherein the function ECWtobedefined opens up a new buffer " in which one can do anything one likes. Even if this new " buffer merely mimics the command window, it will the feature " of co-existing with other buffers -- which is a feature that " the command window does not have! " " That's all for now. " " --Suresh " finish VimTip 682: errorformat for Intel ifort 8.0 http://vim.sourceforge.net/tip_view.php?tip_id= Intel changed the errorformat for their fortran compiler with version 8.0. An errorformat string that works with the new compiler is: set efm=%E%.%#rror:\ %f\\,\ line\ %l:\ %m,\%-C%.%#,\%-Z\%p^ VimTip 683: HOWTO - Integrate MS .NET and gvim.exe http://vim.sourceforge.net/tip_view.php?tip_id= HOWTO: Integrate MS Visual Studio .NET and gvim.exe [Disclaimer: This is NOT a tip on how to get Vim to run inside of MS Visual Studio .NET. I have not yet found anyone who can make that work, so this is the next best thing. VisVim.dll seems to only work with VS6.] If you are someone who prefers Vim and uses ( or must use ) MS Visual Studio .NET for development and you have been struggling with a less than perfect integration of the two, this tip may help you tighten that up. I've been working with the two together since .NET came out and this tip is a compilation of all the tricks and setup I use. THE KEY: Before you do anything else, do this. goto Tools > External Tools > Add: Title: &Vim Command: C:\Vim\vim62\gvim.exe Arguments: +$(CurLine) -- $(ItemPath) Initial directory: $(TargetDir) This will allow you to use the key combination Alt-t-v to open the current file at the current line in a new vim browser. The browser will start at the directory of that file, so ':e .' will edit the directory of that file. THE SECOND KEY: In order to effectively use the two together and make sure .NET does not complain about it's files changing, goto Tools > Options > Environment > Documents and ensure these two options are checked: + Detect when file is changed outside the environment + Auto-load changes (if not currently modified inside the environment) CTAGS: This is an obligatory statement, but a lot of MS developers do not know about ctags. Google for it and use it. This enables you to jump to tags, preview function declarations, use tab completion, and ton of things you can't live without. My personal mappings are: map " use C-] to goto a tag and C-[ to come back up the tag stack noremap } " use C-P to preview a tag in a small window For tag completion, there are a TON of options, but i use vimtip #102 because it's simple and does the job: inoremap =InsertTabWrapper("forward") inoremap =InsertTabWrapper("backward") One snag for ctags on MS is that the tag pathnames require the old dos style pathnames. Use the appropriate DIR switches to figure yours out: set tags=./tags,tags,c:/projects/tags,c:/PROGRA~1/MIEEF7~1/tags If you must use make at the command line ( I don't compile at command line for .NET but i've gotten it working. not sure where this tip was ), use: set autowrite setlocal errorformat=\ %#%f(%l)\ :\ %#%t%[A-z]%#\ %m setlocal makeprg=devenv\ c:/Projects/MySolution.sln\ -build\ release Lastly, if you are afraid to leave the IDE because you like Visual Assist's file browser, I'm maintaining a script to emulate that behavior [ProjectBrowse.vim]. It requires the unix find command which can be easily obtained via the cygwin win-unix set of utils. map :ProjectBrowse c:\Projects\ May the Vim be with you --heina VimTip 684: Preview Current HTML in Browser on Mac OS X http://vim.sourceforge.net/tip_view.php?tip_id= There are a few tips on previewing current HTML documents in a Windows browser, but none I could find for Mac OS X. By studying the others, though, I stumbled on a mapping that works. The at the end anticipates the "Hit ENTER or type command to continue" message. :map p :!open -a Safari % VimTip 685: Search without need to escape frontslashes http://vim.sourceforge.net/tip_view.php?tip_id= This comes in handy if you have the full path of a file in your clipboard, and want to find it in your current buffer. Instead of using "/" to search, use "?" then paste. You don't need to escape the frontslashes, so no need to edit the pattern. If you wish to search forward, just hit "/" and Enter. If you want to use it again, use the "?" history, not the "/". If someone knows an easier way, please let me know! :help / :help ? VimTip 686: Easier Buffer Switching http://vim.sourceforge.net/tip_view.php?tip_id= The command is very handy for fast buffer switching. Used by itself, it switches you to the previous buffer you were editing. With a number before it, it switches to that buffer number. However, I find it's location on the keyboard inconvenient. With a few extra mappings, buffer switching can be easy indeed. Pick an unused, easy-to-type char - I picked \ : :nnoremap \ Put that in your .vimrc. Now to switch to buffer 13, type 13\. You can also toggle between 2 buffers by simply pressing \. This is also handy in insert mode: hit 13\ and you jump to buffer 13, still in insert mode. Map it to whatever key you find easiest to press - or simply use , it's still useful. VimTip 687: Mac OS X clipboard sharing http://vim.sourceforge.net/tip_view.php?tip_id= As of my knowledge there is no clipboard register for Mac OS X unlike Windows (vimtip #21). However you can use pbcopy/pbpaste command to achieve the same thing. Example :.!pbcopy "Copy current line clipboard :4,8!pbcopy "Copy line 4 to 8 :!echo "%:p" | pbcopy "Copy current filename to clipboard :r !pbpaste "Paste clipboard content to current line For more information, :help filter VimTip 688: lid & cscope = custom grep http://vim.sourceforge.net/tip_view.php?tip_id= Sometimes you want to use quickfix for some other things than grep & make. You can always replace one of them and then return to what it was. So, I have in my .vimrc: === fu! Mycscope(func) let tmp1=&grepprg let tmp2=&grepformat set grepformat=%f\ %*[a-zA-Z_0-9]\ %l\ %m set grepprg=cscope\ -R\ -L\ -3 exe "grep ".a:func exe "set grepprg=".escape(tmp1,' ') exe "set grepformat=".escape(tmp2, ' ') endf command -nargs=* CScope :silent call Mycscope("") === This will create the command CScope, that does a cscope's "find functions calling this function" with quickfix. Another example: lid === fu! Mylid(arg) let tmp1=&grepprg set grepprg=lid\ -Rgrep\ -s\ $* exe "grep ".a:arg exe "set grepprg=".escape(tmp1," ") endf command -nargs=* Lid :silent call Mylid("") === Bug: sometimes vim is unable to come back from the command, and you have to hit CTRL+C. I have no idea why. VimTip 689: Word Count http://vim.sourceforge.net/tip_view.php?tip_id= To count the words in a file: g To count the words in a block, select the block and once again g The output looks something like this: Selected 6 of 358 Lines; 37 of 2281 Words; 186 of 13426 Bytes For more information, :help 12.5 (http://vimdoc.sourceforge.net/htmldoc/usr_12.html#12.5) VimTip 690: Reloading a file using a different encoding http://vim.sourceforge.net/tip_view.php?tip_id= You can reload a file using a different encoding if vim wasn't able to detect the correct encoding: :e ++enc= For example, on Windows in western Europe, the default encoding is latin1. However I often use vim to edit batch files they must be encoded using the console codepage which is is usually cp850 or cp437. So I reload the file using this command: :e ++enc=cp850 VimTip 691: gf for standard URL, like file:///C:/myfile.txt http://vim.sourceforge.net/tip_view.php?tip_id= To make gf worked for URL, say, file:///C:/myfile.txt I copy the following to my _vimrc on Windows au BufReadCmd file:///* exe "bd!|edit ".substitute(expand(""),"file:/*","","") Thanks for Bram to offer me such a tip: http://groups.yahoo.com/group/vim/message/49108 VimTip 692: runtime syntax check for php http://vim.sourceforge.net/tip_view.php?tip_id= Ever wanted to just check your php script to see if it had any syntax errors ? Similar to perl -c ?. You could always do it by doing php -l, with this little macro, you can do it in your buffer. Just add the following line in your .vimrc, and whenever you want to test, press ctrl b voila. map :!php -l % VimTip 693: One page summary of color schemes http://vim.sourceforge.net/tip_view.php?tip_id= With so many color schemes on vim.org to choose from, sometimes it's hard to decide which one(s) to use. I have created a page to show off all the color schemes that I have downloaded from here. Hopefully this page will be useful to the rest of the vim community. http://www.cs.cmu.edu/~maverick/VimColorSchemeTest/ The page will be updated as I collect more color schemes. VimTip 694: Really *QUICK SAVE* and back to edit http://vim.sourceforge.net/tip_view.php?tip_id= You are about the modify an important file. You want to save this original file under a different name (and keep the file view). Quick, think of a new name... -- oh, time wasted, for you could have quickly typed in ";s" and got back to the modification at hand... ________________________ map ;s :up \| saveas! %:p:r-=strftime("%y%m%d")-bak.txt \| 3sleep \| e # " Dated-BAKUP date number format, re-edit original " first update, else changes get lost on re-edit, " saves view (attn: write alone does not save view) " thus better than generic copy at OS level, " but be careful when split editing _________________________ The above saves the original file with a date-stamp as part of the filename. Note that it overwrites throughout a single day. If you want a more narrow period of time for overwrites, then supplement above map with hour, min, or seconds. The 3sleep is there just to visually verify that the save has taken place. Happy Vimming... VimTip 695: Naviguer dans l'aide avec un clavier AZERTY http://vim.sourceforge.net/tip_view.php?tip_id= Pour naviguer dans l'aide en ligne de Vim, la touche documentée dans l'aide pour suivre les liens (tags) est Ctrl+]. Sur un clavier français, la combinaison de touches est Ctrl+$ (le même code de touche est envoyé à Vim). PS: This tip is in french because it is only useful for AZERTY keyboard users, which are AFAIK french speaking people. VimTip 696: Make mouse drag not select text or go into visual mode http://vim.sourceforge.net/tip_view.php?tip_id= It drives me crazy that frequently when I click in a window, it goes into visual mode for a few characters and thus I can't type normal command mode commands. I'm finding I always have to press "v" to exit visual mode before I can use vim again. I finally figured out how to disable visual mode using the mouse: noremap noremap! VimTip 697: FRENCH character maps (not phrenology!) http://vim.sourceforge.net/tip_view.php?tip_id= This illustrates the Power of the Pinkie finger... (ie. the semi-colon for QWERTY keyboards). I wanted a scheme which was easy to memorize for French characters. Take a couple of minutes to study the pattern below, and its "logical" ordering alphabetically... once understood, I hope it will serve you a lifetime of writing « les belles lettres ». Happy Vimming! ______________ " FRENCH Mappings " scheme in alphabetic order " where _ denotes primary letter " " à _â ä " _ç " è _ê ë é " _î ï " _ô ö " ù _û ü " " For capital letters, use the ~ or U operator. " Note: French usage does not require putting accents " on capital letters, with the exception of Ç, unless " you're typing all caps, e.g., Ecoutez ! vs. ÉCOUTEZ ! " " Note: map! for Insert and Command-line, i.e. imap & cmap " map! ;z à map! ;a â map! ;b ä map! ;c ç map! ;d è map! ;e ê map! ;f ë map! ;g é map! ;i î map! ;j ï map! ;o ô map! ;p ö imap ;q « »hi " ^inserts within Quotations map! ;t ù map! ;u û map! ;v ü VimTip 698: mbox archive emails http://vim.sourceforge.net/tip_view.php?tip_id= 1. First see: http://www.vim.org/maillist.php#help Follow the instructions to get hold of the archive messages you need. For example, I sent an email to the following address to retrieve mails 43413 to 43512: vim-get.43413_43512@vim.org They will be returned as individual attachments to a single mail, one reply per request. 2. Save all the attachments in a new temporary directory, say /tmp/temp. 3. Download the following script: http://kmail.kde.org/unsupported/xfmail2mbox.sh 4. Run the script, passing the aforementioned directory as an argument: $ xfmail2mbox /tmp/temp (where $ indicates a shell command). This will create a file called /tmp/temp.mbox, an mbox format file of emails found in /tmp/temp VimTip 699: enable servername capability in vim/xterm http://vim.sourceforge.net/tip_view.php?tip_id= This tip applies only to non-GUI vim running in xterm under X11/XWindows (linux, unix or cygwin). 1. When you want to use vim's 'clientserver' features, you have this problem with non-GUI vim under xterm: - in vim under xterm, 'servername' is disabled by default even when 'clientserver' feature is compiled into vim. This is different from GUI gvim, where 'servername' is enabled by default. 2. If you want to enable 'servername' for vim/xterm, the first thing to check is whether vim has 'clientserver' feature compiled-in: do ':version' and check for +clientserver; or do 'vim -h| grep servername' in shell. If 'clientserver' is compiled in, proceed to step 3. If 'clientserver' is not compiled in, you have several choices: - symlink vim to gvim (if you have gvim installed). - install vim with 'clientserver' support from binaries - build vim from sources with clientserver support and install it 3. After you checked that vim has 'clientserver' compiled in, there are several methods to enable 'servername' for vim/xterm. Methods are listed below: Method (A) If you the want simplest solution, just define shell aliases: For csh/tcsh: alias vim 'vim --servername vim' For bash/ksh: alias vim='vim --servername vim' The drawback of this method is that when vim will not have servername enabled when started from a script. Method (B) When you're non-root user and vim is installed system-wide by sysadmin: - create directory $HOME/myvim: mkdir $HOME/myvim - add directory $HOME/myvim to your $PATH, but make sure it appears in the PATH the first, before all other directories, or at least before the directory where vim is installed (command 'which vim' tells you where) - do 'which vim'. Remember directory where system-wide vim is installed. You'll use name of this directory in the next step, in the 2nd line of the script. - create script called 'vim' in directory $HOME/myvim, with these 2 lines: #!/bin/sh exec /usr/local/bin/vim --servername vim "$@" - nb: you *must* use full pathname in the 2nd line of the script - chmod a+x $HOME/myvim/vim - if your shell is tcsh/csh, do 'unhash' Method (C) When you are root user and you want to enable 'server' for all users; or when you are non-root user and you installed vim yourself under your $HOME: - find out where vim is installed: % which vim - cd to the directory where vim is installed - remember name of this directory, you'll use in the nest step in the 2nd line of the script: - in same directory, create script called 'vim.s' with this contents: #!/bin/sh exec /usr/local/bin/vim.bin --servername vim "$@" - nb: you *must* use full pathname in the 2nd line of the script - chmod a+x vim.s - mv vim vim.bin - mv vim.s vim Done. The drawback of this method is that when you reinstall vim, you need to repeat the renaming and VimTip 700: indenting for Java http://vim.sourceforge.net/tip_view.php?tip_id= I needed to do a few tweaks to .vimrc get Java code looking smooth in vim and I'm passing the joy. This is probably good for at least 80% of Java programmers. Hope this helps my fellow Java/Vim peeps. Randy Solomonson My .vimrc file: "Take care of indents for Java. set autoindent set si set shiftwidth=4 "Java annonymous classes. Sometimes, you have to use them. set cinoptions+=j1 VimTip 701: Simple code beautifier http://vim.sourceforge.net/tip_view.php?tip_id= Occasionally, I get code from other people who, for instance, don't like to put spaces in the for-loops or assignments. For example, what I get looks like for(int j=0;jd) and what I would like to see is for ( int j = 0; j < size; j ++ ) if ( vector[j] > d ) Here are a few vimrc lines, that can help. Put them in your .vimrc, or .vim/after/ftplugin/cpp.vim (or whatever language you are using), then you can beautify at least single lines using one mouse click. nmenu Misc.Beautify.For :s/for\s*(\s*/for ( /:s/\s*)\s*$/ )/:s/\(\i\+\)\s*=\s*/\1 = /:s/\s*\([=<>!]=\\|[<>]\)\s*/ \1 /:s/\s*\(--\\|++\)/\1/:s/\s*;\s*/; /g nmenu Misc.Beautify.Func :s/\s*)/ )/g:s/\s*\([(,]\)\s*/\1 /g:s/(\s\+)/()/g nmenu Misc.Beautify.If :s/if\s*(\s*/if ( /:s/\s*)\s*$/ )/:silent s/\s*\([=<>!]=\\|[<>]\)\s*/ \1 / nmenu Misc.Beautify.Assign :s/\s*\([-+*\/&\|]\?\)\s*=\s*/ \1= /g (Each nmenu-line must be one single line!) Tip: if you need to beautify several lines, tear of the menu. Of course, being simple regexp's, these little helpers can be fooled pretty easily by complicated code, but they should work for 90% of your code. HTH, Gabriel. VimTip 703: Make html auto-readable in vim http://vim.sourceforge.net/tip_view.php?tip_id= REPOSTING, all the HTML on LHS of regexp got converted by the WEB server: function! Mosh_html2text() :silent! %s/\<//g :silent! %s/\&/&/g :silent! %s/\"/"/g :silent! %s/\ / /g :silent! %s/\ñ/\~/g :silent! %s/\

//g :silent! %s/\
/ /g :silent! %s/\/ /g :set readonly endfun :autocmd BufRead *.htm* :call Mosh_html2text() " -- Mohsin Ahmed, http://www.cs.albany.edu/~mosh VimTip 705: Make html auto-readable in vim http://vim.sourceforge.net/tip_view.php?tip_id= Make html readable in gvim: function! Mosh_html2text() :silent! %s/&lt;//g :silent! %s/&amp;/&/g :silent! %s/&quot;/"/g :silent! %s/&nbsp;/ /g :silent! %s/&ntilde;/\~/g :silent! %s/

//g :silent! %s/
/ /g :silent! %s// /g :set readonly endfun :autocmd BufRead *.htm* :call Mosh_html2text() " -- Mohsin Ahmed, http://www.cs.albany.edu/~mosh VimTip 706: Make html auto-readable in vim http://vim.sourceforge.net/tip_view.php?tip_id= Make html readable in gvim, add this to your ~/_vimrc function! Mosh_html2text() :silent! %s/&lt;//g :silent! %s/&amp;/&/g :silent! %s/&quot;/"/g :silent! %s/&nbsp;/ /g :silent! %s/&ntilde;/\~/g :silent! %s/

//g :silent! %s/
/^M/g :silent! %s// /g :set readonly endfun :autocmd BufRead *.htm* :call Mosh_html2text() " -- Mohsin Ahmed, http://www.cs.albany.edu/~mosh VimTip 707: Map xmmsctrl commandos in you vimrc file http://vim.sourceforge.net/tip_view.php?tip_id= In case you haven't installed xmmsctrl, you can get it by clicking download on this page: http://user.it.uu.se/~adavid/utils Add the following to your vimrc file: "XMMS mappings map :echo substitute(system('xmmsctrl title'), "\n", "", "") map :call system("xmmsctrl launch") map :call system("xmmsctrl quit") map :call system("xmmsctrl play") map :call system("xmmsctrl stop") map :call system("xmmsctrl pause") map :call system("xmmsctrl shuffle") map :call system("xmmsctrl next") map :call system("xmmsctrl previous") VimTip 708: Converting LANG to UTF-8 http://vim.sourceforge.net/tip_view.php?tip_id= On my system I converted from a single byte character set (any of ISO-8859-15 type sets) to use a variable multi-byte UTF-8 encoding. When I did so my mappings that used to work that were set in my ~/.vimrc were wrong because my ~/.vimrc was written to assume ISO-8859-1/latin1. The LANG environment variable set during user login tells GNU libc6 and most programs written for Unix to use a different character encoding by default. My new setting of LANG=en_US.UTF-8 incorrectly made vim assume that my ~/.vimrc was also written in UTF-8 and stored as if fileencoding=utf-8. This was a problem for meta key bindings. Also any character code above 127 in UTF-8 is represented by two bytes instead of only one, so any characters above 127 will be misinterpreted after converting. A quick solution to make your old file work exactly as intended is to wrap your ~/.vimrc at the top and bottom with 'encoding' commands like this: set encoding=iso-8859-1 [ bulk of ~/.vimrc file] set encoding=utf-8 This allows the keys to be correctly assigned as intended when the .vimrc was created. In my case this was before I changed my LANG setting. In addition to using a new LANG environment variable set in ~/.bashrc (vim correctly reads it and changes to :set encoding=utf-8) I have also set fileencodings=iso-8859-1 in ~/.vimrc so that it matches the system-default locale setting of libc6. This is so that all old (and new) files on my disk match up with what is expected by the rest of my system. Vim will automatically do a file conversion upon reading and writing each file. This seems safe but more testing is required. The best reference I found for these issues is: http://www.cl.cam.ac.uk/~mgk25/unicode.html related vimtips include vimtip #246 vimtip #546 and vimtip #576 VimTip 709: if you create lots of shell scripts http://vim.sourceforge.net/tip_view.php?tip_id= If you create lot of shell scripts, then you'll find this useful: " automatically give executable permissions if filename is *.sh au BufWritePost *.sh :!chmod a+x " automatically insert "#!/bin/sh" line for *.sh files au BufEnter *.sh if getline(1) == "" | :call setline(1, "#!/bin/sh") | endif " automatically give executable permissions if file begins with #!/bin/sh au BufWritePost * if getline(1) =~ "^#!/bin/[a-z]*sh" | silent !chmod a+x | endif Yakov Lerner VimTip 710: Save time by typing and running templates instead of routine code. http://vim.sourceforge.net/tip_view.php?tip_id= The idea is pretty simple. 1.There's template script written in perl (see sources below.) 2. and mapping in visual mode: vnoremap :!perl E:\\Devtools\\vim\\vimfiles\\template\truler.pl The template markers are: TS: TB: TE: TF: