Tiny Code

Tiny Code


vi macros

Many years ago I learned vi, the visual editor which came with Unix. At the time it was one of two full screen editors readily available on nearly every version of Unix - the other being Emacs. For some reason, the vi commands seemed more intuitive to me. This was probably because I'd previously spent a fair amount of time using a PC editor distributed by IBM called "PE" (which stood for personal editor). In any case, it turned out to be a fortunate choice because vi quickly became available for every computing platform I used. Emacs was also ported to the same platforms but had higher resource requirements (memory and disk space) than I could afford on my hobbyist budget.

I wouldn't recommend anyone not already familiar with vi go through the steep learning curve to learn its somewhat cryptic commands. For those of us who have gone through that painful learning experience, the commands become second nature.

The end result is that I've been using vi for about 20 years and have come up with a few macros I use to save time. These are two character macros which help me perform various operations on blocks of text. My favorite vi port, vim, has many additional commands such as visual block commands which I use frequently. People learning vim and not needing to switch back to a more standard version of vi will probably not find these terribly useful. However I sometimes still need to edit files on Sun servers where vim is not readily available, so I find my macros pretty handy.

Here's a list of the block macros I use most often.

\m - marks beginning of line block
\y - yanks from beginning of line block to current line
\d - deletes from beginning of line block to current line
\p - pastes block previously yanked or deleted to current line
\i - indent block by shiftwidth
\I - indent block by 1 character
\u - unindent block by shiftwidth
\U - unindent block by 1 character

Here are the actual macro definitions. In the following definitions, the ^M is entered by typing a Control-V (which causes the next character to be entered without any special processing) followed by a Control-M (also known as a carriage return).

" delete lines (from mark to cursor pos. - uses b mark, b buffer)
map \d mb"ad'a`b
" indent one shiftwidth (which I have set to 4 characters)
map \i :'a,.>^M
" indent (1 char)
map \I :set sw=1^M:'a,.>^M:set sw=4^M
" mark beginning of a line block (uses the a mark)
map \m ma
" paste lines previously yanked or deleted at cursor pos.
map \p "aP
" unindent one shiftwidth (4 char)
map \u :'a,.<
" unindent (1 char)
map \U :set sw=1^M:'a,.<^M:set sw=4^M
" yank lines (from mark to cursor pos. - uses b mark, b buffer)
map \y mb"ay'a`b

No comments: