Vi For Smarties

Lesson Seven


Command Mode Macros (:map)

  1. Use :map followed by a space, a key, another space, and a macro definition to map a complex command or series of commands to that key. Not all keys can be mapped with this command. It is best to choose a key which you rarely or never use in your editing. If the command includes any special characters, such as Esc, Enter, Tab, or any Ctrl characters, use a <Ctrl-v> (hold down the Ctrl key and press v) before each special character.
    Example: :map @ I/* <Ctrl-v><Esc>A */<Ctrl-v><Esc>0 followed by hitting Enter will make it so that hitting @ in command mode will insert C style "/* */" comments (without the quotes) around the line which the cursor is on. Vi will go to the beginning of the line, insert a "/* " (without the quotes), hit Esc for you, go the end of the line, append a " */" (without the quotes), hit Esc for you again, then place the cursor back on the beginning of the line and leave you in command mode.
  2. BE VERY CAREFUL! Sometimes macros can become recursive. If you are not an advanced macro user, do NOT attempt to put the key being mapped anywhere inside the actual macro definition itself.
    Example: In the C commenting macro above, you would not want to put the @ symbol anywhere in the rest of the macro.

Insert Mode Abbreviations (:ab)

  1. Use :ab followed by a space, a short abbreviation (no spaces in the abbreviation!), another space, and a definition for the abbreviation to make a macro that will self-expand when typed in insert mode.
    Example: :ab ilv I Love Vi followed by hitting Enter will cause ilv to be a macro which self-expands to the phrase I Love Vi when typed in insert mode. From insert mode, try typing Everyone knows that ilv and I'm proud of it! You will notice that after you type the ilv and hit the spacebar, it expands to the proper phrase.
  2. BE VERY CAREFUL! The same warning that applies to command mode macros also applies to insert mode abbreviations. Sometimes the abbreviation can become recursive.

Customizing Vi (.exrc)

  1. Any of the colon (ed/ex) commands may be put into a setup file in your home directory called .exrc so that you may customize Vi to act however you want without having to type in each setting by hand every time you start the editor. Your .exrc should contain one complete command per line. When entering commands into the file, omit the beginning colon. Thus, a line that would normally begin with :map would instead begin with map when it is in your .exrc file.
  2. Users of the various Vi clones, such as Vim, Nvi, and Elvis, should consult their documentation to see if there is a more appropriate name for the setup file. Vim, for example, uses .vimrc instead.

Until you have mastered everything on this page, you are not ready for Quiz Two.


Copyright © 2001 jerry_y_wang@yahoo.com. All rights reserved.