Merge from vendor branch LESS:
[dragonfly.git] / contrib / nvi / docs / tutorial / vi.advanced
1 Section 26: Index to the rest of the tutorial
2
3 The remainder of the tutorial can be perused at your leisure.  Simply find the
4 topic of interest in the following list, and {/Section xx:/^M} to get to the
5 appropriate section.  (Remember that ^M means the return key) 
6
7 The material in the following sections is not necessarily in a bottom up
8 order.  It should be fairly obvious that if a section mentions something with
9 which you are not familiar, say, buffers, you might {/buffer/^M} followed by
10 several {n} to do a keyword search of the file for more details on that item.
11 Another point to remember is that commands are surrounded by curly-braces and
12 can therefore be found rather easily.  To see where, say, the X command is
13 used try {/{X}/^M}.  Subsequent {n} will show you other places the command was
14 used.  We have tried to maintain the convention of placing the command letter
15 surrounded by curly-braces on the section line where that command is
16 mentioned.
17
18 Finally, you should have enough 'savvy' at this point to be able to do your
19 own experimentation with commands without too much hand-holding on the part of
20 the tutorial.  Experimentation is the best way to learn the effects of the
21 commands.
22
23  Section      Topic - description
24  -------      -------------------
25 (Sections 1 through 25 are located in the file vi.beginner.)
26     1         introduction: {^F} {ZZ}
27     2         introduction (con't) and positioning: {^F} {^B}
28     3         introduction (con't) and positioning: {^F} {^B}
29     4         positioning: {^F} {^B} ^M (return key)
30     5         quitting: {:q!} ^M key
31     6         marking, cursor and screen positioning: {m} {G} {'} {z}
32     7         marking, cursor and screen positioning: {m} {G} {'} {z}
33     8         marking, cursor and screen positioning: {z} {m} {'}
34     9         marking and positioning: {m} {''}
35    10         line positioning: {^M} {-}
36    11         scrolling with {^M}
37    12         scrolling with {-} and screen adjustment {z}
38    13         notes on use of tutorial
39    14         other scrolling and postioning commands: {^E} {^Y} {^D} {^U}
40    15         searching: {/ .. /^M}
41    16         searching: {? .. ?^M} {n} (in search strings ^ $)
42    17         searching: \ and magic-characters in search strings
43    18         colon commands, exiting: {:} {ZZ}
44    19         screen positioning: {H} {M} {L}
45    20         character positioning: {w} {b} {0} {W} {B} {e} {E} {'} {`}
46    21         cursor positioning: {l} {k} {j} {h}
47    22         adding text: {i} {a} {I} {A} {o} {O} ^[ (escape key)
48    23         character manipulation: {f} {x} {X} {w} {l} {r} {R} {s} {S} {J}
49    24         undo: {u} {U}
50    25         review
51 (The following sections are in this file.)
52    26         Index to the rest of the tutorial ******** YOU ARE HERE *******
53    27         discussion of repeat counts and the repeat command: {.}
54    28         more on low-level character motions: {t} {T} {|}
55    29         advanced correction operators: {d} {c}
56    30         updating the screen: {^R}
57    31         text buffers: {"}
58    32         rearranging and duplicating text: {p} {P} {y} {Y}
59    33         recovering lost lines
60    34         advanced file manipulation with vi
61    34.1          more than one file at a time: {:n}
62    34.2          reading files and command output: {:r}
63    34.3          invoking vi from within vi: {:e} {:vi}
64    34.4          escaping to a shell: {:sh} {:!}
65    34.5          writing parts of a file: {:w}
66    34.6          filtering portions of text: {!}
67    35         advanced searching: magic patterns 
68    36         advanced substitution: {:s} 
69    37         advanced line addressing: {:p} {:g} {:v}
70    38         higher level text objects and nroff: ( ) { } [[ ]]
71    39         more about inserting text
72    40         more on operators: {d} {c} {<} {>} {!} {=} {y}
73    41         abbreviations: {:ab}
74    42         vi's relationship with the ex editor: {:}
75    43         vi on hardcopy terminals and dumb terminals: open mode
76    44         options: {:set} {setenv EXINIT}
77    44.1          autoindent
78    44.2          autoprint
79    44.3          autowrite
80    44.4          beautify
81    44.5          directory
82    44.6          edcompatible
83    44.7          errorbells
84    44.8          hardtabs
85    44.9          ignorecase
86    44.10         lisp
87    44.11         list
88    44.12         magic
89    44.13         mesg                    
90    44.14         number
91    44.15         open
92    44.16         optimize
93    44.17         paragraphs
94    44.18         prompt
95    44.19         readonly
96    44.20         redraw
97    44.21         remap
98    44.22         report
99    44.23         scroll
100    44.24         sections
101    44.25         shell
102    44.26         shiftwidth
103    44.27         showmatch
104    44.28         slowopen
105    44.29         tabstop
106    44.30         tags
107    44.31         taglength
108    44.32         term
109    44.33         terse
110    44.34         timeout
111    44.35         ttytype
112    44.36         warn
113    44.37         window
114    44.38         wrapscan
115    44.39         wrapmargin
116    44.40         writeany
117    44.41         w300, w1200, w9600
118
119 Section 27: repetition counts and the repeat command {.}
120
121 Most vi commands will use a preceding count to affect their behavior in some
122 way.  We have already seen how {3x} deletes three characters, and {22G} moves
123 us to line 22 of the file.  For almost all of the commands, one can survive by
124 thinking of these leading numbers as a 'repeat count' specifying that the
125 command is to be repeated so many number of times.
126
127 Other commands use the repeat count slightly differently, like the {G} command
128 which use it as a line number.
129
130 For example:
131
132 {3^D} means scroll down in the file three lines.  Subsequent {^D} OR {^U} will
133 scroll only three lines in their respective directions!
134
135 {3z^M} says put line three of the file at the top of the screen, while {3z.}
136 says put line three as close to the middle of the screen as possible.
137
138 {50|} moves the cursor to column fifty in the current line.
139
140 {3^F} says move forward 3 screenfulls.  This is a repetition count.  The
141 documents advertise that {3^B} should move BACK three screenfulls, but I
142 can't get it to work.
143
144 Position the cursor on some text and try {3r.}.  This replaces three characters
145 with '...'.  However, {3s.....^[} is the same as {3xi.....^[}.
146
147 Try {10a+----^[}.
148
149 A very useful instance of a repetition count is one given to the '.' command,
150 which repeats the last 'change' command.  If you {dw} and then {3.}, you will
151 delete first one and then three words.  You can then delete two more words with
152 {2.}.  If you {3dw}, you will delete three words.  A subsequent {.} will delete
153 three more words.  But a subsequent {2.} will delete only two words, not three
154 times two words.
155
156 Caveat: The author has noticed that any repetition count with {^B} will NOT
157 work: indeed, if you are at the end of your file and try {3^B} sufficiently
158 often, the editor will hang you in an infinite loop.  Please don't try it:
159 take my word for it.
160
161 Section 28: {t} {T} {|}
162
163 Position the cursor on line 13 below:
164
165 Line 13: Four score and seven years ago, our forefathers brought ...
166
167 Note that {fv} moves the cursor on/over the 'v' in 'seven'.  Do a {0} to return
168 to the beginning of the line and try a {tv}.  The cursor is now on/over the
169 first 'e' in 'seven'.  The {f} command finds the next occurrence of the
170 specified letter and moves the cursor to it.  The {t} command finds the
171 specified letter and moves the cursor to the character immediately preceding
172 it.  {T} searches backwards, as does {F}.
173
174 Now try {60|}: the cursor is now on the 'o' in 'brought', which is the
175 sixtieth character on the line.
176
177 Section 29: {d} {c}
178
179 Due to their complexity we have delayed discussion of two of the most powerful
180 operators in vi until now.  Effective use of these operators requires more
181 explanation than was deemed appropriate for the first half of the tutorial.
182
183 {d} and {c} are called operators instead of commands because they consist of
184 three parts: a count specification or a buffer specification (see section
185 #BUFFERS), the {d} or {c}, and the object or range description.  We will not
186 discuss buffers at this stage, but will limit ourselves to count
187 specifications.  Examples speak louder than words: position the cursor at the
188 beginning of line 14:
189
190 Line 14: Euclid alone has looked on beauty bear.
191
192 Obviously, there is something wrong with this quotation.  Type {2fb} to
193 position the cursor on the 'b' of 'bear'.  Now, type {cwbare^[}
194 and observe the results.  The {cw} specifies that the change command {c} is to
195 operate on a word object.  More accurately, it specifies that the range of the
196 change command includes the next word.
197
198 Position the cursor on the period in Line 14. (one way is to use {f.})
199 Now, type {cbbeast^[}.  This specifies the range of the change command to be the
200 previous word (the 'b' reminiscent of the {b} command).  If we had wished to
201 delete the word rather than change it, we would have used the {d} operator,
202 rather than the {c} operator.
203
204 Position the cursor at the beginning of the line with {0}.  Type
205 {d/look/^M}.  The search string specified the range of the delete.
206 Everything UP TO the word 'looking' was deleted from the line.
207
208 In general, almost any command that would move the cursor will specify a range
209 for these commands.  The most confusing exception to this rule is when {dd} or
210 {cc} is entered: they refer to the whole line.  Following is a summary of the
211 suffixes (suffices? suffici?) and the ranges they specify:
212
213     suffix        will delete{d}/change{c}
214     ------        ------------------------
215       ^[            cancels the command
216       w             the word to the right of the cursor
217       W             ditto, but ignoring punctuation
218       b             the word to the left of the cursor
219       B             ditto, but ignoring punctuation
220       e             see below.
221       E               ditto
222       (space)       a character
223       $             to the end of the line
224       ^             to the beginning of the line
225       / .. /        up to, but not including, the string
226       ? .. ?        back to and including the string
227       fc            up to and including the occurrence of c 
228       Fc            back to and including the occurrence of c
229       tc            up to but not including the occurrence of c
230       Tc            back to but not including the occurrence of c
231       ^M            TWO lines (that's right: two)
232       (number)^M    that many lines plus one
233       (number)G     up to and including line (number)
234       (             the previous sentence if you are at the beginning of
235                     the current sentence, or the current sentence up to where 
236                     you are if you are not at the beginning of the current 
237                     sentence.  Here, 'sentence' refers to the intuitive
238                     notion of an English sentence, ending with '!', '?',
239                     or '.' and followed by an end of line or two spaces.
240       )             the rest of the current sentence
241       {             analogous to '(', but in reference to paragraphs:
242                     sections of text surrounded by blank lines
243       }             analogous to ')', but in reference to paragraphs
244       [[            analogous to '(', but in reference to sections
245       ]]            analogous to ')', but in reference to sections
246       H             the first line on the screen
247       M             the middle line on the screen
248       L             the last line on the screen
249       3L            through the third line from the bottom of the screen
250       ^F            forward a screenful
251       ^B            backward a screenful
252       :
253       :  etc. etc. etc.
254
255 This list is not exhaustive, but it should be sufficient to get the idea
256 across: after the {c} or {d} operator, you can specify a range with another
257 move-the-cursor command, and that is the region of text over which the command
258 will be effective.
259
260 Section 30: updating the screen {^R}
261
262 Vi tries to be very intelligent about the type of terminal you are working on
263 and tries to use the in-terminal computing power (if any) of your terminal.
264 Also if the terminal is running at a low baud rate (say 1200 or below), vi sets
265 various parameters to make things easier for you.  For example, if you were
266 running on a 300 baud terminal (that's 30 characters per second transmission
267 rate) not all 24 lines of the screen would be used by vi.  In addition, there
268 is a large portion of the editor keeping track of what your screen currently
269 looks like, and what it would look like after a command has been executed.  Vi
270 then compares the two, and updates only those portions of the screen that have
271 changed.
272
273 Furthermore, some of you may have noticed (it depends on your terminal) that 
274 deleting lines or changing large portions of text may leave some lines on the 
275 screen looking like: 
276
277 meaning that this line of the screen does not correspond to any line in your
278 file. It would cost more to update the line than to leave it blank for the
279 moment.  If you would like to see your screen fully up-to-date with the
280 contents of your file, type {^R}.
281
282 To see it in action, delete several lines with {5dd}, type {^R}, and then type
283 {u} to get the lines back.
284
285 Here is as good a place as any to mention that if the editor is displaying the
286 end of your file, there may be lines on the screen that look like: 
287
288 indicating that that screen line would not be affected by {^R}.  These lines
289 simply indicate the end of the file.
290
291 Section 31: text buffers {"}
292
293 Vi gives you the ability to store text away in "buffers".  This feature is very
294 convenient for moving text around in your file.  There are a total of thirty-
295 five buffers available in vi.  There is the "unnamed" buffer that is used by all
296 commands that delete text, including the change operator {c}, the substitute
297 and replace commands {s} and {r}, as well as the delete operator {d} and delete
298 commands {x} and {X}.  This buffer is filled each time any of these commands
299 are used. However, the undo command {u} has no effect on the unnamed buffer.
300
301 There are twenty-six buffers named 'a' through 'z' which are available for the
302 user.  If the name of the buffer is capitalized, then the buffer is not
303 overwritten but appended to.  For example, the command {"qdd} will delete one
304 line and store that line in the 'q' buffer, destroying the previous contents of
305 the buffer.  However, {"Qdd} will delete one line of text and append that line
306 to the current contents of the 'q' buffer.
307
308 Finally, there are nine buffers named '1' through '9' in which the last nine
309 deletes are stored.  Buffer 1 is the default buffer for the modify commands and
310 is sometimes called the unnamed buffer.
311
312 To reference a specific buffer, use the double-quote command {"} followed by
313 the name of the buffer.  The next two sections show how buffers can be used to
314 advantage.
315
316 Section 32: rearranging and duplicating text: {y} {Y} {p} {P}
317
318 Position yourself on line 15 below and {z^M}:
319
320 Line 15: A tree as lovely as a poem ...
321 Line 16: I think that I shall never see
322
323 Type {dd}.  Line 15 has disappeared and been replaced with the empty line (one
324 with the single character @ on it) or (again depending on your terminal) Line
325 16 has moved up and taken its place.  We could recover Line 15 with an undo
326 {u} but that would simply return it to its original location.  Obviously, the
327 two lines are reversed, so we want to put line 15 AFTER line 16.  This is
328 simply done with the put command {p}, which you should type now.  What has
329 happened is that {dd} put Line 15 into the unnamed buffer, and the {p} command
330 retrieved the line from the unnamed buffer.
331
332 Now type {u} and observe that Line 15 disappears again (the put was undone
333 without affecting the unnamed buffer).  Type {P} and see that the capital {P}
334 puts the line BEFORE the cursor.
335
336 To get Line 15 where it belongs again type {dd}{p}.
337
338 Also in Line 15 note that the words 'tree' and 'poem' are reversed.  Using the
339 unnamed buffer again: {ft}{dw}{ma}{fp}{P}{w}{dw}{`aP} will set things aright 
340 (note the use of the reverse quote).
341
342 The put commands {p} and {P} do not affect the contents of the buffer.
343 Therefore, multiple {p} or {P} will put multiple copies of the unnamed buffer
344 into your file.
345
346 Experiment with {d} and {p} on words, paragraphs, etc.  Whatever {d}
347 deletes, {p} can put.
348
349 Position the cursor on Line 17 and {z^M}:
350
351 Line 17: interest apple cat elephant boy dog girl hay farmer
352
353 Our task is to alphabetize the words on line 17.  With the named buffers (and a
354 contrived example) it is quite easy:
355
356 {"idw}{"adw}{"cdw}{"edw}{"bdw}{"ddw}{"gdw}{"hdw}{"fdw}
357
358 stores each of the words in the named buffer corresponding to the first letter
359 of each of the words ('interest' goes in buffer "i, 'apple' goes in buffer "a,
360 etc.).  Now to put the words in order type:
361
362 {"ap$}{"bp$}{"cp$}{"dp$}{"ep$}{"fp$}{"gp$}{"hp$}{"ip$}
363
364 Notice that, because 'farmer' was at the end of the line, {dw} did not include
365 a space after it, and that, therefore, there is no space between 'farmer' and
366 'girl'.  This is corrected with {Fg}{i ^[}.
367
368 This example could have been done just as easily with lines as with
369 words.
370
371 You do not have to delete the text in order to put it into a buffer.  If all
372 you wish to do is to copy the text somewhere else, don't use {d}, rather use
373 the yank commands {y} or {Y}.  {y} is like {d} and {c} - an operator rather
374 than a command.  It, too, takes a buffer specification and a range
375 specification.  Therefore, instead of {dw}{P} to load the unnamed buffer with a
376 word without deleting the word, use {yw} (yank a word).
377
378 {Y} is designed yank lines, and not arbitrary ranges.  That is, {Y} is
379 equivalent to {yy} (remember that operators doubled means the current line),
380 and {3Y} is equivalent to {3yy}.
381
382 If the text you yank or modify forms a part of a line, or is an object such as
383 a sentence which partially spans more than one line, then when you put the text
384 back, it will be placed after the cursor (or before if you use {P}).  If the
385 yanked text forms whole lines, they will be put back as whole lines, without
386 changing the current line.  In this case, the put acts much like the {o} or {O}
387 command.
388
389 The named buffers "a through "z are not affected by changing edit files.
390 However, the unnamed buffer is lost when you change files, so to move text from
391 one file to another you should use a named buffer.
392
393 Section 33: recovering lost lines
394
395 Vi also keeps track of the last nine deletes, whether you ask for it or not.
396 This is very convenient if you would like to recover some text that was
397 accidentally deleted or modified.  Position the cursor on line 18 following,
398 and {z^M}.
399
400
401 Line 18: line 1
402 Line 19: line 2
403 Line 20: line 3
404 Line 21: line 4
405 Line 22: line 5
406 Line 23: line 6
407 Line 24: line 7
408 Line 25: line 8
409 Line 26: line 9
410 Type {dd} nine times: now don't cheat with {9dd}!  That is totally different.
411
412 The command {"1p} will retrieve the last delete.  Furthermore, when the
413 numbered buffers are used, the repeat-command command {.} will increment the
414 buffer numbers before executing, so that subsequent {.} will recover all nine
415 of the deleted lines, albeit in reverse order.  If you would like to review the
416 last nine deletes without affecting the buffers or your file, do an undo {u}
417 after each put {p} and {.}:
418
419 {"1p}{u}{.}{u}{.}{u}{.}{u}{.}{u}{.}{u}{.}{u}{.}{u}{.}
420
421 will show you all the buffers and leave them and your file intact.
422
423 If you had cheated above and deleted the nine lines with {9dd}, all nine lines
424 would have been stored in both the unnamed buffer and in buffer number 1. 
425 (Obviously, buffer number 1 IS the unnamed buffer and is just the default
426 buffer for the modify commands.)
427
428 Section 34: advanced file manipulation: {:r} {:e} {:n} {:w} {!} {:!}
429
430 We've already looked at writing out the file you are editing with the
431 {:w} command.  Now let's look at some other vi commands to make editing
432 more efficient.
433
434 Section 34.1: more than one file at a time {:n} {:args}
435
436 Many times you will want to edit more than one file in an editing session.
437 Instead of entering vi and editing the first file, exiting, entering vi and
438 editing the second, etc., vi will allow you to specify ALL files that you wish
439 to edit on the invocation line.  Therefore, if you wanted to edit file1 and
440 file2:
441
442 % vi file1 file2
443
444 will set up file1 for editing.  When you are done editing file one, write it
445 out {:w^M} and then type {:n^M} to get the next file on the list.  On large
446 programming projects with many source files, it is often convenient just to
447 specify all source files with, say:
448
449 % vi *.c
450
451 If {:n^M} brings in a file that does not need any editing, another {:n^M}
452 will bring in the next file.
453
454 If you have made changes to the first file, but decide to discard these changes
455 and proceed to the next file, {:n!^M} forces the editor to discard the current
456 contents of the editor.
457
458 You can specify a new list of files after {:n}; e.g., {:n f1 f2 f3^M}.  This
459 will replace the current list of files (if any).
460
461 You can see the current list of files being edited with {:args^M}.
462
463 Section 34.2: reading files and command output: {:r}
464
465 Typing {:r fname^M} will read the contents of file fname into the editor and
466 put the contents AFTER the cursor line.
467
468 Typing {:r !cmd^M} will read the output of the command cmd and place that
469 output after the cursor line.
470
471 Section 34.3: invoking vi from within vi: {:e} {:vi}
472
473 To edit another file not mentioned on the invocation line, type {:e filename^M}
474 or {:vi filename^M}.  If you wish to discard the changes to the current file,
475 use the exclamation point after the command, e.g. {:e! filename^M}.
476
477 Section 34.4: escaping to a shell: {:sh} {:!} {^Z}
478
479 Occasionally, it is useful to interrupt the current editing session to perform
480 a UNIX task.  However, there is no need to write the current file out, exit
481 the editor, perform the task, and then reinvoke the editor on the same file.
482 One thing to do is to spin off another process.  If there are several UNIX
483 commands you will need to execute, simply create another shell with {:sh^M}.
484 At this point, the editor is put to sleep and will be reawakened when you log
485 out of the shell.
486
487 If it is a single command that you want to execute, type {:!cmd^M}, where cmd
488 is the command that you wish to run.  The output of the command will come to
489 the terminal as normal, and will not be made part of your file.  The message
490 "[Hit return to continue]" will be displayed by vi after the command is
491 finished.  Hitting return will then repaint the screen.  Typing another
492 {:!cmd^M} at this point is also acceptable.
493
494 However, there is a quicker, easier way: type {^Z}.  Now this is a little
495 tricky, but hang in there.  When you logged into UNIX, the first program you
496 began communicating with was a program that is called a "shell" (i.e. it 'lays
497 over' the operating system protecting you from it, sort of like a considerate
498 porcupine).  When you got your first prompt on the terminal (probably a '%'
499 character) this was the shell telling you to type your first command.  When
500 you typed {vi filename} for some file, the shell did not go away, it just went
501 to sleep.  The shell is now the parent of vi.  When you type {^Z} the editor
502 goes to sleep, the shell wakes up and says "you rang?" in the form of another
503 prompt (probably '%').  At this point you are talking to the shell again and
504 you can do anything that you could before including edit another file!  (The
505 only thing you can't do is log out: you will get the message "There are
506 stopped jobs.")
507
508 When your business with the shell is done, type {fg} for 'foreground' and the
509 last process which you ^Z'd out of will be reawakened and the shell will go
510 back to sleep.  I will refer you to the documentation for the Berkeley shell
511 'csh' for more information on this useful capability.
512
513 Section 34.5: writing parts of a file: {:w}
514
515 The {:w} command will accept a range specifier that will then write only a
516 selected range of lines to a file.  To write this section to a file, position
517 the cursor on the section line (e.g. {/^Section 34.5:/^M}) and {z^M}.  Now type
518 {^G} to find out the line number (it will be something like "line 513").  Now
519 {/^Section 34.6:/-1^M} to find the last line of this section, and {^G} to find
520 its line number (it will be something like 542).  To write out this section of
521 text by itself to a separate file which we will call "sepfile", type
522 {:510,542w sepfile^M}.  If sepfile already exists, you will have to use the
523 exclamation point: {:1147,1168w! sepfile^M} or write to a different, non-
524 existent file.
525
526 {:!cat sepfile^M} will display the file just written, and it should be the
527 contents of this section.
528
529 There is an alternate method of determining the line numbers for the write.
530 {:set number^M} will repaint the screen with each line numbered.  When the file
531 is written and the numbers no longer needed, {:set nonumber^M} will remove the
532 numbers, and {^R} will adjust the screen.
533
534 Or, if you remember your earlier lessons about marking lines of text,
535 mark the beginning and ending lines.  Suppose we had used {ma} to mark the
536 first line of the section and {mb} to mark the last.  Then the command
537 {:'a,'bw sepfile^M} will write the section into "sepfile".  In general,
538 you can replace a line number with the 'name' of a marked line (a single-quote
539 followed by the letter used to mark the line)
540
541
542 Section 34.6: filtering portions of text: {!}
543
544 {!} is an operator like {c} and {d}.  That is, it consists of a repetition
545 count, {!}, and a range specifier.  Once the {!} operator is entered in its
546 entirety, a prompt will be given at the bottom of the screen for a UNIX
547 command.  The text specified by the {!} operator is then deleted and
548 passed/filtered/piped to the UNIX command you type.  The output of the UNIX
549 command is then placed in your file.  For example, place the cursor at the
550 beginning of the following line and {z^M}:
551
552 ls -l vi.tutorial
553 ********* marks the bottom of the output from the ls command **********
554
555 Now type {!!csh^M}.  The line will be replaced with the output from the ls
556 command.  The {u} command works on {!}, also.
557
558 Here is an extended exercise to display some of these capabilities.  When this
559 tutorial was prepared, certain auxiliary programs were created to aid in its
560 development.  Of major concern was the formatting of sections of the tutorial
561 to fit on a single screen, particularly the first few sections.  What was
562 needed was a vi command that would 'format' a paragraph; that is, fill out
563 lines with as many words as would fit in eighty columns.  There is no such vi
564 command.  Therefore, another method had to be found.
565
566 Of course, nroff was designed to do text formatting.  However, it produces a
567 'page'; meaning that there may be many blank lines at the end of a formatted
568 paragraph from nroff.  The awk program was used to strip these blank lines from
569 the output from nroff.  Below are the two files used for this purpose: I refer
570 you to documentation on nroff and awk for a full explanation of their function.
571 Position the cursor on the next line and {z^M}.
572
573 ******** contents of file f **********
574 #
575 nroff -i form.mac | awk "length != 0 { print }"
576 ***** contents of file form.mac ******
577 .na
578 .nh
579 .ll 79
580 .ec \a
581 .c2 \ 6
582 .cc \ 2
583 **************************************
584
585 Determine the line numbers of the two lines of file f.  They should be
586 something like 574 and 575, although you better double check: this file is
587 under constant revision and the line numbers may change inadvertently.  Then
588 {:574,575w f^M}.  Do the same for the lines of file form.mac.  They will be
589 approximately 577 and 582.  Then {:577,582w form.mac^M}.  File f must have
590 execute privileges as a shell file: {:!chmod 744 f^M}.
591
592 Observe that this paragraph is
593 rather ratty in appearance.  With our newly created files we can
594 clean it up dramatically.  Position the cursor at the beginning
595 of this paragraph and type the following sequence of
596 characters 
597 (note that we must abandon temporarily our convention
598 of curly braces since the command itself contains a curly brace - we 
599 will use square brackets for the nonce): [!}f^M].
600
601 Here is a brief explanation of what has happened.  By typing [!}f^M] we
602 specified that the paragraph (all text between the cursor and the first blank
603 line) will be removed from the edit file and piped to a UNIX program called
604 "f".  This is a shell command file that we have created.  This shell file runs
605 nroff, pipes its output to awk to remove blank lines, and the output from awk
606 is then read back into our file in the place of the old, ratty paragraph.  The
607 file form.mac is a list of commands to nroff to get it to produce paragraphs
608 to our taste (the right margin is not justified, the line is 79 characters
609 long, words are not hyphenated, and three nroff characters are renamed to
610 avoid conflict: note that in this file, the {^G} you see there is vi's display
611 of the control-G character, and not the two separate characters ^ up-arrow and
612 G upper-case g).
613
614 This example was created before the existence of the fmt program.  I now type
615 [!}fmt^M] to get the same effect much faster.  Actually, I don't type those
616 six keys each time: I have an abbreviation (which see).
617
618 Section 35: searching with magic patterns
619
620 The documentation available for "magic patterns" (i.e. regular expressions) is
621 very scanty.  The following should explain this possibly very confusing feature
622 of the editor.  This section assumes that the magic option is on.  To make
623 sure, you might want to type {:set magic^M}.
624
625 By "magic pattern" we mean a general description of a piece of text that the
626 editor attempts to find during a search.  Most search patterns consist of
627 strings of characters that must be matched exactly, e.g.  {/card/^M} searches
628 for a specific string of four characters.  Let us suppose that you have
629 discovered that you consistently have mistyped this simple word as either ccrd
630 or czrd (this is not so far-fetched for touch typists).  You could {/ccrd/^M}
631 and {n} until there are no more of this spelling, followed by {/czrd/^M} and
632 {n} until there are no more of these.  Or you could {/c.rd/^M} and catch all of
633 them on the first pass.  Try typing {/c.rd/^M} followed by several {n} and
634 observe the effect.
635
636 Line 27: card cord curd ceard
637
638 When '.' is used in a search string, it has the effect of matching any single
639 character.
640
641 The character '^' (up-arrow) used at the beginning of a search string means
642 the beginning of the line.  {/^Line 27/^M} will find the example line above,
643 while {/Line 27/^M} will find an occurrence of this string anywhere in the
644 line.
645
646 Similarly, {/ the$/^M} will find all occurrences of the word 'the' occurring
647 at the end of a line.  There are several of them in this file.
648
649 Note that {:set nomagic^M} will turn off the special meaning of these magic
650 characters EXCEPT for '^' and '$' which retain their special meanings at the
651 beginning and end of a search string.  Within the search string they hold no
652 special meaning.  Try {/\/ the$\//^M} and note that the dollar-sign is not the
653 last character in the search string.  Let the dollar-sign be the last
654 character in the search string, as in {/\/ the$/^M} and observe the result.
655
656 Observe the result of {/back.*file/^M}.  This command, followed by sufficient
657 {n}, will show you all lines in the file that contain both the words 'back'
658 and 'file' on the same line.  The '*' magic character specifies that the
659 previous regular expression (the '.' in our example) is to be repeatedly
660 matched zero or more times.  In our example we specified that the words 'back'
661 and 'file' must appear on the same line (they may be parts of words such as
662 'backwards' or 'workfile') separated by any number (including zero) of
663 characters.
664
665 We could have specified that 'back' and 'file' are to be words by themselves by
666 using the magic sequences '\<' or '\>'.  E.g.  {/\<back\>.*\<file\>/^M}.  The
667 sequence '\<' specifies that this point of the search string must match the
668 beginning of a word, while '\>' specifies a match at the end of a word.  By
669 surrounding a string with these characters we have specified that they must be
670 words.
671
672 To find all words that begin with an 'l' or a 'w', followed by an 'a' or an
673 'e', and ending in 'ing', try {/\<[lw][ea][a-z]*ing\>/^M}.  This will match
674 words like 'learning', 'warning', and 'leading'.  The '[..]' notation matches
675 exactly ONE character.  The character matched will be one of the characters
676 enclosed in the square brackets.  The characters may be specified individually
677 as in [abcd] or a '-' may be used to specify a range of characters as in [a-d].
678 That is, [az] will match the letter 'a' OR the letter 'z', while [a-z] will
679 match any of the lower case letters from 'a' through 'z'.  If you would like to
680 match either an 'a', a '-', or a 'z', then the '-' must be escaped: [a\-z] will
681 match ONE of the three characters 'a', '-', or 'z'.
682
683 If you wish to find all Capitalized words, try {/\<[A-Z][a-z]*\>/^M}.  The
684 following will find all character sequences that do NOT begin with an
685 uncapitalized letter by applying a special meaning to the '^' character in
686 square brackets: {/\<[^a-z][a-z]*\>/^M}.  When '^' is the first character of a
687 square-bracket expression, it specifies "all but these characters".  (No
688 one claimed vi was consistent.)
689
690 To find all variable names (the first character is alphabetic, the remaining
691 characters are alphanumeric):  try {/\<[A-Za-z][A-Za-z0-9]*\>/^M}.
692
693 In summary, here are the primitives for building regular expressions:
694
695      ^      at beginning of pattern, matches beginning of line
696      $      at end of pattern, matches end of line
697      .      matches any single character
698      \<     matches the beginning of a word
699      \>     matches the end of a word
700      [str]  matches any single character in str
701      [^str] matches any single character NOT in str
702      [x-y]  matches any character in the ASCII range between x and y
703      *      matches any number (including zero) of the preceding pattern
704
705 Section 36: advanced substitution: {:s} 
706
707 The straightforward colon-substitute command looks like the substitute
708 command of most line-oriented editors.  Indeed, vi is nothing more than a
709 superstructure on the line-oriented editor ex and the colon commands are
710 simply a way of accessing commands within ex (see section #EX).  This gives us
711 a lot of global file processing not usually found in visual oriented editors.
712
713 The colon-substitute command looks like: {:s/ .. / .. /^M} and will find the
714 pattern specified after the first slash (this is called the search pattern),
715 and replace it with the pattern specified after the second slash (called,
716 obviously enough, the replacement pattern).  E.g. position the cursor on line
717 28 below and {:s/esample/example/^M}:
718
719 Line 28: This is an esample.
720
721 The {u} and {U} commands work for {:s}.  The first pattern (the search pattern)
722 may be a regular expression just as for the search command (after all, it IS a
723 search, albeit limited to the current line).  Do an {u} on the above line, and
724 try the following substitute, which will do almost the same thing: 
725 {:s/s[^ ]/x/^M}.  
726 Better undo it with {u}.  The first pattern {s[^ ]} matches an 's'
727 NOT followed by a blank: the search therefore ignores the 's'es in 'This' and
728 'is'.  However, the character matched by {[^ ]} must appear in the replacement
729 pattern.  But, in general, we do not know what that character is!  (In this
730 particular example we obviously do, but more complicated examples will follow.)
731 Therefore, vi (really ex) has a duplication mechanism to copy patterns matched
732 in the search string into the replacement string.  Line 29 below is a copy of
733 line 28 above so you can adjust your screen.
734
735 Line 29: This is an esample.
736
737 In general, you can nest parts of the search pattern in \( .. \) and refer to
738 it in the replacement pattern as \n, where n is a digit.  The problem outlined
739 in the previous paragraph is solved with {:s/s\([^ ]\)/x\1/^M}: try it.  Here
740 \1 refers to the first pattern grouping \( .. \) in the search string.
741
742 Obviously, for a single line, this is rather tedious.  Where it becomes
743 powerful, if not necessary, is in colon-substitutes that cover a range of
744 lines.  (See the next section for a particularly comprehensive example.)
745
746 If the entire character sequence matched by the search pattern is needed in
747 the replacement pattern, then the unescaped character '&' can be used.  On
748 Line 29 above, try {:s/an e.ample/not &/^M}.  If another line is to have the
749 word 'not' prepended to a pattern, then '~' can save you from re-typing the
750 replacement pattern.  E.g. {:s/some pattern/~/^M} after the previous example
751 would be equivalent to {:s/some pattern/not &/^M}.
752
753 One other useful replacement pattern allows you to change the case of
754 individual letters.  The sequences {\u} and {\l} cause the immediately
755 following character in the replacement to be converted to upper- or lower-case,
756 respectively, if this character is a letter.  The sequences {\U} and {\L} turn
757 such conversion on, either until {\E} or {\e} is encountered, or until the end
758 of the replacement pattern.
759
760 For example, position the cursor on a line: pick a line, any line.  Type
761 {:s/.*/\U&/^M} and observe the result.  You can undo it with {u}.
762
763 The search pattern may actually match more than once on a single line.
764 However, only the first pattern is substituted.  If you would like ALL
765 patterns matched on the line to be substituted, append a 'g' after the
766 replacement pattern: {:s/123/456/g^M} will substitute EVERY occurrence
767 on the line of 123 with 456.
768
769 Section 37: advanced line addressing: {:p} {:g} {:v}
770
771 Ex (available through the colon command in vi) offers several methods for
772 specifying the lines on which a set of commands will act.  For example, if you
773 would like to see lines 50 through 100 of your file: {:50,100p^M} will display
774 them, wait for you to [Hit return to continue], and leave you on line 100.
775 Obviously, it would be easier just to do {100G} from within vi.  But
776 what if you would like to make changes to just those lines?  Then the
777 addressing is important and powerful.
778
779 Line 30: This is a text.
780 Line 31: Here is another text.
781 Line 32: One more text line.
782
783 The lines above contain a typing error that the author of this tutorial tends
784 to make every time he attempts to type the word 'test'.  To change all of these
785 'text's into 'test's, try the following:
786 {:/^Line 30/,/^Line 32/s/text/test/^M}.  This finds the beginning and end of
787 the portion of text to be changed, and limits the substitution to each of the
788 lines in that range.  The {u} command applies to ALL of the substitutions as 
789 a group.
790
791 This provides a mechanism for powerful text manipulations.
792 And very complicated examples.
793
794 Line 33: This test is a.
795 Line 34: Here test is another.
796 Line 35: One line more test.
797
798 The above three lines have the second word out of order.  The following command
799 string will put things right.  Be very careful when typing this: it is very
800 long, full of special characters, and easy to mess up.  You may want to
801 consider reading the following section to understand it before trying the
802 experiment.  Don't worry about messing up the rest of the file, though: the
803 address range is specified.
804
805 {:/^Line 33/,/^Line 35/s/\([^:]*\): \([^ ]*\) \([^ ]*\) \([^.]*\)/\1: \2 \4 \3/^M}
806
807 There are several things to note about this command string.  First of all, the
808 range of the substitute was limited by the address specification {/^Line
809 33/,/^Line 35/^M}.  It might have been simpler to do {:set number^M} to see the
810 line numbers directly, and then, in place of the two searches, typed
811 the line numbers, e.g. {1396,1398}.  Or to mark the lines with {ma} and {mb}
812 and use {'a,'b}.
813
814 Then follows the substitute pattern itself.  To make it easier to understand
815 what the substitute is doing, the command is duplicated below with the various
816 patterns named for easier reference:
817
818      s/\([^:]*\): \([^ ]*\) \([^ ]*\) \([^.]*\)/\1: \2 \4 \3/
819        |--\1---|  |--\2---| |--\3---| |--\4---|
820       |--------search pattern------------------|-replacement|
821                                                |--pattern---|
822
823 In overview, the substitute looks for a particular pattern made up of 
824 sub-patterns, which are named \1, \2, \3, and \4.  These patterns are specified
825 by stating what they are NOT.  Pattern \1 is the sequence of characters that
826 are NOT colons: in the search string, {[^:]} will match exactly one character
827 that is not a colon, while appending the asterisk {[^:]*} specifies that the
828 'not a colon' pattern is to be repeated until no longer satisfied, and
829 {\([^:]*\)} then gives the pattern its name, in this case \1.  Outside of the
830 specification of \1 comes {: }, specifying that the next two characters must be
831 a colon followed by a blank.
832
833 Patterns \2 and \3 are similar, specifying character sequences that are
834 not blanks.  Pattern \4 matches up to the period at the end of the line.
835
836 The replacement pattern then consists of specifying the new order of the
837 patterns.
838
839 This is a particularly complicated example, perhaps the most complicated
840 in this tutorial/reference.  For our small examples, it is obviously
841 tedious and error prone.  For large files, however, it may be the most
842 efficient way to make the desired modifications.
843
844 (The reader is advised to look at the documentation for awk.  This tool is very
845 powerful and slightly simpler to use than vi for this kind of file
846 manipulation.  But, it is another command language to learn.)
847
848 Many times, you will not want to operate on every line in a certain
849 range.  Rather you will want to make changes on lines that satisfy
850 certain patterns; e.g. for every line that has the string 'NPS' on it,
851 change 'NPS' to 'Naval Postgraduate School'.  The {:g} addressing
852 command was designed for this purpose.  The example of this paragraph
853 could be typed as {:g/NPS/s//Naval Postgraduate School/^M}.
854
855 The general format of the command is {:g/(pattern)/cmds^M} and it
856 works in the following way: all lines that match the pattern
857 following the {:g} are 'tagged' in a special way.  Then each of these
858 lines have the commands following the pattern executed over them.
859
860 Line 36: ABC rhino george farmer Dick jester lest
861 Line 37: george farmer rhino lest jester ABC
862 Line 38: rhino lest george Dick farmer ABC jester 
863
864 Type:
865
866 {:g/^Line.*ABC/s/Dick/Harry Binswanger/|s/george farmer/gentleman george/p^M}
867
868 There are several things of note here.  First, lines 36, 37, and 38 above are
869 tagged by the {:g}.  Type {:g/^Line.*ABC/p^M} to verify this.  Second, there
870 are two substitutes on the same line separated by '|'.  In general, any colon
871 commands can be strung together with '|'.  Third, both substitutes operate on
872 all three lines, even though the first stubstitute works on only two of the
873 lines (36 and 38).  Fourth, the second substitute works on only two lines (36
874 and 37) and those are the two lines printed by the trailing 'p'.
875
876 The {:v} command works similarly to the {:g} command, except that the sense of
877 the test for 'tagging' the lines is reversed: all lines NOT matching the search
878 pattern are tagged and operated on by the commands.
879
880 Using {^V} to quote carriage return (see section 39) can be used in global
881 substitutions to split two lines.  For example, the command 
882 {:g/\.  /s//.^V^M/g^M} will change your file so that each sentence is on a 
883 separate line.  (Note that we have to 'escape' the '.', because '.' by itself
884 matches any character.  Our command says to find any line which contains a 
885 period followed by 2 spaces, and inserts a carriage return after the period.)
886
887 Caveat:  In some of the documentation for ex and vi you may find the
888 comment to the effect that {\^M} can be used between commands following
889 {:g}.  The author of this tutorial has never gotten this to work and has
890 crashed the editor trying.
891
892 Section 38: higher level text objects and nroff: {(} {)} [{] [}] {[[} {]]}
893
894 (Note: this section may be a little confusing because of our command
895 notation.  Using curly braces to surround command strings works fine as
896 long as the command string does not contain any curly braces itself.
897 However, the curly braces are legitimate commands in vi.  Therefore, for
898 any command sequence that contains curly braces, we will surround that
899 sequence with SQUARE braces, as on the previous Section line.)
900
901 In working with a document, particularly if using the text formatting
902 programs nroff or troff, it is often advantageous to work in terms of
903 sentences, paragraphs, and sections.  The operations {(} and {)} move to
904 the beginning of the previous and next sentences, respectively.  Thus
905 the command {d)} will delete the rest of the current sentence; likewise
906 {d(} will delete the previous sentence if you are at the beginning of
907 the current sentence, or, if you are not at the beginning of a sentence,
908 it will delete the current sentence from the beginning 
909 up to where you are.
910
911 A sentence is defined to end at a '.', '!', or '?' which is followed
912 by either the end of a line, or by two spaces.  Any number of closing
913 ')', ']', '"', and ''' characters may appear after the '.', '!', or '?'
914 before the spaces or end of line.  Therefore, the {(} and {)} commands
915 would recognize only one sentence in the following line, but two
916 sentences on the second following line.
917
918 Line 39: This is one sentence. Even though it looks like two.
919 Line 40: This is two sentences.  Because it has two spaces after the '.'.
920
921 The operations [{] and [}] move over paragraphs and the operations {[[}
922 and {]]} move over sections.
923
924 A paragraph begins after each empty line, and also at each of a set of nroff
925 paragraph macros.  A section begins after each line with a form-feed ^L in the
926 first column, and at each of a set of nroff section macros.  When preparing a
927 text file as input to nroff, you will probably be using a set of nroff macros
928 to make the formatting specifications easier, or more to your taste.  These
929 macros are invoked by beginning a line with a period followed by the one or two
930 letter macro name. Vi has been programmed to recognize these nroff macros, and
931 if it doesn't recognize your particular macro you can use the {:set paragraphs}
932 or {:set sections} commands so that it will.
933
934 Section 39: more about inserting text
935
936 There are a number of characters which you can use to make correnctions
937 during input mode.  These are summarized in the following table.
938
939     ^H      deletes the last input character
940     ^W      deletes the last input word
941     (erase) same as ^H; each terminal can define its own erase character; 
942             for some it is ^H, for others it is the DELETE key, and for
943             others it is '@'.
944     (kill)  deletes the input on this line; each terminal can define its
945             own line-kill character; for some it is ^U, for others it is
946             '@'; you will need to experiment on your terminal to find
947             out what your line-kill and erase characters are.
948     \       escapes a following ^H, (kill), and (erase) characters: i.e.
949             this is how to put these characters in your file.
950     ^[      escape key; ends insertion mode
951     ^?      the delete key; interrupts an insertion, terminating it
952             abnormally.
953     ^M      the return key; starts a new line.
954     ^D      backtabs over the indentation set by the autoindent option
955     0^D     backtabs over all indentation back to the beginning of the line
956     ^^D     (up-arrow followed by control-d)same as 0^D, except the indentation 
957             will be restored at the beginning of the next line.
958     ^V      quotes the next non-printing character into the file
959
960 If you wish to type in your erase or kill character (say # or @ or ^U) then you
961 must precede it with a \, just as you would do at the normal system command
962 level.  A more general way of typing non-printing characters into the file is
963 to precede them with a ^V.  The ^V echoes as a ^ character on which the cursor
964 rests.  This indicates that the editor expects you to type a control character
965 and it will be inserted into the file at that point.  There are a few
966 exceptions to note.  The implementation of the editor does not allow the null
967 character ^@ to appear in files.  Also the linefeed character ^J is used by the
968 editor to separate lines in the file, so it cannot appear in the middle of a
969 line.  (Trying to insert a ^M into a file, or putting it in the replacement 
970 part of a substitution string will result in the matched line being split in 
971 two.  This, in effect, is how to split lines by using a substitution.)  You can 
972 insert any other character, however, if you wait for the editor to echo the ^ 
973 before you type the character.  In fact, the editor will treat a following 
974 letter as a request for the corresponding control character.  This is the only 
975 way to type ^S or ^Q, since the system normally uses them to suspend and resume 
976 output and never gives them to the editor to process.
977
978 If you are using the autoindent option you can backtab over the indent which it
979 supplies by typing a ^D.  This backs up to the boundary specified by the
980 shiftwidth option.  This only works immediately after the supplied autoindent.
981
982 When you are using the autoindent option you may wish to place a label at the
983 left margin of a line.  The way to do this easily is to type ^ (up-arrow) and
984 then ^D.  The editor will move the cursor to the left margin for one line, and
985 restore the previous indent on the next.  You can also type a 0 followed
986 immediately by a ^D if you wish to kill all indentation and not have it resume
987 on the next line.
988
989 Section 40: more on operators: {d} {c} {<} {>} {!} {=} {y}
990
991 Below is a non-exhaustive list of commands that can follow the operators
992 to affect the range over which the operators will work.  However, note
993 that the operators {<}, {>}, {!}, and {=} do not operate on any object
994 less than a line.  Try {!w} and you will get a beep.  To get the
995 operator to work on just the current line, double it.  E.g. {<<}.
996
997     suffix        will operate on
998     ------        ------------------------
999       ^[            cancels the command
1000       w             the word to the right of the cursor
1001       W             ditto, but ignoring punctuation
1002       b             the word to the left of the cursor
1003       B             ditto, but ignoring punctuation
1004       e             see below.
1005       E               ditto
1006       (space)       a character
1007       $             to the end of the line
1008       ^             to the beginning of the line
1009       / .. /        up to, but not including, the string
1010       ? .. ?        back to and including the string
1011       fc            up to and including the occurrence of c 
1012       Fc            back to and including the occurrence of c
1013       tc            up to but not including the occurrence of c
1014       Tc            back to but not including the occurrence of c
1015       ^M            TWO lines (that's right: two)
1016       (number)^M    that many lines plus one
1017       (number)G     up to and including line (number)
1018       (             the previous sentence if you are at the beginning of
1019                     the current sentence, or the current sentence up to where 
1020                     you are if you are not at the beginning of the current 
1021                     sentence.  Here, 'sentence' refers to the intuitive
1022                     notion of an English sentence, ending with '!', '?',
1023                     or '.' and followed by an end of line or two spaces.
1024       )             the rest of the current sentence
1025       {             analogous to '(', but in reference to paragraphs:
1026                     sections of text surrounded by blank lines
1027       }             analogous to ')', but in reference to paragraphs
1028       [[            analogous to '(', but in reference to sections
1029       ]]            analogous to ')', but in reference to sections
1030       H             the first line on the screen
1031       M             the middle line on the screen
1032       L             the last line on the screen
1033       3L            through the third line from the bottom of the screen
1034       ^F            forward a screenful
1035       ^B            backward a screenful
1036       :
1037       :  etc. etc. etc.
1038
1039 This list is not exhaustive, but it should be sufficient to get the idea
1040 across: after the operator, you can specify a range with a move-the-cursor
1041 command, and that is the region of text over which the operator will be
1042 effective.
1043
1044 Section 41: abbreviations: {:ab}
1045
1046 When typing large documents you may find yourself typing a large phrase
1047 over and over.  Vi gives you the ability to specify an abbreviation for
1048 a long string such that typing the abbreviation will automatically
1049 expand into the longer phrase.
1050
1051 Type {:ab nps Naval Postgraduate School^M}.  Now type:
1052
1053 {iThis is to show off the nps's UNIX editor.^M^[}
1054
1055 Section 42: vi's relationship with the ex editor: {:}
1056
1057 Vi is actually one mode of editing within the editor ex.  When you are
1058 running vi you can escape to the line oriented editor of ex by giving
1059 the command {Q}.  All of the colon-commands which were introduced above
1060 are available in ex.  Likewise, most ex commands can be invoked from vi
1061 using {:}.   
1062
1063 In rare instances, an internal error may occur in vi.  In this case you
1064 will get a diagnostic and will be left in the command mode of ex.  You can
1065 then save your work and quit if you wish by giving the command {x} after
1066 the colon prompt of ex.  Or you can reenter vi (if you are brave) by
1067 giving ex the command {vi}.
1068
1069 Section 43: vi on hardcopy terminals and dumb terminals: open mode
1070
1071 (The author has not checked the following documentation for accuracy.  It is
1072 abstracted from the Introduction to Vi Editing document.)
1073
1074 If you are on a hardcopy terminal or a terminal which does not have a cursor
1075 which can move off the bottom line, you can still use the command set of vi,
1076 but in a different mode.  When you give the vi command to UNIX, the editor will
1077 tell you that it is using open mode.  This name comes from the open command in
1078 ex, which is used to get into the same mode.
1079
1080 The only difference between visual mode (normal vi) and open mode is the way in
1081 which the text is displayed.
1082
1083 In open mode the editor uses a single line window into the file, and moving
1084 backward and forward in the file causes new lines to be displayed, always below
1085 the current line.  Two commands of vi work differently in open: {z} and {^R}.
1086 The {z} command does not take parameters, but rather draws a window of context
1087 around the current line and then returns you to the current line.
1088
1089 If you are on a hardcopy terminal, the {^R} command will retype the current
1090 line.  On such terminals, the editor normally uses two lines to represent the
1091 current line.  The first line is a copy of the line as you started to edit it,
1092 and you work on the line below this line.  When you delete characters, the
1093 editor types a number of \'s to show you the characters which are deleted.  The
1094 editor also reprints the current line soon after such changes so that you can
1095 see what the line looks like again.
1096
1097 It is sometimes useful to use this mode on very slow terminals which can
1098 support vi in the full screen mode.  You can do this by entering ex and using
1099 an {open} command.
1100
1101 *********************************************************************
1102 Section 44: options: {:set} {setenv EXINIT}
1103
1104 You will discover options as you need them.  Do not worry about them very much
1105 on the first pass through this document.  My advice is to glance through them,
1106 noting the ones that look interesting, ignoring the ones you don't understand,
1107 and try re-scanning them in a couple of weeks.
1108
1109 If you decide that you have a favorite set of options and would like to change
1110 the default values for the editor, place a {setenv EXINIT} command in your
1111 .login file.  When you are given an account under UNIX your directory has
1112 placed in it a file that is executed each time you log in.  If one of the
1113 commands in this file sets the environment variable EXINIT to a string of vi
1114 commands, you can have many things done for you each time you invoke vi.  For
1115 example, if you decide that you don't like tabstops placed every eight columns
1116 but prefer every four columns, and that you wish the editor to insert linefeeds
1117 for you when your typing gets you close to column 72, and you want
1118 autoindentation, then include the following line in your .login file:
1119
1120 setenv EXINIT='set tabstop=4 wrapmargin=8 autoindent'
1121
1122 or equivalently
1123
1124 setenv EXINIT='se ts=4 wm=8 ai'
1125
1126 Each time you bring up vi, this command will be executed and the options set.
1127
1128 There are forty options in the vi/ex editor that the user can set for his/her
1129 own convenience.  They are described in more detail in individual sections
1130 below.  The section line will show the full spelling of the option name, the
1131 abbreviation, and the default value of the option.  The text itself
1132 comes from the ex reference manual and is not the epitome of clarity.
1133
1134 Section 44.1: {autoindent}, {ai} default: noai
1135
1136 Can be used to ease the preparation of structured program text.  At the
1137 beginning of each append, change or insert command or when a new line is opened
1138 or created by an append, change, insert, or substitute operation within open or
1139 visual mode, ex looks at the line being appended after, the first line changed
1140 or the line inserted before and calculates the amount of white space at the
1141 start of the line.  It then aligns the cursor at the level of indentation so
1142 determined.
1143
1144 If the user then types lines of text in, they will continue to be justified at
1145 the displayed indenting level.  If more white space is typed at the beginning
1146 of a line, the following line will start aligned with the first non-white
1147 character of the previous line.  To back the cursor up to the preceding tab
1148 stop one can hit {^D}.  The tab stops going backwards are defined at multiples
1149 of the shiftwidth option.  You cannot backspace over the indent, except by
1150 sending an end-of-file with a {^D}.  A line with no characters added to it
1151 turns into a completely blank line (the white space provided for the autoindent
1152 is discarded). Also specially processed in this mode are lines beginning with
1153 an up-arrow `^' and immediately followed by a {^D}.  This causes the input to
1154 be repositioned at the beginning of the line, but retaining the previous indent
1155 for the next line.  Similarly, a `0' followed by a {^D} repositions at the
1156 beginning but without retaining the previous indent.  Autoindent doesn't happen
1157 in global commands or when the input is not a terminal.
1158
1159 Section 44.2: {autoprint}, {ap} default: ap
1160
1161 Causes the current line to be printed after each delete, copy, join, move,
1162 substitute, t, undo or shift command.  This has the same effect as supplying a
1163 trailing `p' to each such command.  Autoprint is suppressed in globals, and
1164 only applies to the last of many commands on a line.
1165
1166 Section 44.3: {autowrite}, {aw} default: noaw
1167
1168 Causes the contents of the buffer to be written to the current file if you have
1169 modified it and give a next, rewind, stop, tag, or {!} command, or a control-
1170 up-arrow {^^} (switch files) or {^]} (tag goto) command in visual.  Note, that
1171 the edit and ex commands do not autowrite.  In each case, there is an
1172 equivalent way of switching when autowrite is set to avoid the autowrite
1173 ({edit} for next, rewind!  for rewind, stop!  for stop, tag!  for tag, shell
1174 for {!}, and {:e #} and a {:ta!} command from within visual).
1175
1176 Section 44.4: {beautify}, {bf} default: nobeautify
1177
1178 Causes all control characters except tab ^I, newline ^M and form-feed ^L to be
1179 discarded from the input.  A complaint is registered the first time a backspace
1180 character is discarded.  Beautify does not apply to command input.
1181
1182 Section 44.5: {directory}, {dir} default: dir=/tmp 
1183
1184 Specifies the directory in which ex places its buffer file.  If this directory
1185 in not writable, then the editor will exit abruptly when it fails to be able to
1186 create its buffer there.
1187
1188 Section 44.6: {edcompatible} default: noedcompatible
1189
1190 Causes the presence or absence of g and c suffixes on substitute commands to be
1191 remembered, and to be toggled by repeating the suffices.  The suffix r makes
1192 the substitution be as in the {~} command, instead of like {&}.
1193
1194 [Author's note: this should not concern users of vi.]
1195
1196 Section 44.7: {errorbells}, {eb} default: noeb
1197
1198 Error messages are preceded by a bell.  However, bell ringing in open and
1199 visual modes on errors is not suppressed by setting noeb.  If possible the
1200 editor always places the error message in a standout mode of the terminal (such
1201 as inverse video) instead of ringing the bell.
1202
1203 Section 44.8: {hardtabs}, {ht} default: ht=8
1204
1205 Gives the boundaries on which terminal hardware tabs are set (or on which the
1206 system expands tabs).
1207
1208 Section 44.9: {ignorecase}, {ic} default: noic
1209
1210 All upper case characters in the text are mapped to lower case in regular
1211 expression matching.  In addition, all upper case characters in regular
1212 expressions are mapped to lower case except in character class specifications
1213 (that is, character in square brackets).
1214
1215 Section 44.10: {lisp} default: nolisp
1216
1217 Autoindent indents appropriately for lisp code, and the {(}, {)}, [{], [}],
1218 {[[}, and {]]} commands in open and visual modes are modified in a
1219 striaghtforward, intuitive fashion to have meaning for lisp.
1220
1221 [Author's note: but don't ask me to define them precisely.]
1222
1223 Section 44.11: {list} default: nolist
1224
1225 All printed lines will be displayed (more) unambiguously, showing tabs as ^I
1226 and end-of-lines with `$'.  This is the same as in the ex command {list}.
1227
1228 Section 44.12: {magic} default: magic for {ex} and {vi}, nomagic for edit.
1229
1230 If nomagic is set, the number of regular expression metacharacters is greatly
1231 reduced, with only up-arrow `^' and `$' having special effects.  In addition
1232 the metacharacters `~' and `&' of the replacement pattern are treated as normal
1233 characters.  All the normal metacharacters may be made magic when nomagic is
1234 set by preceding them with a `\'.
1235
1236 [Author's note: In other words, if magic is set a back-slant turns the magic
1237 off for the following character, and if nomagic is set a back-slant turns the
1238 magic ON for the following character.  And, no, we are not playing Dungeons and
1239 Dragons, although I think the writers of these option notes must have played it
1240 all the time.]
1241
1242 Section 44.13: {mesg} default: mesg
1243
1244 Causes write permission to be turned off to the terminal while you are in
1245 visual mode, if nomesg is set.
1246
1247 [Author's note: I don't know if anyone could have made any one sentence
1248 paragraph more confusing than this one.  What it says is: mesg allows people to
1249 write to you even if you are in visual or open mode; nomesg locks your terminal
1250 so they can't write to you and mess up your screen.]
1251
1252 Section 44.14: {number, nu} default: nonumber
1253
1254 Causes all output lines to be printed with their line numbers.  In addition
1255 each input line will be prompted with its line number.
1256
1257 Section 44.15: {open} default: open
1258
1259 If {noopen}, the commands open and visual are not permitted.  This is set for
1260 edit to prevent confusion resulting from accidental entry to open or visual
1261 mode.
1262
1263 [Author's note: As you may have guessed by now, there are actually three
1264 editors available under Berkeley UNIX that are in reality the same
1265 program, ex, with different options set: ex itself, vi, and edit.]
1266
1267 Section 44.16: {optimize, opt} default: optimize
1268
1269 Throughput of text is expedited by setting the terminal to not do automatic
1270 carriage returns when printing more than one (logical) line of output, greatly
1271 speeding output on terminals without addressable cursors when text with leading
1272 white space is printed.
1273
1274 [Author's note: I still don't know what this option does.]
1275
1276 Section 44.17: {paragraphs, para} default: para=IPLPPPQPP LIbp
1277
1278 Specifies the paragraphs for the [{] and [}] operations in open and visual.
1279 The pairs of characters in the option's value are the names of the nroff macros
1280 which start paragraphs.
1281
1282 Section 44.18: {prompt} default: prompt
1283
1284 Command mode input is prompted for with a `:'.
1285
1286 [Author's note: Doesn't seem to have any effect on vi.]
1287
1288 Section 44.19: {readonly}, {ro} default: noro, unless invoked with -R 
1289                                          or insufficient privileges on file
1290
1291 This option allows you to guarantee that you won't clobber your file by
1292 accident.  You can set the option and writes will fail unless you use an `!'
1293 after the write.  Commands such as {x}, {ZZ}, the autowrite option, and in
1294 general anything that writes is affected.  This option is turned on if you
1295 invoke the editor with the -R flag.
1296
1297 Section 44.20: {redraw} default: noredraw
1298
1299 The editor simulates (using great amounts of output), an intelligent terminal
1300 on a dumb terminal (e.g. during insertions in visual the characters to the
1301 right of the cursor position are refreshed as each input character is typed).
1302 Useful only at very high baud rates, and should be used only if the system is
1303 not heavily loaded: you will notice the performance degradation yourself.
1304
1305 Section 44.21: {remap} default: remap
1306
1307 If on, macros are repeatedly tried until they are unchanged.  For example, if o
1308 is mapped to O, and O is mapped to I, then if remap is set, o will map to I,
1309 but if noremap is set, it will map to O .
1310
1311 Section 44.22: {report} default: report=5 for ex and vi, 2 for edit
1312
1313 Specifies a threshold for feedback from commands.  Any command which modifies
1314 more than the specified number of lines will provide feedback as to the scope
1315 of its changes.  For commands such as global, open, undo, and visual which have
1316 potentially more far reaching scope, the net change in the number of lines in
1317 the buffer is presented at the end of the command, subject to this same
1318 threshold.  Thus notification is suppressed during a global command on the
1319 individual commands performed.
1320
1321 Section 44.23: {scroll} default: scroll=1/2 window
1322
1323 Determines the number of logical lines scrolled when a {^D} is received from a
1324 terminal in command mode, and determines the number of lines printed by a
1325 command mode z command (double the value of scroll).
1326
1327 [Author's note: Doesn't seem to affect {^D} and {z} in visual (vi) mode.]
1328
1329 Section 44.24: sections {sections} default: sections=SHNHH HU 
1330
1331 Specifies the section macros from nroff for the {[[} and {]]} operations in
1332 open and visual.  The pairs of characters in the options's value are the names
1333 of the macros which start paragraphs.
1334
1335 Section 44.25: {shell}, {sh} default: sh=/bin/sh 
1336
1337 Gives the path name of the shell forked for the shell escape command `!', and
1338 by the shell command.  The default is taken from SHELL in the environment, if
1339 present.
1340
1341 [Editor's note: I would suggest that you place the following line in
1342 your .login file:
1343 setenv SHELL '/bin/csh'
1344 ]
1345
1346 Section 44.26: {shiftwidth}, {sw} default: sw=8 
1347
1348 Used in reverse tabbing with {^D} when using autoindent to append text, and
1349 used by the shift commands.  Should probably be the same value as the tabstop
1350 option.
1351
1352 Section 44.27: {showmatch}, {sm} default: nosm 
1353
1354 In open and visual mode, when a `)' or `}' is typed, if the matching `(' or `{'
1355 is on the screen, move the cursor to it for one second.  Extremely useful with
1356 complicated nested expressions, or with lisp.
1357
1358 Section 44.28: {slowopen}, {slow} default: terminal dependent
1359
1360 Affects the display algorithm used in visual mode, holding off display updating
1361 during input of new text to improve throughput when the terminal in use is both
1362 slow and unintelligent.  See "An Introduction to Display Editing with Vi" for
1363 more details.
1364
1365 Section 44.29: {tabstop}, {ts} default: ts=8
1366
1367 The editor expands tabs ^I to tabstop boundaries in the display.
1368
1369 Section 44.30: {taglength}, {tl} default: tl=0
1370
1371 Tags are not significant beyond this many characters.
1372 A value of zero (the default) means that all characters are significant.
1373
1374 Section 44.31: {tags} default: tags=tags /usr/lib/tags
1375
1376 A path of files to be used as tag files for the tag command.  A requested tag
1377 is searched for in the specified files, sequentially.  By default files called
1378 tags are searched for in the current directory and in /usr/lib (a master file
1379 for the entire system).
1380
1381 [Author's note: The author of this tutorial has never used this option, nor
1382 seen it used.  I'm not even sure I know what they are talking about.]
1383
1384 Section 44.32: {term} default: from environment variable TERM
1385
1386 The terminal type of the output device.
1387
1388 Section 44.33: {terse} default: noterse
1389
1390 Shorter error diagnostics are produced for the experienced user.
1391
1392 Section 44.34: {timeout} default: timeout
1393
1394 Causes macros to time out after one second.  Turn it off and they will
1395 wait forever.  This is useful if you want multi-character macros, but if
1396 your terminal sends escape sequences for arrow keys, it will be
1397 necessary to hit escape twice to get a beep.
1398
1399 [Editor's note: Another paragraph which requires a cryptographer.]
1400
1401 Section 44.35: ttytype
1402
1403 [Editor's note: I have found no documentation for this option at all.]
1404
1405 Section 44.36: {warn} default: warn
1406
1407 Warn if there has been `[No write since last change]' before a `!' command
1408 escape.
1409
1410 Section 44.37: {window} default: window=speed dependent
1411
1412 The number of lines in a text window in the visual command.  The default is 8
1413 at slow speeds (600 baud or less), 16 at medium speed (1200 baud), and the full
1414 screen (minus one line) at higher speeds.
1415
1416 Section 44.38: {wrapscan}, {ws} default: ws
1417
1418 Searches using the regular expressions in addressing will wrap around past the
1419 end of the file.
1420
1421 Section 44.39: {wrapmargin}, {wm} default: wm=0
1422
1423 Defines a margin for automatic wrapover of text during input in open and visual
1424 modes.  The numeric value is the number of columns from the right edge of the
1425 screen around which vi looks for a convenient place to insert a new-line
1426 character (wm=0 is OFF).  This is very convenient for touch typists.
1427 Wrapmargin behaves much like fill/nojustify mode does in nroff.
1428
1429 Section 44.40: {writeany}, {wa} default: nowa
1430
1431 Inhibit the checks normally made before write commands, allowing a write to any
1432 file which the system protection mechanism will allow.
1433
1434 Section 44.41: {w300}, {w1200}, {w9600} defaults: w300=8
1435                                                  w1200=16
1436                                                  w9600=full screen minus one
1437
1438 These are not true options but set the default size of the window for when the
1439 speed is slow (300), medium (1200), or high (9600), respectively.  They are
1440 suitable for an EXINIT and make it easy to change the 8/16/full screen rule.
1441
1442 Section 45: Limitations
1443
1444 Here are some editor limits that the user is likely to encounter:
1445        1024   characters per line
1446        256    characters per global command list
1447        128    characters per file name
1448        128    characters in the previous inserted and deleted text in open or 
1449               visual
1450        100    characters in a shell escape command
1451        63     characters in a string valued option
1452        30     characters in a tag name
1453        250000 lines in the file (this is silently enforced).
1454
1455 The visual implementation limits the number of macros defined with map to 32,
1456 and the total number of characters in macros to be less than 512.
1457
1458 [Editor's note: these limits may not apply to versions after 4.1BSD.]