File Under: Programming

Advanced VI Tutorial


Well, mobile Webmonkey, if you read our article Tutorial:VI Tutorial for Beginners on the basics of vi, you’ve probably jumped feet first into vi practice, discovered that the mouse really doesn’t work, and practiced a little deleting and adding text of your own. But typing jjjjjjjjjjjj and dw might seem a little limited for serious HTML work. This tutorial focuses on what happens when you’ve mastered the basic moves in vi and are ready for a little more functionality.


Contents

  1. File Manipulation
  2. More Moving Around
  3. Searching and Replacing
  4. Cutting and Pasting
  5. Your Turn

File Manipulation

So far, you’ve moved around within one single vi file. Let’s step back a minute and review how you can manipulate that vi file within a Unix system.

Typing vi filename opens the file – but you knew that already. Any other file manipulation — saving, recovering, or quitting a file — must be done in edit mode. If you’re not sure whether you’re in edit mode, hit the Escape key before doing anything.

If you want to save your work, all you have to do is type:

:w!

This tells the system to write the newest version of the file into the directory where the file lives. If you’ve made a bunch of unsaved changes, then decided you’d rather revert back to the file you started with, go to edit mode and type:

:e!

This will tell the editor to return to the last written (saved) version of the file. If you’d rather bail on the file, just switch to edit mode and type:

:q!

And you’ll have quit vi.

One of the neatest things about vi is that you can string a few commands together. So if I was in a file and wanted to save my changes and quit, I could just type:

:wq!

You also can perform the following handy vi tricks (remember, these must be done in edit mode, so hit the Escape key if you can’t remember which mode you’re in):

To save the file you’re working in as a different filename, type:

:w%.newfilename

where newfilename is, obviously, the new name of the file.

To save just part of the file as a new file (which is a handy thing to know if you’re breaking down a Web page into a series of server-side includes), figure out the line numbers of the first and last lines in the chunk o’ file you want to save (pressing control-g displays all the line numbers in the document), then type:

:l1,l2w newfile

where l1 is the first line of the chunk, l2 is the last line of the chunk, and newfile is the name of the new file.

To recover your file after you’ve blown your buffer or the system has crashed on you, you’ll need to reopen the file and tell the editor to go searching for the last edited copy. To do this, type:

vi -rfilename

You will need to do this at least once in your life.

To open a file at a particular pattern (which comes in handy if you’re debugging your HTML and you know what you need to fix, or if you’ve got an HTML file with a 50-line script within the <head> tags and you want to skip ahead to the body), type:

vi +/pattern filename

So if I wanted to open the file monkeys.html at bananabanana, I’d type:

webmonkey:/usr/diva/> vi +/bananabanana monkeys.html


More Moving Around

Last time, we learned that the four most basic moves — up, down, left, and right — can be mapped, respectively, to the k, j, h, and l keys. But punching in hhhhhhhhhhh gets tedious and is fairly inefficient. There are other shortcuts for getting around.

Typing “w” moves you forward word by word, with the cursor highlighting the beginning of each word, and “b” moves you back word by word.

To go to the end of any word you’ve landed on, type “e” and your cursor will move to the last character in the word. You can also glide between chunks of text:Typing “)” takes you to the start of the next sentence and typing “(” will move you back to the start of the sentence immediately before your cursor. Typing “]” takes you to the beginning of the next paragraph (handy for web pages with lots of text) and “[” takes you — you guessed it — back. You can also use the line numbers to your advantage. Typing “:n,” where n is the line number, whizzes you to the beginning of that line, as does typing “nG” (again, n is the line number).

Tip:You can also control where the cursor falls when you want to move from edit mode to insert mode. You already know that typing i” allows you to insert text right where the cursor was; to insert text to the right of the cursor, hit “a” instead. Or, you can open a whole new line by typing “o.”

Searching and Replacing

One of the reasons I prefer to do my fast fixes in vi is because it’s far quicker than downloading a file, fixing it in an app, and then uploading it again. One of the most frequent fixes I do is searching for and replacing a string of characters in a file.

Searching for text is easy:To search for a string of characters in a document, type:

:/string

The editor will look for that string from the cursor forward, through the rest of the document. You can also search backwards, by typing:

:?string

So if I had a document that read like this:

It may not be the only Unix text editor out there, but it's the only one I'm writing about today. This editor is notable for the uniquely named clones it's spawned:elvis, stevie, vile, and vim.

and my cursor was right before the “u” in “uniquely,” I would type ” :/it's” if I wanted to go looking for the next instance of “it’s” in the document. On the other hand, if I’m looking for the word “Unix,” I’d type:

:?unix

Note that this search command only works on a one-shot basis:If you’re looking for multiple instances of the word “elvis,” you’d repeat your search string by typing “:n” or “:.” (any time you type a period, it tells the editor to repeat the last command).

We’ve tackled searching, so let’s move on to replacing. There are a lot of ways to do this, none of them particularly graceful. To replace a character in a word — say you wanted to change “vile” to “vibe” — make sure the cursor highlights the character l, and type rb (the second letter becomes the replacement letter). Fairly simple, yes? In fact, this is just a rehash of Tutorial:VI Tutorial for Beginners.

If you’re set to tank a line of text and write over it, just move your cursor to the beginning of the line, type cc, and begin typing your new text.

Now it’s time for vi’s trick: searching and replacing. The command is frightening enough to merit its own line:

:g/string/s//replace-term string2/g

where “string” is the word you’re searching for and “string2″ is the replacement word. The whole command looks a little gory, but it works.


Cutting and Pasting

By now, you should be comfortable with moving around a file rapidly, searching for text, and replacing text. It’s time to work on a more complex text manipulation:cutting and pasting text. Let’s work with the example below.

Let's say you're trapped on a planet with a number of very large and very hungry Klingons. Your only hope is to call for a Starfleet captain. Who do you call? Kirk, because he'd kick Klingon butt? Picard, because the Klingon Empire honored its treaty with the Federation? Or Janeway, because she'd take you back to the Quadrant Delta where there aren't any Klingons?

First, I’m going to move the cursor to the phrase “Quadrant Delta.” Any Trekker worth his or her tricorder knows it’s the “Delta Quadrant.” So I’m going to swap the order of the two words by moving my cursor to the “Q” in Quadrant; typing “dw” to delete the word; moving my cursor to the space right after the “a” in “Delta”; and hitting “p.” This tells the editor to put the deleted text (“Quadrant”) in the space immediately after the cursor.

I could have done this a little differently using the “P” key. “P” puts text immediately before the cursor; if I had decided that P was the way to go, I would move my cursor to the “D” in Delta, type “dw” to delete “Delta,” move my cursor to the “Q” in Quadrant, and type “P” to paste the text.

Let’s say I just want to add a little emphasis to the example and point out that these Klingons are giant, mutant Klingons. Lacking decent adjectives, I’m just going to say that the Klingons are “very very very large” Klingons. This means copying the word “very” and pasting it a few times. Type ” yw” (this copies the word), move the cursor to the place where you want to begin pasting “very,” and type “p” to your heart’s content.

If you look at the yw syntax a little more closely, you’ll see that it resembles the syntax for deleting:yw means to yank (copy) a word, dw means to delete it. This resemblance continues all the way through the whole family of yanking commands:You can type “yy” to yank a whole line of text, “y[[” to yank a whole section, and so on.


Your Turn

This ends your introduction to vi. By this point, you’re probably comfortable enough to type “man vi” on a Unix prompt and begin deducing what sort of neat specialized vi commands there are. It’s a powerful tool that could save you a good deal of time.