Developer

Vi for programmers, part 2

Continuing our look at vi, this second part of the series concludes with more tips and tricks on everything from copying and pasting to searching for words or patterns. Read on to get the most out of this powerful text editor.

In part 1 of this series, we introduced you to some of the power in ViM's feature set and the flexibility it offers developers on the UNIX platform. Continuing with the theme of making ViM more programmer-friendly, this second part of the series concludes with more tips and tricks to make vi a powerful editing tool in your arsenal.

We'll cover a number of topics including copying and pasting code between scripts in different windows, searching for words or patterns, and storing your settings so they'll load automatically the next time you open your files.

Multiple-window editing

When you're writing code, it's common to switch back and forth between multiple files, either for reference or to copy/paste lines of code. On the Windows platform, this is simple—as the name suggests, all you need to do is open multiple windows and work on them simultaneously.

But what happens in a UNIX console? Like all the best text editors, ViM supports viewing and editing files in different windows.

To see how this works, simply type

:split

from inside vi and watch as your window subdivides horizontally into two. Each subwindow will display the contents of the selected file, and you can move around independently in each one. To move from one window to the other, type

<CTRL>-w-w.

To open a new blank window, type

:new

Instead of having the same file appear in each window, you can tell ViM to open a different file in the new window by adding the file path and name after the split command, as below:

:split /tmp/test.c

The cut, copy, and paste commands—d, y, and p—work as usual and can be used to move text from one window to another. If your console and ViM build support "visual mode," you can even "select" blocks of text and "drag and drop" them between windows.

Performing searches

Need to search your code for a particular word or pattern? Use the / operator, followed by the search string:

/string to search for

ViM will now take you to the next match for your search string. To move forward progressively through the list of matches, keep tapping n.

To search backwards, use the ? operator instead, as in:

?john

If the word you're searching for is already under the cursor, save yourself some typing by using another well-known shortcut. Place the cursor under the search word and type the asterisk (*). ViM will jump to the next match for that word.

You can use the

:set ignorecase

option if you want ViM to perform case-insensitive matching. Also, I like to use the

:set hlsearch

option as well for my searches. This automatically highlights all the matches to the search string in the document, and it's really useful when you're doing things like looking for "all calls to my function hamandeggs(), which I've now decided to change to jamandfigs()".


Tip

Remember that you can use regular expressions in your search strings as well.


Now that you know how to search, let's take a look at how to replace text and how to store your favorite settings.

Performing substitutions

A common programming task involves performing substitutions in a script—for example, correcting a variable name. For such tasks, ViM offers a very powerful substitution command. Here's an example that replaces all occurrences of the variable colour with color on the current line:

:s/colour/color/gi

The g flag ensures that all occurrences on the current line are replaced (without it, only the first occurrence would be replaced), while the i flag performs a case-insensitive search.

You can have ViM confirm each substitution by adding a c flag:

:s/colour/color/gic

Most often, though, you won't want to replace on just a single line. After all, you can do that manually. Instead, you'll usually want to perform a search-and-replace operation across the entire file. The true power of ViM thus becomes evident when you add a range to the previous command, like this:

:1,$s/colour/color/gi

This tells ViM to search and replace across the entire file, from lines 1 (beginning) to $ (end). You can obviously use custom page ranges as well.

Comparing files

In case you need to compare two or more scripts to see what's changed between them, you can use ViM's built-in diff command to view the differences. To do this, start ViM with the -d option, followed by the files to be compared:

$ vim -d expenses.c expenses-old.c

In this mode, ViM starts up with each file occupying a separate vertical window. The differences between the two files are highlighted in different colors (if your terminal supports it) or with marks (if it doesn't). It's possible to switch between windows using the standard window-tab shortcuts discussed earlier.

If you're editing both files simultaneously, two interesting commands exist to make your life simpler. Type

:diffupdate

at any point to recompare the files and update the windows with the latest differences, and type

:set scrollbind

to have the two windows scroll in unison (extremely useful if you're comparing two versions of the same file!).

(Re)storing ViM settings

An interesting yet often overlooked feature of ViM lies in its ability to import custom settings from the file being edited. Typically, you'd use this feature to override the global or personal ViM settings (in vimrc files) with settings that are optimized for editing a particular file.

Therefore, you could automatically turn on auto-indenting for C files, or set a custom color scheme for CGI scripts, simply by appending the appropriate variables to the bottom of the file in what are known as modelines.

Here's how such a settings line might look:

 vim:tw=10:autoindent:

Important: Note the space at the beginning of the line!

If the raw code above will break your script interpreter, you can use the following alternative syntax, which encloses the ViM modeline in comments so that it's ignored by the parser:

/* vim: set autoindent tw=10: */

In order to tell ViM to read the custom settings when the file is opened for editing, you must turn on modeline parsing by typing

:set modeline

in ViM, or by adding it to the ViM startup configuration files.

Editor's Picks

Free Newsletters, In your Inbox