Discussion:
vi editor FAQ (Frequently Asked Question List), Part 1/2
(too old to reply)
E. Larry Lidz
2007-04-12 04:26:33 UTC
Permalink
Archive-name: editor-faq/vi/part1
Posting-Frequency: every fifteen days
Last-modified: 2007-04-11
Version: 1.92

vi editor FAQ
-------------

0.0 - Introduction -- How do I use this FAQ?

This document is broken into multiple sections. First, a general
introduction and discussion of what vi is in sections 0 and 1. Section
2 is a collection of "novice" questions, questions that someone without
much experience with vi might ask. These include the differences
between command and insert mode, and continue ending with questions
such as "How do I cut and paste?" Then, section 3 is geared toward the
intermediate vi user. Starting with "How do I do a search and
replace," and continuing onward from there, until it finally ends with
a discussion of vi macros. Also included is a vi quick reference.
This should give a canonical list of vi commands. Next, is a list of
:set commands, all of which can be put into a .exrc file to customize
your editing environment.
The quick reference was confirmed on a machine running SunOS with the
System V distribution of vi. Each command should work under System V and
UCB versions of vi other than the one shipped with SunOS, but I have
not personally confirmed this.
Unless otherwise specified this document assumes that you are in
command mode.
An attempt was made to retain much of the terminology used in the
original vi documentation, whenever I could remember what it was.
Also, I will often refer to regular expressions (often called
regex's). Please look at the man page (man 5 regexp will show it on
most Unix programs) or another reference (the O'Reilly Mastering
Regular Expressions book in the bibliography, for example) for more
information on what they are and what they do. They're really useful,
and it won't be a waste of time. Trust me.

0.1 - Index

First File:

0.0 - Introduction -- How do I use this FAQ?
0.1 - Index
0.2 - Can I distribute this FAQ?
0.3 - What can you do to help out with this faq?
0.4 - Where can I read this FAQ in other languages?
1.0 - What is vi?
1.1 - What is the big deal about vi? Why does anyone use it? More
importantly, why should *I* use it?
1.2 - Wow! This sounds great! Is there any reason not to use vi?
1.3 - What different operating systems is vi available for?
1.4 - Okay, you've convinced me. I'm going to learn vi. Where do I
start?
1.5 - What are some of the vi clones that are available?
2.0 - Learning vi.
2.1 - What games will help me learn vi?
2.2 - What is the difference between Command mode & Insert mode?
2.3 - Wait, my keyboard doesn't have a <Esc> key! What should I do?
2.4 - What are all of those ~s?
2.5 - I can't get used to using hjkl, do you have any suggestions?
2.6 - How do I quit without saving?
2.7 - How do I insert a file?
2.8 - How do I search for text?
2.9 - How do I search for a control sequence?
2.10 - How do I reformat text?
2.11 - How do I copy text?
2.12 - Ahhhh!!! I just hit dG and lost my dissertation! What can I
do? (Or, I've just made a mistake, what should I do?)
2.13 - vi appears to be frozen or acting strange, what can I do?
(Also, I can't get rid of the colon prompt, now what?)
2.14 - I've just written my dissertation and have been told that I
need to have each section in a different file, what should
I do?
2.15 - What's the deal with all of these : commands?
2.16 - Argh! vi has gone crazy! None of the commands work! Now what?
3.0 - How do you do a search and replace?
3.1 - My / key is broken! How can I search and replace?
3.2 - How do I run a program from within vi?
3.3 - Ahhh!! I was writing my dissertation, and the computer crashed!
3.4 - Any tips for making vi programmer friendly?
3.5 - Macros -- How do I write them?
3.6 - How do I make a function key a Macro?
3.7 - Is there anyway to abbreviate text?
3.8 - How do I spell check the current document?
3.9 - How do I get rid the ^M's at the end of each line of my file?
How do I make a macro to do it?
3.10 - I've got a hardcopy terminal, can I still use vi?
3.11 - Oh, okay, is THAT what open mode is? But I don't have a
hardcopy terminal, and it still starts in open mode!
3.12 - How can I get the source code to vi?
4.0 - More advanced topics in vi
4.1 - I see that sections are defined by SHNHH HU and paragraphs by
IPLPPPQPPLIbp by default? What language is that in? What in
the world does it mean?
4.2 - But when I program, I've noticed that I can use ]] and [[
to move between functions. My functions don't have .SH or
anything at the beginning, what gives?
4.3 - How do I work with multiple files at the same time?
4.4 - So, I've started up vi, but now I want to be able to edit another
file. How do I do this?
4.5 - How can I get back to the first file, though?
4.6 - But I'm only wanting to edit one file at a time. I've got one
open and I want to switch permenatly to another file. How do
I do that?
4.7 - How do I add another file into the middle of my current file?

Second File:

5.0 - What's online at the vi archives?
6.0 - Silly vi tricks, and silly macros
6.1 - Silly vi tricks
6.2 - Silly macros
7.0 - Alphabetical vi quick reference
7.1 - Command mode input options ( : commands)
7.2 - set options
8.0 - Setting up .exrc file
8.1 - Sample .exrc file
9.0 - Bugs in vi
10.0 - Glossary of terms
11.0 - Bibliography of Books that cover vi

0.2 - Can I distribute this FAQ?

Yes, as long as you do not alter it in any fashion, or charge any
money for it. If you plan on including it in a book, CDRom, or other
such publication, please contact me first.

0.3 - What can you do to help out with this faq?

First, send me any errors that you may find. Also, any suggestions
that you might have are also appreciated. Better yet, anything that
you think is unclear. My email address is:
***@pobox.com
Also, use vi! Spread the word! I'm sorry I can't list everyone who
has contributed to this faq, as many, many people have given me advice
and helped out, but I fear if I were to, the list of contributors would
become as long as the document itself.

0.4 - Where can I read this FAQ in other languages?

[Note: I've lost my list of other people's translations, if you've
translated the FAQ to another language and your translation is not
listed here, please let me know. ]

Marc Simon (***@astrolabe.frmug.org) has translated the FAQ into
French. It is available at: <http://tux.u-strasbg.fr/vim/vifaq.html>.

Daniel Silva has translated the FAQ into Portuguese. It is available
at: <http://www.linuxdicas.com.br/vifaq.txt>.

If you're interested in translating the FAQ into another language, let
me know, I'm always happy to have it be more widely available. If you
let me know before you start working on it I can make sure you're not
duplicating someone else's efforts.

1.0 - What is vi?

vi is a Visual Editor (hence the name -- vi for VIsual). What is a
visual editor (as opposed to a non-visual one)? Visual editors are
ones that let you see multiple lines of the document that you are
editing as you edit it. This seems pretty common in most editors
today, so the idea of a non-visual editor is a little strange.
Examples of non-visual editors are sed, ex, ed, and edlin (the last one
being the editor shipped with DOS until relatively recently.)
vi was written by William Joy as part of the bsd distribution of
Unix. It was later used by AT&T, and has been standard Unix since.

1.1 - What is the big deal about vi? Why does anyone use it? More
importantly, why should *I* use it?

vi is the default visual editor under Unix, and is therefore shipped
with all recent versions of Unix. (Recent being defined as post 1984
or so.) This means that whenever you run across a machine that is
running a Unix of some sort, you will know that you have a powerful
editor at your finger tips. Why else? vi is a powerful editor. Also,
once you know vi, you can edit files really quickly, as it is extremely
economical with the keystrokes. Due to its different modes for
inserting and issuing commands, it is much faster than most non-mode
based editors. It is also a very small editor. (The version on my
machine is 200k) Also, it can do almost anything, as long as you know
how to get it to do what you want.
Furthermore, as an editor it allows a lot of interaction with the
Unix operating system. It allows you to use many of the powerful Unix
utilities from within vi. It's possible to, from within vi, kill off a
list of specific processes that you want to kill. If you haven't given
yourself permission to write to the file you're editing by accident, you
can change the permission without leaving vi.
vi works by having commands that work on objects. By learning only a
few commands and a few objects you can learn how to do a lot of things,
simply by combining the commands and the objects. Even the commands are
separated into subcategories. For example, the movement commands and
the modification commands are different. If you know that d is the
command to delete, and j is the command to go down a line, and you know
how to combine them (dj), you can delete down one line. When you use
numbers it gets even more powerful. d5j will delete 5 lines below you.
Then, once you learn the character for "paragraph" (}), you already
know how to delete 5 paragraphs.


1.2 - Wow! This sounds great! Is there any reason not to use vi?

Yes. There is a very good reason. It can be somewhat hard to learn,
and until you do so, it will be slow and painful. Once you learn it,
it will be faster, but the process of learning it is slow. I've been
asked if vi was an easy editor to learn, whether it was intuitive or
not. My general response to this question is: "Yes, some of us think
so. But most people think that we are crazy."

1.3 - What different operating systems is vi available for?

Unix. That's it. (Well, technically, the 4.3BSD version included
support for VMS as well.) However, there are many, many clones of vi
that are available for different operating systems. I personally have
used vi clones under: Unix, Dos, OS/2, Mac System 7. (See below for a
list of specifics.)

1.4 - Okay, you've convinced me. I'm going to learn vi. Where do I
start?

Well... That's a tricky one. There are many good books out there
that cover vi; most books on Unix have at least one chapter devoted to
it. There are also many books devoted specifically to vi. I don't
have any preference, so your best bet might be to ask your local vi
guru where they learned. Also, play around. Fire up vi with a
non-important document (your dissertation is NOT a good document to
learn vi with...) and play around. I can't imagine anyone learning vi
without playing around with it quite a bit. Remember, if you get
confused, just hit the Escape key a couple of times, and you'll be in
command mode again.
I should mention at some point, and I guess here is as good a place
as any, that people who think they might want to do Unix system
administration, or any type of configuration of Unix machines will
probably also want to learn ed or ex, as some versions of Unix do not
put vi in the root partition, and one might be stranded without it at
some point. Ed is a good choice.

1.5 - What are some of the vi clones that are available?

Just to list a few: STvi (STevie), elvis, vile, vim, and nvi, xvi.

elvis is available for: Amiga, DOS, OS/2, Unix, VMS, Atari,
Psion3a Handheld.

Stratus machines running VOS can get elvis at:
ftp://ftp.stratus.com/pub/vos/tools/tools.html

Lemmy is available for Win95/NT at:
http://www.accessone.com/~jai

nvi is the vi that ships with BSD 4.4.

STevie is available for: Atari ST, DOS, Unix, Macintosh.
MacOS is available at any info-mac mirror in /info-mac/text
(Such as ftp://ftp.hawaii.edu/pub/mac/info-mac/text)
Stratus machines running VOS can get STevie at:
ftp://ftp.stratus.com/pub/vos/tools/tools.html


vile is available for: BeOS, DOS, OS/2, Unix, VMS, Window95, WindowsNT
The source is available at: http://www.vile.cx.
xvile, a X-windows aware version of vile exists, as well.

Vim is available for: AmigaOS, Atari MiNT, BeOS, DOS, MacOS,
OS/2, Unix, VMS, Windows
General information, documentation and much more about Vim is on
http://www.vim.org/ The Vim Pages
A list of sites which mirror Vim is available at:
http://www.vim.org/dist.html Vim Distribution Page
There are three mailing list for Vim:
"VIM announcements list" vim-***@vim.org
"VIM help mailing list" ***@vim.org
"VIM development list" vim-***@vim.org
Information on subscription is on page
http://www.vim.org/mail.html

viper is available for GNU Emacs.
ftp://ftp.cs.sunysb.edu/pub/TechReports/kifer/viper.tar.Z

xvi is available for: DOS, Unix.

Mortice Kern Systems (***@mks.com), who I have absolutely no
affiliation with, offers a commercial version of vi for DOS/Windows,
OS/2, and WindowsNT. It is included as part of the MKS Toolkit (a set
of Unix-like tools for Windows) and cannot be purchased separately.

There are some differences between the different vi clones. Many
offer improvements, but most still allow the commands that are listed
in this document, but there may be some differences. Refer to the
documentation that comes with the clone for details.

2.0 - Learning vi.

These are some basic hints for the novice vi user. First, keep a
command summary with you at all times. A quick reference guide/command
summary is included later on. Second, get a good book that covers vi.
This document is not the best way to learn it (at least not yet.) I'm
not sure if this document should teach people to to use vi from
scratch, as there are many good books on it already. However, there
are hints here. As for choosing a book, the standard rules apply:
look at it before buying it. See if any of it makes sense to you.
Make sure that it has exercises that you can practice with. Compare it
with other books -- after all, vi can be very confusing, and you want
to make sure that it is the book that is confusing, and not just that
you underestimated the difficulty of learning vi.
Also, seek out vilearn or vitutor, programs designed to teach you the
basics of vi.

2.1 - What games will help me learn vi?

This may seem a bit silly, but there are many games on Unix systems
that can help you learn to use vi. These help particularly with the
basics. Although I don't know of any games that help with every vi
command, I do know of a few that will help you learn to use hjkl to
move the cursor around. NetHack, a rogue-like game, is particularly
good for this, as it is a large game and can be entertaining for quite
some time. Nethack is available from ftp.uu.net in /pub/games/nethack.
Not to make the other games sound worse, but some other ones are:
rogue, moria, omega, worm, and snake.

Another fun thing to do to learn vi better is to play a game with
friends to figure out the least number of vi keystrokes needed to do a
specific task in vi.

2.2 - What is the difference between Command mode & Insert mode?

Often cited as one of the main problems with vi, and equally often
cited as being one of its best strengths, vi differentiates between a
"Command mode" and an "Insert mode." Understanding this difference is
VITAL to learning vi. When one starts vi it starts in command mode.
In this mode, one can move around the file, and issue commands to
change certain areas of the text, cut, copy and paste sections of the
text and do much more. Insert mode is where one can actually insert
text. In other words, command mode is used to move around the
document, and insert mode is used to type text into the document.
Commands such as: a, i, c, C, O, o and others will switch one from
command mode to insert mode.
<Esc> or <ctrl-c> will take one out of insert mode and return one to
command mode.
Get used to this distinction. It is one of the things that makes vi
different from most other editors. It also allows one to do a lot of
things without taking one's hands from the standard keyboard position.
For novices it is often nice to know what mode you are in. If you
type: "echo set showmode >> $HOME/.exrc" at the Unix command line, it
will make it so that each time vi is started it will default to showing
the mode on the bottom right of the screen. (To understand what this
is doing, see the sections on "setting up a .exrc" and the "set
options.") If it does not show anything in the bottom right, it means
that you are in command mode. I call a few different modes (append,
open and insert) "insert mode" in this document.

2.3 - Wait, my keyboard doesn't have a <Esc> key! What should I do?

Try hitting <ctrl-[> instead. If your keyboard has a <Meta> key, try
that. If you don't have a <Meta> key, many keyboards use <Alt>,
<Diamond>, <Start> or <Menu> as a <Meta> key (however, if you've got
any of those keys, you almost certainly have an <Esc> key). If neither
of these work, try <ctrl-3>. Some DEC terminals use the F11 key as
escape.

2.4 - What are all of those ~s?

They're just there to let you know where the bottom of your file is,
they are not actually in your document, and you do not need to worry
about them.

2.5 - I can't get used to using hjkl, do you have any suggestions?

First, if your terminal is set properly and you have a good
connection, you should be able to use the arrow keys. However, if you
think that you will be using vi a lot, then it makes sense to learn
hjkl, as they are faster to type. Also, there are occasions where you
may have a bad connection and the ESC sequences may get lost.
Here is a simple mnemonic to help remember this: j extends below the
line, and k above the line when written by hand.

2.6 - How do I quit without saving?

:q! will do it.

2.7 - How do I insert a file?

:r <filename>

For example, to insert the file /etc/motd, type: :r /etc/motd

This will insert the file at the current location in the file you are
working on. If you specify a number before the r, it will insert it at
that location in the file.

2.8 - How do I search for text?

/<text> will search forward. ?<text> will search backwards. ?? or
// will repeat the last search. It is worth noting that these are
pretty much standard in Unix. In addition, in vi, n will repeat the
last search in the same direction as the original search. N will
repeat the last search pattern in the opposite direction of the
original search. For example /foo will find the next occurrence of "foo"
from where you are. n will find the one after that. N will take you to
the first occurrence. Hitting N a second time will get the same result
as ?foo would have in the first place.

Regular Expressions may be used within searches.

2.9 - How do I search for a control sequence?

/<ctrl-v><ctrl-<seq>>

<ctrl-v> will tell vi to take the next character literally, and not to take
it as a command.

2.10 - How do I reformat text?

If your computer has the program fmt on it, all you need to do is
type !}fmt from command mode (without a : before it). This will
reformat the text from the current location until the end of the
paragraph. If your machine does not have fmt, you need to find a
similar program. (I gather there are many such programs available from
the public domain, but I do not know much about them.)

You may also want to look into par. Par is similar to fmt in
function, but has more feature. Par can be downloaded from:
http://www.cs.berkeley.edu/~amc/Par.

2.11 - How do I copy text?

Okay, this might be a bit complicated. Take from this section what
you can, and reread it a few times. Also, experiment.
"<letter>yy will copy one line of text into register <letter>. (A
register is vi-lingo for a place to store data that was cut or copied.)
<letter> must be between a and z. "<letter>dd will delete one line and
place it in register <letter>. You may use a number before the yy or
dd to specify the number of lines. Using an uppercase <letter> will
append the text into the register leaving what was there before.
"<letter>p will put the text after the cursor. "<letter>P will put it
before the cursor. If the register contains the beginning or end of a
line, the line will be placed on another line as appropriate. Y may be
used as a short cut for yy. In addition, y$, yH, yM, etc. are valid,
as are the equivalent d commands. For quick cuts and pastes, no
register need be specified. In this case, no appending is allowed, and
the register will be removed if another delete command is given.
(Including x).
For example, to move the previous paragraph, one would go to the top
of the paragraph, type "a13dd, move to the position in which one wishes
to put the paragraph, and then type "ap to put it below the current
line.
Now, presumably you want to be able to cut and paste into areas that
are not just the end of the line. In order to do this, use m<letter>
to mark an area. This letter may be the same as a cut/copy register,
they are stored in different area of memory. Then, type "<register>[y
or d]`<letter>. Where <register> is the register to put the text into,
<letter> is the letter used to mark, and y or d as appropriate.

2.12 - Ahhhh!!! I just hit dG and lost my dissertation! What can I
do? (Or, I've just made a mistake, what should I do?)

u will undo the last command. U will undo changes to the current
line. (Granted, a one line dissertation would not be much.) :e! will
reload the current document without saving any changes. In addition,
deleted text gets stored in the registers numbered from 1 to 9. "<n>p
will put the last nth deletion. You can quickly search the registers
by trying one, hitting u, and trying the next. (In order to expedite
this, vi uses . slightly differently than normal. Instead of repeating
the last command, it will try the next register, so all you need to do
is: "1p u . u ., etc. until you undo the delete you want to undo.)

2.13 - vi appears to be frozen or acting strange, what can I do?
(Also, I can't get rid of the colon prompt, now what?)

If vi appears to have frozen, make sure that you haven't hit <ctrl-S>
by mistake. In order to undo a <ctrl-s>, hit <ctrl-q>.
If there is a colon and you can't get rid of it, you've entered ex by
accident. Generally this happens by hitting "Q" from command mode.
Just type vi to get back into vi.

2.14 - I've just written my dissertation and have been told that I need
to have each section in a different file, what should I do?

:[m],[n]w <filename> will save between lines m and n to <filename>.
This line numbering method works for almost every : command. If you
use :[m],[n]w >> <filename> it will append it to the file.

2.15 - What's the deal with all of these : commands?

The commands that follow a : are commands from the ex editor. These
allow a lot of flexibility and power. For example, there are many
different ways to search and replace, all of which have some
similarities (in fact, they are in some ways the same...)

2.16 - Argh! vi has gone crazy! None of the commands work! Now what?

The most common time for vi to act insane when it comes to typing is
when the caps lock key has accidentally been hit. Many keyboards on
Unix servers have caps lock and control in the opposite position from
many PCs, causing people to occasionally hit it. Just for fun, try
navigating in vi with the caps lock on sometime.

3.0 - How do you do a search and replace?

Well, there are a few methods. The simplest is:

:s/old/new/g
But, this only does it on the current line... So:
:%s/old/new/g
In general:
:[range]s/old/new/[cgi]

Where [range] is any line range, including line numbers, $ (end of
file), . (current location), % (current file), or just two numbers with
a comma or semicolon between them. (Or even: .,+5 to mean the next
five lines).

[cgi] is either c, g, i, or nothing. c tells vi to prompt you before
the changes, g to change all of the occurrences on a line. (type yes
to tell vi to change it.) i tells vi to be case insensitive on the
search. The g after the last slash tells it to replace more than just
the first occurrence on each line.

Another method is:
:g/foobar/s/bar/baz/g This searches for foobar, and changes it to
foobaz. It will leave jailbars alone, which the other method will not.
Unfortunately, if jailbars appears on the same line as foobar, it will
change, too.

Of course you can also use regular expression search patterns, and a
few other commands in the replacement part of the text. If you use \(
and \) in the pattern to escape a sequence (and use \1, \2, etc., you
can do lots of nifty things.

For example:
:g/foo/s/^\([^ ]*\) \([^ ]*\)/\2 \1/
will swap the first and second words on every line containing "foo".

Special sequences allowed are:
& everything which was matched by the search
\[1-9] The contents of the 1st-9th \(\) pair
\u The next character will be made uppercase
\U The characters until \e or \E will be made uppercase
\l The next character will be made lowercase
\L The characters until \e or \E will be made lowercase
\[eE] end the selection for making upper or lowercase


3.1 - My / key is broken! How can I search and replace?

Well, okay, it doesn't really need to be a /. Lots of things will
work fine. (letters, numbers and a few other things won't...)

3.2 - How do I run a program from within vi?

:!cmd will run the program cmd. :sh will run an interactive shell.
Within this shell, you may, if you want, run vi again. This is
particularly useful when you are editing makefiles and config files for
programs in an attempt to get a program to compile. The advantage over
:e is that you do not need to save the file, and it will be in its old
place when you exit the shell. (I advise saving the file anyway...)

3.3 - Ahhh!! I was writing my dissertation, and the computer crashed!

Well, you should get mail about this, but you should be able to
recover the file by typing vi -r <filename> where <filename> is the
name of the file that you were editing at the time of the crash. vi -r
will give you a list of files that can be recovered.

3.4 - Any tips for making vi programmer friendly?

:set ai will make it auto-indent for you.
:set sw=# where # is a number will set the shiftwidth (tabwidth).
You can then use <<, >> to shift a line left or right. Plus, you
can use <% to shift a {, ( or [ set left or right (with >%).
You must be on top of the specific {, }, (, ), [ or ] of the pair
to shift them.
:set sm will show the matching {, ( or [ when you type the closing
one.
:set lisp will make some changes that are useful for lisp
programming. () will move back and forth over s-expressions, and {}
will move without stopping at atoms.

3.5 - Macros -- How do I write them?

:map <lhs> <rhs> where <lhs> is up to ten characters and <rhs> is up
to 100. This will make it so that whenever you type <lhs> it will
replace it with <rhs>. All macros should start in command mode (except
those defined with map!), but may end in any mode you desire. Remember
to use <ctrl-v> before any control characters that you may use.
If you are using an Ex command, such as |, it needs to be escaped
while vi is scanning the line. You should map it as :map foo
<ctrl-v><ctrl-v>|.
:unmap <lhs> will remove the macro. :map! <lhs> <rhs> will make
<lhs> insert <rhs> into the text of the document. map! macros may have
lhs's that are much longer.

3.6 - How do I make a function key a Macro?

If <lhs> is #n where n is 0-9, it will be mapped to the appropriate
function key.

3.7 - Is there anyway to abbreviate text?

Yep, of course. This is vi, it can do anything. :ab email
***@pobox.com will make it so that whenever you type email as
a specific word, it will extend it to the entire unabbreviated
word. :una email will unabbreviate it.

3.8 - How do I spell check the current document?

Here is a macro to do it. These should be put in your .exrc file.
(More on .exrc files later on.) It is a pretty simple macro, it just
calls ispell on the current file. Of course, to use this you need
ispell on your system. To use it, just hit V with vi. (V is not used
by vi, so it makes a good key.)

map V :w<enter>:!ispell % <enter>:e!<enter><enter>

The second <enter> makes it so that one does not need to hit return
after it is done checking the spelling.

3.9 - How do I get rid the ^M's at the end of each line of my file?
How do I make a macro to do it?

These generally appear from DOS files that get converted to Unix.
They're easy to get rid of.
:%s/<ctrl-v><enter>//g will do it.

The macro bit is a bit trickier. Not something that most people can
guess on their own. Here it is:
map v :%s/<ctrl-v><ctrl-v><ctrl-v><ctrl-v><ctrl-v><enter>//g

Yes, that's right. 5 of them. The last one is to escape the enter.
Two of the other four are to escape the other two <ctrl-v>'s. Since the
macro gets read on the ex line, you need to have two <ctrl-v>'s (since you
are searching for <ctrl-v> <enter> to replace it with nothing...)

In general, if you are having trouble with a macro that uses the ex
line, you need to escape things a lot. Sometimes it is quicker to just
keep throwing <ctrl-v>'s in until it works.

3.10 - I've got a hardcopy terminal, can I still use vi?

Okay, okay, so I don't expect anyone to actually ask this... But, I
thought it was bizarre enough to throw in anyway. (And, it actually
answers a very common question...)
vi will start up in a specific mode, called "open mode" in this
situation. Things work more or less the same. Deleted characters will
appear on your print out as \'s. vi will act as if the size of the
window is only one line. ^r will retype the current line. z redraws
the window around the current line.

3.11 - Oh, okay, is THAT what open mode is? But I don't have a
hardcopy terminal, and it still starts in open mode!

Well, what is happening here is that vi doesn't know what type of
terminal you have. It decides that in this situation the best thing to
do is to assume that you have the worst terminal possible. This might
not seem useful, as not very many people need open mode, but it also is
the mode that needs to know the least information about your terminal.
Now, how to deal with it. It is possible to change it for the
specific session, but in general, this is not useful. If you know
your terminal type, you can set it from the Unix prompt (setenv TERM
<termtype> under csh and it's variants, and: TERM=<termtype> ; export
TERM under sh and its variants.).
Better yet would be to edit your .profile or .cshrc to include this so
it is automatically done for you when you login. (Of course, you need
to either know ed or be able to set it at the Unix prompt before you'll
be able to edit the file...)
If you do not know your terminal type, try vt100. Most modern
terminals and terminal emulators can emulate vt100. If this does not
work, find someone to help you.

3.12 - How can I get the source code to vi?

The source code to the original vi is available from:
<http://ex-vi.berlios.de>.

You may also want to look at the source for some of the various vi
clones.

4.0 - More advanced topics in vi.

4.1 - I see that sections are defined by SHNHH HU and paragraphs by
IPLPPPQPPLIbp by default? What language is that in? What in the world
does it mean?

Man pages are written in a language called nroff/troff. Nroff is a
general purpose text formatting language, similar to TeX. What does
this have to do with vi and the sections? Use the Unix more command to
look at a man page (say, /usr/man/man1/vi.1 or something). You'll see
parts of the page split into sections, like .SH Name. The .SH is
defining a section of the man page. Notice that SH is the first two
characters of the section set option.
The section and paragraph sections are defined by a listing of pairs
of macros for nroff/troff. The next section will start with a period
and then any of the pairs of letters that the section is defined as.
Paragraphs work the same way -- except that a blank line is also
considered a paragraph break.

4.2 - But when I program, I've noticed that I can use ]] and [[ to move
between functions. My functions don't have .SH or anything at the
beginning, what gives?

Luckily for many C programmers, an open curly brace at the beginning
of a line is also defined as a section break.

4.3 - How do I work with multiple files at the same time?

vi allows for multiple files to be open at the same time. Unlike many
editors, you only see one file at a time. If you start vi with multiple
files on the command line they'll all be opened up. You'll start out in
the first file, and you can move to the next file by typing :n. If
you've made changes to the current file that you don't want to keep,
you can go on by using :n!. Note that this will discard any changes
that you've made. If you want to save, you need to use :w first.

4.4 - So, I've started up vi, but now I want to be able to edit another
file. How do I do this?

:n <filename> will load that file into vi. You'll need to save your
current file.

4.5 - How can I get back to the first file, though?

:e # will edit the last file that you were editing. You can use this
to swap back and forth quickly between two different files. If you are
editing many files, you can use :n to cycle between them.

4.6 - But I'm only wanting to edit one file at a time. I've got one
open and I want to switch permanently to another file. How do I do that?

Just use :e <filename> and it will load it up.

4.7 - How do I add another file into the middle of my current file?

:r <filename> will read in a new file at the current location. It is
worth noting that Unix in general deals with the output of commands as
files in many respects. Because of this, you can easily read in the
output of a command into the file: :r !<command> will read in the
output.

Copyright, E. Larry Lidz, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
2002, 2003, 2004, 2005, 2006, 2007.
All Rights Reserved.
E. Larry Lidz
2007-04-12 04:26:33 UTC
Permalink
Archive-name: editor-faq/vi/part2
Posting-Frequency: every fifteen days
Last-modified: 2007-04-11
Version: 1.92

5.0 - What's online at the vi archives?

There is a FAQ posted frequently which gives a list of all the files
that are online at the vi archive. It also gives a list of addresses
which mirror the vi archive. The main address is ftp://alf.uib.no/pub/vi, but it is
archived at many, many sites. The vi-archive faq lists all of them.
Please check that faq before ftping to it, as there is almost definitely
a closer and therefore faster site to you than the one in Norway.
A few mirrors are: ftp://ftp.uwp.edu/pub/vi
ftp://ftp.uu.net/pub/text-processing/vi.
ftp://ftp.cc.monash.edu.au/pub/vi
ftp://ftp.s.u-tokyo.ac.jp/misc/vi-archive
The site has many, many files on vi, including a few clones. It also
has the UCB distribution of vi, and lots of useful macros. Check it
out.

6.0 - Silly vi tricks, and silly macros

This section is for silly vi tricks, and silly macros. Actually, any
interesting vi tricks and macros are acceptable, as long as they are
not too lengthy. I will add any that are suggested to me that I think
are reasonable.

6.1 - Silly vi tricks
Note: Also check out the Silly macros down below. Many macros and
tricks are interchangeable.

xp This will delete the character under the cursor, and put it
afterwards. In other words, it swaps the location of two characters.

ddp Similar to xp, but swapping lines.

yyp duplicate a line

uu Undo and redo last change. (This will take you to the last
modification to the file without changing anything.) You can also use
this to compare the changes to a line. Make the changes to the line,
press U to undo the changes to the current line, and then press u to
toggle between the two versions.

:g/.*/m0
This will reverse the order of the lines in the current file.
m0 is the ex command to move the line to line 0.

:v/./d or :g/^$/d
Removes all blank lines.

:g/^[ <ctrl-v><tab>]*$/d
Removes all lines that only have whitespace.

:v/./$s/$/<ctrl-v><enter>./|'';/./-1j|$d
Replaces multiple blank lines with just one blank line.

6.2 - Silly macros
Note: <ctrl-x> means hold down control, and hit x.

Swap character and one vertically above:
map * kxjphxkP

Fold a line that's too long
map g $80<ctrl-v><ctrl-v>|F r<ctrl-v><enter>

Change case on most words
map v ywmno<ctrl-v><esc>P:s/./\~/g<ctrl-v><enter>0"nDdd`***@n

Put `and' around the current word
map *` i`<ctrl-v><esc>ea'<ctrl-v><esc>

Put 'and' around the current word
map *' i'<ctrl-v><esc>ea'<ctrl-v><esc>

Put "and" around the current word
map *" i"<ctrl-v><esc>ea"<ctrl-v><esc>

Put `and' around the current word
map! `` <ctrl-v><esc>bi`<ctrl-v><esc>ea'

Split a line at the cursor, and put a > at the beginning of the next
line. (For quoting Usenet, etc). I had some trouble with my old
version of this under some versions, so I've redone it, and I think
that it should work.
map g may0O<ctrl-v><esc>P`ao<ctrl-v><esc>P:s/./ /g<ctrl-v><enter>0i><ctrl-v><esc>$mb`ay$`bP'add

Insert one character
map g i$<ctrl-v><esc>r

Format a paragraph without the fmt program. (To use, use J a few
times, then this a few times)
map K 072lBhr<ctrl-v><enter>

Or, a little less elegantly, but without the need to use J and K
multiple times.
map K {wma}b:'a,.j<ctrl-v><enter>:s/\(.........................................................\)/\1<ctrl-v><ctrl-v><ctrl-v><enter>/g<ctrl-v><enter>

Make ctrl-x work as cut, ctrl-v as paste, ctrl-p as copy. You should
mark the beginning of the area as m (use mm). (ctrl-c cannot be
remapped when it is defined as the interrupt character in Unix.)
map <ctrl-v><ctrl-x> "zd`m
map <ctrl-v><ctrl-p> "zy`m
map <ctrl-v><ctrl-v><ctrl-v><ctrl-v> "zP`m

Save a read-only file. Careful, it changes the permissions. When
done, it changes them to read/write owner, read for everyone else. Note
that this might not be the same as the original permissions.
map K :!chmod 666 %<ctrl-v><enter>:w!<ctrl-v><enter><ctrl-v><enter>
:!chmod 644 %<ctrl-v><enter>

vi status line (sort of...) [Note: It's slow...]
map <ctrl-v><up-arrow> k<ctrl-v><ctrl-g>
map <ctrl-v><down-arrow> j<ctrl-v><ctrl-g>
map k k<ctrl-v><ctrl-g>
map j j<ctrl-v><ctrl-g>
map <ctrl-v><ctrl-f> <ctrl-v><ctrl-f><ctrl-v><ctrl-g>
map <ctrl-v><ctrl-b> <ctrl-v><ctrl-b><ctrl-v><ctrl-g>
map H H<ctrl-v><ctrl-g>
map M M<ctrl-v><ctrl-g>
map L L<ctrl-v><ctrl-g>
map G G<ctrl-v><ctrl-g>
map <ctrl-v><ctrl-u> <ctrl-v><ctrl-u><ctrl-v><ctrl-g>
map <ctrl-v><ctrl-d> <ctrl-v><ctrl-d><ctrl-v><ctrl-g>

center a line
map = 080i <ctrl-v><esc>$78hd0^D:s/ / /g<ctrl-v><enter>$p

redefine tab to insert 5 spaces instead of a tab marker
map! <ctrl-v><ctrl-i> <space><space><space><space><space>

switch current and last line (repeat to reverse a file)
map v Gdd''Pj

yank until end of line, run it in a shell and read in the result
map v y$o<ctrl-v><esc>pI:r!<ctrl-v><esc>"***@a

allow vi to backspace over text that was inserted in a previous
insert mode
map! <ctrl-v><ctrl-?> $<ctrl-v><esc>Xs
map! <ctrl-v><ctrl-h> $<ctrl-v><esc>Xs

print the document to the default printer (for BSD replace lp with lpr).
map v 1G!Glp<ctrl-v><enter>u

set # to toggle line numbers on and off:
map \o# o:se nu<ctrl-v><enter>:se nonu<ctrl-v><esc>-:map \o# "wp<ctrl-v><enter>
map \d# "w2dd
map \x# "***@x"xpk
map # ma3L\o#\x#\d#`a:<ctrl-v><enter>

Quote the current paragraph with '>'s.
map Z> mc{jma}kmb:'a,'bs/^ /> /<ctrl-v><enter>'c

Allow <ctrl-z> to suspend processes within insert mode
map! <ctrl-v><ctrl-z> <ctrl-v<esc>:stop<ctrl-v><enter>
Make all tabs spaces
map! <ctrl-v><ctrl-v><ctrl-v><ctrl-i> <ctrl-v><ctrl-v><space>

Replace all tabs with the proper amount of spaces for the given
tabstop. Removing the last two character (4<enter>) will allow you to
specify the tabstop: #t4<enter>
map #t 1G!Gpr -t -e4<ctrl-v><enter>
map #T !}pr -t -e4<ctrl-v><enter>}

Insert a ruler above the current line
map #r O<ctrl-v><esc>i....+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8<ctrl-v><esc>

This is a macro that redefines itself: (more for heuristic reasons
than anything else) It inserts foo the first time it is run, and bar
all subsequent times.
map K ifoo<ctrl-v><esc>:map K ibar<ctrl-v><ctrl-v><ctrl-v><esc><ctrl-v><enter>

This makes end notes. It will insert a [#] at the current location
and put a [#] at the bottom of the document and let you type there.
Hitting `a will take you back to the original location once you are
done with your end note. [#] will be the number of the end note, not
the literal # character. (Pretty crazy, huh?)
map K ma1GO[0]<ctrl-v><esc>G$?\[[0-9]*\]<ctrl-v><enter>lyt]`aa<ctrl-v><enter><ctrl-v><esc>O<ctrl-v><esc>pI:r!echo '1 <ctrl-v><esc>A + p' <ctrl-v><ctrl-v>| dc<ctrl-v><ctrl-v><ctrl-v><ctrl-v><ctrl-v><ctrl-v><ctrl-v><enter><ctrl-v><esc>0"***@y0i[<ctrl-v><esc>A]<ctrl-v><esc>kkJJJmb1Gdd`bF[yf]Go<ctrl-v><esc>pA

7.0 - Alphabetical vi quick reference

... means that something needs to be specified before or after the
command, as appropriate. This is normally a cursor movement
key (h,j,k,l,w,b, etc.) or a line number.

# (where # is a number) following command n times...
: go to ex-mode
) next sentence
( previous sentence
} next paragraph
{ previous paragraph
]] next section
[[ previous section
0 beginning of line
$ end of line
^ first non-whitespace character
+ first character of next line
- first character of previous line
(spacebar) next character
(return) next line
/ search forward
? search backward
% find match of current parenthesis, brace, or bracket
, reverse direction of last f, F, t, or T
; repeat last f, F, t, or T
. repeat last command
` goto mark
' goto beginning of line with mark
`` return to previous mark or location before a search
'' go to start of line of previous mark or location before search
~ switch case of current character
" store in register
@ execute command in register
! send next to command, replace output (eg !}fmt passes the current
paragraph to the command fmt, and replaces the output with
whatever fmt returns.)
!! send line to command
shift line one shiftwidth to the right
<< shift line one shiftwidth to the left
% shift until matching (, [, or { to the right
<% shift until matching (, [, or { to the left
a append after the current location
A append at the end of the line
^a unused
b beginning of previous word
B beginning of previous word, ignore punctuation
^b scroll back one screen
c change until...
C change to end of line
^c ends insert mode, unused in command mode (if defined as interrupt)
d delete until...
D delete to end of line
^d scroll down half a window, moves to previous shiftwidth in insert
mode
e end of word
E end of word, ignore punctuation
^e scroll screen down one line
f find...
F find backward...
^f scroll forward one screen
g unused
G ...Goto [defaults to end of file]
^g show status line
h left
H first line on screen
^h backspace in insert mode, left in command mode
i insert before current location
I insert before first non-whitespace character on line
^i tab in insert, unused in command
j down
J join next line with current line
^j down in command, create newline in insert
k up
K unused
^k unused
l right
L last line on screen
^l redraw screen
m mark position into register
M middle of screen
^m carriage return
n repeat last search
N repeat last search, reverse direction
^n down in command
o open line below current
O open line above current
^o unused
p put below current line
P put above current line
^p up in command
q unused
Q quit and run ex
^q unused
r replace current character
R replace characters until insert mode is left
^r redraw screen in command mode
s substitute
S substitute entire line
^s unused
t to...
T backward to...
^t moves to next shiftwidth.
u undo last change
U undo changes to current line
^u scroll up half a window
v unused
V unused
^v unused in command, quotes next character in insert
w beginning of next word
W beginning of next word, ignore punctuation
^w unused in command, in insert move back to beginning of previous
word
x delete current character
X delete previous character
^x unused
y yank...
Y yank current line
^y scroll screen up one line
z reposition screen around line (Return to top of screen, . to
middle, - to bottom)
ZZ write (only if changes have been made) and quit
^z unused

7.1 - Command mode input options ( : commands)

(Note: this is not a canonical list, just some of the more important
ones.)

:r <file> read <file> into current text
:r !<command> read output from command <command> into current text
:nr <file> read in at line number
:!<file> run command, return
:sh goto shell
:so <file> read and execute commands from <file>
:x write (only if changes have been made) and quit
:wq write and quit
:l1,l2w <file> write between lines l1 and l2 to <file>. If <file>
is not specified, assume current. If l1,l2 not
specified, assume entire file (making it :w)
:w >> <file> append to <file>. May use line numbers
:w! overwrite current file
:q quit
:q! quit, forget changes
:e <file> edit <file> without leaving vi
:e! forget changes since last write
:n edit next file
:e +n <file> edit <file> at line n, if no end, assume end of file
:n <files> specify <files> as new list of files to edit
:e# edit alternate file (if :e <file> is used, alternate is
the original file)
:args show files to be edited
:rew rewind list of files to top
:map m n create a macro (make m do n)
:map! m n create an insert mode macro (make m do n)
:unmap m destroy macro m
:unmap! m destroy insert mode macro m
:ab <1> <2> abbreviate - replace <1> with <2> whenever typed as
a word
:unab <1> unabbreviate <1>
:cd <directory> cd to <directory>
:set <option> set <option>...

7.2 - set options

The abbreviations in parenthesis may be used. Syntax:

:set <option> <param> (If <param> is expected)
Multiple options may be specified on one line.
:set <option>? displays the value of the <option>
:set all displays the value of all the options.
For options without a value, set no<option> turns it off.

Option: Default: What it does:

autoindent (ai) noai Makes new lines automatically
indent to the position as the
line above or below
autoprint (ap) ap Display changes after each
command
autowrite (aw) noaw Automatically save file
before :n, :!
beautify (bf) nobf Ignore all control characters
during input (except tab,
newline, formfeed)
directory= (dir=) /tmp Name of the directory to store
buffer
edcompatible noedcompatible Use ed-like features on
substitute
errorbells (eb) errorbells Sound bell on error
exrc (ex) noexrc Allow .exrc files outside home
dir
hardtabs= (ht=) 8 Set boundary for hardware tabs
ignore case (ic) noic Ignore case in regex expressions
lisp nolisp Turn on lisp mode
list nolist Display all tabs, end of lines
magic magic Enable more regex expressions
mesg mesg Allows mesgs to be sent to
terminal
number (nu) nonumber Displays line numbers in file
open open Allows open and visual
optimize (opt) optimize Optimizes throughput of text by
not sending carriage returns
when printing text
paragraphs= (para=) IPLPPPQPPLIbp Sets the delimiters for { & }
prompt prompt Command mode input gives : prompt
readonly (ro) noro Cannot write unless ! is given
redraw noredraw Redraw screen when edits are made
remap remap Allows macros that point to other
macros
report= 5 Report changes if they effect > x
lines
scroll 1/2 window Amount of screen to scroll when
scroll down is received in
command mode. Also, number of
lines printer by z. (z prints
2*scroll)
sections= SHNHH HU Defines end of section for [[
and ]]
shell= (sh=) /bin/sh Default shell. Uses SHELL
environment, if set
shiftwidth= (sw=) 8 Characters to shift when using
shift commands
showmatch (sm) nosm Show matching {, }, (, ), [, or ]
showmode noshowmode Shows which mode you are in.
slowopen (slow) Do not update display
immediately after insert
tabstop= (ts=) 8 Sets tabstop length
taglength= (tl=) 0 Number of characters significant
for tags (0 means all
characters)
tags= tag, /usr/lib/tags Define pathname of files
containing tags.
term= Set the terminal type
terse noterse Display shorter error messages
timeout (to) timeout Keyboard maps timeout after one
second
ttytype= Set the terminal type
warn warn Display "No write since last
change" messages
window= (w=) Number of lines in window in visual
mode
wrapmargin= (wm=) 0 Set the right margin. Greater
than 0 will word wrap n spaces
from the edge of the screen
wrapscan (ws) ws Searches wrap around end of file
writeany (wa) nowa Allow saving to any file

8.0 - Setting up .exrc file

Any commands that can be used in command input mode ( : commands),
may be used in a .exrc, which will load automatically whenever you
start vi. In addition, the source command (so), abbreviations (ab),
and macros may be used. There may not be any blank lines in your
.exrc. A " in the first column may be used to tell vi that what
follows is a comment.

8.1 - Sample .exrc file

This .exrc file is a real one. Mine. Because of that, it doesn't
set as many options as one might wish it did to get a good idea of what
may be used. However, it should get the basic idea down, and it is
quite straightforward.

First, note that you do not need to specify the :, it is assumed.

" Ignore case on search
set ic
" set wordwrap 9 characters from the right
set wm=9
" show matching parenthesis
set sm
" set the shell to be zsh
set sh=/nfs/kimbark/k4/ellidz/bin/zsh
" a few abbreviations for my email addresses
ab zdille E. Larry Lidz - ***@pobox.com
ab --l -Larry
" uppercase V will run ispell -x (-x tells it not to save backups) on current
" file
map V :w<ctrl-v><enter>:!ispell -x %<ctrl-v><enter>:e!<ctrl-v><enter><ctrl-v><enter>
" = will center the line... if I can get it to work
map = 80I <ctrl-v><esc>$78hd0:s/ / /g<ctrl-v><enter>$p
" v will reformat the current paragraph
map v {0!}fmt<ctrl-v><enter>
" Splits a line in two at current cursor location, puts a > at the
"beginning of the line
map g may0O<ctrl-v><esc>P`ay$:s/./ /g<ctrl-v><enter>0i><ctrl-v><esc>`aPa <ctrl-v><esc>D
" Change the case on the current word
map K ywmno<ctrl-v><ctrl-v><ctrl-v><esc>P:s/./\~/g<ctrl-v><ctrl-v><ctrl-v><enter>0"nDdd`***@n

9.0 - Bugs in vi

I'd like to say that vi is bug free, but unfortunately, it's not.
These bugs are bugs in the original vi, not necessarily in any of the
different clones.

Macros for _ do not always work properly.
#~ does not work under AIX

The left and right hand side of macro definitions can be at most 100
characters. If they're more than 100 characters it doesn't give a
decent error message -- it either says that it is too dangerous to map
or that the rhs is missing.

10.0 - Glossary of terms

This glossary will be updated as people suggest terms that they do
not understand. Please let me know if you have any suggestions.

command mode
Command mode is the mode within vi where the user gives commands to
vi. (Including cursor movement commands, editing commands, etc.)

ed
A non-visual editor under Unix.

<Esc>
The escape key. A key on a keyboard normally marked by escape.
Sometimes ^[ will work in its place. If there is no escape key,
sometimes the Meta key will work.

ex
An editor under Unix, all commands preceded with : are passed to
it.

insert mode
Insert mode is the mode within vi where text is inserted into the
document.

macro
A macro is a shortcut key combination. For example, a macro allows
one to hit one letter and have it execute a few different commands.

open mode
Open mode is the mode that vi will start in if it cannot determine
your terminal type, or if it believes you have a hardware or glass-tube
terminal.

regular expressions (RegEx) (RE)
Regular expressions, commonly known as "RegEx" or "REs" are a set
of key combinations that are meant to allow people to have a large
variety of control over what they are searching for. RegEx is used a
lot under Unix, and is common between many programs.

sed
Stream editor. An editor that has no interface. All commands
are given from the command line.

vi
The editor to which this FAQ is dedicated.

11.0 - Bibliography of Books that cover vi
VI QUICK REFERENCE/HELP CARDS
Specialized System Consultants, Inc.
(206)-367-8649
P.O. Box 55549
Seattle, WA 98155

Unix Programming Tools,
Eric Foster-Johnson
M and T Books, 1997.
ISBN 1-55851-482-1
Includes a CD-ROM containing vim.
http://www.pconline.com/~erc/Unixprog.htm

The ULTIMATE GUIDE to the VI and EX Text Editors
Hewlett Packard Company (authors)
The Benjamin/Cummings Publishing Company, Inc.
ISBN 0-8053-4460-8

A PRACTICAL GUIDE TO THE Unix SYSTEM
Mark G. Sobell
Benjamin Cummings Publisher

LEARNING THE VI EDITOR
Linda Lamb
O'Reilly & Associates
ISBN 0-937175-67-6

Unix POWER TOOLS (particularly for macros)
O'Reilly & Associates

MASTERING REGULAR EXPRESSIONS (for RegEx)
Jeffrey Friedl
O'Reilly & Associates, 1997
ISBN 1-56592-257-3

Unix TEXT PROCESSING
Hayden Books, 1987
Dale Dougherty and Tim O'Reilly
ISBN 0-8104-6291-5

An Introduction to Display Editing with Vi' & 'EX reference Manual' in
Unix programmers Manual vol. II
Bill Joy
Berkeley Software

Vi iMproved (VIM)
Steve Oualline
New Riders
ISBN 0735710015

EL EDITOR VI. MANUAL DE REFERENCIA
RA-MA Editorial.

Please make suggestions as to what books are most useful for learning
vi. I will add books to this section as people suggest them to me.

Copyright, E. Larry Lidz, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
2002, 2003, 2004, 2005, 2006, 2007.
All Rights Reserved.

Continue reading on narkive:
Loading...