From: Mitchell Wyle Date: Thu, 14 Feb 91 12:48:53 +0100 To: werner@rascal.ics.utexas.edu Subject: My beginner's intro to the vi editor You might want to store this on rascal somewhere, send it to unix neophytes stuck using vi, and announce it to your connections. It appeared in my column in the Sun Observer in May 1990. sccs version control @(#)c8 1.3 90/03/16 17:57:39 "More on vi" On Campus "The Sun Observer" May 1990 A whole bunch of readers sent me e-mail (thank you all!) asking for more articles about vi. One reader added reason number 11 in defense of vi: You don't have to learn many commands to be productive. Another claimed that secretaries seem to type at vi much faster than emacs which "seems to have been invented for two-fingered typists." Most of the e-mail messages asked for a discussion of map macros and .exrc files. This month I'll discuss how to teach (or learn) vi, emphasising the order in which the commands are taught. Even if you do not teach vi or feel that you know vi pretty well, I encourage you to read about these commands; you might be surprised at what should be taught when. Macros and .exrc files will come in the next vi installment. The order in which command functions are taught is important. It is all too easy for a user to fall into a rut of repeating the use of several tens of the same edit command to accomplish an edit task which can be accomplished by pressing one button. It is also typically the case that the one-button command is more natural than having to repeatedly push the same key fifty times. I did my master's dissertation on text editing, and during my research I had to look at the key strokes of several hundred edit sessions. It amazed me how many people didn't know how to delete a line or how to delete a word; they hit the key thirty or forty times! Text editing involves what the cognitive psychologists call "mental chunking" of edit tasks; the user has a mental model of what he wants to do and translates the model into editor commands. More advanced users use more powerful commands (larger chunks) while novice users use only primitive commands. Sun co-founder Bill Joy, when he designed the vi command structure, used the concept that all commands should be given in the same way, and that they should all operate on *any* text entity. The basic paradigm of giving vi edit commands is command where is an optional repeat count, command is the one-letter vi command, and entity is a character, word, line, sentence, paragraph, or section. This mental model of editing is a bit complicated for new users and should not be presented too soon. If a new user learns an advanced task or concept too soon, the command will soon be forgotten for lack of use. On the other hand, the large number of different vi commands is intimidating, and important commands are often skipped. The lack of a standard tutorial for intermediate users also contributes to the general ignorance of productive vi editing in Unix. Industry versus Academia Although learning the more esoteric and advanced commands takes many months of experience, vi basics can be mastered in just a few lessons. Dennis G. Rears (drears@pica.army.mil) developed a vi course for complete novices, and was kind enough to distribute his course slides via e-mail. Mr. Rears developed the course for the U.S. army. His course is very well organized and illustrates an interesting contrast between academic *teaching* and military or industrial *training*. Here on campus and generally in academia, there is often an antagonism between teachers and students. There is very little feedback or course evaluation. Professors are beyond criticism or reproach. Truth and Knowledge are sold to bright young people who struggle full-time to assimilate Megabits of information, while teaching styles, course materials, lectures, and course quality vary enormously. In industry or in the military, the entire system is geared towards a trainee's learning the task or procedure. Instructors, course materials, and exams are evaluated and revised to optimize the learning process. Teachers work much closer to students and there is no antagonism. When a student fails an exam, the *system* failed. The student, recruiter, exam, teacher, and even the course are all evaluated to find out what went wrong. In academia, the student is always blamed for failure. I was once in a foreign language class with a Russian student who boasted that the fastest measurable learning rate in bits per second is achieved by new recruits in the Russian army who have to learn Russian. Some of the methods used are not applicable to industrial training or academic education, but the point is that there is still plenty of room for improvement in our education systems. Although typing and editing skills are highly essential, learning them is not deemed worthy of academic attention. A student's learning or productivity skills are completely ignored on campus. I think I've digressed far enough; Let's get on with the course: Five easy lessons The first vi edit session should familiarize the student with the following commands: . i - insert mode . - leave insert mode and enter command mode . hjkl - move the cursor left, down, up, right . - delete the character left of the cursor (in both modes) . :wq - write the file and quit the editor . :q! - quit the editor without saving. That's all! There are many people who never learn any more than these commands, yet they can perform every edit function in vi, though somewhat inefficiently. The second lesson consists of: . w - move forward one word . b - move backward one word . w - move forward n words . the concept of command where the command is repeated n times. This concept applies to cursor movement from the last lesson, w, b, and all other commands learned in this lesson. Practice with j and k. . 0 - move to beginning of current line . $ - move to end of current line . x - delete character upon which cursor rests . dd - delete line Notice that these commands are not grouped according to category or functionality. Every textbook and tutorial I have seen makes the same mistake of teaching useless commands early because they happen to fall into the "movement" category or function similar to other important commands. Remember when teaching text editing that the user forms a mental model about the editing task and that the order in which the task is taught is also important. The third lesson should include the following commands: . ^F - scroll forward one screen; practice ^F also! . ^B - scroll backwards one screen . /pat - search for the regular expression *pat* Here is a good place to teach some useful regular expressions; make sure they are motivating and useful! I teach the ^, $, \<, and .* metacharacters in that order. Examples from the grep(1) manual page are good for C programmers; most of the vi books have good examples for secretaries. . n Find next occurrence of search pattern pat. At this point the student has learned enough material to practice some pretty sophisticated editing tasks. The new commands in this third lesson should be exercised along with new uses of the commands from the earlier lessons. The standard editing examples from the vi tutorials and text books can be used, or the instructor can invent his own examples. For English speaking people, I use Lincoln's Gettysburg address. Somehow the concepts are timeless and if the students think about the words they're typing, they get more out of that text than most typing tutor examples. Consider the difference between "...quick brown foxed jumped slyly over the lazy dog," and "...a new nation conceived in brotherhood and dedicated to the proposition that all men are created equal." As is often the case using Unix utilities, it takes most people years of experience to "get inside the head" of the designers and to use the commands and functions as efficiently as the authors of the utilities. One should never expect secretaries to compose complex macros and amazingly clever regular expressions. Nonetheless, one can expect most users to attain an intermediate level of editing expertise using a good fraction of the commands. The fourth lesson introduces the un-do and re-do features: . u - un-do last command . . - re-do last command . G - Goto line number n (useful for programmers) . % - Match parenthesis or bracket These commands should be used frequently by programmers. The G command places the cursor at the beginning of line number n. I personally use this command very often right after issuing a :!cc % command, which compiles the program I am currently editing. The compiler displays the lines on which errors occurred and the G command in vi takes me right to the line with the error. The u command is very useful after one too many dd (delete line) commands to rescue that deleted line. It has some intelligence built into it but does not compare well with emacs' undo levels. Vi does have text buffers 1 through 9 which contain the last 9 deleted lines of text (1 is the last line, 2 is second to last, etc.). You can access these buffers with the " command, as in "2p. I still have to admit that emacs' concept of kill buffering is much better. The dot "." command should also become second nature to intermediate users to repeat a command a few times. I find that many simple repetitive tasks can be accomplished more quickly using the . command than by writing a macro. For example, I find myself deleting a few lines or words by typing dd (or dw) and then the dot command five or ten times. I admit it would save key strokes to use dd or dw, but somehow my mind is not always in a state where I can plan in advance and chunk large tasks into a more powerful command. Repeat counts are somehow easier for me to use with cursor positioning. I type $ a lot to get to the end of the line, but I'll also type 7w to move seven words over, or 9^F to move 9 screens down. Lesson five involves moving around more efficiently, using text markers. . ma mark the current position with marker a. . `a go to cursor position marked a. There are, of course, 26 markers, using lower-case letters a through z. In text files of several hundred or several thousand lines, these commands really help. I am embarrassed to admit that I learned them relatively late, but when editing program text I use them all the time. Students coming from wordstar or its off-shoots will feel at home using these commands. First time users will need good, motivating examples. When teaching vi to novices, spend time in preparing your lesson plan to construct good examples of using these commands. For programmers, I recommend marking the current position in a function, going to the definition of a particular struct or record, and then going back to the code using that data structure. Of course using tags will accomplish this type of task much better, but for now it's still a good example. For secretaries, mark the current editing position a few hundred lines deep in a file, and then go back to the beginning (1G) read something there, and finally move back to the marked position. . } beginning of next paragraph . ) beginning of next sentence These commands are hardly ever used but they can be enormous time- savers! Even if the students completely forget how to use these commands or how to invoke them, it is important that they remember that entities extend beyond character, word, and line to include paragraphs and sections. Later, when the concept of command is drilled in, they just might remember that can mean paragraph and section. At any rate, teach the } command early and have your students practice moving around by sentences and paragraphs. Again, at this point I suggest a lot of practice with good examples. Although the first five lessons contain the commands which should account for more than 80% of all key strokes, there are still many nuances and basic concepts missing from these lessons. Some advanced commands and concepts The sixth lesson includes change mode, yanking text, and some basic line editing functions. It is again somewhat niggardly in the number of new commands presented because time for practice is so important. . cw change word At this point the student should be introduced to the most important, all-pervasive vi concept of command . Using the d command with all the different entities (character, word, line, paragraph, and section) should be reviewed. Cursor movement is just a degenerate form of this paradigm! All new commands will fit into this form, and the exercises should emphasize using words and paragraphs, not just characters and lines. . y yank . p put Start with simple word yw and line yy yanking and then progress to paragraphs y} and several lines 9yy. I emphasize combining this command with advanced cursor movement. For example, a good exercise is to mark the current position, move to a certain paragraph, yank it, then return to the original position, and finally put the paragraph there. A typical key stroke sequence might be: ma3^Fjjjy{`ap ma (mark current position with marker a) 3^F (scroll three screens forward) jjj (move to a certain line position) y{ (yank the paragraph) `a (return to original position) p (put the paragraph to the right of current cursor position) . J Join lines I always find myself teaching this command early, as intermediate users get frustrated at not being able to use the key to join lines together. When revising text, the constant editing of phrases and sentences cause the lines of paragraphs to become fragmented. Manually filling a paragraph using J and carriage return insertion becomes necessary if the student wants nice bushy paragraphs. There are, of course, macros and more advance features to fill paragraphs, but at this point it is a good exercise of the J command to do manual paragraph filling. . :s The "ex" (line mode) substitute command I find it a good idea immediately to teach the full format of this command, namely :s/bad/good/. The first range I teach is % for every line. Other ranges (in order of importance) include 1,. from first line to current line, .,$ from current line to the last line in the file, and explicit line number ranges. Options include g for global and q for query. The ex commands are a bit powerful for beginners, and I usually stress the black box approach of learning (by rote) a few forms without trying to understand all the underlying power. Some good examples to teach are :%s/bad/good/g which substitutes the word "good" for the word "bad" everywhere in the file, and :.,$s/^/> / which puts the text "> " in front of every line. . :g The "ex" global command This command is often necessary to delete lines matching some pattern as in :g/^From: /d which would delete all lines which start with the text "From: ". It is very tempting at this point to discuss other "ex" commands such as :e, :w and :r, but the student will most probably forget some important points if he is bombarded with too much information at once. Try to avoid information overload and take a break after this lesson. The die-hard super nerds who absorb advanced editing techniques like sponges should refer to a comprehensive book or command reference. The concept behind the design of this curse is to make vi users more productive by teaching appropriate commands with motivating examples in the proper order. I am assuming that references are available to the students which list all these commands. Lesson seven should start with a review of command and the instructor should give even more examples of using movement and deletion commands within this paradigm. Then come variations of commands which the students have already learned, and finally the important "ex" commands are taught. . a - append text, like the "i" command, but appends . e - move to the end of a word . D - delete from current position to the end of the line . ?pat - search backwards for pattern . ^G - display information about current file I actually use this command quite often to figure out which line I'm at. It can be used in conjunction with the "ex" d command as in the following editing sequence: /bbad^Gjj:172,.d /bbad (find the beginning of some bad text) ^G (find out which line we're on) /ebad (find the end of the bad text) jj (move down two lines) :172,.d (delete all lines from 172 to current line inclusive) I admit that using text markers is much more elegant, as in: /bbadma/ebadjjd`a /bbad (find bad text) ma (mark this point with marker a) /ebad (find end of bad text jj (move down two lines to the real end of bad text) d`a (delete from marker a to here) But we all have to learn to crawl before we can walk, and as I mentioned earlier, I started using text markers relatively late. Some people have the concept of line numbers more prominently in their cognitive models of text editing while other people are more comfortable with symbolic markers. Vi is powerful enough to offer both kinds of users enough commands and options that they can both work productively. . :r (read file) . :e (edit file) . :! (shell command) At this point it is a good idea to teach the generalized form of ex commands, namely :
[!][parameters][flags]. The :e! command is a very good example because it allows catastrophic damage to be saved without leaving vi. :w! file is dangerous but also worth teaching. The astute reader will note that there are a lot of useful vi commands are missing in these lessons, especially the r (revise) and z (zero window) commands which are very useful when working at low baud rates. Also missing are the assorted capital letter commands whose actions are only slightly different from their lower case cousins such as A (append at end of line), I (insert at beginning of line), C (change entire line) etc. For a beginner, these commands are superfluous. Don't teach them in the first week. In the next vi article, we'll round out this course with an introduction to macros and catch up on some of the more useful scrolling commands. We'll also go through more typical examples of every day use -- appropriate everyday use! Then, we can finally get to the fun stuff and discuss macro libraries .exrc files and other advanced features. In the mean time, here is a quiz: What would happen if one typed ;ce if the following line were in his ~/.exrc file? map ;ce :s/^[ ]*//^V^M$ma81a ^[81^V|D`alld0:s/ / /g^M$p^Mk$x^M