Maintaining Large Programs
**************************

This chapter describes Emacs features for maintaining large programs.

Version Control
===============

A version control system is a package that can record multiple versions of a source file, storing information such as the creation time of each version, who created it, and a description of what was changed in that version.

The Emacs version control interface is called VC.  Its commands work with several different version control systems; currently, it supports GNU Arch, Bazaar, CVS, Git, Mercurial, Monotone, RCS, SCCS/CSSC, and Subversion.  Of these, the GNU project distributes CVS, GNU Arch, RCS, and Bazaar.

VC is enabled automatically whenever you visit a file that is governed by a version control system.  To disable VC entirely, set the customizable variable vc-handled-backends to nil (see Customizing VC).

Introduction to Version Control
-------------------------------

VC allows you to use a version control system from within Emacs, integrating the version control operations smoothly with editing. Though VC cannot completely bridge the gaps between version control systems with widely differing capabilities, it does provide a uniform interface to many version control operations. Regardless of which version control system is in use, you will be able to do basic operations in much the same way.

This section provides a general overview of version control, and describes the version control systems that VC supports.  You can skip this section if you are already familiar with the version control system you want to use.

Understanding the problems it addresses
.......................................

Version control systems provide you with three important capabilities:

  * Reversibility: the ability to back up to a previous state if you discover that some modification you did was a mistake or a bad idea.

  * Concurrency: the ability to have many people modifying the same collection of files knowing that conflicting modifications can be detected and resolved.

  * History: the ability to attach historical data to your data, such as explanatory comments about the intention behind each change to it.  Even for a programmer working solo, change histories are an important aid to memory; for a multi-person project, they are a vitally important form of communication among developers.

Supported Version Control Systems
.................................

VC currently works with many different version control systems or back ends:

  * SCCS was the first version control system ever built, and was long ago superseded by more advanced ones.  VC compensates for certain features missing in SCCS (e.g., tag names for releases) by implementing them itself.  Other VC features, such as multiple branches, are simply unavailable.  Since SCCS is non-free, we recommend avoiding it.

  * CSSC is a free replacement for SCCS.  You should use CSSC only if, for some reason, you cannot use a more recent and better-designed version control system.

  * RCS is the free version control system around which VC was initially built.  Almost everything you can do with RCS can be done through VC. However, you cannot use RCS over the network, and it only works at the level of individual files rather than projects.

  * CVS is the free version control system that was, until recently (circa 2008), used by the majority of free software projects.  Nowadays, it is slowly being superseded by newer systems.  CVS allows concurrent multi-user development either locally or over the network.  It lacks support for atomic commits or file moving/renaming.  VC supports all basic editing operations under CVS.  For some less common tasks, you still need to call CVS from the command line.  Note also that before using CVS you must set up a repository, which is a subject too complex to treat here.

  * Subversion (SVN) is a free version control system designed to be similar to CVS but without its problems.  It supports atomic commits of filesets, and versioning of directories, symbolic links, meta-data, renames, copies, and deletes.

  * GNU Arch is a version control system designed for distributed work. It differs in many ways from older systems like CVS and RCS.  It provides different methods for interoperating between users, support for offline operations, and good branching and merging features.  It also supports atomic commits of filesets and file moving/renaming.  VC does not support all operations provided by GNU Arch, so you must sometimes invoke it from the command line.

  * Git is a distributed version control system invented by Linus Torvalds to support development of Linux (his kernel).  It supports atomic commits of filesets and file moving/renaming.  One significant feature of git is that it largely abolishes the notion of a single centralized repository; instead, each working copy of a git project is its own repository and coordination is done through repository-sync operations.  VC supports most git operations, with the exception of news merges and repository syncing; these must be done from the command line.

  * Mercurial (hg) is a distributed version control system broadly resembling GNU Arch and git, with atomic fileset commits and file moving/renaming.  Like git, it is fully decentralized.  VC supports most Mercurial commands, with the exception of repository sync operations; this needs to be done from the command line.

  * Bazaar (bzr) is a distributed version control system that supports both repository-based and distributed versioning, with atomic fileset commits and file moving/renaming.  VC supports most basic editing operations under Bazaar.

Previous versions of VC supported a version control system known as Meta-CVS.  This support has been dropped because of limited interest from users and developers.

Concepts of Version Control
...........................

When a file is under version control, we say that it is registered in the version control system.  The system has a repository which stores both the file's present state and its change history---enough to reconstruct the current version or any earlier version.  The repository also contains other information, such as log entries that describe the changes made to each file.

A file checked out of a repository is called the work file.  You edit the work file and make changes in it, as you would with an ordinary file.  After you are done with a set of changes, you check in or commit the file; this records the changes in the repository, along with a log entry for those changes.

A copy of a file stored in a repository is called a revision. The history of a file is a sequence of revisions.  Each revisions is named by a revision ID.  The format of the revision ID depends on the version control system; in the simplest case, it is just an integer.

To go beyond these basic concepts, you will need to understand three aspects in which version control systems differ. They can be locking-based or merging-based; they can be file-based or changeset-based; and they can be centralized or decentralized.  VC handles all these modes of operation, but it cannot hide the differences.

A version control system typically has some mechanism to coordinate between users who want to change the same file.  There are two ways to do this: merging and locking.

In a version control system that uses merging, each user may check out and modify a work file at any time.  The system lets you merge your work file, which may contain changes that have not been checked in, with the latest changes that others have checked into the repository.

Older version control systems use a locking scheme instead. Here, work files are normally read-only.  To edit a file, you ask the version control system to make it writable for you by locking it; only one user can lock a given file at any given time.  This procedure is analogous to, but different from, the locking that Emacs uses to detect simultaneous editing of ordinary files (see Interlocking).  When you check in your changes, that unlocks the file, and the work file becomes read-only again.  Other users may then lock the file to make their own changes.

Both locking and merging systems can have problems when multiple users try to modify the same file at the same time.  Locking systems have lock conflicts; a user may try to check a file out and be unable to because it is locked.  In merging systems, merge conflicts happen when you check in a change to a file that conflicts with a change checked in by someone else after your checkout.  Both kinds of conflict have to be resolved by human judgment and communication.  Experience has shown that merging is superior to locking, both in convenience to developers and in minimizing the number and severity of conflicts that actually occur.

SCCS always uses locking.  RCS is lock-based by default but can be told to operate in a merging style.  CVS and Subversion are merge-based by default but can be told to operate in a locking mode. Distributed version control systems, such as GNU Arch, git, and Mercurial, are exclusively merging-based.

VC mode supports both locking and merging version control.  The terms ``checkin'' and ``checkout'' come from locking-based version control systems; newer version control systems have slightly different operations usually called ``commit'' and ``update'', but VC hides the differences between them as much as possible.

On SCCS, RCS, CVS, and other early version control systems, version control operations are file-based: each file has its own comment and revision history separate from that of all other files in the system.  Later systems, beginning with Subversion, are changeset-based: a checkin may include changes to several files, and the entire set of changes is treated as a unit by the system.  Any comment associated with the change does not belong to a single file, but to the changeset itself.

Changeset-based version control is more flexible and powerful than file-based version control; usually, when a change to multiple files has to be reversed, it's good to be able to easily identify and remove all of it.

Early version control systems were designed around a centralized model in which each project has only one repository used by all developers.  SCCS, RCS, CVS, and Subversion share this kind of model.  One of its drawbacks is that the repository is a choke point for reliability and efficiency.

GNU Arch pioneered the concept of decentralized version control, later implemented in git, Mercurial, and Bazaar.  A project may have several different repositories, and these systems support a sort of super-merge between repositories that tries to reconcile their change histories.  At the limit, each developer has his/her own repository, and repository merges replace checkin/commit operations.

VC's job is to help you manage the traffic between your personal workfiles and a repository.  Whether that repository is a single master or one of a network of peer repositories is not something VC has to care about.  Thus, the difference between a centralized and a decentralized version control system is invisible to VC mode.

Types of Log File
.................

Projects that use a version control system can have two types of log for changes.  One is the log maintained by the version control system: each time you check in a change, you fill out a log entry for the change (see Log Buffer).  This is called the version control log.

The other kind of log is the file ChangeLog (see Change Log).  It provides a chronological record of all changes to a large portion of a program---typically one directory and its subdirectories. A small program would use one ChangeLog file; a large program may have a ChangeLog file in each major directory. See Change Log.  Programmers have used change logs since long before version control systems.

Changeset-based version systems typically maintain a changeset-based modification log for the entire system, which makes change log files somewhat redundant.  One advantage that they retain is that it is sometimes useful to be able to view the transaction history of a single directory separately from those of other directories.

A project maintained with version control can use just the version control log, or it can use both kinds of logs.  It can handle some files one way and some files the other way.  Each project has its policy, which you should follow.

When the policy is to use both, you typically want to write an entry for each change just once, then put it into both logs.  You can write the entry in ChangeLog, then copy it to the log buffer with C-c C-a when checking in the change (see Log Buffer).  Or you can write the entry in the log buffer while checking in the change, and later use the C-x v a command to copy it to ChangeLog (see Change Logs and VC).

Version Control and the Mode Line
---------------------------------

When you visit a file that is under version control, Emacs indicates this on the mode line.  For example, RCS-1.3 says that RCS is used for that file, and the current version is 1.3.

The character between the back-end name and the revision ID indicates the version control status of the file.  - means that the work file is not locked (if locking is in use), or not modified (if locking is not in use).  : indicates that the file is locked, or that it is modified.  If the file is locked by some other user (for instance, jim), that is displayed as RCS:jim:1.3.

On a graphical display, you can move the mouse over this mode line indicator to pop up a ``tool-tip'', which displays a more verbose description of the version control status.  Pressing Mouse-1 over the indicator pops up a menu of VC commands.  This menu is identical to the Tools / Version Control menu item.

When Auto Revert mode (see Reverting) reverts a buffer that is under version control, it updates the version control information in the mode line.  However, Auto Revert mode may not properly update this information if the version control status changes without changes to the work file, from outside the current Emacs session.  If you set auto-revert-check-vc-info to t, Auto Revert mode updates the version control status information every auto-revert-interval seconds, even if the work file itself is unchanged.  The resulting CPU usage depends on the version control system, but is usually not excessive.

Basic Editing under Version Control
-----------------------------------

Most VC commands operate on VC filesets.  A VC fileset is a collection of one or more files that a VC operation acts on.  When you type VC commands in a buffer visiting a version-controlled file, the VC fileset is simply that one file.  When you type them in a VC Directory buffer, and some files in it are marked, the VC fileset consists of the marked files (see VC Directory Mode).

The principal VC command is an all-purpose command, C-x v v (vc-next-action), that performs either locking, merging or a check-in (depending on the situation) on the current VC fileset.  You can use C-x v v in a file-visiting buffer or in a VC Directory buffer.

C-x v v
     Perform the appropriate next version control operation on the VC fileset.

The precise action of C-x v v depends on the state of the VC fileset, and whether the version control system uses locking or merging.  This is described in detail in the subsequent sections.

VC filesets are the way that VC mode bridges the gap between file-based and changeset-based version control systems.  They are, essentially, a way to pass multiple file arguments as a group to version control commands.  For example, on Subversion, a checkin with a multi-file VC fileset becomes a joint commit, as though you had typed svn commit with those file arguments at the shell command line.  All files in a VC fileset must be under the same version control system; if they are not, Emacs signals an error when you attempt to execute a command on the fileset.

Support for VC filesets and changeset-based version control systems is the main improvement to VC in Emacs 23.  When you mark multi-file VC in a VC Directory buffer, VC operations treat them as a VC fileset, and operate on them all at once if the version control system is changeset-based.  See VC Directory Mode.

VC filesets are distinct from the ``named filesets'' used for viewing and visiting files in functional groups (see Filesets). Unlike named filesets, VC filesets are not named and don't persist across sessions.

Basic Version Control with Merging
..................................

When your version control system is merging-based (the default for CVS and all newer version control systems), work files are always writable; you need not do anything special to begin editing a file. The status indicator on the mode line is - if the file is unmodified; it flips to : as soon as you save any changes (see VC Mode Line).

Here is what C-x v v does when using a merging-based system:

  * If the work file is the same as in the repository, it does nothing.

  * If you have not changed the work file, but some other user has checked in changes to the repository, C-x v v merges those changes into the work file.

  * If you have made modifications to the work file, C-x v v attempts to check in your changes.  To do this, Emacs first reads the log entry for the new revision (see Log Buffer).  If some other user has checked in changes to the repository since you last checked it out, the checkin fails.  In that case, type C-x v v again to merge those changes into your own work file; this puts the work file into a ``conflicted'' state.  Type C-x v v to clear the ``conflicted'' state; VC then regards the file as up-to-date and modified, and you can try to check it in again.

     To pick up any recent changes from the repository without trying to commit your own changes, type C-x v m RET. See Merging.

These rules also apply when you use RCS in its ``non-locking'' mode, except that changes will not be automatically merged from the repository.  Nothing informs you if another user has checked in changes in the same file since you began editing it; when you check in your revision, his changes are removed (however, they remain in the repository and are thus not irrevocably lost).  Therefore, you must verify that the current revision is unchanged before checking in your changes.  In addition, locking is possible with RCS even in this mode: C-x v v with an unmodified file locks the file, just as it does with RCS in its normal locking mode (see VC With A Locking VCS).

Basic Version Control with Locking
..................................

Under a locking-based version control system (such as SCCS, and RCS in its default mode), C-x v v does the following:

  * If the file is not locked, C-x v v locks it, and makes it writable so that you can change it.

  * If the file is locked by you, and contains changes, C-x v v checks in the changes.  In order to do this, it first reads the log entry for the new revision.  See Log Buffer.

  * If the file is locked by you, but you have not changed it since you locked it, C-x v v releases the lock and makes the file read-only again.

  * If the file is locked by some other user, C-x v v asks you whether you want to ``steal the lock'' from that user.  If you say yes, the file becomes locked by you, but a message is sent to the person who had formerly locked the file, to inform him of what has happened.

These rules also apply when you use CVS in locking mode, except that there is no such thing as stealing a lock.

Advanced Control in C-x v v
...........................

When you give a prefix argument to vc-next-action (C-u C-x v v), it still performs the next logical version control operation, but accepts additional arguments to specify precisely how to do the operation.

  * If the file is modified (or locked), you can specify the revision ID to use for the new version that you check in.  This is one way to create a new branch (see Branches).

  * If the file is not modified (and unlocked), you can specify the revision to select; this lets you start working from an older revision, or on another branch.  If you do not enter any revision, that takes you to the highest (``head'') revision on the current branch; therefore C-u C-x v v RET is a convenient way to get the latest version of a file from the repository.

  * Instead of the revision ID, you can also specify the name of a version control system.  This is useful when one file is being managed with two version control systems at the same time (see Local Version Control).

Features of the Log Entry Buffer
................................

When you check in changes, Emacs pops up a buffer called *VC-Log* for you to enter a log entry.

After you have finished editing the log message, type C-c C-c to exit the buffer and commit the change.

In the *VC-Log* buffer, typing C-c C-f (log-edit-show-files) displays a list of files in the VC fileset you are committing.  If you called C-x v v directly from a work file, the VC fileset consists of that single file, so this command is not very useful.  If you called C-x v v from a VC directory buffer, the VC fileset may consist of multiple files (see VC Directory Mode).

Type C-c C-d (log-edit-show-diff) to show a ``diff'' of the changes you have made (i.e., the differences between the work file and the repository revision from which you started editing the file). The diff is displayed in a special buffer in another window. See Comparing Files.

If you have written an entry in the ChangeLog (see Change Log), type C-c C-a (log-edit-insert-changelog) to pull it into the *VC-Log* buffer.  If the topmost item in the ChangeLog was made under your user name on the current date, this command searches that item for entries that match the file(s) to be committed; if found, these entries are inserted. See Change Logs and VC, for the opposite way of working---generating ChangeLog entries from the revision control log.

To abort a check-in, just don't type C-c C-c in that buffer.  You can switch buffers and do other editing.  As long as you don't try to check in another file, the entry you were editing remains in the *VC-Log* buffer, and you can go back to that buffer at any time to complete the check-in.

If you change several source files for the same reason, it is often convenient to specify the same log entry for many of the files.  (This is the normal way to do things on a changeset-oriented system, where comments are attached to changesets rather than the history of individual files.)  The most convenient way to do this is to mark all the files in VC Directory Mode and check in from there; the log buffer will carry the fileset information with it and do a group commit when you type C-c C-c.

You can also browse the history of previous log entries to duplicate a checkin comment. This can be useful when you want several files to have checkin comments that vary only slightly from each other. The commands M-n, M-p, M-s and M-r for doing this work just like the minibuffer history commands (except that these versions are used outside the minibuffer).

Each time you check in a change, the log entry buffer is put into VC Log Edit mode, which involves running two hooks: text-mode-hook and vc-log-mode-hook.  See Hooks.

Examining And Comparing Old Revisions
-------------------------------------

One of the convenient features of version control is the ability to examine any revision of a file, or compare two revisions.

C-x v ~ REVISION RET
     Examine revision REVISION of the visited file, in a buffer of its own.

C-x v =
     Compare the buffer contents associated with the current fileset with the working revision(s) from which you started editing.

C-u C-x v = RET OLDVERS RET NEWVERS RET
     Compare the specified two repository revisions of the current fileset.

C-x v g
     Display an annotated version of the file: for each line, show the latest revision in which it was modified.

To examine an old revision, visit the work file and type C-x v ~ REVISION RET (vc-revision-other-window).  Here, REVISION is either the desired revision ID (see VCS Concepts), or the name of a tag or branch (see Tags). This command puts the text of the old revision in a file named FILENAME.~REVISION~, and visits it in its own buffer in a separate window.

C-x v = (vc-diff) compares the current buffer contents of each file in the current VC fileset (saving them if necessary) with the repository revision from which you started editing.  Note that the latter may or may not be the latest revision of the file(s).  The diff is displayed in a special buffer in another window.  See Comparing Files.

To compare two arbitrary revisions of the current VC fileset, call vc-diff with a prefix argument: C-u C-x v =.  This prompts for two revision IDs, using the minibuffer, and displays the diff in a special buffer in another window.  Instead of providing a revision ID, you can give an empty input, which specifies the current contents of the work file; or a tag or branch name (see Tags). If your version control system is file-based (e.g. CVS) rather than changeset-based (Subversion, GNU Arch, git, Mercurial), supplying a revision ID for a multi-file fileset (as opposed to a symbolic tag name) is unlikely to return diffs that are connected in any meaningful way.

If you invoke C-x v = or C-u C-x v = from a buffer that is neither visiting a version-controlled file nor a VC directory buffer, these commands generate a diff of all registered files in the current directory and its subdirectories.

C-x v = works by running a variant of the diff utility designed to work with the version control system in use.  The options to pass to the diff command are taken from the first non-nil value of vc-BACKEND-diff-switches, vc-diff-switches, and diff-switches (see Comparing Files), in that order. Since nil means to check the next variable in the sequence, either of the first two may use the value t to mean no switches at all. Most of the vc...diff-switches variables default to nil, but some default to t.  These are for those version control systems (e.g. SVN) whose diff implementations do not accept common options (e.g. -c) likely to be in diff-switches.

The buffer produced by C-x v = supports the commands of Compilation mode (see Compilation Mode), such as C-x ` and C-c C-c, in both the ``old'' and ``new'' text, and they always find the corresponding locations in the current work file.  (Older revisions are not, in general, present as files on your disk.)

For some back ends, you can display the file annotated with per-line revision information, by typing C-x v g (vc-annotate).  This creates a new buffer (the ``annotate buffer'') displaying the file's text, with each part colored to show how old it is.  Text colored red is new, blue means old, and intermediate colors indicate intermediate ages.  By default, the color is scaled over the full range of ages, such that the oldest changes are blue, and the newest changes are red.

When you give a prefix argument to this command, Emacs reads two arguments using the minibuffer: the ID of which revision to display and annotate (instead of the current file contents), and the time span in days the color range should cover.

From the annotate buffer, these and other color scaling options are available from the VC-Annotate menu.  In this buffer, you can also use the following keys to browse the annotations of past revisions, view diffs, or view log entries:

p
     Annotate the previous revision, that is to say, the revision before the one currently annotated.  A numeric prefix argument is a repeat count, so C-u 10 p would take you back 10 revisions.

n
     Annotate the next revision---the one after the revision currently annotated.  A numeric prefix argument is a repeat count.

j
     Annotate the revision indicated by the current line.

a
     Annotate the revision before the one indicated by the current line. This is useful to see the state the file was in before the change on the current line was made.

f
     Show in a buffer the file revision indicated by the current line.

d
     Display the diff between the current line's revision and the previous revision.  This is useful to see what the current line's revision actually changed in the file.

D
     Display the diff between the current line's revision and the previous revision for all files in the changeset (for VC systems that support changesets).  This is useful to see what the current line's revision actually changed in the tree.

l
     Show the log of the current line's revision.  This is useful to see the author's description of the changes in the revision on the current line.

w
     Annotate the working revision--the one you are editing.  If you used p and n to browse to other revisions, use this key to return to your working revision.

v
     Toggle the annotation visibility.  This is useful for looking just at the file contents without distraction from the annotations.

The Secondary Commands of VC
----------------------------

This section explains the secondary commands of VC.

Registering a File for Version Control
......................................

You can put any file under version control by simply visiting it, and then typing C-x v i (vc-register).

C-x v i
     Register the visited file for version control.

To register the file, Emacs must choose which version control system to use for it.  If the file's directory already contains files registered in a version control system, Emacs uses that system.  If there is more than one system in use for a directory, Emacs uses the one that appears first in vc-handled-backends (see Customizing VC). On the other hand, if there are no files already registered, Emacs uses the first system from vc-handled-backends that could register the file (for example, you cannot register a file under CVS if its directory is not already part of a CVS tree); with the default value of vc-handled-backends, this means that Emacs uses RCS in this situation.

If locking is in use, C-x v i leaves the file unlocked and read-only.  Type C-x v v if you wish to start editing it.  After registering a file with CVS, you must subsequently commit the initial revision by typing C-x v v.  Until you do that, the revision ID appears as @@ in the mode line.

The default initial revision ID for a newly registered file varies by what VCS you are using; normally it will be 1.1 on VCSes that use dot-pair revision IDs and 1 on VCSes that use monotonic IDs. You can specify a different default by setting the variable vc-default-init-revision, or you can give C-x v i a numeric argument; then it reads the initial revision ID for this particular file using the minibuffer.

If vc-initial-comment is non-nil, C-x v i reads an initial comment to describe the purpose of this source file.  Reading the initial comment works like reading a log entry (see Log Buffer).

VC Status Commands
..................

C-x v l
     Display revision control state and change history.

To view the detailed revision control status and history of a file, type C-x v l (vc-print-log).  This pops up a special buffer named *vc-change-log*, in a new window, that displays the history of changes to the current file, including the text of the log entries.  The point is centered at the revision of the file that is currently being visited.

In the *vc-change-log* buffer, you can use the following keys to move between the logs of revisions and of files, to view past revisions, to modify change comments, to view annotations and to view diffs:

p
     Move to the previous revision-item in the buffer.  (Revision entries in the log buffer are usually in reverse-chronological order, so the previous revision-item usually corresponds to a newer revision.)  A numeric prefix argument is a repeat count.

n
     Move to the next revision-item (which most often corresponds to the previous revision of the file).  A numeric prefix argument is a repeat count.

P
     Move to the log of the previous file, when the logs of multiple files are in the log buffer (see VC Directory Mode).  Otherwise, just move to the beginning of the log.  A numeric prefix argument is a repeat count, so C-u 10 P would move backward 10 files.

N
     Move to the log of the next file, when the logs of multiple files are in the log buffer (see VC Directory Mode).  It also takes a numeric prefix argument as a repeat count.

a
     Annotate the revision indicated by the current line.

e
     Modify the change comment displayed at point.  Note that not all VC systems support modifying change comments.

f
     Visit the revision indicated at the current line, like typing C-x v ~ and specifying this revision's ID (see Old Revisions).

d
     Display the diff (see Comparing Files) between the revision indicated at the current line and the next earlier revision.  This is useful to see what actually changed in the file when the revision indicated on the current line was committed.

D
     Display the changeset diff (see Comparing Files) between the revision indicated at the current line and the next earlier revision. This is useful to see all the changes to all files that the revision indicated on the current line did when it was committed.

Undoing Version Control Actions
...............................

C-x v u
     Revert the buffer and the file to the working revision from which you started editing the file.

C-x v c
     Remove the last-entered change from the master for the visited file. This undoes your last check-in.

If you want to discard your current set of changes and revert to the working revision from which you started editing the file, use C-x v u (vc-revert-buffer).  If the version control system is locking-based, this leaves the file unlocked, and you must lock it again before making new changes.  C-x v u requires confirmation, unless it sees that you haven't made any changes with respect to the master copy of the working revision.

C-x v u is also the command to unlock a file if you lock it and then decide not to change it.

To cancel a change that you already checked in, use C-x v c (vc-rollback).  This command discards all record of the most recent checked-in revision, but only if your work file corresponds to that revision---you cannot use C-x v c to cancel a revision that is not the latest on its branch.  Note that many version control systems do not support rollback at all; this command is something of a historical relic.

VC Directory Mode
-----------------

When you are working on a large program, it is often useful to find out which files have changed within an entire directory tree, or to view the status of all files under version control at once, and to perform version control operations on collections of files.  You can use the command C-x v d (vc-dir) to make a directory listing that includes only files relevant for version control.  This creates a VC Directory buffer and displays it in a separate window.

The VC Directory buffer works with all the version control systems that VC supports.  For CVS, Emacs also offers a more powerful facility called PCL-CVS.  See About PCL-CVS (PCL-CVS --- The Emacs Front-End to CVS).

The VC Directory Buffer
.......................

The VC Directory buffer contains a list of version-controlled files in the current directory and its subdirectories.  Files which are up-to-date (have no local differences from the repository copy) are usually hidden; if all files in a subdirectory are up-to-date, the subdirectory is hidden as well.  There is an exception to this rule: if VC mode detects that a file has changed to an up-to-date state since you last looked at it, that file and its state are shown.

If a directory uses more that one version control system, you can select which system to use for the vc-dir command by invoking vc-dir with a prefix argument: C-u C-x v d.

The line for an individual file shows the version control state of the file.  Under RCS and SCCS, the name of the user locking the file is shown; under CVS, an abbreviated version of the cvs status output is used.  Here is an example using CVS:

                            ./
         modified           file1.c
         needs-update       file2.c
         needs-merge        file3.c

In this example, file1.c is modified with respect to the repository, and file2.c is not.  file3.c is modified, but other changes have also been checked in to the repository---you need to merge them with the work file before you can check it in.

In the above, if the repository were on a remote machine, VC only contacts it when the variable vc-stay-local (or vc-cvs-stay-local) is nil (see CVS Options).  This is because access to the repository may be slow, or you may be working offline and not have access to the repository at all.  As a consequence, VC would not be able to tell you that file3.c is in the ``merge'' state; you would learn that only when you try to check-in your modified copy of the file, or use a command such as C-x v m.

In practice, this is not a problem because CVS handles this case consistently whenever it arises.  In VC, you'll simply get prompted to merge the remote changes into your work file first.  The benefits of less network communication usually outweigh the disadvantage of not seeing remote changes immediately.

When a VC directory displays subdirectories it omits some that should never contain any files under version control.  By default, this includes Version Control subdirectories such as RCS and CVS; you can customize this by setting the variable vc-directory-exclusion-list.

VC Directory Commands
.....................

VC Directory mode has a full set of navigation and marking commands for picking out filesets.  Some of these are also available in a context menu invoked by the mouse-2 button.

Up- and down-arrow keys move in the buffer; n and p  also move vertically as in other list-browsing modes.  SPC and TAB behave like down-arrow, and BackTab behaves like up-arrow.

Both C-m and f visit the file on the current line.  o visits that file in another window.  q dismisses the directory buffer.

x hides up-to-date files.

m marks the file or directory on the current line.  If the region is active, m marks all the files in the region.  There are some restrictions when marking: a file cannot be marked if any of its parent directories are marked, and a directory cannot be marked if any files in it or in its child directories are marked.

M marks all the files with the same VC state as the current file if the cursor is on a file.  If the cursor is on a directory, it marks all child files.  With a prefix argument: marks all files and directories.

u unmarks the file or directory on the current line.  If the region is active, it unmarks all the files in the region.

U marks all the files with the same VC state as the current file if the cursor is on a file.  If the cursor is on a directory, it unmarks all child files.  With a prefix argument: unmarks all marked files and directories.

It is possible to do search, search and replace, incremental search, and incremental regexp search on multiple files.  These commands will work on all the marked files or the current file if nothing is marked. If a directory is marked, the files in that directory shown in the VC directory buffer will be used.

S searches the marked files.

Q does a query replace on the marked files.

M-s a C-s does an incremental search on the marked files.

M-s a C-M-s does an incremental search on the marked files.

Commands are also accessible from the VC-dir menu.  Note that some VC backends use the VC-dir menu to make available extra backend specific commands.

Normal VC commands with the C-x v prefix work in VC directory buffers.  Some single-key shortcuts are available as well; =, +, l, i, and v behave as through prefixed with C-x v.

The command C-x v v (vc-next-action) operates on all the marked files, so that you can check in several files at once. If the underlying VC supports atomic commits of multiple-file changesets, C-x v v with a selected set of modified but not committed files will commit all of them at once as a single changeset.

When C-x v v (vc-next-action) operates on multiple files, all of those files must be either in the same state or in compatible states (added, modified and removed states are considered compatible).  Otherwise it signals an error.  This differs from the behavior of older versions of VC, which did not have fileset operations and simply did vc-next-action on each file individually.

If any files are in a state that calls for commit, C-x v v reads a single log entry and uses it for the changeset as a whole.  If the underling VCS is file- rather than changeset-oriented, the log entry will be replicated into the history of each file.

Multiple Branches of a File
---------------------------

One use of version control is to maintain multiple ``current'' revisions of a file.  For example, you might have different revisions of a program in which you are gradually adding various unfinished new features.  Each such independent line of development is called a branch.  VC allows you to create branches, switch between different branches, and merge changes from one branch to another. Please note, however, that branches are not supported for SCCS.

A file's main line of development is usually called the trunk. You can create multiple branches from the trunk.  How the difference between trunk and branch is made visible is dependent on whether the VCS uses dot-pair or monotonic version IDs.

In VCSes with dot-pair revision IDs, the revisions on the trunk are normally IDed 1.1, 1.2, 1.3, etc.  At any such revision, you can start an independent branch.  A branch starting at revision 1.2 would have revision ID 1.2.1.1, and consecutive revisions on this branch would have IDs 1.2.1.2, 1.2.1.3, 1.2.1.4, and so on.  If there is a second branch also starting at revision 1.2, it would consist of revisions 1.2.2.1, 1.2.2.2, 1.2.2.3, etc.

In VCSes with monotonic revision IDs, trunk revisions are IDed as 1, 2, 3, etc.  A branch from (say) revision 2 might start with 2.1 and continue through 2.2, 2.3, etc.  But naming conventions for branches and subbranches vary widely on these systems, and some (like Mercurial) never depart from the monotonic integer sequence at all. Consult the documentation of the VCS you are using.

If you omit the final component of a dot-pair revision ID, that is called a branch ID.  It refers to the highest existing revision on that branch---the head revision of that branch.  The branches in the dot-pair example above have branch IDs 1.2.1 and 1.2.2.

Switching between Branches
..........................

To switch between branches, type C-u C-x v v and specify the revision ID you want to select.  On a locking-based system, this version is then visited unlocked (write-protected), so you can examine it before locking it.  Switching branches in this way is allowed only when the file is not locked.

On a VCS with dot-pair IDs, you can omit the minor part, thus giving only the branch ID; this takes you to the head version on the chosen branch.  If you only type RET, Emacs goes to the highest version on the trunk.

After you have switched to any branch (including the main branch), you stay on it for subsequent VC commands, until you explicitly select some other branch.

Creating New Branches
.....................

To create a new branch from a head revision (one that is the latest in the branch that contains it), first select that revision if necessary, lock it with C-x v v, and make whatever changes you want.  Then, when you check in the changes, use C-u C-x v v.  This lets you specify the revision ID for the new revision.  You should specify a suitable branch ID for a branch starting at the current revision. For example, if the current revision is 2.5, the branch ID should be 2.5.1, 2.5.2, and so on, depending on the number of existing branches at that point.

To create a new branch at an older revision (one that is no longer the head of a branch), first select that revision (see Switching Branches).  Your procedure will then differ depending on whether you are using a locking or merging-based VCS.

On a locking VCS, you will need to lock the old revision branch with C-x v v.  You'll be asked to confirm, when you lock the old revision, that you really mean to create a new branch---if you say no, you'll be offered a chance to lock the latest revision instead.  On a merging-based VCS you will skip this step.

Then make your changes and type C-x v v again to check in a new revision.  This automatically creates a new branch starting from the selected revision.  You need not specially request a new branch, because that's the only way to add a new revision at a point that is not the head of a branch.

After the branch is created, you ``stay'' on it.  That means that subsequent check-ins create new revisions on that branch.  To leave the branch, you must explicitly select a different revision with C-u C-x v v.  To transfer changes from one branch to another, use the merge command, described in the next section.

Merging Branches
................

When you have finished the changes on a certain branch, you will often want to incorporate them into the file's main line of development (the trunk).  This is not a trivial operation, because development might also have proceeded on the trunk, so that you must merge the changes into a file that has already been changed otherwise.  VC allows you to do this (and other things) with the vc-merge command.

C-x v m (vc-merge)
     Merge changes into the work file.

C-x v m (vc-merge) takes a set of changes and merges it into the current version of the work file.  It firsts asks you in the minibuffer where the changes should come from.  If you just type RET, Emacs merges any changes that were made on the same branch since you checked the file out (we call this merging the news). This is the common way to pick up recent changes from the repository, regardless of whether you have already changed the file yourself.

You can also enter a branch ID or a pair of revision IDs in the minibuffer.  Then C-x v m finds the changes from that branch, or the differences between the two revisions you specified, and merges them into the current revision of the current file.

As an example, suppose that you have finished a certain feature on branch 1.3.1.  In the meantime, development on the trunk has proceeded to revision 1.5.  To merge the changes from the branch to the trunk, first go to the head revision of the trunk, by typing C-u C-x v v RET.  Revision 1.5 is now current.  If locking is used for the file, type C-x v v to lock revision 1.5 so that you can change it.  Next, type C-x v m 1.3.1 RET.  This takes the entire set of changes on branch 1.3.1 (relative to revision 1.3, where the branch started, up to the last revision on the branch) and merges it into the current revision of the work file.  You can now check in the changed file, thus creating revision 1.6 containing the changes from the branch.

It is possible to do further editing after merging the branch, before the next check-in.  But it is usually wiser to check in the merged revision, then lock it and make the further changes.  This will keep a better record of the history of changes.

When you merge changes into a file that has itself been modified, the changes might overlap.  We call this situation a conflict, and reconciling the conflicting changes is called resolving a conflict.

Whenever conflicts occur during merging, VC detects them, tells you about them in the echo area, and asks whether you want help in merging. If you say yes, it starts an Ediff session (see Ediff (The Ediff Manual)).

If you say no, the conflicting changes are both inserted into the file, surrounded by conflict markers.  The example below shows how a conflict region looks; the file is called name and the current master file revision with user B's changes in it is 1.11.

     <<<<<<< name
       USER A'S VERSION
     =======
       USER B'S VERSION
     >>>>>>> 1.11

Then you can resolve the conflicts by editing the file manually.  Or you can type M-x vc-resolve-conflicts after visiting the file. This starts an Ediff session, as described above.  Don't forget to check in the merged version afterwards.

Multi-User Branching
....................

It is often useful for multiple developers to work simultaneously on different branches of a file.  CVS and later systems allow this by default; for RCS, it is possible if you create multiple source directories.  Each source directory should have a link named RCS which points to a common directory of RCS master files. Then each source directory can have its own choice of selected revisions, but all share the same common RCS records.

This technique works reliably and automatically, provided that the source files contain RCS version headers (see Version Headers). The headers enable Emacs to be sure, at all times, which revision ID is present in the work file.

If the files do not have version headers, you must instead tell Emacs explicitly in each session which branch you are working on.  To do this, first find the file, then type C-u C-x v v and specify the correct branch ID.  This ensures that Emacs knows which branch it is using during this particular editing session.

     [file vc1-xtra.texi not included]

Change Logs
===========

A change log file contains a chronological record of when and why you have changed a program, consisting of a sequence of entries describing individual changes.  Normally it is kept in a file called ChangeLog in the same directory as the file you are editing, or one of its parent directories.  A single ChangeLog file can record changes for all the files in its directory and all its subdirectories.

Change Log Commands
-------------------

The Emacs command C-x 4 a adds a new entry to the change log file for the file you are editing (add-change-log-entry-other-window).  If that file is actually a backup file, it makes an entry appropriate for the file's parent---that is useful for making log entries for functions that have been deleted in the current version.

C-x 4 a visits the change log file and creates a new entry unless the most recent entry is for today's date and your name.  It also creates a new item for the current file.  For many languages, it can even guess the name of the function or other object that was changed.

When the variable add-log-keep-changes-together is non-nil, C-x 4 a adds to any existing item for the file rather than starting a new item.

If add-log-always-start-new-record is non-nil, C-x 4 a always makes a new entry, even if the last entry was made by you and on the same date.

If the value of the variable change-log-version-info-enabled is non-nil, C-x 4 a adds the file's version number to the change log entry.  It finds the version number by searching the first ten percent of the file, using regular expressions from the variable change-log-version-number-regexp-list.

The change log file is visited in Change Log mode.  In this major mode, each bunch of grouped items counts as one paragraph, and each entry is considered a page.  This facilitates editing the entries. C-j and auto-fill indent each new line like the previous line; this is convenient for entering the contents of an entry.

You can use the next-error command (by default bound to C-x `) to move between entries in the Change Log, when Change Log mode is on.  You will jump to the actual site in the file that was changed, not just to the next Change Log entry.  You can also use previous-error to move back in the same list.

You can use the command M-x change-log-merge to merge other log files into a buffer in Change Log Mode, preserving the date ordering of entries.

Version control systems are another way to keep track of changes in your program and keep a change log.  In the VC log buffer, typing C-c C-a (log-edit-insert-changelog) inserts the relevant Change Log entry, if one exists (see Log Buffer).  You can also insert a VC log entry into a Change Log buffer by typing C-x v a (vc-update-change-log) in the Change Log buffer (see Change Logs and VC).

Format of ChangeLog
-------------------

A change log entry starts with a header line that contains the current date, your name, and your email address (taken from the variable add-log-mailing-address).  Aside from these header lines, every line in the change log starts with a space or a tab.  The bulk of the entry consists of items, each of which starts with a line starting with whitespace and a star.  Here are two entries, both dated in May 1993, with two items and one item respectively.

     1993-05-25  Richard Stallman  <rms@gnu.org>

             * man.el: Rename symbols `man-*' to `Man-*'.
             (manual-entry): Make prompt string clearer.

             * simple.el (blink-matching-paren-distance):
             Change default to 12,000.

     1993-05-24  Richard Stallman  <rms@gnu.org>

             * vc.el (minor-mode-map-alist): Don't use it if it's void.
             (vc-cancel-version): Doc fix.

One entry can describe several changes; each change should have its own item, or its own line in an item.  Normally there should be a blank line between items.  When items are related (parts of the same change, in different places), group them by leaving no blank line between them.

You should put a copyright notice and permission notice at the end of the change log file.  Here is an example:

     Copyright 1997, 1998 Free Software Foundation, Inc.
     Copying and distribution of this file, with or without modification, are
     permitted provided the copyright notice and this notice are preserved.

Of course, you should substitute the proper years and copyright holder.

Tags Tables
===========

A tag is a reference to a subunit in a program or in a document.  In program source code, tags reference syntactic elements of the program: functions, subroutines, data types, macros, etc.  In a document, tags reference chapters, sections, appendices, etc.  Each tag specifies the name of the file where the corresponding subunit is defined, and the position of the subunit's definition in that file.

A tags table records the tags extracted by scanning the source code of a certain program or a certain document.  Tags extracted from generated files reference the original files, rather than the generated files that were scanned during tag extraction.  Examples of generated files include C files generated from Cweb source files, from a Yacc parser, or from Lex scanner definitions; .i preprocessed C files; and Fortran files produced by preprocessing .fpp source files.

To produce a tags table, you use the etags command, submitting it a document or the source code of a program. etags writes the tags to a tags table file, or tags file in short.  The conventional name for a tags file is TAGS.

Emacs uses the information recorded in tags tables in commands that search or replace through multiple source files: these commands use the names of the source files recorded in the tags table to know which files to search.  Other commands, such as M-., which finds the definition of a function, use the recorded information about the function names and positions to find the source file and the position within that file where the function is defined.

See also the Ebrowse facility, which is tailored for C++. See Ebrowse (Ebrowse User's Manual).

Source File Tag Syntax
----------------------

Here is how tag syntax is defined for the most popular languages:

  * In C code, any C function or typedef is a tag, and so are definitions of struct, union and enum. #define macro definitions, #undef and enum constants are also tags, unless you specify --no-defines when making the tags table. Similarly, global variables are tags, unless you specify --no-globals, and so are struct members, unless you specify --no-members.  Use of --no-globals, --no-defines and --no-members can make the tags table file much smaller.

     You can tag function declarations and external variables in addition to function definitions by giving the --declarations option to etags.

  * In C++ code, in addition to all the tag constructs of C code, member functions are also recognized; member variables are also recognized, unless you use the --no-members option.  Tags for variables and functions in classes are named CLASS::VARIABLE and CLASS::FUNCTION.  operator definitions have tag names like operator+.

  * In Java code, tags include all the constructs recognized in C++, plus the interface, extends and implements constructs. Tags for variables and functions in classes are named CLASS.VARIABLE and CLASS.FUNCTION.

  * In LaTeX text, the argument of any of the commands \chapter, \section, \subsection, \subsubsection, \eqno, \label, \ref, \cite, \bibitem, \part, \appendix, \entry, \index, \def, \newcommand, \renewcommand, \newenvironment or \renewenvironment is a tag.

     Other commands can make tags as well, if you specify them in the environment variable TEXTAGS before invoking etags.  The value of this environment variable should be a colon-separated list of command names.  For example,

          TEXTAGS="mycommand:myothercommand"
          export TEXTAGS

     specifies (using Bourne shell syntax) that the commands \mycommand and \myothercommand also define tags.

  * In Lisp code, any function defined with defun, any variable defined with defvar or defconst, and in general the first argument of any expression that starts with (def in column zero is a tag.

  * In Scheme code, tags include anything defined with def or with a construct whose name starts with def.  They also include variables set with set! at top level in the file.

Several other languages are also supported:

  * In Ada code, functions, procedures, packages, tasks and types are tags.  Use the --packages-only option to create tags for packages only.

     In Ada, the same name can be used for different kinds of entity (e.g., for a procedure and for a function).  Also, for things like packages, procedures and functions, there is the spec (i.e. the interface) and the body (i.e. the implementation).  To make it easier to pick the definition you want, Ada tag name have suffixes indicating the type of entity:

     /b
          package body.

     /f
          function.

     /k
          task.

     /p
          procedure.

     /s
          package spec.

     /t
          type.

     Thus, M-x find-tag RET bidule/b RET will go directly to the body of the package bidule, while M-x find-tag RET bidule RET will just search for any tag bidule.

  * In assembler code, labels appearing at the beginning of a line, followed by a colon, are tags.

  * In Bison or Yacc input files, each rule defines as a tag the nonterminal it constructs.  The portions of the file that contain C code are parsed as C code.

  * In Cobol code, tags are paragraph names; that is, any word starting in column 8 and followed by a period.

  * In Erlang code, the tags are the functions, records and macros defined in the file.

  * In Fortran code, functions, subroutines and block data are tags.

  * In HTML input files, the tags are the title and the h1, h2, h3 headers.  Also, tags are name= in anchors and all occurrences of id=.

  * In Lua input files, all functions are tags.

  * In makefiles, targets are tags; additionally, variables are tags unless you specify --no-globals.

  * In Objective C code, tags include Objective C definitions for classes, class categories, methods and protocols.  Tags for variables and functions in classes are named CLASS::VARIABLE and CLASS::FUNCTION.

  * In Pascal code, the tags are the functions and procedures defined in the file.

  * In Perl code, the tags are the packages, subroutines and variables defined by the package, sub, my and local keywords.  Use --globals if you want to tag global variables. Tags for subroutines are named PACKAGE::SUB.  The name for subroutines defined in the default package is main::SUB.

  * In PHP code, tags are functions, classes and defines.  Vars are tags too, unless you use the --no-members option.

  * In PostScript code, the tags are the functions.

  * In Prolog code, tags are predicates and rules at the beginning of line.

  * In Python code, def or class at the beginning of a line generate a tag.

You can also generate tags based on regexp matching (see Etags Regexps) to handle other formats and languages.

Creating Tags Tables
--------------------

The etags program is used to create a tags table file.  It knows the syntax of several languages, as described in Tag Syntax. Here is how to run etags:

     etags INPUTFILES...

The etags program reads the specified files, and writes a tags table named TAGS in the current working directory.  You can optionally specify a different file name for the tags table by using the --output=FILE option; specifying - as a file name prints the tags table to standard output.

If the specified files don't exist, etags looks for compressed versions of them and uncompresses them to read them.  Under MS-DOS, etags also looks for file names like mycode.cgz if it is given mycode.c on the command line and mycode.c does not exist.

etags recognizes the language used in an input file based on its file name and contents.  You can specify the language with the --language=NAME option, described below.

If the tags table data become outdated due to changes in the files described in the table, the way to update the tags table is the same way it was made in the first place.  If the tags table fails to record a tag, or records it for the wrong file, then Emacs cannot possibly find its definition until you update the tags table.  However, if the position recorded in the tags table becomes a little bit wrong (due to other editing), the worst consequence is a slight delay in finding the tag.  Even if the stored position is very far wrong, Emacs will still find the tag, after searching most of the file for it.  That delay is hardly noticeable with today's computers.

Thus, there is no need to update the tags table after each edit. You should update a tags table when you define new tags that you want to have listed, or when you move tag definitions from one file to another, or when changes become substantial.

One tags table can virtually include another.  Specify the included tags file name with the --include=FILE option when creating the file that is to include it.  The latter file then acts as if it covered all the source files specified in the included file, as well as the files it directly contains.

If you specify the source files with relative file names when you run etags, the tags file will contain file names relative to the directory where the tags file was initially written.  This way, you can move an entire directory tree containing both the tags file and the source files, and the tags file will still refer correctly to the source files.  If the tags file is - or is in the /dev directory, however, the file names are made relative to the current working directory.  This is useful, for example, when writing the tags to /dev/stdout.

When using a relative file name, it should not be a symbolic link pointing to a tags file in a different directory, because this would generally render the file names invalid.

If you specify absolute file names as arguments to etags, then the tags file will contain absolute file names.  This way, the tags file will still refer to the same files even if you move it, as long as the source files remain in the same place.  Absolute file names start with /, or with DEVICE:/ on MS-DOS and MS-Windows.

When you want to make a tags table from a great number of files, you may have problems listing them on the command line, because some systems have a limit on its length.  The simplest way to circumvent this limit is to tell etags to read the file names from its standard input, by typing a dash in place of the file names, like this:

     find . -name "*.[chCH]" -print | etags -

Use the option --language=NAME to specify the language explicitly.  You can intermix these options with file names; each one applies to the file names that follow it.  Specify --language=auto to tell etags to resume guessing the language from the file names and file contents.  Specify --language=none to turn off language-specific processing entirely; then etags recognizes tags by regexp matching alone (see Etags Regexps).

The option --parse-stdin=FILE is mostly useful when calling etags from programs.  It can be used (only once) in place of a file name on the command line.  Etags will read from standard input and mark the produced tags as belonging to the file FILE.

etags --help outputs the list of the languages etags knows, and the file name rules for guessing the language.  It also prints a list of all the available etags options, together with a short explanation.  If followed by one or more --language=LANG options, it outputs detailed information about how tags are generated for LANG.

Etags Regexps
-------------

The --regex option provides a general way of recognizing tags based on regexp matching.  You can freely intermix this option with file names, and each one applies to the source files that follow it. If you specify multiple --regex options, all of them are used in parallel.  The syntax is:

     --regex=[{LANGUAGE}]/TAGREGEXP/[NAMEREGEXP/]MODIFIERS

The essential part of the option value is TAGREGEXP, the regexp for matching tags.  It is always used anchored, that is, it only matches at the beginning of a line.  If you want to allow indented tags, use a regexp that matches initial whitespace; start it with [ \t]*.

In these regular expressions, \ quotes the next character, and all the GCC character escape sequences are supported (\a for bell, \b for back space, \d for delete, \e for escape, \f for formfeed, \n for newline, \r for carriage return, \t for tab, and \v for vertical tab).

Ideally, TAGREGEXP should not match more characters than are needed to recognize what you want to tag.  If the syntax requires you to write TAGREGEXP so it matches more characters beyond the tag itself, you should add a NAMEREGEXP, to pick out just the tag. This will enable Emacs to find tags more accurately and to do completion on tag names more reliably.  You can find some examples below.

The MODIFIERS are a sequence of zero or more characters that modify the way etags does the matching.  A regexp with no modifiers is applied sequentially to each line of the input file, in a case-sensitive way.  The modifiers and their meanings are:

i
     Ignore case when matching this regexp.

m
     Match this regular expression against the whole file, so that multi-line matches are possible.

s
     Match this regular expression against the whole file, and allow . in TAGREGEXP to match newlines.

The -R option cancels all the regexps defined by preceding --regex options.  It too applies to the file names following it.  Here's an example:

     etags --regex=/REG1/i voo.doo --regex=/REG2/m \
         bar.ber -R --lang=lisp los.er

Here etags chooses the parsing language for voo.doo and bar.ber according to their contents.  etags also uses REG1 to recognize additional tags in voo.doo, and both REG1 and REG2 to recognize additional tags in bar.ber.  REG1 is checked against each line of voo.doo and bar.ber, in a case-insensitive way, while REG2 is checked against the whole bar.ber file, permitting multi-line matches, in a case-sensitive way.  etags uses only the Lisp tags rules, with no user-specified regexp matching, to recognize tags in los.er.

You can restrict a --regex option to match only files of a given language by using the optional prefix {LANGUAGE}. (etags --help prints the list of languages recognized by etags.)  This is particularly useful when storing many predefined regular expressions for etags in a file.  The following example tags the DEFVAR macros in the Emacs source files, for the C language only:

     --regex='{c}/[ \t]*DEFVAR_[A-Z_ \t(]+"\([^"]+\)"/'

When you have complex regular expressions, you can store the list of them in a file.  The following option syntax instructs etags to read two files of regular expressions.  The regular expressions contained in the second file are matched without regard to case.

     --regex=@CASE-SENSITIVE-FILE --ignore-case-regex=@IGNORE-CASE-FILE

A regex file for etags contains one regular expression per line.  Empty lines, and lines beginning with space or tab are ignored. When the first character in a line is @, etags assumes that the rest of the line is the name of another file of regular expressions; thus, one such file can include another file.  All the other lines are taken to be regular expressions.  If the first non-whitespace text on the line is --, that line is a comment.

For example, we can create a file called emacs.tags with the following contents:

             -- This is for GNU Emacs C source files
     {c}/[ \t]*DEFVAR_[A-Z_ \t(]+"\([^"]+\)"/\1/

and then use it like this:

     etags --regex=@emacs.tags *.[ch] */*.[ch]

Here are some more examples.  The regexps are quoted to protect them from shell interpretation.

  * Tag Octave files:

          etags --language=none \
                --regex='/[ \t]*function.*=[ \t]*\([^ \t]*\)[ \t]*(/\1/' \
                --regex='/###key \(.*\)/\1/' \
                --regex='/[ \t]*global[ \t].*/' \
                *.m

     Note that tags are not generated for scripts, so that you have to add a line by yourself of the form ###key SCRIPTNAME if you want to jump to it.

  * Tag Tcl files:

          etags --language=none --regex='/proc[ \t]+\([^ \t]+\)/\1/' *.tcl

  * Tag VHDL files:

          etags --language=none \
            --regex='/[ \t]*\(ARCHITECTURE\|CONFIGURATION\) +[^ ]* +OF/' \
            --regex='/[ \t]*\(ATTRIBUTE\|ENTITY\|FUNCTION\|PACKAGE\
            \( BODY\)?\|PROCEDURE\|PROCESS\|TYPE\)[ \t]+\([^ \t(]+\)/\3/'

Selecting a Tags Table
----------------------

Emacs has at any time one selected tags table, and all the commands for working with tags tables use the selected one.  To select a tags table, type M-x visit-tags-table, which reads the tags table file name as an argument, with TAGS in the default directory as the default.

Emacs does not actually read in the tags table contents until you try to use them; all visit-tags-table does is store the file name in the variable tags-file-name, and setting the variable yourself is just as good.  The variable's initial value is nil; that value tells all the commands for working with tags tables that they must ask for a tags table file name to use.

Using visit-tags-table when a tags table is already loaded gives you a choice: you can add the new tags table to the current list of tags tables, or start a new list.  The tags commands use all the tags tables in the current list.  If you start a new list, the new tags table is used instead of others.  If you add the new table to the current list, it is used as well as the others.

You can specify a precise list of tags tables by setting the variable tags-table-list to a list of strings, like this:

     (setq tags-table-list
           '("~/emacs" "/usr/local/lib/emacs/src"))

This tells the tags commands to look at the TAGS files in your ~/emacs directory and in the /usr/local/lib/emacs/src directory.  The order depends on which file you are in and which tags table mentions that file, as explained above.

Do not set both tags-file-name and tags-table-list.

Finding a Tag
-------------

The most important thing that a tags table enables you to do is to find the definition of a specific tag.

M-. TAG RET
     Find first definition of TAG (find-tag).

C-u M-.
     Find next alternate definition of last tag specified.

C-u - M-.
     Go back to previous tag found.

C-M-. PATTERN RET
     Find a tag whose name matches PATTERN (find-tag-regexp).

C-u C-M-.
     Find the next tag whose name matches the last pattern used.

C-x 4 . TAG RET
     Find first definition of TAG, but display it in another window (find-tag-other-window).

C-x 5 . TAG RET
     Find first definition of TAG, and create a new frame to select the buffer (find-tag-other-frame).

M-*
     Pop back to where you previously invoked M-. and friends.

M-. (find-tag) is the command to find the definition of a specified tag.  It searches through the tags table for that tag, as a string, and then uses the tags table info to determine the file that the definition is in and the approximate character position in the file of the definition.  Then find-tag visits that file, moves point to the approximate character position, and searches ever-increasing distances away to find the tag definition.

If an empty argument is given (just type RET), the balanced expression in the buffer before or around point is used as the TAG argument.  See Expressions.

You don't need to give M-. the full name of the tag; a part will do.  This is because M-. finds tags in the table which contain TAG as a substring.  However, it prefers an exact match to a substring match.  To find other tags that match the same substring, give find-tag a numeric argument, as in C-u M-.; this does not read a tag name, but continues searching the tags table's text for another tag containing the same substring last used. If you have a real META key, M-0 M-. is an easier alternative to C-u M-..

Like most commands that can switch buffers, find-tag has a variant that displays the new buffer in another window, and one that makes a new frame for it.  The former is C-x 4 ., which invokes the command find-tag-other-window.  The latter is C-x 5 ., which invokes find-tag-other-frame.

To move back to places you've found tags recently, use C-u - M-.; more generally, M-. with a negative numeric argument.  This command can take you to another buffer.  C-x 4 . with a negative argument finds the previous tag location in another window.

As well as going back to places you've found tags recently, you can go back to places from where you found them.  Use M-*, which invokes the command pop-tag-mark, for this.  Typically you would find and study the definition of something with M-. and then return to where you were with M-*.

Both C-u - M-. and M-* allow you to retrace your steps to a depth determined by the variable find-tag-marker-ring-length.

The command C-M-. (find-tag-regexp) visits the tags that match a specified regular expression.  It is just like M-. except that it does regexp matching instead of substring matching.

Searching and Replacing with Tags Tables
----------------------------------------

The commands in this section visit and search all the files listed in the selected tags table, one by one.  For these commands, the tags table serves only to specify a sequence of files to search.  These commands scan the list of tags tables starting with the first tags table (if any) that describes the current file, proceed from there to the end of the list, and then scan from the beginning of the list until they have covered all the tables in the list.

M-x tags-search RET REGEXP RET
     Search for REGEXP through the files in the selected tags table.

M-x tags-query-replace RET REGEXP RET REPLACEMENT RET
     Perform a query-replace-regexp on each file in the selected tags table.

M-,
     Restart one of the commands above, from the current location of point (tags-loop-continue).

M-x tags-search reads a regexp using the minibuffer, then searches for matches in all the files in the selected tags table, one file at a time.  It displays the name of the file being searched so you can follow its progress.  As soon as it finds an occurrence, tags-search returns.

Having found one match, you probably want to find all the rest.  To find one more match, type M-, (tags-loop-continue) to resume the tags-search.  This searches the rest of the current buffer, followed by the remaining files of the tags table.

M-x tags-query-replace performs a single query-replace-regexp through all the files in the tags table.  It reads a regexp to search for and a string to replace with, just like ordinary M-x query-replace-regexp.  It searches much like M-x tags-search, but repeatedly, processing matches according to your input.  See Replace, for more information on query replace.

You can control the case-sensitivity of tags search commands by customizing the value of the variable tags-case-fold-search.  The default is to use the same setting as the value of case-fold-search (see Search Case).

It is possible to get through all the files in the tags table with a single invocation of M-x tags-query-replace.  But often it is useful to exit temporarily, which you can do with any input event that has no special query replace meaning.  You can resume the query replace subsequently by typing M-,; this command resumes the last tags search or replace command that you did.  For instance, to skip the rest of the current file, you can type M-> M-,.

The commands in this section carry out much broader searches than the find-tag family.  The find-tag commands search only for definitions of tags that match your substring or regexp.  The commands tags-search and tags-query-replace find every occurrence of the regexp, as ordinary search commands and replace commands do in the current buffer.

These commands create buffers only temporarily for the files that they have to search (those which are not already visited in Emacs buffers). Buffers in which no match is found are quickly killed; the others continue to exist.

It may have struck you that tags-search is a lot like grep.  You can also run grep itself as an inferior of Emacs and have Emacs show you the matching lines one by one. See Grep Searching.

Tags Table Inquiries
--------------------

M-x list-tags RET FILE RET
     Display a list of the tags defined in the program file FILE.

M-x tags-apropos RET REGEXP RET
     Display a list of all tags matching REGEXP.

M-x list-tags reads the name of one of the files described by the selected tags table, and displays a list of all the tags defined in that file.  The ``file name'' argument is really just a string to compare against the file names recorded in the tags table; it is read as a string rather than as a file name.  Therefore, completion and defaulting are not available, and you must enter the file name the same way it appears in the tags table.  Do not include a directory as part of the file name unless the file name recorded in the tags table includes a directory.

M-x tags-apropos is like apropos for tags (see Apropos).  It finds all the tags in the selected tags table whose entries match REGEXP, and displays them.  If the variable tags-apropos-verbose is non-nil, it displays the names of the tags files together with the tag names.

You can customize the appearance of the output by setting the variable tags-tag-face to a face.  You can display additional output with M-x tags-apropos by customizing the variable tags-apropos-additional-actions---see its documentation for details.

You can also use the collection of tag names to complete a symbol name in the buffer.  See Symbol Completion.

     [file emerge-xtra.texi not included]