Sven Guckes@vim.org ©1995-2001

Last update: Wed Dec 27 00:15:00 MET 2000

VIM - Questions and Answers

The following questions have been answered by now. Thanks to everyone who helped!

Please read the part about "terminology" below in case you are in doubt about terms used within the text here. And do not hesitate to send in more answers, improvements, and corrections to typos. Thanks!


Color Setup

[001010] Vim allows to change colors for quite a few things, such as the color for normal text ("Normal"), selected text ("Visual"), search matches ("Search"), commented text ("Comment"), and all the characters that represent non-existing or hidden parts of the text. (such as TABS, trailing whitespace, end-of-lines, and the tilde lines after the end-of-buffer).

I've thrown in "LineNr term=NONE" to turn off the default underlining of line numbers as

  " setup by David Risner drisner@eskimo.com
  " http://david.risner.org/ [001010]
  set background=dark
  highlight Comment guibg=Black    guifg=Red    gui=italic
  highlight LineNr  term=NONE
  highlight NonText guifg=Gray95   guibg=Black  gui=bold
  highlight Normal  guibg=Black    guifg=Gray95
  highlight Search  guibg=Cyan     guifg=Black  gui=underline
  highlight Visual  guibg=Yellow   guifg=Black  gui=underline

Encryption and Decryption - :X command

000915 Vim offers builtin encrpytion and descryption with the command ":X".

Frequent Problem: Users encrypt files but forget the key; therefore they cannot get their data back.

FAQ: "How can I get my data back? Can you decrypt my data for me?"

Usual Answer: When you lose your key then you are lost. Encrpytion is meant to keep people from decrypting your data ho do not have the correct key. In this case this means you. Sorry!

Solution: DONT LOSE YOUR KEYS! (As simple as that. ;-)

Prevention: (1) Use the correct escape: An empty input! Just press the RETURN key so there will be no input. Without an input (read: "key") there can be no proper encryption, of course. With Vim you can also type ESC to abort the current command. Pleas enote however that the command will still be added to the command line history - feature!

(2) Remap ":X"! The problem is often caused by a typo: The user tries to "exit+save" with ":x" but types ":X" instead. You can map ":X" to ":x" easily:

map :X :x .. and this should prevent the accidental input of ":X".

From: bgriffin@ic.sunysb.edu (Eli the bearded) Newsgroups: comp.editors Subject: Re: Encryption in vi - Help! Date: 6 Mar 1996 07:23:39 GMT Message-ID: <4hjehr$4v4@abel.cc.sunysb.edu> vi uses the same encryption as the Unix crypt command. This is a single rotor version of the enigma machine maping 8-bit chars into 8-bit chars. Since text files are a small subset of 8-bit chars, decryption of plain text files is a relatively easy task. [...] Unix crypt is a very poor crypto system. When it was written it was merely low security (with a bonus for security through obfuscation), but computational power has increased vastly since then as have the number of people interested in launching attacks against it. You should never consider it more secure than a small padlock on a diary. (Note this crypt is a different one than the crypt(3) function used for encrypting passwords in a vanilla passwd file. crypt(3) is a one way encryption based on DES. I am not convinced of its security, but I don't know of any attempted attacks on it.) From: Kevin Dempsey Peterson <kevin@cafe.berkeley.edu> Newsgroups: comp.editors Subject: Re: vi emergency Date: Mon, 20 Oct 1997 15:59:27 -0700 Message-ID: <Pine.GSO.3.96.971020155614.8935I-100000@cafe.berkeley.edu> Crypt isn't DES. The crypt(3) call is DES, but the crypt command is a weakened version of the Enigma machine. Try http://www.dodgenet.com/~kwantam/zip/cbw.zip -- kevin@cafe.berkeley.edu Home: (510)665-9670 http://www.ocf.berkeley.edu/~peterson Page: (510)726-8960 The URL to "kwantam" is obsolete. But I found the "cwb.zip" here:
  • ftp://ftp.ecst.csuchico.edu/users/atman/CBW/cbw.zip
  • ftp://ftp.ox.ac.uk/pub/crypto/cryptanalysis/cbw.tar.gz [1994-09-19; 188529 bytes]

    The file "Read.me" says that the archive contains CBW, the "Crypt Breakers Workbench .. originally written by Robert W. Baldwin at MIT."

  • ftp://ftp.ecst.csuchico.edu/users/atman/CBW/cbw.txt
    In this text, Norman Richards (orb@cs.utexas.edu) says on 1992-12-18:
    "cbw is used as a tool to decrypt text files that have been encrypted via the standard unix crypt command. The program breaks the message down into 256 byte blocks. The encryption program itself (to quote the docs) is effectively encrypted by a single rotor enigma system."
    So, maybe CWB can help you decrypt your accidentally encrypted data. I have not tried it. Feedback is welcome. -- But please respect the privacy of others. Thankyou!


    Vim vs CAPS

    The Windows versions of Vim have a problem with the CAPS key: When the CAPS key is down/pressed/ON then typing the numeric keys on the normal keypad (ie not the extra numeric keypad) will produce the upper keys, too. This is *wrong*.

    Mark Johnson had produced a patch for Vim in 1998


    Vim on WindowsNT

    Fighting the Registry

    Problem:  Opening files with spaces in the filename does not work.
    Solution by Scott Borton scottb@uccs.com [980807]:
    
    1. start regedit (start -> run -> "regedit")
       NOTE: we are now in the "Registry Editor" window...
    2. edit -> find... -> "gvim"
       This finds the key class 'My
       Computer\HKEY_CLASSES_ROOT\txtfile\shell\open\command'.
       NOTE: I had previously mapped .txt files to be opened by gvim
       via Explorer's "Open With" facility.
    3. In the Registry Editor data window, double click on:
       'ad(default)  ""C:\Program Files\vim-5.1\gvim.exe" %1"
       This exposes the "Edit String" dialog
    4. Change the "data value"
       from:    C:\Program Files\vim-5.1\gvim.exe %1
       to:      C:\Progra~1\vim-5.1\gvim.exe "%1"
    
       This specification doesn't require quoting of the executable string
       and allows us to quote the argument string which is what we want.
       The nice thing about this is that new mappings of file extensions
       to gvim seem to inherit this execution string.
    

    Online Webster - requesting definitions of words

    Every now and then you maybe have to look up the definition of a word. Here is a simple way to send a request to an "online webster": #!/bin/sh www -n "http://work.ucsd.edu:5141/cgi-bin/http_webster?isindex="$* | more exit 0 Where "www" is the name of the program of your favourite web browser, eg:
    	$ ls -l `which www`
    	[...] ~/bin/www -> /path/bin/lynx
    
    Tip submitted by: t.byfield tbyfield@panix.com [980529]


    Vim on CDE

    On CDE (Common Desktop Environment) the default terminal is "dtterm". There are some problems with it.

    Q: Starting vim overwrites the screen. Why? can I change this?
    A: Dtterm does not support xterm's "alternate-screen controls" (at least it is not mentioned in the manual), so you can't fix it. (This is not a vim/vi/whatever problem.) If you want a terminal with an "alternate screen" then you should get "xterm". As this terminal ships with many systems you probably already have it. The XFree86 3.3 xterm supports ANSI color and VT220 emulation Please take a look at the FAQ:
  • http://dickey.his.com/xterm/xterm.faq.html
    Thomas E. Dickey dickey@clark.net [971031,000605]


    Mapping the Escape Key (ESC)

    Fact: Typing an ESC on the command line "aborts" the command. Q: Why is it that an ESC within a command line mapping *executes* the command on the command line? A: This was done to make Vi mappings work, while at the same time fix that Esc should abort the current command (as is stated in most Vi manuals). See also: ":help c_<Esc>".

    Hint: To abort the current command on the command line, use CTRL-C:

    cmap <c-g> <c-v><c-c>

    Windows: Replacing Notepad with Vim

    WARNING: Although you *can* replace the Notepad with a copy of Vim you are advised not to do so as this breaks printing. Windows uses the notepad with the parameter "/p" to print texts. Vim however, does not understand this parameter, and thus you could lose the "internal printing".

    You are advised to "map" the opening of text files to Vim using the Windows Explorer ("View->Options->File Types"). This can be tedious but should be better.

    File extensions to map would be:

            .C
            .CPP
            .H
            .TXT
    

    If you still think that you must do the replacement then here are more ideas:

    Do not replace the notepad with vim by copying it over!
    THIS IS WRONG: copy c:\vim\vim.exe c:\windows\notepad.exe
    Why: This causes Windows to lose track of the default location of the desired application.

    So you should go about it like this:

    Make backup of notepad
    copy c:\windows\notepad.exe c:\backup\notepad.exe
    Note:

    Make copy of Vim as "notepad"
    copy c:\vim\vim.exe c:\tmp\notepad.exe

    Replace notepad with new copy
    copy c:\tmp\notepad.exe c:\windows\notepad.exe
    Prompt "replace"? Answer with "yes".

    Gregory Harris gregoryh@netscape.com [971231]:

    Win95/NT4:

    • Open any folder
    • Select "View|Options"
    • Select "File Types"
    • Choose "text document"
    • Select "Edit..."
    • Select "Open"
    • Select "Edit..."
    • Change the "Application used to perform the Action" field with the exact path of vim.exe.
    Another description from Joshua Rodman (joshua@wrs.com) [980116]:

    "The answer is not quite as simple as it may seem. There are two places where mappings between extensions and programs are made.

    The "old" win31/NT3 way is done with the aid of the file manager "winfile".
    The "new" win95/NT4 way is done with the aid of the windows explorer.
    
    Mostly setting the method which matches your OS version will cause the behavior to happen, but I sometimes end up finding it necessary to set both depending upon what the launching application is doing.

    Both these settings are, of course, set in the registry.

    The Win31/NT3 way:

    • Run file manager (START->RUN->Winfile under NT4/95)
    • Find and select a file of the appropriate type
    • From the File menu, select Associate...
    • Vim will most likely not be on the list of programs to "Associate With:" so select the browse button, and find vim.exe with the resulting interface. Alternatively, instead of a flat association, you could select New Type and associate a laundry list of extensions with Type: Text and the program Vim.
    Win95/NT4 way:
    • Open any explorer window.. ie.. double click on any drive, folder, etc.
    • From the resulting window, select the File->Options.
    • Select the File Types tab
    • Scroll down to find the type Text Document.
    • Select Text Document and click Edit.
    • In the resulting dialog, select OPEN from the actions list, and click Edit.
    • Under "Application used to perform action:" type in the path to your vim.exe, or click the Browse button to graphically select the location of your vim.exe.
    • Note that if you do not want ALL these extensions opening VIM you will need to delete the type and reconstruct multiple replacements. Windows is _VERY_ inflexible about the editing of types.
    000904: Matthew White mwhite@csu.edu.au comments on "replacing notepad with vim" on a Windows2000 machine:
    You can do it but you need to delete notepad.exe from the directory /winnt/system32/DllCache. (This directory is probably hidden.) Once this has been done you can copy vim as notepad.exe over the top of /winnt/notepad.exe and also /winnt/system32/notepad.exe.
    So - do these things work? Or are there any problems with this? Please let me know! Sven guckes@vim.org

    Thanks to these people for their help:

    Matthew White        mwhite@csu.edu.au [000904]
    Joe Tschida     jtschida@wavefront.com [971231]
    Gregory Harris   gregoryh@netscape.com [971231]
    Ron Aaron           ron@mossbayeng.com [980116]
    

    Printing Text Files

    Printing Text with Line Numbers

    Once in a while it is nice to print a file with line numbers, eg when you want to compare files with somebody and need to talk about that "statement in line, uh, ..", well, you know.

    So how do you print a file with line numbers? Well, there are several ways to kill a cat... Apropos, here's one way:

    cat -n filename

    And then there is "pr" ("convert text files for printing"):

    pr -tn' 3' file


    [970910]


    Vim on DOS

    [970818] Vim on DOS takes about 400K. And when you use the "shell" it might not work because there is not enough space left for the shell. In that case you simply have to cut down on some extra programs to gain the space you need to "shell out" from Vim.

    VIM GUI - Athena and Motif distribution

    For installing VIM GUI you need "Athena and Motif". If you have a standard X11 distribution installed, then the Athena libraries should be there. Motif is commercial and a license needs to be bought.

    But there is an option: Get Lesstif (a Motif clone) and is available for free:

    X11 distrib: ftp://ftp.x.org/ 
    Lesstif:     http://www.lesstif.org/ 
    Motif:       http://www.rdg.opengroup.org/ 
    

    Quoted Printable (QP code)

    Problem: QP encoded text, eg when replying to a QP encoded mail or post.

    Solution: Highlight the text and then use ",QPD" to decode. And ",QPE" to encode. Of course you need the following definitions and the associated scripts "qpdecode" and "qpencode":

    vmap ,QPD :!qpdecode vmap ,QPE :!qpencode script "qpdecode": perl -pe 's/\=([0-9A-Fa-f]{2})/chr(hex($1))/ge; s/\=\n//;' script "qpencode": #!/usr/bin/perl -p s/([^\n\t -~]|[ \t]$)/'='.sprintf("%02X",ord($1))/ge;s/(.{70}[^=\n]{2})/$1=\n/;

    Parenthize text

    Parenthize current word: map ,, maa0<ESC>mbbma$a x<ESC>`awgebi(<ESC>ea)<ESC>$xx`blx`a

    Long and short mappings and timeout

    Q: I have defined a mapping for "longcommand" - but why does it work sometimes and sometimes it doesn't?
    A: The longer the command name the longer it takes to type in. And if you pause in between for more than the "timeoutlen" then it is considered that you write text and thus you did not complete the mapped key sequence. Just type with less pauses or increase the pause. ;-) You can also define an abbreviation for command line as this is independent of timeouts.

    VIM - "vimrc"

    A program without a configuration usually is hard to use. That's why you should know about VIM's setup file.

    The usual way of using a setup file for UNIX programs is to put a file into the home directory. Most programs read commands from this file, hence the suffix for these files is "rc". The filename starts with a dot (".") as these files do not get listed with a simple "ls" command. Setup files usually are not looked at often, and there are quite a lot of them.

    So the setup file for vim is the file $HOME/.vimrc, abbreviated as "vimrc".

    When talking about the setup file of a program then the location $HOME is often left out as well as the dot prefix of the filename. So we talk about the "vimrc" instead of "$HOME/.vimrc". Sometimes we will just say "rc file" or even "rc".

    NOTE: Actually there are more init files involved. As vi is based on "ex" it also uses "$HOME/.exrc".

    NOTE on exrc: Some version of vi seem to choke on empty lines in the exrc.

    There are three kinds of things which are defined in the vimrc:

    Settings ("set")
    The command "set" changes the values of the internal variables. The variables affect the way vim works.
    Abbreviations ("ab")
    An abbreviations is a word which is to be replaced by another word. (What did you expect? :-)
    Mappings ("map")
    A mapping defines a new command. You can change the internal commands ("builtins") that way or create new commands.

    Sample Settings

    Sven's vimrc is available as http://www.vim.org/rc

    Sample Abbreviations

    Abbreviations are quite simple word to word translations. Very handy when you type the same things over and over again. It is useful for long words like this: "Donaudampfschiffahrtsgesellschaftkapitaenwitwengesetzzusatzparagraph" This actually is a proper German word. Don't ask! The abbreviation for this word might be "DON" and the definition in the vimrc would look like this: ab DON Donaudampfschiffahrtsgesellschaftkapitaenwitwengesetzzusatzparagraph

    I also use abbreviations for Email addresses, important file name such as setup files, and some URLS of my web pages.

    Examples:

    ab _vimrc $HOME/.vimrc ab _mymail guckes@math.fu-berlin.de ab _homepage http://www.math.fu-berlin.de/~guckes/ NOTE: It does not matter how many spaces there are between the abbreviation and the expanded word. This allows for some nice formatting. Abbreviations can be a lot more than mere word substitutons, though. Actually anything you type can used. [TODO: HTML example]

    Sample Mappings

    Mappings make the use of VIM more interesting yet. Complex commands be made with just a few keystrokes.

    Caveat: Mapping must be "prefix free", ie no mapping must be the prefix of any other mapping. Example: "map ,abc foo" and "map ,abcd bar" will give you the error message "Ambigous mapping".

    " 950101 ,v = vimrc editing (edit this file) map ,v :e $HOME/.vimrc " 950101 ,u = "update" by reading this file map ,u :source $HOME/.vimrc " " 950101 g = goto first line " 951112 the new vim defines "g" as a new command, eg "gg" will go to first line " map g 1G " " === Text editing " " - Formatting " " 950330 ,dp = dequote current paragraph map ,dp {jma}kmb:'a,'bs/^> *// " 950330 ,qp = quote current paragraph map ,qp {jma}kmb:'a,'bs/^/> / " " - Inserting texts " " 950101 ,c = "copy notice" (tell addressee that text is a copy of an article) "map ,c 1G}:r COPY " 950101 ,re = read ELMSIG map ,re G:r ELMSIG " 950101 ,da = "date insert" map ,da :r!date " 950101 ,dt = "date and time insert" map ,dt :r!date +\%y\%m\%d\%t\%T " 950101 ,h = "helloagain" (indicates reply to reply) map ,h 1GOHello, again! " 950101,950620 ,C = "check alias" " 950101 ,s = "sign" - read in signature file (requires manual completion) map ,s :r $HOME/public_html/sig/sig. " 950101 ,t = "text" - read in text file (requires manual completion) map ,t :r $HOME/public_html/txt/ " "END

    Map Example - Ninety-nine Bottles of Beer

    [...]

    Increasing a number with Vi

    This macro increments the number the cursor is on:
    " marks with z , executes register x.
    map +   mz"xy G\+w
    map \+w or0^Mr9^Mr8^Mr7^Mr6^Mr5^Mr4^Mr3^Mr2^Mr1^Mr0^M^M?^[\+x
    map \+x "xp"xdd@xbk"xdd11L11dd`z@x`z^L
    
    With VIM you just position the cursor on the number, enter the number to add followed by ^A. the number 100 thus changes to 123 after the command "23^A". [960927]


    Viewing file with continuous update

    [990628]
    Situation:  You look at a file that contains the output of a program.
    The program continuously changes the file (usually by *appending* data).
    Q: How do I know that there is an update on the file without leaving vim?
    A1: (from within Vim)
    Load the latest version of the file into the edit buffer with the
    command ":e!".
    A2: (external) Use "tail -f" on the file in another window.
    A3: (external) Use "less _F" on the file in another window.
        From the manual to the pager "less":
    	F	Scroll forward, and keep trying to read when the end of
    		file is reached. Normally this command would be used when
    		already at the end of the file. It is a way to monitor the
    		tail of a file which is growing while it is being viewed.
    		(The behavior is similar to the "tail -f" command.)
    A4: Add these autocommands for the filename pattern PAT:
    	:au FileChangedShell PAT e!
    	:au CursorHold       PAT e!
    	:au FocusGained      PAT e!
    If you only want to view logfiles with syntax-highlighting
    then search for "colortail" on http://www.freshmeat.net!
    You may wish to add ithat the cursor automatically jump to the end of the
    buffer, too (by adding ":norm G" [without the quotes]).
    [Thanks to Thomas Köhler jean-luc@picard.franken.de 990704 for this]
    

    The Angle Notation

    [960927]
    Q: Why does "<CR>" not chaged to a ^M with :autocmd ?
    A: The <> notation is only recognized with the :map command.
       You cannot use it with :autocmd .
    Workaround:  Use a :cmap to define a command and use it for your :autocmd.
    Example:
    	:cmap _addbufmenu :menu Buffers.% :buffer %
    	:au! BufReadPre * normal :_addbufmenu
    One remaining problem: file names with a "." in them will cause a submenu to
    be created.  This needs some extra stuff to put a backslash before the ".".
    This is left as an exercise to the reader... :-).
    Solution:
    :cmap _addbufmenu :menu Buffers.1 :buffer %
    :autocmd! BufNewFile,BufReadPre * normal O^["%p0:s/\./\\./g^M"1yydd:_addbufmenu
    For the second line the '^[' and the '^M' is actually cntrl-v, Escape and
    cntr-v, cntrl-m. Bit of a hack, but works just fine.
    To avoid that, more can be moved to the mapping.
    nmap _xaddbufmenu O%:s/\./\\./g0"9y$u:menu Buffers.9 :buffer
    %
    autocmd BufNewFile,BufReadPre * normal _xaddbufmenu
     
    One remaining problem:  The current yank register is changed.
    "Y:np" doesn't work as expected.
    

    VIM within SUN's shelltool

    Vi in a shelltool on Sun switches from insert to command mode on pressing an arrow key because the byte sequence resulting from pressing the key starts with , and vi doesn't interpret the sequence. VIM, however, does, and you can use arrow keys to move in your text while remaining in insert mode. [960622]


    Delete/Remove commands

    Q: How do I delete blocks?
    A: :g/first/,/last/d NOTE: This assumes that all these blocks have the same string "first" in the first line as well having the same string "last" in the last line. All lines in between are skipped!!

    Q: How do you remove all empty lines?
    A:

    :g/^$/d

    Q: How do you remove all lines with whitespace (spaces or tabs) in them?
    A:

    If the lines contain

    Q: How do you "squeeze" a range of empty lines to a single empty line?
    A1:

    :v/./.,/./-1join to compact 2 or more blank lines into just one. [Rick Hellicar (hellicar@prl.philips.co.uk)]
    A2: map _b GoZ^[:g/^[ ^I]*$/,/[^ ^I]/-j^MGdd Note that this mapping inserts an extra line at the end of the buffer and removes it after the global command is done. This trick makes it possible that the global command works on the last part of the buffer, too. [Robert Webb (robertw@wormald.com.au)]
    [960326]


    Mapping the TAB key

    [960311] Q: How do you map the tab key?
    A: :map ^V^V^V^I right-hand-side

    Mapping the ESC key

    On some keyboards the escape key is not placed place very well. It's either part of the numeric block or it can be a small button (as with some Macintosh keyboards). But do not despair - make your own escape key! You can map one of the commands keys you do not need to ESC. Example: map CTRL-o to ESC: :map   That's ":map CTRL-vCTRL-o CTRL-vCTRL-ESC".
    [960311]

    Helpfile (vim_ref.txt)

    Problem: After relocation of the documentation, vim cannot find the help text.

    Question: How do you tell vim where the helpfile is?

    Answer: To tell vim where to find the help file, set the variable "helpfile" to the correct value, ie including the full path. As with most variables you can abbreviate "helpfile to "hf".

    Example:

    :set hf=/path/vim_ref.txt

    VIM - Invocation / Startup

    The easiest way to start "vim" is to simply enter "vim" at the prompt of your shell. If your shell can find "vim" then it will start it.

    Now vim should show you an "empty buffer". A "buffer" is a part of the computer's memory where only vim may change data. While editing you change the contents of this buffer. As you are not making any changes to a "file" on your "file system" you make changes to something "virtual". To apply these changes to a file you have to give the "write" command.

    Before we can go on I will have to explain how the programs tells your "text imput" from the input it has to interpret as "commands".


    VIM - Command Mode vs Append/Insert/Open/Replace Mode

    Vim is a "modal editor", ie deepending on the current mode the keys you type have a different meaning. When in command mode, the keys are interpreted as commands; most commanly these either move the cursor ("jumps") or they change the text (delete/insert).

    After startup Vim is in command mode. Type 'i' to switch to insert mode; now all the keys are simply inserted as text - except ESC which is used to "escape" from insert mode and switch back to command mode.

    Exiting Vim is done with the command ":x", ie you type ':' to switch to "ex mode", followed by the 'x' (think of "exit") and then you enter this command by typing the 'return' key. The exit command will automatically save the changes you made back to the associated file.

    NOTE: When you are on command mode then typing ESC will not exit that mode but stay right in it. As feedback on this you do not get an error message but a "beep". When the machine or the response is slow then you will find yourself in the situation that you are not sure whether your ESC has been received and has changed the mode, so you might type ESC again to make sure. This can result in two ESC being sent where the first does change the mode and the second results in a beep. Don't worry - no data is lost, nothing is broken. Just ignore the beep! However, the beeping can be quite annoying to people around you, so you can turn it off with the command ":set noeb vb t_vb=". You might want to put this into your setup file, too.


    VIM - Online Help

    [960311,990223] One of the best improvements over Vi is the "online help". Just enter the command ":help" (press return key to "enter"!) and VIM will open a window with the help text in it.

    You can also give a word after the help command and Vim will try to find something that matches this word. Actually, Vim tried to make a match on the words within an "index" of all help documents, known as "tags". This index is thus also known as *the* "tags file".

    You can also just enter some prefix of a tag and let Vim show you all possible completions that it finds in the "tags file". Just enter ":help prefix" and type a CTRL-D after that.

    Example: You are looking for info about "formats" or "formatting"; so enter ":help s" followed by the CTRL-D. This would show something like this on the screen:

    :help format<CTRL-D> 'formatprg' Unix-format 'nrformats' formatting file-formats 'grepformat' 'formatoptions' DOS-format-write 'fileformat' format-comments Mac-format-write errorformat format-bullet-list Unix-format-write 'fileformats' Mac-format dos-file-formats 'errorformat' DOS-format tags-file-format errorformat-changed The ":help" command for Vim-3 just shows an index of help pages. All help pages can be accessed directly by pressing the associated letter - except for 'a' and 'b': The letter 'a' gives you the index page, the letter 'b' is the command to move "back" to the previous help page.


    Jumping back to marked line *and* position

    Q: How do I get back to the exact position within a line I have marked with 'a'? A: Use "`a" (that's a backtick!).

    Display of current command input

    Q: How I see what I type? A: Use ":set showcmd".

    VIM - DOS/Windows version

    Q: Why does gvim-Win32 show the ISO (Unix) character set?
    A: Bram: I think only the Win32 GUI version uses the ISO (Unix) character set. All other DOS and Windows versions use the DOS character set. Currently there is no way to switch character set. I would not know how to do that under DOS or Windows. For the Win32 GUI it should be possible, if I can find the documentation for it.
    [970911]

    Q: Who can I ask about the DOS/Windows version? A: Here is a short list:

    Win32 (Windows NT and Windows 95) version
    George V. Reilly (gvr@halcyon.com>
    OS 16-bit real-mode version
    Any volunteers?
    DOS DJGPP 32-bit protected-mode version
    Any volunteers?
    If you are using the DOS version of VIM then you might get strange screen flashing or color changing. The reason could be that "highlighting" is on. Use the command ":set hl=" to turn highlighting (hl) off.

    Q. How do you paste into Vim when running Windows 95?
    A. In the properties dialog box for the MS-DOS window, go to "MS-DOS Prompt/Misc/Fast pasting" and make sure that it is NOT checked.


    VIM DOS/Windows - Shell invocation

    The following commands to show a dir listing fail because the "!" invokes a shell, so there is no need for "sh" or "command.com": :!sh dir/w :!command/c dir/w :!\command.com/c dir/w :!csh dir/w The proper way is: :!dir /w To start command.com use ":!sh".

    Changing line feeds from DOS to UNIX

    Situation: You edit a file with DOS end-of-lines (EOL), ie. lines end in two characters - ASCII#13 ("carriage return" aka "CR") followed by ASCII#10 ("linefeed" aka "LF"); but you want to turn this file into a Unix file, for which the EOL is only a linefeed (ASCII#10, LF).

    Q: How to turn (13,10) into (10)? A: Assume that the file is in the current buffer. Use the power of vim: :set fileformat=unix :w Or use the power of Perl: An empty perl script should do the trick as Perl automatically writes files with the correct eol character for the system it's being run on: :%!perl -pe ";"

    VIM - Backup Files

    By default, backup files are maintained. That is, editing 'file' will create 'file.bak' in the current directory. This can be turned off with ':set nobackup nowritebackup'. By default, a swap file is created in the current directory for crash recovery purposes. Vi puts its crash recovery file in /tmp. To make vim do something like this, use ':set dir=>/tmp'. The '>' stops it from trying the current directory first. [950306]

    VIM - Tranposing characters and lines

    A frequent typing error is tranposing two characters, ie you type them in the wrong order. Example: You type "in" as "ni". So what is the easiest method of changing this? Some editors have a "transpose command" usually bound to "control-t". However, this is no standard. And "vim" does not have it. However, it is as easy as deleting the first charcter and placing it after the second. You can do this by placing the cursor on the first character and then use the command sequence "xp".
    Example: "ni" Put the cursor on the "n". Use "x" to delete the "n". Note: The cursor will be placed on the next charcter, ie "i". Use "p" to "put" the deleted text (the "n") after the current position ("i"). Result: "in" You can also start on the second character and use "Xp". Command "X" deletes the character *before* the current character.
    Tranposition of two lines works in the same way, ie delete one line and put it after/before the adjoining one. The command sequences here are "ddp" and "ddP". [950306]

    VIM - Paragraph formatting

    How to format a paragraph (block).
    • step1: Go to first line (character) of the paragraph to format.
    • step2: Press "Q". Note: A capital "Q" - not a lower case "q".
    • step3: Press "}". (On the Mac keyboard with German layout: alt-9)
    • => paragraph formatted (hopefully)
    You can also format text by calling an external program. The nicest formatter I have seen so far is "par" - see the notes on the Vim Utilities Page.


    1) Type (esc) to switch to command mode 2) Enter the command ":help" (press return key to "enter"!). VIM will show you an index of help pages. All help pages can be accessed directly by pressing the associated letter. <li> <xmp> On msdos, if you get any strange screen flashing or color changing, try: :set hl= This will turn highlighting (hl) off. By default, backup files are maintained. That is, editing 'file' will create 'file.bak' in the current directory. This can be turned off with ':set nobackup nowritebackup'. By default, a swap file is created in the current directory for crash recovery purposes. Vi puts its crash recovery file in /tmp. To make vim do something like this, use ':set dir=>/tmp'. The '>' stops it from trying the current directory first. [950306]

    Substitute in line range

    Q: How do you substitute from line marked with x to a line marked with y ? A: :'x,'ys/this/that/

    Reading in a file

    Q: How do I append a signature to my text? A: Jump to the end of the text with "G" and then read in the signature file. Q: How do I read in a file to the current buffer? A: Use ":r file". The contents of "file" will be appended *after* the current line. Q: How do I read in the output of a command? A: Use ":r!command".

    Abbreviations

    Q: Why cant I abbraviate "'xy"? A: The abbreviation consists of a non-id character followed by two id characters, which does not satisfy either category of a "full-id". However, "_ps" and "'p" will work.

    Highlight mode jumping

    Q: Are there commands to jump to the beginning/end of the highlighted text?
    A: Yes, command 'o' will jump to the beginning/end of the highlighted text.

    Completion of negated settings

    Q: Why does completion of ":set n" not show negated settings, eg "noautoindent"? Completion of ":set no" seems to work.
    A: The thing is that the "no" is not actually part of the option's name, the name comes after that. So after "no" vim knows to complete any boolean setting name (starts the completion just after the "no", which is not part of the name). After "n", vim will complete all setting names starting with "n". It would be a bumber if you wanted to complete "number", but had to wade through all the boolean option names with "no" prepended too.
    Answer by Robert Webb robertw@wormald.com.au, author of the completion code.

    Formatting text

    vim4 allows to format the current paragraph with "Qp". The "Q" means "format" and the following "p" will let the formatting operate on the current paragraph. The really good thing is that it preserves "quoting".

    Note: Since Vim-5 the command for the "internal text formatting" has changed to "gq" since the 'Q' was needed for Vi compatibility.

    However, the builtin formatting command does not suit everybody. There are a few scripts about which you can use to pipe your text through. Here are two scripts - one in PERL and one in AWK:
    mfmt.pl
    fmt.awk
    Basic knowledge about PERL and AWK required. Caveat: scripts are not tested yet! use at own risk! [TODO: test the scripts]


    Insert mode not local to window

    Someone reports: vim does not remember the mode of a window, i.e if you are editing two files, one in command mode, and the other in inset mode, and changing from the file edited in insert mode to the file edited in command mode, by cliking with the mouse in file edited in command mode this file is = now edited in insert mode.

    MrVIM answers: This is intentional. Mode does not stick with a window. The mode is global to all windows. This is different from some other Vi clones, I suppose (some also have a different command line for each window).


    Digraphs

    Q: Is there a command to remove any or all digraphs? A: No. There is a table that is defined at compile time. You can only add new ones. Adding a command to remove digraphs is on the todo list.

    Starting in insert mode

    Some people like their editor to be in insert mode after the start. Q: How I do let vim start in insert mode? A: :set insertmode This should go into the vimrc of course. ;-)

    Turning off the beep

    If you want vim to stop beeping then all you need is ":set vb" which tries to do a screen flash rather than an audible beep. Some terminals can't do screen flashes, but if yours does and you don't want it to flash or beep then use ":set vb t_vb=".

    NOTE: In version 3.0 you would get some characters on the command line (which you can't see unless you have a very slow terminal).


    UUencoding text

    Sending text like a vimrc will sometimes lose special characters. Therefore uuencoding them is a good idea. Q: How do I encode text with uuencode? A: !uuencode filename

    Reading man pages

    Manual pages use the combination "_^H" to underline text. When you read in a man page into a buffer then you will want to get rid of these characters. Using sed is an easy way to filter these away: :r!man man|sed -s "s/_^H//g"

    EXINIT prob

    Adding EXINIT="set ex" to the environment does not always enable loading of the ~/.exrc file. It DOES work on a NeXT running MachOS (a BSD bastardization), but under IRIX it actually *causes* vi to look in the current directory for its init file. The winning answer came from Senthil Kumar (after I figured out the precise syntax): setenv EXINIT "source ~/.exrc"

    Specification of current filename without extension

    For some commands it is useful to specify the current filename. You can specify the current filename with "%" which is useful for many shell commands.
    Q: Is there a way to specify the current filename without the extension?
    A: Yes, use "%<".
    

    Turning off message "Thanks for flying vim"

    When using vim in an xterm it renames the title of that window to "Thanks for flying vim" on exit. Q: How to turn off the message "Thanks for flying vim"? A: :set notitle

    Turning off shell access

    Setting the shell to "/bin/false" is not enough! You must turn off the following things, too:
    • File name expansions in all ex commands.
    • The ex :! and the vi ! commands.
    • The ex ":read !" and ":write !" commands.
    • The ex :shell, :stop and :suspend commands.
    • The vi ^Z command.
    Also, take a look at Secure Editors by Freedman, Sharp & Associates, where you'll find editors binaries for AIX, ULTRIX, HP-UX, IRIX, M88k, OSF1, SunOS, Solaris. There are three editor binaries and one pager binary for each platform that have been modified so that they will not spawn processes or allow the user to work with files other than the initially loaded file. You cannot get out of them via ex or ^Z escapes. Also, the initially loaded file must be specified with a complete pathname on the command line. Secure, non-escapable binaries are provided for:
    • elvis - a vi workalike.
    • mg - a GnuEmacs-like editors.
    • umacs - same as mg, but with key bindings more like Gosling-style Emacs.
    • less - a GNU pager, an improved `more` command.

    Executing a line as a command from the shell

    Ever wanted to tell people which command to execute? Testing it yourself requires you to type in the command again. But with vim's feature of stuffing the contents of a buffer onto the command line this is easier than ever! " Yank the current line into buffer y and execute it map - "yyy:@y^M " Use buffer y buffer y yy yank current line : switch to command line @y^M put contents of buffer y onto command line

    Mappings with if-then-else

    Situation: I want to re-map '0', so that '0' does the same thing as default when the cursor is *not* in the first column. When the cursor *is* in the first column, I what '0' to do what '$' does : moves the cursor to the last column. Q: VIM commands do not have an if-then-else syntax. However, there is a solution for your problem if you use plain vi: map 0 my^V|mzl$`z`y`` Based on the fact that vi doesn't consider a jump to the same character position a jump and thus doesn't reset the previous (``) mark in this case. Because it didn't work on lines of length 0 or 1, I added the l (ell) to make it error out in this case, which should be satisfactory unless you're trying to use this as a subroutine from another macro. Might be able to improve on this if you don't like this. This unfortunately doesn't work under VIM 3.0, even in the compatibility mode. VIM marks are incompatible with vi marks in that Vim apparently doesn't consider a jump to another character position on the same line as a real jump, so doesn't save the previous location in ``. Hope you needed this for real vi! GregUbben@aol.com

    Assigning TAB as the expand key

    Situation: When I hit (tab) to complete a filename all I get is a ctrl-I. My first attempt to fix the problem was to redefine the wildchar variable to a different key (wildchar is the character used to invoke file completion, default is (tab)). I've tried to change the 'wildchar' variable in the .vimrc file, but my attempts have failed: No matter what key I assign to the variable wildchar=0 is what I get after startup. I know that vim is seeing the .vimrc file because I can change other variables. I've also tried to change wildchar using the set command from the : prompt with no luck. A: You must specify the wildchar character with a three character digit decimal equivalent. Using "wildchar=009" will assign the TAB character.

    Modeless vim

    Situation: People seem to prefer "modeless editors". Q: How to make vim modeless. A: There are a few things that vim has which could help make it seem like a modeless editor (if you really want it to :-) - From insert mode, ^O may be hit and then followed by any command-mode command, eg ^Odd as mentioned above. After the command is finished you will be back in insert mode again. - There is a setting 'insertmode', which can be set in your .vimrc or .exrc. If set, then editing files always starts in insert mode. - The cursor keys, page-up, page-down keys work in insert mode as expected.

    Changing colours

    Situation: The blue background looks great on color monitor, but on my notebook I like to have either black or white background. Q: Is there an easy way to change the VIM background color? A: From: Wolfgang Schumacher schumach@cs.tu-berlin.de Here's the _vimrc for my notebook. I hope it helps (proceeding on the assumption that you have an IBM compatible) - or read vim's msdos.doc. The ^[ sequence is the escape character (entered by typing <ctrl>V <esc>): set autoindent nojoinspaces backspace=2 shiftwidth=2 set ignorecase ruler report=0 visualbell set dir=>c:\\tmp nobackup showmatch map g G set t_ti=^[\|79m "invert mode: bwht(15) on red(64) e.g. v set t_so=^[\|14m "standout mode: yel(14) on blk(0) e.g. :set set t_tb=^[\|14m "bold mode: yel(14) on blk(0) e.g. :!ls ^D set t_tp=^[\|07m "normal text: wht(07) on blk(0) set t_se=^[\|07m "normal text: wht(07) on blk(0) " COLOURS background foreground foreground " =============================================================== " 128 blinking + 0 black + 0 black 8 gray " 16 blue 1 blue 9 light blue " 32 green 2 green 10 light green " 48 cyan 3 cyan 11 light cyan " 64 red 4 red 12 light red " 80 magenta 5 magenta 13 light magenta " 96 brown 6 brown 14 yellow " 112 white 7 white 15 bright white

    Disabling suspend

    Situation: I use vim as the editor for composing emails with ELM. ELM somehow loses vim when you suspend it. So I need to disable the suspend command of vim. Q: How to disable the "suspend" with ^z ? A: Remap the ^z to start a shell: map ^Z :shell^M Situation: I do not want the mapping in my vimrc as I only need it with vim when I call it from ELM. Q: So how tell I vim on the command line "use vim with the vimrc, but also disable the suspend"? A: Yes, just put the map command into quotes: vim +"map ^Z :shell^M" file How you get the ^Z and ^M through the shell is up to you :-)

    Definition of abbreviation IDs

    Fact: abbreviations can be of any two types: full-id that consists entirely of id characters (= [0-9a-zA-Z_]), and non-id consisting entirely of non-id characters but the last one. Goal: I would like a set of abbreviations beginning by '\' (for TeX use, and one letter is not enough). Or more generally to be able to include anything (but spaces) in an abbreviation. Answer: VIM 4.0 will let you define ids. Stay tuned!

    Multiple Buffers - show only one at a time

    Q: Is there a way to have multiple files open in vim, but only display one at a time? I'd like to switch back and forth between files without having to quit (save) them. I could put the files in windows, but I want to display only one at a time. A: The main thing you probably want is "set hidden" in your .vimrc, then when you change to a new file, the old one becomes hidden, not saved. ":wa" will write all the buffers.

    DOS setup configuration

    From: schumach@cs.tu-berlin.de (Wolfgang Schumacher) Newsgroups: comp.editors Subject: Re: how to config vim on msdos? Date: 13 Nov 1995 12:34:33 GMT References: <47ks4g$fq@nuscc.nus.sg> >i on ms-dos. i installed a vim 3.0 for msdos. everything is nice except that >i cannot config my vim environment, say _vimrc and _exrc. >i tried many times, both in current directory and root directory, >vim still started up with its own default setting. There are several methods - here are two of them: 1st method: set the environment variable VIM (in autoexec) set VIM=<b>path</b> vim will execute the file _vimrc located in <b>path</b> (<b>path</b> is also the default helpfile location) 2nd method: set the environment variable VIMINIT (in autoexec) set VIMINIT=<b>vi-command(s)</b> when vim starts, it will first execute the vi-command(s) specified by VIMINIT (for instance set VIMINIT=:so c:\bin\vim.ini) Wolfgang

    Weird keyboard layouts

    The key bindings on a Mac keyboard with German layout are: / shift-7 [ alt-5 ? shift-sz \ alt-shift-7 ] alt-6 @ alt-shift-1 { alt-7 ~ alt-control-n } alt-8 Just changing a pair of square brackets with ":s/\[\]/\{\}/" requires you to type the sequence : s shift-7 alt-shift-7 alt-5 alt-shift-7 alt-6 shift-7 alt-shift-7 alt-7 alt-shift-7 alt-9 shift-7 whereas the same thing on an american keyboard is : s / \ [ \ ] / \ shift-[ shift-] / Quite a difference, huh?

    So you people using keyboards with English/American layout should be grateful for ASCII. Now, if we had won the woops ;-)


    Executing commands from a file

    Q: How can I put the editing commands in a file, and have vi read that file to execute it?
    A: If you mean you want to manually execute a certain set of commands like a macro from within vi, put ex commands in a file, then use :source filename to execute them. If you want it to run unattended you can redirect input from a file but it is really better to use sed, awk, or perl for batch operations.


    Vim and Spelling Checkers

    Q: How do you use a spell checker with vim?
    A1: The basic Vi method with a small enhancement by Vim: Use a spell checker on the current file *externally*, that is call "check %" from the command line: :!check % .. where "check" is usually "ispell" or (better) "aspell". As there may be modifications to the current buffer you should ":write" them back to the associated file before that. And after the checker has changed the file you should continue with the changed file, so ":edit!" your file again. Summary: :write :!check % :edit! You can map the check command, of course: map ,c :!check %^M With Vim, all this gets a little easier. First, you can ":set autowrite" which will make Vim ":write" the current file before calling an external program so that current modifications will be written to the associated file before an external command gets to see it. And you can use Vim's angle notation to write the CTRL-M at the end of the mapping in ASCII (&;ltCR>). So this goes into your setup file: set autowrite map ,c :!check %<CR>|:e!<CR>

    A2: You can call a spell checker like "ispell" from vim without a problem. A function to look up a word is included with the command "K". From the "manual" (reference.doc):

    K = Run a program to lookup the identifier under the cursor. The name of the program is given with the 'keywordprg' (kp) option (default is "ref"). The identifier is formed of letters, numbers and the underscore. The identifier under or right of the cursor is used. The same can be done with the command ":!{program} {identifier}". There is an example of a program to use in the tools directory of Vim. It is called 'ref' and does a simple spelling check. {not in Vi} So what you do is get a spell checker, eg "ispell", then you issue the command ":set keywordprg=ispell", and then hit "K" on the word you want to look up, ie "check".

    The underscore command '_'

    Q: I don't see a reason for the command "_" - why is it in vim at all?
    A: It's there for the sake of vi-compatibility. It is used internally for vi commands, so when you type "dd" or "cc" etc, it is internally converted to "d_" or "c_". Hint: If you don't need then you can use it as the first character for mappings.


    Pasting yank buffer into command line Fact: You can record keystrokes to a yank buffer and thus you can put it into the edit buffer. Question: How do you paste a yank buffer into the command line? Answer: Assume that there is something in buffer 'y'. Enter ":@y" then hit return.
    Vim's smartindent option is nice. But there's one thing, I dislike a lot: Whenever you start a line with "#", Vim ignores the current indent and places the # at the begin of line. This is o.k. when editing C-code, but if you're writing shell or awk scripts, # introduces a comment... If I want to write something like if [ $a = "x" ]; then # comment about what's done here I have to indent the # line manually. :-( I don't use vim, but I see where that could be a problem. Even in C/C++-code I don't start lines with # at the first column. The product I work on (Preditor/2) uses one codebase to support multiple platforms (OS/2, Windows and Win95/NT). It uses a multi-platform class library and *lots* of #ifs to do this, many of which are nested. If all of th #ifs start in the 1st column, you easily get hopelessly lost and confused. Therefore I always indent the #ifs just like the rest of th code so it can be read. Yes maybe there should be different types of smartindenting? For the moment you can get around this by putting this in your .vimrc or .exrc file: inoremap # X^H# where ^H is typed as <Ctrl-V><Back-Space>. Strange, most C compilers won't allow the # to be anywhere other than in the first column. I think the ANSI standard requires it to be in the first column. You can of course have spaces/tabs after the '#' and before the "if" or whatever. -Rob.
    In Vim 3.0, * (in the command mode) searches forward for the next occurrence of the *word* that is under the cursor. And # searches backward. If you want to search the word which can be part of another word, you can try the following map map \s wb"zyeo/^["zpbb"zy$u@z^M where ^M is Ctrl-V Ctrl-M do one of the following you should be able to relocate the tmp directory: - set directory=/<pathname> in EXINIT - or, "set directory=/<pathname>" in your .exrc file - or, in a vi session do ":set directory=/<pathname>" where pathname is the location you want to put the temp file.
    I have problems using vi with characters which have an ascii value > 128. For example if I insert ue the editor echoes \334 in insert mode. After leaving the insert mode everything is fine. Also fmt removes all characters with ascii > 128 from the text being formated. You have to define the environment-variable LC_CTYPE. If you are using csh then put in your .cshrc following line: setenv LC_CTYPE=iso_8859_1

    Encryption

    Question: I typed ":Call" on the command line and was prompted with "Enter a key"; so I typed something like "123" and then the text seems to have turned into binary characters. What happened?
    Answer: ''Yep, you've encrypted it! I never knew there was a command ":Call" in vi, but it turns out there is, or is it just ":C"?, and it seems to encrypt your file. To recover it, type "crypt < file", and then enter the password when prompted, assuming you're right about the "123" bit!''
    Could not reproduce this. Maybe because we do not have "crypt()" here. -Sven

    Startup message

    Question: When I open a file with vim via `vim filename' vim sometimes displays a message in its status line: "~/myfile" [textmode] 902 lines, 92498 characters Press RETURN or enter command to continue The window now displays nothing else but this message and you have to press RETURN to start the edit session. This is annoying. But vim does this not every time. Sometimes the initial message is shown, sometimes not. It seems to depend on the file beeing edited somehow, but I don't now in which way.
    Answer: This will happen if the message is long enough to collide with the showcmd area, since this would overwrite the message and vim wants to make sure you got a chance to read it. If the file name is short enough then it knows it won't get overwritten so it won't ask for RETURN. Same thing happens while in vim if you type ":e long-file-name..."

    Yanking current word
    (y) - yank
    Q: How do you put the "current word" into the yank buffer?
    A: Use "wbye".
    "ye" will yank to the end of the current word. But we need to put the cursor onto the beginning first. If the cursor is on the beginning of the word then "b" will go to the beginning of the previous word. So we use "w" to go to the next word first. Result: "wbye"
    [950608, 950828]
    Q: In my .vimrc file I have "set backupdir=>$HOME/.vim-bakup" and it whines and complains. The '>' tells vim to only put backups in that directory without checking anywhere else. Problem is it doesn't work. However, "set backupdir=>/home/philip/.vim-bakup" (which is the same thing, really) works just fine. The vim manual says that $HOME (or ~) will work okay, but apparently I've hit a glitch. Any one know what's up?

    A: Environment variables are only expanded at the start of settings, and unfortunately the ">" at the start means that the "$HOME" isn't quite at the start. This was a teeny-weeny buglet. It has been fixed for the next version.

    Increasing a number with leading zeroes removes all leading zeroes except one. This is a bug" with vim3.0. Vim4.0 should fix this.
    Back to the -> VIM Home Page


    Terminology

    Well, before every good text there need be some definitions. They make it easier for you to understand. Please take the time to read this - I am sure you will benefit from it!
    line
    A sequence of characters. Start: First character after an EOL character (or first character of buffer). End: Next EOL character. The EOL is included.
    running text
    A sequence of consecutive characters.
    block
    A sequence of (full) lines.
    paragraph
    see block
    Hmm, this needs a lot more work...

    Why use "ed"?

    Some uses of "ed":
    ed and diff
    "diff" produces output which "ed" can use to update programs to various version levels (the original poor man's "sccs ).
    "diff3" produces output which "ed" can use to update prog2 to make the same changes as were made to change prog1a into prog1b. This comes in handy when you've several rather similar files in which you need to make corresponding edits.

    ed and sed
    Unlike "sed", "ed" can go both forwards and backwards in a file, allowing some scripting which can't be done with "sed".

    grep
    You can demonstrate where "grep" really came from :)
    	:g/RE/p
    


    URL:         http://www.math.fu-berlin.de/~guckes/vim/answer.html
    URL:         http://www.vim.org/answ.html (mirror)
    Created:     Mon Jan  1 00:00:00 MET 1996
    
    Send feedback on this page to
    Sven Guckes guckes@vim.org