The source code for a large C program will usually be spread
over several files. Sometimes, it is difficult to keep track of
which file contains which function definitions. To simplify
matters, a UNIX command called ctags can be used together
with the :tag
command of vi.
ctags creates an information file (a database) that vi uses later to determine which files define which functions. By default, this database file is called tags. This file contains lines of the form:
tag_ID file context
where tag_ID
is the name of the C function or macro,
file
is the source file in which tag_ID
is defined,
and context
is a search pattern that shows the line of code
containing tag_ID
.
From within vi, a command such as:
:! |
|
---|
creates a file named tags under your current directory. tags is a database containing information on the functions defined in file.c. A command like:
:!ctags *.c
creates a tags file describing all the C source files under the directory. [If you'll be using the tags file while you're in some other directory, be sure to use an absolute pathname, like this:
`...` |
|
---|
That will store absolute pathnames (14.2) in the tags file. -JP ]
Now suppose your tags file contains information on all the source files that make up a C program. Also suppose that you want to look at or edit a function in the program but do not know where the function is. From within vi, the command:
:tag
name
will look at the tags file to find out which file contains the
definition of the function name.
It will then read in the file and position
the cursor on the line where the name is defined. In this way,
you don't have to know which file you have to edit; you only have
to decide which function you want to edit.
[My favorite tags shortcut is to put the cursor on the first letter of a
function name in your buffer.
Then press CTRL-]
(Control-right square bracket).
vi will read the tags file and open to the function name that was
under your cursor.
At least, my version of vi will do that! -JP ]
NOTE: If tags isn't working, that may be because you have the vi option nowrapscan set. That's a problem on many versions of vi. If typing the following command fixes tags for you:
:set wrapscan
then add that command to your .exrc file (4.9) or EXINIT variable (6.3). (Thanks to Chris Torek for this tip.)
- from O'Reilly & Associates' Learning the vi Editor, Chapter 7