1;;; vc.el --- drive a version-control system from within Emacs
2
3;; Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 2000,
4;;   2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5
6;; Author:     FSF (see below for full credits)
7;; Maintainer: Andre Spiegel <spiegel@gnu.org>
8;; Keywords: tools
9
10;; $Id$
11
12;; This file is part of GNU Emacs.
13
14;; GNU Emacs is free software; you can redistribute it and/or modify
15;; it under the terms of the GNU General Public License as published by
16;; the Free Software Foundation; either version 2, or (at your option)
17;; any later version.
18
19;; GNU Emacs is distributed in the hope that it will be useful,
20;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22;; GNU General Public License for more details.
23
24;; You should have received a copy of the GNU General Public License
25;; along with GNU Emacs; see the file COPYING.  If not, write to the
26;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
27;; Boston, MA 02110-1301, USA.
28
29;;; Credits:
30
31;; VC was initially designed and implemented by Eric S. Raymond
32;; <esr@snark.thyrsus.com>.  Over the years, many people have
33;; contributed substantial amounts of work to VC.  These include:
34;;   Per Cederqvist <ceder@lysator.liu.se>
35;;   Paul Eggert <eggert@twinsun.com>
36;;   Sebastian Kremer <sk@thp.uni-koeln.de>
37;;   Martin Lorentzson <martinl@gnu.org>
38;;   Dave Love <fx@gnu.org>
39;;   Stefan Monnier <monnier@cs.yale.edu>
40;;   J.D. Smith <jdsmith@alum.mit.edu>
41;;   Andre Spiegel <spiegel@gnu.org>
42;;   Richard Stallman <rms@gnu.org>
43;;   Thien-Thi Nguyen <ttn@gnu.org>
44
45;;; Commentary:
46
47;; This mode is fully documented in the Emacs user's manual.
48;;
49;; Supported version-control systems presently include CVS, RCS, GNU Arch,
50;; Subversion, Meta-CVS, and SCCS (or its free replacement, CSSC).
51;;
52;; Some features will not work with old RCS versions.  Where
53;; appropriate, VC finds out which version you have, and allows or
54;; disallows those features (stealing locks, for example, works only
55;; from 5.6.2 onwards).
56;; Even initial checkins will fail if your RCS version is so old that ci
57;; doesn't understand -t-; this has been known to happen to people running
58;; NExTSTEP 3.0.
59;;
60;; You can support the RCS -x option by customizing vc-rcs-master-templates.
61;;
62;; Proper function of the SCCS diff commands requires the shellscript vcdiff
63;; to be installed somewhere on Emacs's path for executables.
64;;
65;; If your site uses the ChangeLog convention supported by Emacs, the
66;; function log-edit-comment-to-change-log could prove a useful checkin hook,
67;; although you might prefer to use C-c C-a (i.e. log-edit-insert-changelog)
68;; from the commit buffer instead or to set `log-edit-setup-invert'.
69;;
70;; The vc code maintains some internal state in order to reduce expensive
71;; version-control operations to a minimum.  Some names are only computed
72;; once.  If you perform version control operations with the backend while
73;; vc's back is turned, or move/rename master files while vc is running,
74;; vc may get seriously confused.  Don't do these things!
75;;
76;; Developer's notes on some concurrency issues are included at the end of
77;; the file.
78;;
79;; ADDING SUPPORT FOR OTHER BACKENDS
80;;
81;; VC can use arbitrary version control systems as a backend.  To add
82;; support for a new backend named SYS, write a library vc-sys.el that
83;; contains functions of the form `vc-sys-...' (note that SYS is in lower
84;; case for the function and library names).  VC will use that library if
85;; you put the symbol SYS somewhere into the list of
86;; `vc-handled-backends'.  Then, for example, if `vc-sys-registered'
87;; returns non-nil for a file, all SYS-specific versions of VC commands
88;; will be available for that file.
89;;
90;; VC keeps some per-file information in the form of properties (see
91;; vc-file-set/getprop in vc-hooks.el).  The backend-specific functions
92;; do not generally need to be aware of these properties.  For example,
93;; `vc-sys-workfile-version' should compute the workfile version and
94;; return it; it should not look it up in the property, and it needn't
95;; store it there either.  However, if a backend-specific function does
96;; store a value in a property, that value takes precedence over any
97;; value that the generic code might want to set (check for uses of
98;; the macro `with-vc-properties' in vc.el).
99;;
100;; In the list of functions below, each identifier needs to be prepended
101;; with `vc-sys-'.  Some of the functions are mandatory (marked with a
102;; `*'), others are optional (`-').
103;;
104;; STATE-QUERYING FUNCTIONS
105;;
106;; * registered (file)
107;;
108;;   Return non-nil if FILE is registered in this backend.
109;;
110;; * state (file)
111;;
112;;   Return the current version control state of FILE.  For a list of
113;;   possible values, see `vc-state'.  This function should do a full and
114;;   reliable state computation; it is usually called immediately after
115;;   C-x v v.  If you want to use a faster heuristic when visiting a
116;;   file, put that into `state-heuristic' below.
117;;
118;; - state-heuristic (file)
119;;
120;;   If provided, this function is used to estimate the version control
121;;   state of FILE at visiting time.  It should be considerably faster
122;;   than the implementation of `state'.  For a list of possible values,
123;;   see the doc string of `vc-state'.
124;;
125;; - dir-state (dir)
126;;
127;;   If provided, this function is used to find the version control state
128;;   of all files in DIR in a fast way.  The function should not return
129;;   anything, but rather store the files' states into the corresponding
130;;   `vc-state' properties.
131;;
132;; * workfile-version (file)
133;;
134;;   Return the current workfile version of FILE.
135;;
136;; - latest-on-branch-p (file)
137;;
138;;   Return non-nil if the current workfile version of FILE is the latest
139;;   on its branch.  The default implementation always returns t, which
140;;   means that working with non-current versions is not supported by
141;;   default.
142;;
143;; * checkout-model (file)
144;;
145;;   Indicate whether FILE needs to be "checked out" before it can be
146;;   edited.  See `vc-checkout-model' for a list of possible values.
147;;
148;; - workfile-unchanged-p (file)
149;;
150;;   Return non-nil if FILE is unchanged from its current workfile
151;;   version.  This function should do a brief comparison of FILE's
152;;   contents with those of the master version.  If the backend does not
153;;   have such a brief-comparison feature, the default implementation of
154;;   this function can be used, which delegates to a full
155;;   vc-BACKEND-diff.  (Note that vc-BACKEND-diff must not run
156;;   asynchronously in this case, see variable `vc-disable-async-diff'.)
157;;
158;; - mode-line-string (file)
159;;
160;;   If provided, this function should return the VC-specific mode line
161;;   string for FILE.  The default implementation deals well with all
162;;   states that `vc-state' can return.
163;;
164;; - dired-state-info (file)
165;;
166;;   Translate the `vc-state' property of FILE into a string that can be
167;;   used in a vc-dired buffer.  The default implementation deals well
168;;   with all states that `vc-state' can return.
169;;
170;; STATE-CHANGING FUNCTIONS
171;;
172;; * register (file &optional rev comment)
173;;
174;;   Register FILE in this backend.  Optionally, an initial revision REV
175;;   and an initial description of the file, COMMENT, may be specified.
176;;   The implementation should pass the value of vc-register-switches
177;;   to the backend command.
178;;
179;; - init-version (file)
180;;
181;;   The initial version to use when registering FILE if one is not
182;;   specified by the user.  If not provided, the variable
183;;   vc-default-init-version is used instead.
184;;
185;; - responsible-p (file)
186;;
187;;   Return non-nil if this backend considers itself "responsible" for
188;;   FILE, which can also be a directory.  This function is used to find
189;;   out what backend to use for registration of new files and for things
190;;   like change log generation.  The default implementation always
191;;   returns nil.
192;;
193;; - could-register (file)
194;;
195;;   Return non-nil if FILE could be registered under this backend.  The
196;;   default implementation always returns t.
197;;
198;; - receive-file (file rev)
199;;
200;;   Let this backend "receive" a file that is already registered under
201;;   another backend.  The default implementation simply calls `register'
202;;   for FILE, but it can be overridden to do something more specific,
203;;   e.g. keep revision numbers consistent or choose editing modes for
204;;   FILE that resemble those of the other backend.
205;;
206;; - unregister (file)
207;;
208;;   Unregister FILE from this backend.  This is only needed if this
209;;   backend may be used as a "more local" backend for temporary editing.
210;;
211;; * checkin (file rev comment)
212;;
213;;   Commit changes in FILE to this backend.  If REV is non-nil, that
214;;   should become the new revision number.  COMMENT is used as a
215;;   check-in comment.  The implementation should pass the value of
216;;   vc-checkin-switches to the backend command.
217;;
218;; * find-version (file rev buffer)
219;;
220;;   Fetch revision REV of file FILE and put it into BUFFER.
221;;   If REV is the empty string, fetch the head of the trunk.
222;;   The implementation should pass the value of vc-checkout-switches
223;;   to the backend command.
224;;
225;; * checkout (file &optional editable rev)
226;;
227;;   Check out revision REV of FILE into the working area.  If EDITABLE
228;;   is non-nil, FILE should be writable by the user and if locking is
229;;   used for FILE, a lock should also be set.  If REV is non-nil, that
230;;   is the revision to check out (default is current workfile version).
231;;   If REV is t, that means to check out the head of the current branch;
232;;   if it is the empty string, check out the head of the trunk.
233;;   The implementation should pass the value of vc-checkout-switches
234;;   to the backend command.
235;;
236;; * revert (file &optional contents-done)
237;;
238;;   Revert FILE back to the current workfile version.  If optional
239;;   arg CONTENTS-DONE is non-nil, then the contents of FILE have
240;;   already been reverted from a version backup, and this function
241;;   only needs to update the status of FILE within the backend.
242;;
243;; - cancel-version (file editable)
244;;
245;;   Cancel the current workfile version of FILE, i.e. remove it from the
246;;   master.  EDITABLE non-nil means that FILE should be writable
247;;   afterwards, and if locking is used for FILE, then a lock should also
248;;   be set.  If this function is not provided, trying to cancel a
249;;   version is caught as an error.
250;;
251;; - merge (file rev1 rev2)
252;;
253;;   Merge the changes between REV1 and REV2 into the current working file.
254;;
255;; - merge-news (file)
256;;
257;;   Merge recent changes from the current branch into FILE.
258;;
259;; - steal-lock (file &optional version)
260;;
261;;   Steal any lock on the current workfile version of FILE, or on
262;;   VERSION if that is provided.  This function is only needed if
263;;   locking is used for files under this backend, and if files can
264;;   indeed be locked by other users.
265;;
266;; HISTORY FUNCTIONS
267;;
268;; * print-log (file &optional buffer)
269;;
270;;   Insert the revision log of FILE into BUFFER, or the *vc* buffer
271;;   if BUFFER is nil.
272;;
273;; - show-log-entry (version)
274;;
275;;   If provided, search the log entry for VERSION in the current buffer,
276;;   and make sure it is displayed in the buffer's window.  The default
277;;   implementation of this function works for RCS-style logs.
278;;
279;; - wash-log (file)
280;;
281;;   Remove all non-comment information from the output of print-log.  The
282;;   default implementation of this function works for RCS-style logs.
283;;
284;; - logentry-check ()
285;;
286;;   If defined, this function is run to find out whether the user
287;;   entered a valid log entry for check-in.  The log entry is in the
288;;   current buffer, and if it is not a valid one, the function should
289;;   throw an error.
290;;
291;; - comment-history (file)
292;;
293;;   Return a string containing all log entries that were made for FILE.
294;;   This is used for transferring a file from one backend to another,
295;;   retaining comment information.  The default implementation of this
296;;   function does this by calling print-log and then wash-log, and
297;;   returning the resulting buffer contents as a string.
298;;
299;; - update-changelog (files)
300;;
301;;   Using recent log entries, create ChangeLog entries for FILES, or for
302;;   all files at or below the default-directory if FILES is nil.  The
303;;   default implementation runs rcs2log, which handles RCS- and
304;;   CVS-style logs.
305;;
306;; * diff (file &optional rev1 rev2 buffer)
307;;
308;;   Insert the diff for FILE into BUFFER, or the *vc-diff* buffer if
309;;   BUFFER is nil.  If REV1 and REV2 are non-nil, report differences
310;;   from REV1 to REV2.  If REV1 is nil, use the current workfile
311;;   version (as found in the repository) as the older version; if
312;;   REV2 is nil, use the current workfile contents as the newer
313;;   version.  This function should pass the value of (vc-switches
314;;   BACKEND 'diff) to the backend command.  It should return a status
315;;   of either 0 (no differences found), or 1 (either non-empty diff
316;;   or the diff is run asynchronously).
317;;
318;; - diff-tree (dir &optional rev1 rev2)
319;;
320;;   Insert the diff for all files at and below DIR into the *vc-diff*
321;;   buffer.  The meaning of REV1 and REV2 is the same as for
322;;   vc-BACKEND-diff.  The default implementation does an explicit tree
323;;   walk, calling vc-BACKEND-diff for each individual file.
324;;
325;; - annotate-command (file buf &optional rev)
326;;
327;;   If this function is provided, it should produce an annotated display
328;;   of FILE in BUF, relative to version REV.  Annotation means each line
329;;   of FILE displayed is prefixed with version information associated with
330;;   its addition (deleted lines leave no history) and that the text of the
331;;   file is fontified according to age.
332;;
333;; - annotate-time ()
334;;
335;;   Only required if `annotate-command' is defined for the backend.
336;;   Return the time of the next line of annotation at or after point,
337;;   as a floating point fractional number of days.  The helper
338;;   function `vc-annotate-convert-time' may be useful for converting
339;;   multi-part times as returned by `current-time' and `encode-time'
340;;   to this format.  Return nil if no more lines of annotation appear
341;;   in the buffer.  You can safely assume that point is placed at the
342;;   beginning of each line, starting at `point-min'.  The buffer that
343;;   point is placed in is the Annotate output, as defined by the
344;;   relevant backend.  This function also affects how much of the line
345;;   is fontified; where it leaves point is where fontification begins.
346;;
347;; - annotate-current-time ()
348;;
349;;   Only required if `annotate-command' is defined for the backend,
350;;   AND you'd like the current time considered to be anything besides
351;;   (vs-annotate-convert-time (current-time)) -- i.e. the current
352;;   time with hours, minutes, and seconds included.  Probably safe to
353;;   ignore.  Return the current-time, in units of fractional days.
354;;
355;; - annotate-extract-revision-at-line ()
356;;
357;;   Only required if `annotate-command' is defined for the backend.
358;;   Invoked from a buffer in vc-annotate-mode, return the revision
359;;   corresponding to the current line, or nil if there is no revision
360;;   corresponding to the current line.
361;;
362;; SNAPSHOT SYSTEM
363;;
364;; - create-snapshot (dir name branchp)
365;;
366;;   Take a snapshot of the current state of files under DIR and name it
367;;   NAME.  This should make sure that files are up-to-date before
368;;   proceeding with the action.  DIR can also be a file and if BRANCHP
369;;   is specified, NAME should be created as a branch and DIR should be
370;;   checked out under this new branch.  The default implementation does
371;;   not support branches but does a sanity check, a tree traversal and
372;;   for each file calls `assign-name'.
373;;
374;; - assign-name (file name)
375;;
376;;   Give name NAME to the current version of FILE, assuming it is
377;;   up-to-date.  Only used by the default version of `create-snapshot'.
378;;
379;; - retrieve-snapshot (dir name update)
380;;
381;;   Retrieve a named snapshot of all registered files at or below DIR.
382;;   If UPDATE is non-nil, then update buffers of any files in the
383;;   snapshot that are currently visited.  The default implementation
384;;   does a sanity check whether there aren't any uncommitted changes at
385;;   or below DIR, and then performs a tree walk, using the `checkout'
386;;   function to retrieve the corresponding versions.
387;;
388;; MISCELLANEOUS
389;;
390;; - make-version-backups-p (file)
391;;
392;;   Return non-nil if unmodified repository versions of FILE should be
393;;   backed up locally.  If this is done, VC can perform `diff' and
394;;   `revert' operations itself, without calling the backend system.  The
395;;   default implementation always returns nil.
396;;
397;; - repository-hostname (dirname)
398;;
399;;   Return the hostname that the backend will have to contact
400;;   in order to operate on a file in DIRNAME.  If the return value
401;;   is nil, it means that the repository is local.
402;;   This function is used in `vc-stay-local-p' which backends can use
403;;   for their convenience.
404;;
405;; - previous-version (file rev)
406;;
407;;   Return the version number that precedes REV for FILE, or nil if no such
408;;   version exists.
409;;
410;; - next-version (file rev)
411;;
412;;   Return the version number that follows REV for FILE, or nil if no such
413;;   version exists.
414;;
415;; - check-headers ()
416;;
417;;   Return non-nil if the current buffer contains any version headers.
418;;
419;; - clear-headers ()
420;;
421;;   In the current buffer, reset all version headers to their unexpanded
422;;   form.  This function should be provided if the state-querying code
423;;   for this backend uses the version headers to determine the state of
424;;   a file.  This function will then be called whenever VC changes the
425;;   version control state in such a way that the headers would give
426;;   wrong information.
427;;
428;; - delete-file (file)
429;;
430;;   Delete FILE and mark it as deleted in the repository.  If this
431;;   function is not provided, the command `vc-delete-file' will
432;;   signal an error.
433;;
434;; - rename-file (old new)
435;;
436;;   Rename file OLD to NEW, both in the working area and in the
437;;   repository.  If this function is not provided, the renaming
438;;   will be done by (vc-delete-file old) and (vc-register new).
439;;
440;; - find-file-hook ()
441;;
442;;   Operation called in current buffer when opening a file.  This can
443;;   be used by the backend to setup some local variables it might need.
444;
445;; - find-file-not-found-hook ()
446;;
447;;   Operation called in current buffer when opening a non-existing file.
448;;   By default, this asks the user if she wants to check out the file.
449
450;;; Code:
451
452(require 'vc-hooks)
453(require 'ring)
454(eval-when-compile
455  (require 'cl)
456  (require 'compile)
457  (require 'dired)      ; for dired-map-over-marks macro
458  (require 'dired-aux))	; for dired-kill-{line,tree}
459
460(if (not (assoc 'vc-parent-buffer minor-mode-alist))
461    (setq minor-mode-alist
462	  (cons '(vc-parent-buffer vc-parent-buffer-name)
463		minor-mode-alist)))
464
465;; General customization
466
467(defgroup vc nil
468  "Version-control system in Emacs."
469  :group 'tools)
470
471(defcustom vc-suppress-confirm nil
472  "If non-nil, treat user as expert; suppress yes-no prompts on some things."
473  :type 'boolean
474  :group 'vc)
475
476(defcustom vc-delete-logbuf-window t
477  "If non-nil, delete the *VC-log* buffer and window after each logical action.
478If nil, bury that buffer instead.
479This is most useful if you have multiple windows on a frame and would like to
480preserve the setting."
481  :type 'boolean
482  :group 'vc)
483
484(defcustom vc-initial-comment nil
485  "If non-nil, prompt for initial comment when a file is registered."
486  :type 'boolean
487  :group 'vc)
488
489(defcustom vc-default-init-version "1.1"
490  "A string used as the default version number when a new file is registered.
491This can be overridden by giving a prefix argument to \\[vc-register].  This
492can also be overridden by a particular VC backend."
493  :type 'string
494  :group 'vc
495  :version "20.3")
496
497(defcustom vc-command-messages nil
498  "If non-nil, display run messages from back-end commands."
499  :type 'boolean
500  :group 'vc)
501
502(defcustom vc-checkin-switches nil
503  "A string or list of strings specifying extra switches for checkin.
504These are passed to the checkin program by \\[vc-checkin]."
505  :type '(choice (const :tag "None" nil)
506		 (string :tag "Argument String")
507		 (repeat :tag "Argument List"
508			 :value ("")
509			 string))
510  :group 'vc)
511
512(defcustom vc-checkout-switches nil
513  "A string or list of strings specifying extra switches for checkout.
514These are passed to the checkout program by \\[vc-checkout]."
515  :type '(choice (const :tag "None" nil)
516		 (string :tag "Argument String")
517		 (repeat :tag "Argument List"
518			 :value ("")
519			 string))
520  :group 'vc)
521
522(defcustom vc-register-switches nil
523  "A string or list of strings; extra switches for registering a file.
524These are passed to the checkin program by \\[vc-register]."
525  :type '(choice (const :tag "None" nil)
526		 (string :tag "Argument String")
527		 (repeat :tag "Argument List"
528			 :value ("")
529			 string))
530  :group 'vc)
531
532(defcustom vc-dired-listing-switches "-al"
533  "Switches passed to `ls' for vc-dired.  MUST contain the `l' option."
534  :type 'string
535  :group 'vc
536  :version "21.1")
537
538(defcustom vc-dired-recurse t
539  "If non-nil, show directory trees recursively in VC Dired."
540  :type 'boolean
541  :group 'vc
542  :version "20.3")
543
544(defcustom vc-dired-terse-display t
545  "If non-nil, show only locked files in VC Dired."
546  :type 'boolean
547  :group 'vc
548  :version "20.3")
549
550(defcustom vc-directory-exclusion-list '("SCCS" "RCS" "CVS" "MCVS" ".svn" "{arch}")
551  "List of directory names to be ignored when walking directory trees."
552  :type '(repeat string)
553  :group 'vc)
554
555(defcustom vc-diff-switches nil
556  "A string or list of strings specifying switches for diff under VC.
557When running diff under a given BACKEND, VC concatenates the values of
558`diff-switches', `vc-diff-switches', and `vc-BACKEND-diff-switches' to
559get the switches for that command.  Thus, `vc-diff-switches' should
560contain switches that are specific to version control, but not
561specific to any particular backend."
562  :type '(choice (const :tag "None" nil)
563		 (string :tag "Argument String")
564		 (repeat :tag "Argument List"
565			 :value ("")
566			 string))
567  :group 'vc
568  :version "21.1")
569
570(defcustom vc-diff-knows-L nil
571  "*Indicates whether diff understands the -L option.
572The value is either `yes', `no', or nil.  If it is nil, VC tries
573to use -L and sets this variable to remember whether it worked."
574  :type '(choice (const :tag "Work out" nil) (const yes) (const no))
575  :group 'vc)
576
577(defcustom vc-allow-async-revert nil
578  "Specifies whether the diff during \\[vc-revert-buffer] may be asynchronous.
579Enabling this option means that you can confirm a revert operation even
580if the local changes in the file have not been found and displayed yet."
581  :type '(choice (const :tag "No" nil)
582                 (const :tag "Yes" t))
583  :group 'vc
584  :version "22.1")
585
586;;;###autoload
587(defcustom vc-checkout-hook nil
588  "Normal hook (list of functions) run after checking out a file.
589See `run-hooks'."
590  :type 'hook
591  :group 'vc
592  :version "21.1")
593
594(defcustom vc-annotate-display-mode 'fullscale
595  "Which mode to color the output of \\[vc-annotate] with by default."
596  :type '(choice (const :tag "By Color Map Range" nil)
597		 (const :tag "Scale to Oldest" scale)
598		 (const :tag "Scale Oldest->Newest" fullscale)
599		 (number :tag "Specify Fractional Number of Days"
600			 :value "20.5"))
601  :group 'vc)
602
603;;;###autoload
604(defcustom vc-checkin-hook nil
605  "Normal hook (list of functions) run after a checkin is done.
606See also `log-edit-done-hook'."
607  :type 'hook
608  :options '(log-edit-comment-to-change-log)
609  :group 'vc)
610
611;;;###autoload
612(defcustom vc-before-checkin-hook nil
613  "Normal hook (list of functions) run before a file is checked in.
614See `run-hooks'."
615  :type 'hook
616  :group 'vc)
617
618(defcustom vc-logentry-check-hook nil
619  "Normal hook run by `vc-backend-logentry-check'.
620Use this to impose your own rules on the entry in addition to any the
621version control backend imposes itself."
622  :type 'hook
623  :group 'vc)
624
625;; Annotate customization
626(defcustom vc-annotate-color-map
627  (if (and (tty-display-color-p) (<= (display-color-cells) 8))
628      ;; A custom sorted TTY colormap
629      (let* ((colors
630	      (sort
631	       (delq nil
632		     (mapcar (lambda (x)
633			       (if (not (or
634					 (string-equal (car x) "white")
635					 (string-equal (car x) "black") ))
636				   (car x)))
637			     (tty-color-alist)))
638	       (lambda (a b)
639		 (cond
640		  ((or (string-equal a "red") (string-equal b "blue")) t)
641		  ((or (string-equal b "red") (string-equal a "blue")) nil)
642		  ((string-equal a "yellow") t)
643		  ((string-equal b "yellow") nil)
644		  ((string-equal a "cyan") t)
645		  ((string-equal b "cyan") nil)
646		  ((string-equal a "green") t)
647		  ((string-equal b "green") nil)
648		  ((string-equal a "magenta") t)
649		  ((string-equal b "magenta") nil)
650		  (t (string< a b))))))
651	     (date 20.)
652	     (delta (/ (- 360. date) (1- (length colors)))))
653	(mapcar (lambda (x)
654		  (prog1
655		      (cons date x)
656		    (setq date (+ date delta)))) colors))
657    ;; Normal colormap: hue stepped from 0-240deg, value=1., saturation=0.75
658    '(( 20. . "#FF3F3F")
659      ( 40. . "#FF6C3F")
660      ( 60. . "#FF993F")
661      ( 80. . "#FFC63F")
662      (100. . "#FFF33F")
663      (120. . "#DDFF3F")
664      (140. . "#B0FF3F")
665      (160. . "#83FF3F")
666      (180. . "#56FF3F")
667      (200. . "#3FFF56")
668      (220. . "#3FFF83")
669      (240. . "#3FFFB0")
670      (260. . "#3FFFDD")
671      (280. . "#3FF3FF")
672      (300. . "#3FC6FF")
673      (320. . "#3F99FF")
674      (340. . "#3F6CFF")
675      (360. . "#3F3FFF")))
676  "Association list of age versus color, for \\[vc-annotate].
677Ages are given in units of fractional days.  Default is eighteen
678steps using a twenty day increment, from red to blue.  For TTY
679displays with 8 or fewer colors, the default is red to blue with
680all other colors between (excluding black and white)."
681  :type 'alist
682  :group 'vc)
683
684(defcustom vc-annotate-very-old-color "#3F3FFF"
685  "Color for lines older than the current color range in \\[vc-annotate]]."
686  :type 'string
687  :group 'vc)
688
689(defcustom vc-annotate-background "black"
690  "Background color for \\[vc-annotate].
691Default color is used if nil."
692  :type 'string
693  :group 'vc)
694
695(defcustom vc-annotate-menu-elements '(2 0.5 0.1 0.01)
696  "Menu elements for the mode-specific menu of VC-Annotate mode.
697List of factors, used to expand/compress the time scale.  See `vc-annotate'."
698  :type '(repeat number)
699  :group 'vc)
700
701(defvar vc-annotate-mode-map
702  (let ((m (make-sparse-keymap)))
703    (define-key m "A" 'vc-annotate-revision-previous-to-line)
704    (define-key m "D" 'vc-annotate-show-diff-revision-at-line)
705    (define-key m "J" 'vc-annotate-revision-at-line)
706    (define-key m "L" 'vc-annotate-show-log-revision-at-line)
707    (define-key m "N" 'vc-annotate-next-version)
708    (define-key m "P" 'vc-annotate-prev-version)
709    (define-key m "W" 'vc-annotate-workfile-version)
710    m)
711  "Local keymap used for VC-Annotate mode.")
712
713;; Header-insertion hair
714
715(defcustom vc-static-header-alist
716  '(("\\.c\\'" .
717     "\n#ifndef lint\nstatic char vcid[] = \"\%s\";\n#endif /* lint */\n"))
718  "*Associate static header string templates with file types.
719A \%s in the template is replaced with the first string associated with
720the file's version control type in `vc-header-alist'."
721  :type '(repeat (cons :format "%v"
722		       (regexp :tag "File Type")
723		       (string :tag "Header String")))
724  :group 'vc)
725
726(defcustom vc-comment-alist
727  '((nroff-mode ".\\\"" ""))
728  "*Special comment delimiters for generating VC headers.
729Add an entry in this list if you need to override the normal `comment-start'
730and `comment-end' variables.  This will only be necessary if the mode language
731is sensitive to blank lines."
732  :type '(repeat (list :format "%v"
733		       (symbol :tag "Mode")
734		       (string :tag "Comment Start")
735		       (string :tag "Comment End")))
736  :group 'vc)
737
738(defcustom vc-checkout-carefully (= (user-uid) 0)
739  "*Non-nil means be extra-careful in checkout.
740Verify that the file really is not locked
741and that its contents match what the master file says."
742  :type 'boolean
743  :group 'vc)
744(make-obsolete-variable 'vc-checkout-carefully
745                        "the corresponding checks are always done now."
746                        "21.1")
747
748
749;; Variables the user doesn't need to know about.
750(defvar vc-log-operation nil)
751(defvar vc-log-after-operation-hook nil)
752
753;; In a log entry buffer, this is a local variable
754;; that points to the buffer for which it was made
755;; (either a file, or a VC dired buffer).
756(defvar vc-parent-buffer nil)
757(put 'vc-parent-buffer 'permanent-local t)
758(defvar vc-parent-buffer-name nil)
759(put 'vc-parent-buffer-name 'permanent-local t)
760
761(defvar vc-disable-async-diff nil
762  "VC sets this to t locally to disable some async diff operations.
763Backends that offer asynchronous diffs should respect this variable
764in their implementation of vc-BACKEND-diff.")
765
766(defvar vc-log-file)
767(defvar vc-log-version)
768
769(defvar vc-dired-mode nil)
770(make-variable-buffer-local 'vc-dired-mode)
771
772;; functions that operate on RCS revision numbers.  This code should
773;; also be moved into the backends.  It stays for now, however, since
774;; it is used in code below.
775;;;###autoload
776(defun vc-trunk-p (rev)
777  "Return t if REV is a revision on the trunk."
778  (not (eq nil (string-match "\\`[0-9]+\\.[0-9]+\\'" rev))))
779
780(defun vc-branch-p (rev)
781  "Return t if REV is a branch revision."
782  (not (eq nil (string-match "\\`[0-9]+\\(\\.[0-9]+\\.[0-9]+\\)*\\'" rev))))
783
784;;;###autoload
785(defun vc-branch-part (rev)
786  "Return the branch part of a revision number REV."
787  (let ((index (string-match "\\.[0-9]+\\'" rev)))
788    (if index
789        (substring rev 0 index))))
790
791(defun vc-minor-part (rev)
792  "Return the minor version number of a revision number REV."
793  (string-match "[0-9]+\\'" rev)
794  (substring rev (match-beginning 0) (match-end 0)))
795
796(defun vc-default-previous-version (backend file rev)
797  "Return the version number immediately preceding REV for FILE,
798or nil if there is no previous version.  This default
799implementation works for MAJOR.MINOR-style version numbers as
800used by RCS and CVS."
801  (let ((branch (vc-branch-part rev))
802        (minor-num (string-to-number (vc-minor-part rev))))
803    (when branch
804      (if (> minor-num 1)
805          ;; version does probably not start a branch or release
806          (concat branch "." (number-to-string (1- minor-num)))
807        (if (vc-trunk-p rev)
808            ;; we are at the beginning of the trunk --
809            ;; don't know anything to return here
810            nil
811          ;; we are at the beginning of a branch --
812          ;; return version of starting point
813          (vc-branch-part branch))))))
814
815(defun vc-default-next-version (backend file rev)
816  "Return the version number immediately following REV for FILE,
817or nil if there is no next version.  This default implementation
818works for MAJOR.MINOR-style version numbers as used by RCS
819and CVS."
820  (when (not (string= rev (vc-workfile-version file)))
821    (let ((branch (vc-branch-part rev))
822	  (minor-num (string-to-number (vc-minor-part rev))))
823      (concat branch "." (number-to-string (1+ minor-num))))))
824
825;; File property caching
826
827(defun vc-clear-context ()
828  "Clear all cached file properties."
829  (interactive)
830  (fillarray vc-file-prop-obarray 0))
831
832(defmacro with-vc-properties (file form settings)
833  "Execute FORM, then maybe set per-file properties for FILE.
834SETTINGS is an association list of property/value pairs.  After
835executing FORM, set those properties from SETTINGS that have not yet
836been updated to their corresponding values."
837  (declare (debug t))
838  `(let ((vc-touched-properties (list t)))
839     ,form
840     (mapcar (lambda (setting)
841	       (let ((property (car setting)))
842		 (unless (memq property vc-touched-properties)
843		   (put (intern ,file vc-file-prop-obarray)
844			property (cdr setting)))))
845	     ,settings)))
846
847;; Random helper functions
848
849(defsubst vc-editable-p (file)
850  "Return non-nil if FILE can be edited."
851  (or (eq (vc-checkout-model file) 'implicit)
852      (memq (vc-state file) '(edited needs-merge))))
853
854;; Two macros for elisp programming
855;;;###autoload
856(defmacro with-vc-file (file comment &rest body)
857  "Check out a writable copy of FILE if necessary, then execute BODY.
858Check in FILE with COMMENT (a string) after BODY has been executed.
859FILE is passed through `expand-file-name'; BODY executed within
860`save-excursion'.  If FILE is not under version control, or locked by
861somebody else, signal error."
862  (declare (debug t) (indent 2))
863  (let ((filevar (make-symbol "file")))
864    `(let ((,filevar (expand-file-name ,file)))
865       (or (vc-backend ,filevar)
866           (error "File not under version control: `%s'" file))
867       (unless (vc-editable-p ,filevar)
868         (let ((state (vc-state ,filevar)))
869           (if (stringp state)
870               (error "`%s' is locking `%s'" state ,filevar)
871             (vc-checkout ,filevar t))))
872       (save-excursion
873         ,@body)
874       (vc-checkin ,filevar nil ,comment))))
875
876;;;###autoload
877(defmacro edit-vc-file (file comment &rest body)
878  "Edit FILE under version control, executing body.
879Checkin with COMMENT after executing BODY.
880This macro uses `with-vc-file', passing args to it.
881However, before executing BODY, find FILE, and after BODY, save buffer."
882  (declare (debug t) (indent 2))
883  (let ((filevar (make-symbol "file")))
884    `(let ((,filevar (expand-file-name ,file)))
885       (with-vc-file
886        ,filevar ,comment
887        (set-buffer (find-file-noselect ,filevar))
888        ,@body
889        (save-buffer)))))
890
891(defun vc-ensure-vc-buffer ()
892  "Make sure that the current buffer visits a version-controlled file."
893  (if vc-dired-mode
894      (set-buffer (find-file-noselect (dired-get-filename)))
895    (while vc-parent-buffer
896      (set-buffer vc-parent-buffer))
897    (if (not buffer-file-name)
898	(error "Buffer %s is not associated with a file" (buffer-name))
899      (if (not (vc-backend buffer-file-name))
900	  (error "File %s is not under version control" buffer-file-name)))))
901
902(defun vc-process-filter (p s)
903  "An alternative output filter for async process P.
904One difference with the default filter is that this inserts S after markers.
905Another is that undo information is not kept."
906  (with-current-buffer (process-buffer p)
907    (save-excursion
908      (let ((buffer-undo-list t)
909            (inhibit-read-only t))
910	(goto-char (process-mark p))
911	(insert s)
912	(set-marker (process-mark p) (point))))))
913
914(defun vc-setup-buffer (&optional buf)
915  "Prepare BUF for executing a VC command and make it current.
916BUF defaults to \"*vc*\", can be a string and will be created if necessary."
917  (unless buf (setq buf "*vc*"))
918  (let ((camefrom (current-buffer))
919	(olddir default-directory))
920    (set-buffer (get-buffer-create buf))
921    (kill-all-local-variables)
922    (set (make-local-variable 'vc-parent-buffer) camefrom)
923    (set (make-local-variable 'vc-parent-buffer-name)
924	 (concat " from " (buffer-name camefrom)))
925    (setq default-directory olddir)
926    (let ((buffer-undo-list t)
927          (inhibit-read-only t))
928      (erase-buffer))))
929
930(defun vc-exec-after (code)
931  "Eval CODE when the current buffer's process is done.
932If the current buffer has no process, just evaluate CODE.
933Else, add CODE to the process' sentinel."
934  (let ((proc (get-buffer-process (current-buffer))))
935    (cond
936     ;; If there's no background process, just execute the code.
937     ;; We used to explicitly call delete-process on exited processes,
938     ;; but this led to timing problems causing process output to be
939     ;; lost.  Terminated processes get deleted automatically
940     ;; anyway. -- cyd
941     ((or (null proc) (eq (process-status proc) 'exit))
942      (eval code))
943     ;; If a process is running, add CODE to the sentinel
944     ((eq (process-status proc) 'run)
945      (let ((sentinel (process-sentinel proc)))
946	(set-process-sentinel proc
947	  `(lambda (p s)
948	     (with-current-buffer ',(current-buffer)
949	       (goto-char (process-mark p))
950	       ,@(append (cdr (cdr (cdr ;strip off `with-current-buffer buf
951                                        ;             (goto-char...)'
952			   (car (cdr (cdr ;strip off `lambda (p s)'
953			    sentinel))))))
954			 (list `(vc-exec-after ',code))))))))
955     (t (error "Unexpected process state"))))
956  nil)
957
958(defvar vc-post-command-functions nil
959  "Hook run at the end of `vc-do-command'.
960Each function is called inside the buffer in which the command was run
961and is passed 3 arguments: the COMMAND, the FILE and the FLAGS.")
962
963(defvar w32-quote-process-args)
964;;;###autoload
965(defun vc-do-command (buffer okstatus command file &rest flags)
966  "Execute a VC command, notifying user and checking for errors.
967Output from COMMAND goes to BUFFER, or *vc* if BUFFER is nil or the
968current buffer if BUFFER is t.  If the destination buffer is not
969already current, set it up properly and erase it.  The command is
970considered successful if its exit status does not exceed OKSTATUS (if
971OKSTATUS is nil, that means to ignore error status, if it is `async', that
972means not to wait for termination of the subprocess; if it is t it means to
973ignore all execution errors).  FILE is the
974name of the working file (may also be nil, to execute commands that
975don't expect a file name).  If an optional list of FLAGS is present,
976that is inserted into the command line before the filename."
977  (and file (setq file (expand-file-name file)))
978  (if vc-command-messages
979      (message "Running %s on %s..." command file))
980  (save-current-buffer
981    (unless (or (eq buffer t)
982                (and (stringp buffer)
983                     (string= (buffer-name) buffer))
984                (eq buffer (current-buffer)))
985      (vc-setup-buffer buffer))
986    (let ((squeezed (remq nil flags))
987	  (inhibit-read-only t)
988	  (status 0))
989      (when file
990	;; FIXME: file-relative-name can return a bogus result because
991	;; it doesn't look at the actual file-system to see if symlinks
992	;; come into play.
993	(setq squeezed (append squeezed (list (file-relative-name file)))))
994      (let ((exec-path (append vc-path exec-path))
995	    ;; Add vc-path to PATH for the execution of this command.
996	    (process-environment
997	     (cons (concat "PATH=" (getenv "PATH")
998			   path-separator
999			   (mapconcat 'identity vc-path path-separator))
1000		   process-environment))
1001	    (w32-quote-process-args t))
1002	(if (and (eq okstatus 'async) (file-remote-p default-directory))
1003	    ;; start-process does not support remote execution
1004	    (setq okstatus nil))
1005	(if (eq okstatus 'async)
1006	    (let ((proc
1007		   (let ((process-connection-type nil))
1008		     (apply 'start-process command (current-buffer) command
1009			    squeezed))))
1010              (unless (active-minibuffer-window)
1011                (message "Running %s in the background..." command))
1012	      ;;(set-process-sentinel proc (lambda (p msg) (delete-process p)))
1013	      (set-process-filter proc 'vc-process-filter)
1014	      (vc-exec-after
1015	       `(unless (active-minibuffer-window)
1016                  (message "Running %s in the background... done" ',command))))
1017	  (let ((buffer-undo-list t))
1018            (setq status (apply 'process-file command nil t nil squeezed)))
1019	  (when (and (not (eq t okstatus))
1020                     (or (not (integerp status))
1021                         (and okstatus (< okstatus status))))
1022	    (pop-to-buffer (current-buffer))
1023	    (goto-char (point-min))
1024	    (shrink-window-if-larger-than-buffer)
1025	    (error "Running %s...FAILED (%s)" command
1026		   (if (integerp status) (format "status %d" status) status))))
1027	(if vc-command-messages
1028	    (message "Running %s...OK" command)))
1029      (vc-exec-after
1030       `(run-hook-with-args 'vc-post-command-functions ',command ',file ',flags))
1031      status)))
1032
1033(defun vc-position-context (posn)
1034  "Save a bit of the text around POSN in the current buffer.
1035Used to help us find the corresponding position again later
1036if markers are destroyed or corrupted."
1037  ;; A lot of this was shamelessly lifted from Sebastian Kremer's
1038  ;; rcs.el mode.
1039  (list posn
1040	(buffer-size)
1041	(buffer-substring posn
1042			  (min (point-max) (+ posn 100)))))
1043
1044(defun vc-find-position-by-context (context)
1045  "Return the position of CONTEXT in the current buffer.
1046If CONTEXT cannot be found, return nil."
1047  (let ((context-string (nth 2 context)))
1048    (if (equal "" context-string)
1049	(point-max)
1050      (save-excursion
1051	(let ((diff (- (nth 1 context) (buffer-size))))
1052	  (if (< diff 0) (setq diff (- diff)))
1053	  (goto-char (nth 0 context))
1054	  (if (or (search-forward context-string nil t)
1055		  ;; Can't use search-backward since the match may continue
1056		  ;; after point.
1057		  (progn (goto-char (- (point) diff (length context-string)))
1058			 ;; goto-char doesn't signal an error at
1059			 ;; beginning of buffer like backward-char would
1060			 (search-forward context-string nil t)))
1061	      ;; to beginning of OSTRING
1062	      (- (point) (length context-string))))))))
1063
1064(defun vc-context-matches-p (posn context)
1065  "Return t if POSN matches CONTEXT, nil otherwise."
1066  (let* ((context-string (nth 2 context))
1067	 (len (length context-string))
1068	 (end (+ posn len)))
1069    (if (> end (1+ (buffer-size)))
1070	nil
1071      (string= context-string (buffer-substring posn end)))))
1072
1073(defun vc-buffer-context ()
1074  "Return a list (POINT-CONTEXT MARK-CONTEXT REPARSE).
1075Used by `vc-restore-buffer-context' to later restore the context."
1076  (let ((point-context (vc-position-context (point)))
1077	;; Use mark-marker to avoid confusion in transient-mark-mode.
1078	(mark-context  (if (eq (marker-buffer (mark-marker)) (current-buffer))
1079			   (vc-position-context (mark-marker))))
1080	;; Make the right thing happen in transient-mark-mode.
1081	(mark-active nil)
1082	;; The new compilation code does not use compilation-error-list any
1083	;; more, so the code below is now ineffective and might as well
1084	;; be disabled.  -- Stef
1085	;; ;; We may want to reparse the compilation buffer after revert
1086	;; (reparse (and (boundp 'compilation-error-list) ;compile loaded
1087	;; 	      ;; Construct a list; each elt is nil or a buffer
1088	;; 	      ;; iff that buffer is a compilation output buffer
1089	;; 	      ;; that contains markers into the current buffer.
1090	;; 	      (save-current-buffer
1091	;; 		(mapcar (lambda (buffer)
1092	;; 			  (set-buffer buffer)
1093	;; 			  (let ((errors (or
1094	;; 					 compilation-old-error-list
1095	;; 					 compilation-error-list))
1096	;; 				(buffer-error-marked-p nil))
1097	;; 			    (while (and (consp errors)
1098	;; 					(not buffer-error-marked-p))
1099	;; 			      (and (markerp (cdr (car errors)))
1100	;; 				   (eq buffer
1101	;; 				       (marker-buffer
1102	;; 					(cdr (car errors))))
1103	;; 				   (setq buffer-error-marked-p t))
1104	;; 			      (setq errors (cdr errors)))
1105	;; 			    (if buffer-error-marked-p buffer)))
1106	;; 			(buffer-list)))))
1107	(reparse nil))
1108    (list point-context mark-context reparse)))
1109
1110(defun vc-restore-buffer-context (context)
1111  "Restore point/mark, and reparse any affected compilation buffers.
1112CONTEXT is that which `vc-buffer-context' returns."
1113  (let ((point-context (nth 0 context))
1114	(mark-context (nth 1 context))
1115	(reparse (nth 2 context)))
1116    ;; The new compilation code does not use compilation-error-list any
1117    ;; more, so the code below is now ineffective and might as well
1118    ;; be disabled.  -- Stef
1119    ;; ;; Reparse affected compilation buffers.
1120    ;; (while reparse
1121    ;;   (if (car reparse)
1122    ;; 	  (with-current-buffer (car reparse)
1123    ;; 	    (let ((compilation-last-buffer (current-buffer)) ;select buffer
1124    ;; 		  ;; Record the position in the compilation buffer of
1125    ;; 		  ;; the last error next-error went to.
1126    ;; 		  (error-pos (marker-position
1127    ;; 			      (car (car-safe compilation-error-list)))))
1128    ;; 	      ;; Reparse the error messages as far as they were parsed before.
1129    ;; 	      (compile-reinitialize-errors '(4) compilation-parsing-end)
1130    ;; 	      ;; Move the pointer up to find the error we were at before
1131    ;; 	      ;; reparsing.  Now next-error should properly go to the next one.
1132    ;; 	      (while (and compilation-error-list
1133    ;; 			  (/= error-pos (car (car compilation-error-list))))
1134    ;; 		(setq compilation-error-list (cdr compilation-error-list))))))
1135    ;;   (setq reparse (cdr reparse)))
1136
1137    ;; if necessary, restore point and mark
1138    (if (not (vc-context-matches-p (point) point-context))
1139	(let ((new-point (vc-find-position-by-context point-context)))
1140	  (if new-point (goto-char new-point))))
1141    (and mark-active
1142         mark-context
1143         (not (vc-context-matches-p (mark) mark-context))
1144         (let ((new-mark (vc-find-position-by-context mark-context)))
1145           (if new-mark (set-mark new-mark))))))
1146
1147(defun vc-revert-buffer1 (&optional arg no-confirm)
1148  "Revert buffer, keeping point and mark where user expects them.
1149Try to be clever in the face of changes due to expanded version control
1150key words.  This is important for typeahead to work as expected.
1151ARG and NO-CONFIRM are passed on to `revert-buffer'."
1152  (interactive "P")
1153  (widen)
1154  (let ((context (vc-buffer-context)))
1155    ;; Use save-excursion here, because it may be able to restore point
1156    ;; and mark properly even in cases where vc-restore-buffer-context
1157    ;; would fail.  However, save-excursion might also get it wrong --
1158    ;; in this case, vc-restore-buffer-context gives it a second try.
1159    (save-excursion
1160      ;; t means don't call normal-mode;
1161      ;; that's to preserve various minor modes.
1162      (revert-buffer arg no-confirm t))
1163    (vc-restore-buffer-context context)))
1164
1165
1166(defun vc-buffer-sync (&optional not-urgent)
1167  "Make sure the current buffer and its working file are in sync.
1168NOT-URGENT means it is ok to continue if the user says not to save."
1169  (if (buffer-modified-p)
1170      (if (or vc-suppress-confirm
1171	      (y-or-n-p (format "Buffer %s modified; save it? " (buffer-name))))
1172	  (save-buffer)
1173	(unless not-urgent
1174	  (error "Aborted")))))
1175
1176(defun vc-default-latest-on-branch-p (backend file)
1177  "Return non-nil if FILE is the latest on its branch.
1178This default implementation always returns non-nil, which means that
1179editing non-current versions is not supported by default."
1180  t)
1181
1182(defun vc-next-action-on-file (file verbose &optional comment)
1183  "Do The Right Thing for a given FILE under version control.
1184If COMMENT is specified, it will be used as an admin or checkin comment.
1185If VERBOSE is non-nil, query the user rather than using default parameters."
1186  (let ((visited (get-file-buffer file))
1187	state version)
1188    (when visited
1189      (if vc-dired-mode
1190          (switch-to-buffer-other-window visited)
1191        (set-buffer visited))
1192      ;; Check relation of buffer and file, and make sure
1193      ;; user knows what he's doing.  First, finding the file
1194      ;; will check whether the file on disk is newer.
1195      ;; Ignore buffer-read-only during this test, and
1196      ;; preserve find-file-literally.
1197      (let ((buffer-read-only (not (file-writable-p file))))
1198        (find-file-noselect file nil find-file-literally))
1199      (if (not (verify-visited-file-modtime (current-buffer)))
1200	  (if (yes-or-no-p "Replace file on disk with buffer contents? ")
1201	      (write-file buffer-file-name)
1202	    (error "Aborted"))
1203	;; Now, check if we have unsaved changes.
1204	(vc-buffer-sync t)
1205	(if (buffer-modified-p)
1206	    (or (y-or-n-p "Operate on disk file, keeping modified buffer? ")
1207		(error "Aborted")))))
1208
1209    ;; Do the right thing
1210    (if (not (vc-registered file))
1211	(vc-register verbose comment)
1212      (vc-recompute-state file)
1213      (if visited (vc-mode-line file))
1214      (setq state (vc-state file))
1215      (cond
1216       ;; up-to-date
1217       ((or (eq state 'up-to-date)
1218	    (and verbose (eq state 'needs-patch)))
1219	(cond
1220	 (verbose
1221	  ;; go to a different version
1222	  (setq version
1223		(read-string "Branch, version, or backend to move to: "))
1224	  (let ((vsym (intern-soft (upcase version))))
1225	    (if (member vsym vc-handled-backends)
1226		(vc-transfer-file file vsym)
1227	      (vc-checkout file (eq (vc-checkout-model file) 'implicit)
1228			   version))))
1229	 ((not (eq (vc-checkout-model file) 'implicit))
1230	  ;; check the file out
1231	  (vc-checkout file t))
1232	 (t
1233	  ;; do nothing
1234	  (message "%s is up-to-date" file))))
1235
1236       ;; Abnormal: edited but read-only
1237       ((and visited (eq state 'edited)
1238	     buffer-read-only (not (file-writable-p file)))
1239	;; Make the file+buffer read-write.  If the user really wanted to
1240	;; commit, he'll get a chance to do that next time around, anyway.
1241	(message "File is edited but read-only; making it writable")
1242	(set-file-modes buffer-file-name
1243			(logior (file-modes buffer-file-name) 128))
1244	(toggle-read-only -1))
1245
1246       ;; edited
1247       ((eq state 'edited)
1248	(cond
1249	 ;; For files with locking, if the file does not contain
1250	 ;; any changes, just let go of the lock, i.e. revert.
1251	 ((and (not (eq (vc-checkout-model file) 'implicit))
1252	       (vc-workfile-unchanged-p file)
1253	       ;; If buffer is modified, that means the user just
1254	       ;; said no to saving it; in that case, don't revert,
1255	       ;; because the user might intend to save after
1256	       ;; finishing the log entry.
1257	       (not (and visited (buffer-modified-p))))
1258	  ;; DO NOT revert the file without asking the user!
1259	  (if (not visited) (find-file-other-window file))
1260	  (if (yes-or-no-p "Revert to master version? ")
1261	      (vc-revert-buffer)))
1262	 (t ;; normal action
1263	  (if (not verbose)
1264	      (vc-checkin file nil comment)
1265	    (setq version (read-string "New version or backend: "))
1266	    (let ((vsym (intern (upcase version))))
1267	      (if (member vsym vc-handled-backends)
1268		  (vc-transfer-file file vsym)
1269		(vc-checkin file version comment)))))))
1270
1271       ;; locked by somebody else
1272       ((stringp state)
1273	(if comment
1274	    (error "Sorry, you can't steal the lock on %s this way"
1275		   (file-name-nondirectory file)))
1276	(vc-steal-lock file
1277                       (if verbose (read-string "Version to steal: ")
1278                         (vc-workfile-version file))
1279		       state))
1280
1281       ;; needs-patch
1282       ((eq state 'needs-patch)
1283	(if (yes-or-no-p (format
1284			  "%s is not up-to-date.  Get latest version? "
1285			  (file-name-nondirectory file)))
1286	    (vc-checkout file (eq (vc-checkout-model file) 'implicit) t)
1287	  (if (and (not (eq (vc-checkout-model file) 'implicit))
1288		   (yes-or-no-p "Lock this version? "))
1289	      (vc-checkout file t)
1290	    (error "Aborted"))))
1291
1292       ;; needs-merge
1293       ((eq state 'needs-merge)
1294	(if (yes-or-no-p (format
1295			  "%s is not up-to-date.  Merge in changes now? "
1296			  (file-name-nondirectory file)))
1297	    (vc-maybe-resolve-conflicts file (vc-call merge-news file))
1298	  (error "Aborted")))
1299
1300       ;; unlocked-changes
1301       ((eq state 'unlocked-changes)
1302	(if (not visited) (find-file-other-window file))
1303	(if (save-window-excursion
1304	      (vc-version-diff file (vc-workfile-version file) nil)
1305	      (goto-char (point-min))
1306	      (let ((inhibit-read-only t))
1307		(insert
1308		 (format "Changes to %s since last lock:\n\n" file)))
1309	      (not (beep))
1310	      (yes-or-no-p (concat "File has unlocked changes.  "
1311				   "Claim lock retaining changes? ")))
1312	    (progn (vc-call steal-lock file)
1313                   (clear-visited-file-modtime)
1314		   ;; Must clear any headers here because they wouldn't
1315		   ;; show that the file is locked now.
1316		   (vc-clear-headers file)
1317		   (write-file buffer-file-name)
1318		   (vc-mode-line file))
1319	  (if (not (yes-or-no-p
1320		    "Revert to checked-in version, instead? "))
1321	      (error "Checkout aborted")
1322	    (vc-revert-buffer1 t t)
1323	    (vc-checkout file t))))))))
1324
1325(defvar vc-dired-window-configuration)
1326
1327(defun vc-next-action-dired (file rev comment)
1328  "Call `vc-next-action-on-file' on all the marked files.
1329Ignores FILE and REV, but passes on COMMENT."
1330  (let ((dired-buffer (current-buffer)))
1331    (dired-map-over-marks
1332     (let ((file (dired-get-filename)))
1333       (message "Processing %s..." file)
1334       (vc-next-action-on-file file nil comment)
1335       (set-buffer dired-buffer)
1336       (set-window-configuration vc-dired-window-configuration)
1337       (message "Processing %s...done" file))
1338    nil t))
1339  (dired-move-to-filename))
1340
1341;; Here's the major entry point.
1342
1343;;;###autoload
1344(defun vc-next-action (verbose)
1345  "Do the next logical version control operation on the current file.
1346
1347If you call this from within a VC dired buffer with no files marked,
1348it will operate on the file in the current line.
1349
1350If you call this from within a VC dired buffer, and one or more
1351files are marked, it will accept a log message and then operate on
1352each one.  The log message will be used as a comment for any register
1353or checkin operations, but ignored when doing checkouts.  Attempted
1354lock steals will raise an error.
1355
1356A prefix argument lets you specify the version number to use.
1357
1358For RCS and SCCS files:
1359   If the file is not already registered, this registers it for version
1360control.
1361   If the file is registered and not locked by anyone, this checks out
1362a writable and locked file ready for editing.
1363   If the file is checked out and locked by the calling user, this
1364first checks to see if the file has changed since checkout.  If not,
1365it performs a revert.
1366   If the file has been changed, this pops up a buffer for entry
1367of a log message; when the message has been entered, it checks in the
1368resulting changes along with the log message as change commentary.  If
1369the variable `vc-keep-workfiles' is non-nil (which is its default), a
1370read-only copy of the changed file is left in place afterwards.
1371   If the file is registered and locked by someone else, you are given
1372the option to steal the lock.
1373
1374For CVS files:
1375   If the file is not already registered, this registers it for version
1376control.  This does a \"cvs add\", but no \"cvs commit\".
1377   If the file is added but not committed, it is committed.
1378   If your working file is changed, but the repository file is
1379unchanged, this pops up a buffer for entry of a log message; when the
1380message has been entered, it checks in the resulting changes along
1381with the logmessage as change commentary.  A writable file is retained.
1382   If the repository file is changed, you are asked if you want to
1383merge in the changes into your working copy."
1384
1385  (interactive "P")
1386  (catch 'nogo
1387    (if vc-dired-mode
1388	(let ((files (dired-get-marked-files)))
1389          (set (make-local-variable 'vc-dired-window-configuration)
1390               (current-window-configuration))
1391	  (if (string= ""
1392		 (mapconcat
1393	             (lambda (f)
1394		       (if (not (vc-up-to-date-p f)) "@" ""))
1395		     files ""))
1396		(vc-next-action-dired nil nil "dummy")
1397	      (vc-start-entry nil nil nil nil
1398			      "Enter a change comment for the marked files."
1399			      'vc-next-action-dired))
1400	    (throw 'nogo nil)))
1401    (while vc-parent-buffer
1402      (pop-to-buffer vc-parent-buffer))
1403    (if buffer-file-name
1404        (vc-next-action-on-file buffer-file-name verbose)
1405      (error "Buffer %s is not associated with a file" (buffer-name)))))
1406
1407;; These functions help the vc-next-action entry point
1408
1409(defun vc-default-init-version (backend) vc-default-init-version)
1410
1411;;;###autoload
1412(defun vc-register (&optional set-version comment)
1413  "Register the current file into a version control system.
1414With prefix argument SET-VERSION, allow user to specify initial version
1415level.  If COMMENT is present, use that as an initial comment.
1416
1417The version control system to use is found by cycling through the list
1418`vc-handled-backends'.  The first backend in that list which declares
1419itself responsible for the file (usually because other files in that
1420directory are already registered under that backend) will be used to
1421register the file.  If no backend declares itself responsible, the
1422first backend that could register the file is used."
1423  (interactive "P")
1424  (unless buffer-file-name (error "No visited file"))
1425  (when (vc-backend buffer-file-name)
1426    (if (vc-registered buffer-file-name)
1427	(error "This file is already registered")
1428      (unless (y-or-n-p "Previous master file has vanished.  Make a new one? ")
1429	(error "Aborted"))))
1430  ;; Watch out for new buffers of size 0: the corresponding file
1431  ;; does not exist yet, even though buffer-modified-p is nil.
1432  (if (and (not (buffer-modified-p))
1433	   (zerop (buffer-size))
1434	   (not (file-exists-p buffer-file-name)))
1435      (set-buffer-modified-p t))
1436  (vc-buffer-sync)
1437
1438  (vc-start-entry buffer-file-name
1439                  (if set-version
1440                      (read-string (format "Initial version level for %s: "
1441					   (buffer-name)))
1442		    (vc-call-backend (vc-responsible-backend buffer-file-name)
1443				     'init-version))
1444                  (or comment (not vc-initial-comment))
1445		  nil
1446                  "Enter initial comment."
1447		  (lambda (file rev comment)
1448		    (message "Registering %s... " file)
1449		    (let ((backend (vc-responsible-backend file t)))
1450		      (vc-file-clearprops file)
1451		      (vc-call-backend backend 'register file rev comment)
1452		      (vc-file-setprop file 'vc-backend backend)
1453		      (unless vc-make-backup-files
1454			(make-local-variable 'backup-inhibited)
1455			(setq backup-inhibited t)))
1456		    (message "Registering %s... done" file))))
1457
1458
1459(defun vc-responsible-backend (file &optional register)
1460  "Return the name of a backend system that is responsible for FILE.
1461The optional argument REGISTER means that a backend suitable for
1462registration should be found.
1463
1464If REGISTER is nil, then if FILE is already registered, return the
1465backend of FILE.  If FILE is not registered, or a directory, then the
1466first backend in `vc-handled-backends' that declares itself
1467responsible for FILE is returned.  If no backend declares itself
1468responsible, return the first backend.
1469
1470If REGISTER is non-nil, return the first responsible backend under
1471which FILE is not yet registered.  If there is no such backend, return
1472the first backend under which FILE is not yet registered, but could
1473be registered."
1474  (if (not vc-handled-backends)
1475      (error "No handled backends"))
1476  (or (and (not (file-directory-p file)) (not register) (vc-backend file))
1477      (catch 'found
1478	;; First try: find a responsible backend.  If this is for registration,
1479	;; it must be a backend under which FILE is not yet registered.
1480	(dolist (backend vc-handled-backends)
1481	  (and (or (not register)
1482		   (not (vc-call-backend backend 'registered file)))
1483	       (vc-call-backend backend 'responsible-p file)
1484	       (throw 'found backend)))
1485	;; no responsible backend
1486	(if (not register)
1487	    ;; if this is not for registration, the first backend must do
1488	    (car vc-handled-backends)
1489	  ;; for registration, we need to find a new backend that
1490	  ;; could register FILE
1491	  (dolist (backend vc-handled-backends)
1492	    (and (not (vc-call-backend backend 'registered file))
1493		 (vc-call-backend backend 'could-register file)
1494		 (throw 'found backend)))
1495	  (error "No backend that could register")))))
1496
1497(defun vc-default-responsible-p (backend file)
1498  "Indicate whether BACKEND is reponsible for FILE.
1499The default is to return nil always."
1500  nil)
1501
1502(defun vc-default-could-register (backend file)
1503  "Return non-nil if BACKEND could be used to register FILE.
1504The default implementation returns t for all files."
1505  t)
1506
1507(defun vc-resynch-window (file &optional keep noquery)
1508  "If FILE is in the current buffer, either revert or unvisit it.
1509The choice between revert (to see expanded keywords) and unvisit depends on
1510`vc-keep-workfiles'.  NOQUERY if non-nil inhibits confirmation for
1511reverting.  NOQUERY should be t *only* if it is known the only
1512difference between the buffer and the file is due to version control
1513rather than user editing!"
1514  (and (string= buffer-file-name file)
1515       (if keep
1516	   (progn
1517	     (vc-revert-buffer1 t noquery)
1518             ;; TODO: Adjusting view mode might no longer be necessary
1519             ;; after RMS change to files.el of 1999-08-08.  Investigate
1520             ;; this when we install the new VC.
1521             (and view-read-only
1522                  (if (file-writable-p file)
1523                      (and view-mode
1524                           (let ((view-old-buffer-read-only nil))
1525                             (view-mode-exit)))
1526                    (and (not view-mode)
1527                         (not (eq (get major-mode 'mode-class) 'special))
1528                         (view-mode-enter))))
1529	     (vc-mode-line buffer-file-name))
1530	 (kill-buffer (current-buffer)))))
1531
1532(defun vc-resynch-buffer (file &optional keep noquery)
1533  "If FILE is currently visited, resynch its buffer."
1534  (if (string= buffer-file-name file)
1535      (vc-resynch-window file keep noquery)
1536    (let ((buffer (get-file-buffer file)))
1537      (if buffer
1538	  (with-current-buffer buffer
1539	    (vc-resynch-window file keep noquery)))))
1540  (vc-dired-resynch-file file))
1541
1542(defun vc-start-entry (file rev comment initial-contents msg action &optional after-hook)
1543  "Accept a comment for an operation on FILE revision REV.
1544If COMMENT is nil, pop up a VC-log buffer, emit MSG, and set the
1545action on close to ACTION.  If COMMENT is a string and
1546INITIAL-CONTENTS is non-nil, then COMMENT is used as the initial
1547contents of the log entry buffer.  If COMMENT is a string and
1548INITIAL-CONTENTS is nil, do action immediately as if the user had
1549entered COMMENT.  If COMMENT is t, also do action immediately with an
1550empty comment.  Remember the file's buffer in `vc-parent-buffer'
1551\(current one if no file).  AFTER-HOOK specifies the local value
1552for vc-log-operation-hook."
1553  (let ((parent (or (and file (get-file-buffer file)) (current-buffer))))
1554    (if vc-before-checkin-hook
1555        (if file
1556            (with-current-buffer parent
1557              (run-hooks 'vc-before-checkin-hook))
1558          (run-hooks 'vc-before-checkin-hook)))
1559    (if (and comment (not initial-contents))
1560	(set-buffer (get-buffer-create "*VC-log*"))
1561      (pop-to-buffer (get-buffer-create "*VC-log*")))
1562    (set (make-local-variable 'vc-parent-buffer) parent)
1563    (set (make-local-variable 'vc-parent-buffer-name)
1564	 (concat " from " (buffer-name vc-parent-buffer)))
1565    (if file (vc-mode-line file))
1566    (vc-log-edit file)
1567    (make-local-variable 'vc-log-after-operation-hook)
1568    (if after-hook
1569	(setq vc-log-after-operation-hook after-hook))
1570    (setq vc-log-operation action)
1571    (setq vc-log-version rev)
1572    (when comment
1573      (erase-buffer)
1574      (when (stringp comment) (insert comment)))
1575    (if (or (not comment) initial-contents)
1576	(message "%s  Type C-c C-c when done" msg)
1577      (vc-finish-logentry (eq comment t)))))
1578
1579(defun vc-checkout (file &optional writable rev)
1580  "Retrieve a copy of the revision REV of FILE.
1581If WRITABLE is non-nil, make sure the retrieved file is writable.
1582REV defaults to the latest revision.
1583
1584After check-out, runs the normal hook `vc-checkout-hook'."
1585  (and writable
1586       (not rev)
1587       (vc-call make-version-backups-p file)
1588       (vc-up-to-date-p file)
1589       (vc-make-version-backup file))
1590  (with-vc-properties
1591   file
1592   (condition-case err
1593       (vc-call checkout file writable rev)
1594     (file-error
1595      ;; Maybe the backend is not installed ;-(
1596      (when writable
1597	(let ((buf (get-file-buffer file)))
1598	  (when buf (with-current-buffer buf (toggle-read-only -1)))))
1599      (signal (car err) (cdr err))))
1600   `((vc-state . ,(if (or (eq (vc-checkout-model file) 'implicit)
1601			  (not writable))
1602		      (if (vc-call latest-on-branch-p file)
1603			  'up-to-date
1604			'needs-patch)
1605		    'edited))
1606     (vc-checkout-time . ,(nth 5 (file-attributes file)))))
1607  (vc-resynch-buffer file t t)
1608  (run-hooks 'vc-checkout-hook))
1609
1610(defun vc-steal-lock (file rev owner)
1611  "Steal the lock on FILE."
1612  (let (file-description)
1613    (if rev
1614	(setq file-description (format "%s:%s" file rev))
1615      (setq file-description file))
1616    (if (not (yes-or-no-p (format "Steal the lock on %s from %s? "
1617				  file-description owner)))
1618	(error "Steal canceled"))
1619    (message "Stealing lock on %s..." file)
1620    (with-vc-properties
1621     file
1622     (vc-call steal-lock file rev)
1623     `((vc-state . edited)))
1624    (vc-resynch-buffer file t t)
1625    (message "Stealing lock on %s...done" file)
1626    ;; Write mail after actually stealing, because if the stealing
1627    ;; goes wrong, we don't want to send any mail.
1628    (compose-mail owner (format "Stolen lock on %s" file-description))
1629    (setq default-directory (expand-file-name "~/"))
1630    (goto-char (point-max))
1631    (insert
1632     (format "I stole the lock on %s, " file-description)
1633     (current-time-string)
1634     ".\n")
1635    (message "Please explain why you stole the lock.  Type C-c C-c when done.")))
1636
1637(defun vc-checkin (file &optional rev comment initial-contents)
1638  "Check in FILE.
1639The optional argument REV may be a string specifying the new version
1640level (if nil increment the current level).  COMMENT is a comment
1641string; if omitted, a buffer is popped up to accept a comment.  If
1642INITIAL-CONTENTS is non-nil, then COMMENT is used as the initial contents
1643of the log entry buffer.
1644
1645If `vc-keep-workfiles' is nil, FILE is deleted afterwards, provided
1646that the version control system supports this mode of operation.
1647
1648Runs the normal hook `vc-checkin-hook'."
1649  (vc-start-entry
1650   file rev comment initial-contents
1651   "Enter a change comment."
1652   (lambda (file rev comment)
1653     (message "Checking in %s..." file)
1654     ;; "This log message intentionally left almost blank".
1655     ;; RCS 5.7 gripes about white-space-only comments too.
1656     (or (and comment (string-match "[^\t\n ]" comment))
1657	 (setq comment "*** empty log message ***"))
1658     (with-vc-properties
1659      file
1660      ;; Change buffers to get local value of vc-checkin-switches.
1661      (with-current-buffer (or (get-file-buffer file) (current-buffer))
1662	(progn
1663	  (vc-call checkin file rev comment)
1664	  (vc-delete-automatic-version-backups file)))
1665      `((vc-state . up-to-date)
1666	(vc-checkout-time . ,(nth 5 (file-attributes file)))
1667	(vc-workfile-version . nil)))
1668     (message "Checking in %s...done" file))
1669   'vc-checkin-hook))
1670
1671(defun vc-finish-logentry (&optional nocomment)
1672  "Complete the operation implied by the current log entry.
1673Use the contents of the current buffer as a check-in or registration
1674comment.  If the optional arg NOCOMMENT is non-nil, then don't check
1675the buffer contents as a comment."
1676  (interactive)
1677  ;; Check and record the comment, if any.
1678  (unless nocomment
1679    ;; Comment too long?
1680    (vc-call-backend (or (and vc-log-file (vc-backend vc-log-file))
1681			 (vc-responsible-backend default-directory))
1682		     'logentry-check)
1683    (run-hooks 'vc-logentry-check-hook))
1684  ;; Sync parent buffer in case the user modified it while editing the comment.
1685  ;; But not if it is a vc-dired buffer.
1686  (with-current-buffer vc-parent-buffer
1687    (or vc-dired-mode (vc-buffer-sync)))
1688  (if (not vc-log-operation) (error "No log operation is pending"))
1689  ;; save the parameters held in buffer-local variables
1690  (let ((log-operation vc-log-operation)
1691	(log-file vc-log-file)
1692	(log-version vc-log-version)
1693	(log-entry (buffer-string))
1694	(after-hook vc-log-after-operation-hook)
1695	(tmp-vc-parent-buffer vc-parent-buffer))
1696    (pop-to-buffer vc-parent-buffer)
1697    ;; OK, do it to it
1698    (save-excursion
1699      (funcall log-operation
1700	       log-file
1701	       log-version
1702	       log-entry))
1703    ;; Remove checkin window (after the checkin so that if that fails
1704    ;; we don't zap the *VC-log* buffer and the typing therein).
1705    (let ((logbuf (get-buffer "*VC-log*")))
1706      (cond ((and logbuf vc-delete-logbuf-window)
1707	     (delete-windows-on logbuf (selected-frame))
1708	     ;; Kill buffer and delete any other dedicated windows/frames.
1709	     (kill-buffer logbuf))
1710	    (logbuf (pop-to-buffer "*VC-log*")
1711		    (bury-buffer)
1712		    (pop-to-buffer tmp-vc-parent-buffer))))
1713    ;; Now make sure we see the expanded headers
1714    (if log-file
1715	(vc-resynch-buffer log-file vc-keep-workfiles t))
1716    (if vc-dired-mode
1717      (dired-move-to-filename))
1718    (run-hooks after-hook 'vc-finish-logentry-hook)))
1719
1720;; Code for access to the comment ring
1721
1722;; Additional entry points for examining version histories
1723
1724;;;###autoload
1725(defun vc-diff (historic &optional not-urgent)
1726  "Display diffs between file versions.
1727Normally this compares the current file and buffer with the most
1728recent checked in version of that file.  This uses no arguments.  With
1729a prefix argument HISTORIC, it reads the file name to use and two
1730version designators specifying which versions to compare.  The
1731optional argument NOT-URGENT non-nil means it is ok to say no to
1732saving the buffer."
1733  (interactive (list current-prefix-arg t))
1734  (if historic
1735      (call-interactively 'vc-version-diff)
1736    (vc-ensure-vc-buffer)
1737    (let ((file buffer-file-name))
1738      (vc-buffer-sync not-urgent)
1739      (if (vc-workfile-unchanged-p buffer-file-name)
1740	  (message "No changes to %s since latest version" file)
1741	(vc-version-diff file nil nil)))))
1742
1743(defun vc-version-diff (file rev1 rev2)
1744  "List the differences between FILE's versions REV1 and REV2.
1745If REV1 is empty or nil it means to use the current workfile version;
1746REV2 empty or nil means the current file contents.  FILE may also be
1747a directory, in that case, generate diffs between the correponding
1748versions of all registered files in or below it."
1749  (interactive
1750   (let ((file (expand-file-name
1751                (read-file-name (if buffer-file-name
1752                                    "File or dir to diff (default visited file): "
1753                                  "File or dir to diff: ")
1754                                default-directory buffer-file-name t)))
1755         (rev1-default nil) (rev2-default nil))
1756     ;; compute default versions based on the file state
1757     (cond
1758      ;; if it's a directory, don't supply any version default
1759      ((file-directory-p file)
1760       nil)
1761      ;; if the file is not up-to-date, use current version as older version
1762      ((not (vc-up-to-date-p file))
1763       (setq rev1-default (vc-workfile-version file)))
1764      ;; if the file is not locked, use last and previous version as default
1765      (t
1766       (setq rev1-default (vc-call previous-version file
1767                                   (vc-workfile-version file)))
1768       (if (string= rev1-default "") (setq rev1-default nil))
1769       (setq rev2-default (vc-workfile-version file))))
1770     ;; construct argument list
1771     (list file
1772           (read-string (if rev1-default
1773			    (concat "Older version (default "
1774				    rev1-default "): ")
1775			  "Older version: ")
1776			nil nil rev1-default)
1777           (read-string (if rev2-default
1778			    (concat "Newer version (default "
1779				    rev2-default "): ")
1780			  "Newer version (default current source): ")
1781			nil nil rev2-default))))
1782  (if (file-directory-p file)
1783      ;; recursive directory diff
1784      (progn
1785        (vc-setup-buffer "*vc-diff*")
1786	(if (string-equal rev1 "") (setq rev1 nil))
1787	(if (string-equal rev2 "") (setq rev2 nil))
1788        (let ((inhibit-read-only t))
1789          (insert "Diffs between "
1790                  (or rev1 "last version checked in")
1791                  " and "
1792                  (or rev2 "current workfile(s)")
1793                  ":\n\n"))
1794        (let ((dir (file-name-as-directory file)))
1795          (vc-call-backend (vc-responsible-backend dir)
1796                           'diff-tree dir rev1 rev2))
1797	(vc-exec-after `(let ((inhibit-read-only t))
1798			  (insert "\nEnd of diffs.\n"))))
1799    ;; Single file diff.  It is important that the vc-controlled buffer
1800    ;; is still current at this time, because any local settings in that
1801    ;; buffer should affect the diff command.
1802    (vc-diff-internal file rev1 rev2))
1803  (set-buffer "*vc-diff*")
1804  (if (and (zerop (buffer-size))
1805	   (not (get-buffer-process (current-buffer))))
1806      (progn
1807	(if rev1
1808	    (if rev2
1809		(message "No changes to %s between %s and %s" file rev1 rev2)
1810	      (message "No changes to %s since %s" file rev1))
1811	  (message "No changes to %s since latest version" file))
1812	nil)
1813    (pop-to-buffer (current-buffer))
1814    ;; Gnus-5.8.5 sets up an autoload for diff-mode, even if it's
1815    ;; not available.  Work around that.
1816    (if (require 'diff-mode nil t) (diff-mode))
1817    (vc-exec-after '(let ((inhibit-read-only t))
1818		      (if (eq (buffer-size) 0)
1819			  (insert "No differences found.\n"))
1820		      (goto-char (point-min))
1821		      (shrink-window-if-larger-than-buffer)))
1822    t))
1823
1824(defun vc-diff-label (file file-rev rev)
1825  (concat (file-relative-name file)
1826	  (format-time-string "\t%d %b %Y %T %z\t"
1827			      (nth 5 (file-attributes file-rev)))
1828	  rev))
1829
1830(defun vc-diff-internal (file rev1 rev2)
1831  "Run diff to compare FILE's revisions REV1 and REV2.
1832Diff output goes to the *vc-diff* buffer.  The exit status of the diff
1833command is returned.
1834
1835This function takes care to set up a proper coding system for diff output.
1836If both revisions are available as local files, then it also does not
1837actually call the backend, but performs a local diff."
1838  (if (or (not rev1) (string-equal rev1 ""))
1839      (setq rev1 (vc-workfile-version file)))
1840  (if (string-equal rev2 "")
1841      (setq rev2 nil))
1842  (let ((file-rev1 (vc-version-backup-file file rev1))
1843        (file-rev2 (if (not rev2)
1844                       file
1845                     (vc-version-backup-file file rev2)))
1846        (coding-system-for-read (vc-coding-system-for-diff file)))
1847    (if (and file-rev1 file-rev2)
1848        (let ((status
1849               (if (eq vc-diff-knows-L 'no)
1850                   (apply 'vc-do-command "*vc-diff*" 1 "diff" nil
1851                          (append (vc-switches nil 'diff)
1852                                  (list (file-relative-name file-rev1)
1853                                        (file-relative-name file-rev2))))
1854                 (apply 'vc-do-command "*vc-diff*" 2 "diff" nil
1855                        (append (vc-switches nil 'diff)
1856                                ;; Provide explicit labels like RCS or
1857                                ;; CVS would do so diff-mode refers to
1858                                ;; `file' rather than to `file-rev1'
1859                                ;; when trying to find/apply/undo
1860                                ;; hunks.
1861                                (list "-L" (vc-diff-label file file-rev1 rev1)
1862                                      "-L" (vc-diff-label file file-rev2 rev2)
1863                                      (file-relative-name file-rev1)
1864                                      (file-relative-name file-rev2)))))))
1865          (if (eq status 2)
1866              (if (not vc-diff-knows-L)
1867                  (setq vc-diff-knows-L 'no
1868                        status (apply 'vc-do-command "*vc-diff*" 1 "diff" nil
1869                                      (append
1870                                       (vc-switches nil 'diff)
1871                                       (list (file-relative-name file-rev1)
1872                                             (file-relative-name file-rev2)))))
1873                (error "diff failed"))
1874            (if (not vc-diff-knows-L) (setq vc-diff-knows-L 'yes)))
1875          status)
1876      (vc-call diff file rev1 rev2))))
1877
1878(defun vc-switches (backend op)
1879  (let ((switches
1880	 (or (if backend
1881		 (let ((sym (vc-make-backend-sym
1882			     backend (intern (concat (symbol-name op)
1883						     "-switches")))))
1884		   (if (boundp sym) (symbol-value sym))))
1885	     (let ((sym (intern (format "vc-%s-switches" (symbol-name op)))))
1886	       (if (boundp sym) (symbol-value sym)))
1887	     (cond
1888	      ((eq op 'diff) diff-switches)))))
1889    (if (stringp switches) (list switches)
1890      ;; If not a list, return nil.
1891      ;; This is so we can set vc-diff-switches to t to override
1892      ;; any switches in diff-switches.
1893      (if (listp switches) switches))))
1894
1895;; Old def for compatibility with Emacs-21.[123].
1896(defmacro vc-diff-switches-list (backend) `(vc-switches ',backend 'diff))
1897(make-obsolete 'vc-diff-switches-list 'vc-switches "22.1")
1898
1899(defun vc-default-diff-tree (backend dir rev1 rev2)
1900  "List differences for all registered files at and below DIR.
1901The meaning of REV1 and REV2 is the same as for `vc-version-diff'."
1902  ;; This implementation does an explicit tree walk, and calls
1903  ;; vc-BACKEND-diff directly for each file.  An optimization
1904  ;; would be to use `vc-diff-internal', so that diffs can be local,
1905  ;; and to call it only for files that are actually changed.
1906  ;; However, this is expensive for some backends, and so it is left
1907  ;; to backend-specific implementations.
1908  (setq default-directory dir)
1909  (vc-file-tree-walk
1910   default-directory
1911   (lambda (f)
1912     (vc-exec-after
1913      `(let ((coding-system-for-read (vc-coding-system-for-diff ',f)))
1914         (message "Looking at %s" ',f)
1915         (vc-call-backend ',(vc-backend f)
1916                          'diff ',f ',rev1 ',rev2))))))
1917
1918(defun vc-coding-system-for-diff (file)
1919  "Return the coding system for reading diff output for FILE."
1920  (or coding-system-for-read
1921      ;; if we already have this file open,
1922      ;; use the buffer's coding system
1923      (let ((buf (find-buffer-visiting file)))
1924        (if buf (with-current-buffer buf
1925                  buffer-file-coding-system)))
1926      ;; otherwise, try to find one based on the file name
1927      (car (find-operation-coding-system 'insert-file-contents file))
1928      ;; and a final fallback
1929      'undecided))
1930
1931;;;###autoload
1932(defun vc-version-other-window (rev)
1933  "Visit version REV of the current file in another window.
1934If the current file is named `F', the version is named `F.~REV~'.
1935If `F.~REV~' already exists, use it instead of checking it out again."
1936  (interactive "sVersion to visit (default is workfile version): ")
1937  (vc-ensure-vc-buffer)
1938  (let* ((file buffer-file-name)
1939	 (version (if (string-equal rev "")
1940		      (vc-workfile-version file)
1941		    rev)))
1942    (switch-to-buffer-other-window (vc-find-version file version))))
1943
1944(defun vc-find-version (file version)
1945  "Read VERSION of FILE into a buffer and return the buffer."
1946  (let ((automatic-backup (vc-version-backup-file-name file version))
1947	(filebuf (or (get-file-buffer file) (current-buffer)))
1948        (filename (vc-version-backup-file-name file version 'manual)))
1949    (unless (file-exists-p filename)
1950      (if (file-exists-p automatic-backup)
1951          (rename-file automatic-backup filename nil)
1952	(message "Checking out %s..." filename)
1953	(with-current-buffer filebuf
1954	  (let ((failed t))
1955	    (unwind-protect
1956		(let ((coding-system-for-read 'no-conversion)
1957		      (coding-system-for-write 'no-conversion))
1958		  (with-temp-file filename
1959		    (let ((outbuf (current-buffer)))
1960		      ;; Change buffer to get local value of
1961		      ;; vc-checkout-switches.
1962		      (with-current-buffer filebuf
1963			(vc-call find-version file version outbuf))))
1964		  (setq failed nil))
1965	      (if (and failed (file-exists-p filename))
1966		  (delete-file filename))))
1967	  (vc-mode-line file))
1968	(message "Checking out %s...done" filename)))
1969    (find-file-noselect filename)))
1970
1971(defun vc-default-find-version (backend file rev buffer)
1972  "Provide the new `find-version' op based on the old `checkout' op.
1973This is only for compatibility with old backends.  They should be updated
1974to provide the `find-version' operation instead."
1975  (let ((tmpfile (make-temp-file (expand-file-name file))))
1976    (unwind-protect
1977	(progn
1978	  (vc-call-backend backend 'checkout file nil rev tmpfile)
1979	  (with-current-buffer buffer
1980	    (insert-file-contents-literally tmpfile)))
1981      (delete-file tmpfile))))
1982
1983;; Header-insertion code
1984
1985;;;###autoload
1986(defun vc-insert-headers ()
1987  "Insert headers into a file for use with a version control system.
1988Headers desired are inserted at point, and are pulled from
1989the variable `vc-BACKEND-header'."
1990  (interactive)
1991  (vc-ensure-vc-buffer)
1992  (save-excursion
1993    (save-restriction
1994      (widen)
1995      (if (or (not (vc-check-headers))
1996	      (y-or-n-p "Version headers already exist.  Insert another set? "))
1997          (let* ((delims (cdr (assq major-mode vc-comment-alist)))
1998                 (comment-start-vc (or (car delims) comment-start "#"))
1999                 (comment-end-vc (or (car (cdr delims)) comment-end ""))
2000                 (hdsym (vc-make-backend-sym (vc-backend buffer-file-name)
2001                                             'header))
2002                 (hdstrings (and (boundp hdsym) (symbol-value hdsym))))
2003            (dolist (s hdstrings)
2004              (insert comment-start-vc "\t" s "\t"
2005                      comment-end-vc "\n"))
2006            (if vc-static-header-alist
2007                (dolist (f vc-static-header-alist)
2008                  (if (string-match (car f) buffer-file-name)
2009                      (insert (format (cdr f) (car hdstrings)))))))))))
2010
2011(defun vc-clear-headers (&optional file)
2012  "Clear all version headers in the current buffer (or FILE).
2013The headers are reset to their non-expanded form."
2014  (let* ((filename (or file buffer-file-name))
2015	 (visited (find-buffer-visiting filename))
2016	 (backend (vc-backend filename)))
2017    (when (vc-find-backend-function backend 'clear-headers)
2018	(if visited
2019	    (let ((context (vc-buffer-context)))
2020	      ;; save-excursion may be able to relocate point and mark
2021	      ;; properly.  If it fails, vc-restore-buffer-context
2022	      ;; will give it a second try.
2023	      (save-excursion
2024		(vc-call-backend backend 'clear-headers))
2025	      (vc-restore-buffer-context context))
2026	  (set-buffer (find-file-noselect filename))
2027	  (vc-call-backend backend 'clear-headers)
2028	  (kill-buffer filename)))))
2029
2030;;;###autoload
2031(defun vc-merge ()
2032  "Merge changes between two versions into the current buffer's file.
2033This asks for two versions to merge from in the minibuffer.  If the
2034first version is a branch number, then merge all changes from that
2035branch.  If the first version is empty, merge news, i.e. recent changes
2036from the current branch.
2037
2038See Info node `Merging'."
2039  (interactive)
2040  (vc-ensure-vc-buffer)
2041  (vc-buffer-sync)
2042  (let* ((file buffer-file-name)
2043	 (backend (vc-backend file))
2044	 (state (vc-state file))
2045	 first-version second-version status)
2046    (cond
2047     ((stringp state)
2048      (error "File is locked by %s" state))
2049     ((not (vc-editable-p file))
2050      (if (y-or-n-p
2051	   "File must be checked out for merging.  Check out now? ")
2052	  (vc-checkout file t)
2053	(error "Merge aborted"))))
2054    (setq first-version
2055	  (read-string (concat "Branch or version to merge from "
2056			       "(default news on current branch): ")))
2057    (if (string= first-version "")
2058	(if (not (vc-find-backend-function backend 'merge-news))
2059	    (error "Sorry, merging news is not implemented for %s" backend)
2060	  (setq status (vc-call merge-news file)))
2061      (if (not (vc-find-backend-function backend 'merge))
2062	  (error "Sorry, merging is not implemented for %s" backend)
2063	(if (not (vc-branch-p first-version))
2064	    (setq second-version
2065		  (read-string "Second version: "
2066			       (concat (vc-branch-part first-version) ".")))
2067	  ;; We want to merge an entire branch.  Set versions
2068	  ;; accordingly, so that vc-BACKEND-merge understands us.
2069	  (setq second-version first-version)
2070	  ;; first-version must be the starting point of the branch
2071	  (setq first-version (vc-branch-part first-version)))
2072	(setq status (vc-call merge file first-version second-version))))
2073    (vc-maybe-resolve-conflicts file status "WORKFILE" "MERGE SOURCE")))
2074
2075(defun vc-maybe-resolve-conflicts (file status &optional name-A name-B)
2076  (vc-resynch-buffer file t (not (buffer-modified-p)))
2077  (if (zerop status) (message "Merge successful")
2078    (smerge-mode 1)
2079    (message "File contains conflicts.")))
2080
2081;;;###autoload
2082(defalias 'vc-resolve-conflicts 'smerge-ediff)
2083
2084;; The VC directory major mode.  Coopt Dired for this.
2085;; All VC commands get mapped into logical equivalents.
2086
2087(defvar vc-dired-switches)
2088(defvar vc-dired-terse-mode)
2089
2090(defvar vc-dired-mode-map
2091  (let ((map (make-sparse-keymap))
2092	(vmap (make-sparse-keymap)))
2093    (define-key map "\C-xv" vmap)
2094    (define-key map "v" vmap)
2095    (set-keymap-parent vmap vc-prefix-map)
2096    (define-key vmap "t" 'vc-dired-toggle-terse-mode)
2097    map))
2098
2099(define-derived-mode vc-dired-mode dired-mode "Dired under VC"
2100  "The major mode used in VC directory buffers.
2101
2102It works like Dired, but lists only files under version control, with
2103the current VC state of each file being indicated in the place of the
2104file's link count, owner, group and size.  Subdirectories are also
2105listed, and you may insert them into the buffer as desired, like in
2106Dired.
2107
2108All Dired commands operate normally, with the exception of `v', which
2109is redefined as the version control prefix, so that you can type
2110`vl', `v=' etc. to invoke `vc-print-log', `vc-diff', and the like on
2111the file named in the current Dired buffer line.  `vv' invokes
2112`vc-next-action' on this file, or on all files currently marked.
2113There is a special command, `*l', to mark all files currently locked."
2114  ;; define-derived-mode does it for us in Emacs-21, but not in Emacs-20.
2115  ;; We do it here because dired might not be loaded yet
2116  ;; when vc-dired-mode-map is initialized.
2117  (set-keymap-parent vc-dired-mode-map dired-mode-map)
2118  (add-hook 'dired-after-readin-hook 'vc-dired-hook nil t)
2119  ;; The following is slightly modified from files.el,
2120  ;; because file lines look a bit different in vc-dired-mode
2121  ;; (the column before the date does not end in a digit).
2122  ;; albinus: It should be done in the original declaration.  Problem
2123  ;; is the optional empty state-info; otherwise ")" would be good
2124  ;; enough as delimeter.
2125  (set (make-local-variable 'directory-listing-before-filename-regexp)
2126  (let* ((l "\\([A-Za-z]\\|[^\0-\177]\\)")
2127         ;; In some locales, month abbreviations are as short as 2 letters,
2128         ;; and they can be followed by ".".
2129         (month (concat l l "+\\.?"))
2130         (s " ")
2131         (yyyy "[0-9][0-9][0-9][0-9]")
2132         (dd "[ 0-3][0-9]")
2133         (HH:MM "[ 0-2][0-9]:[0-5][0-9]")
2134         (seconds "[0-6][0-9]\\([.,][0-9]+\\)?")
2135         (zone "[-+][0-2][0-9][0-5][0-9]")
2136         (iso-mm-dd "[01][0-9]-[0-3][0-9]")
2137         (iso-time (concat HH:MM "\\(:" seconds "\\( ?" zone "\\)?\\)?"))
2138         (iso (concat "\\(\\(" yyyy "-\\)?" iso-mm-dd "[ T]" iso-time
2139                      "\\|" yyyy "-" iso-mm-dd "\\)"))
2140         (western (concat "\\(" month s "+" dd "\\|" dd "\\.?" s month "\\)"
2141                          s "+"
2142                          "\\(" HH:MM "\\|" yyyy "\\)"))
2143         (western-comma (concat month s "+" dd "," s "+" yyyy))
2144         ;; Japanese MS-Windows ls-lisp has one-digit months, and
2145         ;; omits the Kanji characters after month and day-of-month.
2146         (mm "[ 0-1]?[0-9]")
2147         (japanese
2148          (concat mm l "?" s dd l "?" s "+"
2149                  "\\(" HH:MM "\\|" yyyy l "?" "\\)")))
2150    ;; the .* below ensures that we find the last match on a line
2151    (concat ".*" s
2152            "\\(" western "\\|" western-comma "\\|" japanese "\\|" iso "\\)"
2153            s "+")))
2154  (and (boundp 'vc-dired-switches)
2155       vc-dired-switches
2156       (set (make-local-variable 'dired-actual-switches)
2157            vc-dired-switches))
2158  (set (make-local-variable 'vc-dired-terse-mode) vc-dired-terse-display)
2159  (setq vc-dired-mode t))
2160
2161(defun vc-dired-toggle-terse-mode ()
2162  "Toggle terse display in VC Dired."
2163  (interactive)
2164  (if (not vc-dired-mode)
2165      nil
2166    (setq vc-dired-terse-mode (not vc-dired-terse-mode))
2167    (if vc-dired-terse-mode
2168        (vc-dired-hook)
2169      (revert-buffer))))
2170
2171(defun vc-dired-mark-locked ()
2172  "Mark all files currently locked."
2173  (interactive)
2174  (dired-mark-if (let ((f (dired-get-filename nil t)))
2175		   (and f
2176			(not (file-directory-p f))
2177			(not (vc-up-to-date-p f))))
2178		 "locked file"))
2179
2180(define-key vc-dired-mode-map "*l" 'vc-dired-mark-locked)
2181
2182(defun vc-default-dired-state-info (backend file)
2183  (let ((state (vc-state file)))
2184    (cond
2185     ((stringp state) (concat "(" state ")"))
2186     ((eq state 'edited) (concat "(" (vc-user-login-name file) ")"))
2187     ((eq state 'needs-merge) "(merge)")
2188     ((eq state 'needs-patch) "(patch)")
2189     ((eq state 'unlocked-changes) "(stale)"))))
2190
2191(defun vc-dired-reformat-line (vc-info)
2192  "Reformat a directory-listing line.
2193Replace various columns with version control information, VC-INFO.
2194This code, like dired, assumes UNIX -l format."
2195  (beginning-of-line)
2196  (when (re-search-forward
2197         ;; Match link count, owner, group, size.  Group may be missing,
2198         ;; and only the size is present in OS/2 -l format.
2199         "^..[drwxlts-]+ \\( *[0-9]+\\( [^ ]+ +\\([^ ]+ +\\)?[0-9]+\\)?\\) "
2200         (line-end-position) t)
2201      (replace-match (substring (concat vc-info "          ") 0 10)
2202                     t t nil 1)))
2203
2204(defun vc-dired-hook ()
2205  "Reformat the listing according to version control.
2206Called by dired after any portion of a vc-dired buffer has been read in."
2207  (message "Getting version information... ")
2208  (let (subdir filename (buffer-read-only nil))
2209    (goto-char (point-min))
2210    (while (not (eobp))
2211      (cond
2212       ;; subdir header line
2213       ((setq subdir (dired-get-subdir))
2214	;; if the backend supports it, get the state
2215	;; of all files in this directory at once
2216	(let ((backend (vc-responsible-backend subdir)))
2217	  (if (vc-find-backend-function backend 'dir-state)
2218	      (vc-call-backend backend 'dir-state subdir)))
2219        (forward-line 1)
2220        ;; erase (but don't remove) the "total" line
2221	(delete-region (point) (line-end-position))
2222	(beginning-of-line)
2223	(forward-line 1))
2224       ;; file line
2225       ((setq filename (dired-get-filename nil t))
2226        (cond
2227         ;; subdir
2228         ((file-directory-p filename)
2229          (cond
2230           ((member (file-name-nondirectory filename)
2231                    vc-directory-exclusion-list)
2232            (let ((pos (point)))
2233              (dired-kill-tree filename)
2234              (goto-char pos)
2235              (dired-kill-line)))
2236           (vc-dired-terse-mode
2237            ;; Don't show directories in terse mode.  Don't use
2238            ;; dired-kill-line to remove it, because in recursive listings,
2239            ;; that would remove the directory contents as well.
2240            (delete-region (line-beginning-position)
2241                           (progn (forward-line 1) (point))))
2242           ((string-match "\\`\\.\\.?\\'" (file-name-nondirectory filename))
2243            (dired-kill-line))
2244           (t
2245            (vc-dired-reformat-line nil)
2246            (forward-line 1))))
2247         ;; ordinary file
2248         ((and (vc-backend filename)
2249	       (not (and vc-dired-terse-mode
2250			 (vc-up-to-date-p filename))))
2251          (vc-dired-reformat-line (vc-call dired-state-info filename))
2252          (forward-line 1))
2253         (t
2254          (dired-kill-line))))
2255       ;; any other line
2256       (t (forward-line 1))))
2257    (vc-dired-purge))
2258  (message "Getting version information... done")
2259  (save-restriction
2260    (widen)
2261    (cond ((eq (count-lines (point-min) (point-max)) 1)
2262           (goto-char (point-min))
2263           (message "No files locked under %s" default-directory)))))
2264
2265(defun vc-dired-purge ()
2266  "Remove empty subdirs."
2267  (goto-char (point-min))
2268  (while (dired-get-subdir)
2269    (forward-line 2)
2270    (if (dired-get-filename nil t)
2271	(if (not (dired-next-subdir 1 t))
2272	    (goto-char (point-max)))
2273      (forward-line -2)
2274      (if (not (string= (dired-current-directory) default-directory))
2275	  (dired-do-kill-lines t "")
2276	;; We cannot remove the top level directory.
2277	;; Just make it look a little nicer.
2278	(forward-line 1)
2279	(or (eobp) (kill-line))
2280	(if (not (dired-next-subdir 1 t))
2281	    (goto-char (point-max))))))
2282  (goto-char (point-min)))
2283
2284(defun vc-dired-buffers-for-dir (dir)
2285  "Return a list of all vc-dired buffers that currently display DIR."
2286  (let (result)
2287    ;; Check whether dired is loaded.
2288    (when (fboundp 'dired-buffers-for-dir)
2289      (mapcar (lambda (buffer)
2290		(with-current-buffer buffer
2291		  (if vc-dired-mode
2292		      (setq result (append result (list buffer))))))
2293	      (dired-buffers-for-dir dir)))
2294    result))
2295
2296(defun vc-dired-resynch-file (file)
2297  "Update the entries for FILE in any VC Dired buffers that list it."
2298  (let ((buffers (vc-dired-buffers-for-dir (file-name-directory file))))
2299    (when buffers
2300      (mapcar (lambda (buffer)
2301		(with-current-buffer buffer
2302		  (if (dired-goto-file file)
2303		      ;; bind vc-dired-terse-mode to nil so that
2304		      ;; files won't vanish when they are checked in
2305		      (let ((vc-dired-terse-mode nil))
2306			(dired-do-redisplay 1)))))
2307	      buffers))))
2308
2309;;;###autoload
2310(defun vc-directory (dir read-switches)
2311  "Create a buffer in VC Dired Mode for directory DIR.
2312
2313See Info node `VC Dired Mode'.
2314
2315With prefix arg READ-SWITCHES, specify a value to override
2316`dired-listing-switches' when generating the listing."
2317  (interactive "DDired under VC (directory): \nP")
2318  (let ((vc-dired-switches (concat vc-dired-listing-switches
2319                                   (if vc-dired-recurse "R" ""))))
2320    (if (eq (string-match tramp-file-name-regexp dir) 0)
2321        (error "Sorry, vc-directory does not work over Tramp"))
2322    (if read-switches
2323        (setq vc-dired-switches
2324              (read-string "Dired listing switches: "
2325                           vc-dired-switches)))
2326    (require 'dired)
2327    (require 'dired-aux)
2328    (switch-to-buffer
2329     (dired-internal-noselect (expand-file-name (file-name-as-directory dir))
2330                              vc-dired-switches
2331                              'vc-dired-mode))))
2332
2333
2334;; Named-configuration entry points
2335
2336(defun vc-snapshot-precondition (dir)
2337  "Scan the tree below DIR, looking for files not up-to-date.
2338If any file is not up-to-date, return the name of the first such file.
2339\(This means, neither snapshot creation nor retrieval is allowed.\)
2340If one or more of the files are currently visited, return `visited'.
2341Otherwise, return nil."
2342  (let ((status nil))
2343    (catch 'vc-locked-example
2344      (vc-file-tree-walk
2345       dir
2346       (lambda (f)
2347	 (if (not (vc-up-to-date-p f)) (throw 'vc-locked-example f)
2348	   (if (get-file-buffer f) (setq status 'visited)))))
2349      status)))
2350
2351;;;###autoload
2352(defun vc-create-snapshot (dir name branchp)
2353  "Descending recursively from DIR, make a snapshot called NAME.
2354For each registered file, the version level of its latest version
2355becomes part of the named configuration.  If the prefix argument
2356BRANCHP is given, the snapshot is made as a new branch and the files
2357are checked out in that new branch."
2358  (interactive
2359   (list (read-file-name "Directory: " default-directory default-directory t)
2360         (read-string "New snapshot name: ")
2361	 current-prefix-arg))
2362  (message "Making %s... " (if branchp "branch" "snapshot"))
2363  (if (file-directory-p dir) (setq dir (file-name-as-directory dir)))
2364  (vc-call-backend (vc-responsible-backend dir)
2365		   'create-snapshot dir name branchp)
2366  (message "Making %s... done" (if branchp "branch" "snapshot")))
2367
2368(defun vc-default-create-snapshot (backend dir name branchp)
2369  (when branchp
2370    (error "VC backend %s does not support module branches" backend))
2371  (let ((result (vc-snapshot-precondition dir)))
2372    (if (stringp result)
2373	(error "File %s is not up-to-date" result)
2374      (vc-file-tree-walk
2375       dir
2376       (lambda (f)
2377	 (vc-call assign-name f name))))))
2378
2379;;;###autoload
2380(defun vc-retrieve-snapshot (dir name)
2381  "Descending recursively from DIR, retrieve the snapshot called NAME.
2382If NAME is empty, it refers to the latest versions.
2383If locking is used for the files in DIR, then there must not be any
2384locked files at or below DIR (but if NAME is empty, locked files are
2385allowed and simply skipped)."
2386  (interactive
2387   (list (read-file-name "Directory: " default-directory default-directory t)
2388         (read-string "Snapshot name to retrieve (default latest versions): ")))
2389  (let ((update (yes-or-no-p "Update any affected buffers? "))
2390	(msg (if (or (not name) (string= name ""))
2391		 (format "Updating %s... " (abbreviate-file-name dir))
2392	       (format "Retrieving snapshot into %s... "
2393		       (abbreviate-file-name dir)))))
2394    (message "%s" msg)
2395    (vc-call-backend (vc-responsible-backend dir)
2396		     'retrieve-snapshot dir name update)
2397    (message "%s" (concat msg "done"))))
2398
2399(defun vc-default-retrieve-snapshot (backend dir name update)
2400  (if (string= name "")
2401      (progn
2402        (vc-file-tree-walk
2403         dir
2404         (lambda (f) (and
2405		 (vc-up-to-date-p f)
2406		 (vc-error-occurred
2407		  (vc-call checkout f nil "")
2408		  (if update (vc-resynch-buffer f t t)))))))
2409    (let ((result (vc-snapshot-precondition dir)))
2410      (if (stringp result)
2411          (error "File %s is locked" result)
2412        (setq update (and (eq result 'visited) update))
2413        (vc-file-tree-walk
2414         dir
2415         (lambda (f) (vc-error-occurred
2416		 (vc-call checkout f nil name)
2417		 (if update (vc-resynch-buffer f t t)))))))))
2418
2419;; Miscellaneous other entry points
2420
2421;;;###autoload
2422(defun vc-print-log (&optional focus-rev)
2423  "List the change log of the current buffer in a window.
2424If FOCUS-REV is non-nil, leave the point at that revision."
2425  (interactive)
2426  (vc-ensure-vc-buffer)
2427  (let ((file buffer-file-name))
2428    (or focus-rev (setq focus-rev (vc-workfile-version file)))
2429    ;; Don't switch to the output buffer before running the command,
2430    ;; so that any buffer-local settings in the vc-controlled
2431    ;; buffer can be accessed by the command.
2432    (condition-case err
2433        (progn
2434          (vc-call print-log file "*vc-change-log*")
2435          (set-buffer "*vc-change-log*"))
2436      (wrong-number-of-arguments
2437       ;; If this error came from the above call to print-log, try again
2438       ;; without the optional buffer argument (for backward compatibility).
2439       ;; Otherwise, resignal.
2440       (if (or (not (eq (cadr err)
2441                        (indirect-function
2442                         (vc-find-backend-function (vc-backend file)
2443                                                   'print-log))))
2444               (not (eq (caddr err) 2)))
2445           (signal (car err) (cdr err))
2446         ;; for backward compatibility
2447         (vc-call print-log file)
2448         (set-buffer "*vc*"))))
2449    (pop-to-buffer (current-buffer))
2450    (vc-exec-after
2451     `(let ((inhibit-read-only t))
2452    	(log-view-mode)
2453	(goto-char (point-max)) (forward-line -1)
2454	(while (looking-at "=*\n")
2455	  (delete-char (- (match-end 0) (match-beginning 0)))
2456	  (forward-line -1))
2457	(goto-char (point-min))
2458	(if (looking-at "[\b\t\n\v\f\r ]+")
2459	    (delete-char (- (match-end 0) (match-beginning 0))))
2460	;; (shrink-window-if-larger-than-buffer)
2461	;; move point to the log entry for the current version
2462	(vc-call-backend ',(vc-backend file)
2463			 'show-log-entry
2464			 ',focus-rev)
2465        (set-buffer-modified-p nil)))))
2466
2467(defun vc-default-show-log-entry (backend rev)
2468  (with-no-warnings
2469   (log-view-goto-rev rev)))
2470
2471(defun vc-default-comment-history (backend file)
2472  "Return a string with all log entries stored in BACKEND for FILE."
2473  (if (vc-find-backend-function backend 'print-log)
2474      (with-current-buffer "*vc*"
2475	(vc-call print-log file)
2476	(vc-call wash-log file)
2477	(buffer-string))))
2478
2479(defun vc-default-wash-log (backend file)
2480  "Remove all non-comment information from log output.
2481This default implementation works for RCS logs; backends should override
2482it if their logs are not in RCS format."
2483  (let ((separator (concat "^-+\nrevision [0-9.]+\ndate: .*\n"
2484			   "\\(branches: .*;\n\\)?"
2485			   "\\(\\*\\*\\* empty log message \\*\\*\\*\n\\)?")))
2486    (goto-char (point-max)) (forward-line -1)
2487    (while (looking-at "=*\n")
2488      (delete-char (- (match-end 0) (match-beginning 0)))
2489      (forward-line -1))
2490    (goto-char (point-min))
2491    (if (looking-at "[\b\t\n\v\f\r ]+")
2492	(delete-char (- (match-end 0) (match-beginning 0))))
2493    (goto-char (point-min))
2494    (re-search-forward separator nil t)
2495    (delete-region (point-min) (point))
2496    (while (re-search-forward separator nil t)
2497      (delete-region (match-beginning 0) (match-end 0)))))
2498
2499;;;###autoload
2500(defun vc-revert-buffer ()
2501  "Revert the current buffer's file to the version it was based on.
2502This asks for confirmation if the buffer contents are not identical
2503to that version.  This function does not automatically pick up newer
2504changes found in the master file; use \\[universal-argument] \\[vc-next-action] to do so."
2505  (interactive)
2506  (vc-ensure-vc-buffer)
2507  ;; Make sure buffer is saved.  If the user says `no', abort since
2508  ;; we cannot show the changes and ask for confirmation to discard them.
2509  (vc-buffer-sync nil)
2510  (let ((file buffer-file-name)
2511	;; This operation should always ask for confirmation.
2512	(vc-suppress-confirm nil)
2513	(obuf (current-buffer))
2514	status)
2515    (if (vc-up-to-date-p file)
2516        (unless (yes-or-no-p "File seems up-to-date.  Revert anyway? ")
2517          (error "Revert canceled")))
2518    (unless (vc-workfile-unchanged-p file)
2519      (message "Finding changes...")
2520      ;; vc-diff selects the new window, which is not what we want:
2521      ;; if the new window is on another frame, that'd require the user
2522      ;; moving her mouse to answer the yes-or-no-p question.
2523      (let* ((vc-disable-async-diff (not vc-allow-async-revert))
2524             (win (save-selected-window
2525                    (setq status (vc-diff nil t)) (selected-window))))
2526	(vc-exec-after `(message nil))
2527	(when status
2528	  (unwind-protect
2529	      (unless (yes-or-no-p "Discard changes? ")
2530		(error "Revert canceled"))
2531	    (select-window win)
2532	    (if (one-window-p t)
2533		(if (window-dedicated-p (selected-window))
2534		    (make-frame-invisible))
2535	      (delete-window))))))
2536    (set-buffer obuf)
2537    ;; Do the reverting
2538    (message "Reverting %s..." file)
2539    (vc-revert-file file)
2540    (message "Reverting %s...done" file)))
2541
2542;;;###autoload
2543(defun vc-update ()
2544  "Update the current buffer's file to the latest version on its branch.
2545If the file contains no changes, and is not locked, then this simply replaces
2546the working file with the latest version on its branch.  If the file contains
2547changes, and the backend supports merging news, then any recent changes from
2548the current branch are merged into the working file."
2549  (interactive)
2550  (vc-ensure-vc-buffer)
2551  (vc-buffer-sync nil)
2552  (let ((file buffer-file-name))
2553    (if (vc-up-to-date-p file)
2554        (vc-checkout file nil "")
2555      (if (eq (vc-checkout-model file) 'locking)
2556          (if (eq (vc-state file) 'edited)
2557              (error
2558               (substitute-command-keys
2559           "File is locked--type \\[vc-revert-buffer] to discard changes"))
2560            (error
2561             (substitute-command-keys
2562           "Unexpected file state (%s)--type \\[vc-next-action] to correct")
2563                   (vc-state file)))
2564        (if (not (vc-find-backend-function (vc-backend file) 'merge-news))
2565            (error "Sorry, merging news is not implemented for %s"
2566                   (vc-backend file))
2567          (vc-call merge-news file)
2568          (vc-resynch-window file t t))))))
2569
2570(defun vc-version-backup-file (file &optional rev)
2571  "Return name of backup file for revision REV of FILE.
2572If version backups should be used for FILE, and there exists
2573such a backup for REV or the current workfile version of file,
2574return its name; otherwise return nil."
2575  (when (vc-call make-version-backups-p file)
2576    (let ((backup-file (vc-version-backup-file-name file rev)))
2577      (if (file-exists-p backup-file)
2578          backup-file
2579        ;; there is no automatic backup, but maybe the user made one manually
2580        (setq backup-file (vc-version-backup-file-name file rev 'manual))
2581        (if (file-exists-p backup-file)
2582            backup-file)))))
2583
2584(defun vc-default-revert (backend file contents-done)
2585  (unless contents-done
2586    (let ((rev (vc-workfile-version file))
2587          (file-buffer (or (get-file-buffer file) (current-buffer))))
2588      (message "Checking out %s..." file)
2589      (let ((failed t)
2590            (backup-name (car (find-backup-file-name file))))
2591        (when backup-name
2592          (copy-file file backup-name 'ok-if-already-exists 'keep-date)
2593          (unless (file-writable-p file)
2594            (set-file-modes file (logior (file-modes file) 128))))
2595        (unwind-protect
2596            (let ((coding-system-for-read 'no-conversion)
2597                  (coding-system-for-write 'no-conversion))
2598              (with-temp-file file
2599                (let ((outbuf (current-buffer)))
2600                  ;; Change buffer to get local value of vc-checkout-switches.
2601                  (with-current-buffer file-buffer
2602                    (let ((default-directory (file-name-directory file)))
2603                      (vc-call find-version file rev outbuf)))))
2604              (setq failed nil))
2605          (when backup-name
2606            (if failed
2607                (rename-file backup-name file 'ok-if-already-exists)
2608              (and (not vc-make-backup-files) (delete-file backup-name))))))
2609      (message "Checking out %s...done" file))))
2610
2611(defun vc-revert-file (file)
2612  "Revert FILE back to the version it was based on."
2613  (with-vc-properties
2614   file
2615   (let ((backup-file (vc-version-backup-file file)))
2616     (when backup-file
2617       (copy-file backup-file file 'ok-if-already-exists 'keep-date)
2618       (vc-delete-automatic-version-backups file))
2619     (vc-call revert file backup-file))
2620   `((vc-state . up-to-date)
2621     (vc-checkout-time . ,(nth 5 (file-attributes file)))))
2622  (vc-resynch-buffer file t t))
2623
2624;;;###autoload
2625(defun vc-cancel-version (norevert)
2626  "Get rid of most recently checked in version of this file.
2627A prefix argument NOREVERT means do not revert the buffer afterwards."
2628  (interactive "P")
2629  (vc-ensure-vc-buffer)
2630  (let* ((file buffer-file-name)
2631	 (backend (vc-backend file))
2632         (target (vc-workfile-version file)))
2633    (cond
2634     ((not (vc-find-backend-function backend 'cancel-version))
2635      (error "Sorry, canceling versions is not supported under %s" backend))
2636     ((not (vc-call latest-on-branch-p file))
2637      (error "This is not the latest version; VC cannot cancel it"))
2638     ((not (vc-up-to-date-p file))
2639      (error "%s" (substitute-command-keys "File is not up to date; use \\[vc-revert-buffer] to discard changes"))))
2640    (if (null (yes-or-no-p (format "Remove version %s from master? " target)))
2641	(error "Aborted")
2642      (setq norevert (or norevert (not
2643          (yes-or-no-p "Revert buffer to most recent remaining version? "))))
2644
2645      (message "Removing last change from %s..." file)
2646      (with-vc-properties
2647       file
2648       (vc-call cancel-version file norevert)
2649       `((vc-state . ,(if norevert 'edited 'up-to-date))
2650	 (vc-checkout-time . ,(if norevert
2651				0
2652			      (nth 5 (file-attributes file))))
2653	 (vc-workfile-version . nil)))
2654      (message "Removing last change from %s...done" file)
2655
2656      (cond
2657       (norevert ;; clear version headers and mark the buffer modified
2658	(set-visited-file-name file)
2659	(when (not vc-make-backup-files)
2660	  ;; inhibit backup for this buffer
2661	  (make-local-variable 'backup-inhibited)
2662	  (setq backup-inhibited t))
2663	(setq buffer-read-only nil)
2664	(vc-clear-headers)
2665	(vc-mode-line file)
2666	(vc-dired-resynch-file file))
2667       (t ;; revert buffer to file on disk
2668	(vc-resynch-buffer file t t)))
2669      (message "Version %s has been removed from the master" target))))
2670
2671;;;###autoload
2672(defun vc-switch-backend (file backend)
2673  "Make BACKEND the current version control system for FILE.
2674FILE must already be registered in BACKEND.  The change is not
2675permanent, only for the current session.  This function only changes
2676VC's perspective on FILE, it does not register or unregister it.
2677By default, this command cycles through the registered backends.
2678To get a prompt, use a prefix argument."
2679  (interactive
2680   (list
2681    (or buffer-file-name
2682        (error "There is no version-controlled file in this buffer"))
2683    (let ((backend (vc-backend buffer-file-name))
2684	  (backends nil))
2685      (unwind-protect
2686	  (progn
2687	    (unless backend
2688	      (error "File %s is not under version control" buffer-file-name))
2689	    ;; Find the registered backends.
2690	    (dolist (backend vc-handled-backends)
2691	      (when (vc-call-backend backend 'registered buffer-file-name)
2692		(push backend backends)))
2693	    ;; Find the next backend.
2694	    (let ((def (car (delq backend
2695				  (append (memq backend backends) backends))))
2696		  (others (delete backend backends)))
2697	      (cond
2698	       ((null others) (error "No other backend to switch to"))
2699	       (current-prefix-arg
2700		(intern
2701		 (upcase
2702		  (completing-read
2703		   (format "Switch to backend [%s]: " def)
2704		   (mapcar (lambda (b) (list (downcase (symbol-name b)))) backends)
2705		   nil t nil nil (downcase (symbol-name def))))))
2706	       (t def))))
2707	;; Calling the `registered' method can mess up the file
2708	;; properties, so we want to revert them to what they were.
2709	(if (and backend (delete backend backends))
2710	    (vc-call-backend backend 'registered buffer-file-name))))))
2711  (unless (eq backend (vc-backend file))
2712    (vc-file-clearprops file)
2713    (vc-file-setprop file 'vc-backend backend)
2714    ;; Force recomputation of the state
2715    (unless (vc-call-backend backend 'registered file)
2716      (vc-file-clearprops file)
2717      (error "%s is not registered in %s" file backend))
2718    (vc-mode-line file)))
2719
2720;;;###autoload
2721(defun vc-transfer-file (file new-backend)
2722  "Transfer FILE to another version control system NEW-BACKEND.
2723If NEW-BACKEND has a higher precedence than FILE's current backend
2724\(i.e.  it comes earlier in `vc-handled-backends'), then register FILE in
2725NEW-BACKEND, using the version number from the current backend as the
2726base level.  If NEW-BACKEND has a lower precedence than the current
2727backend, then commit all changes that were made under the current
2728backend to NEW-BACKEND, and unregister FILE from the current backend.
2729\(If FILE is not yet registered under NEW-BACKEND, register it.)"
2730  (let* ((old-backend (vc-backend file))
2731	 (edited (memq (vc-state file) '(edited needs-merge)))
2732	 (registered (vc-call-backend new-backend 'registered file))
2733	 (move
2734	  (and registered    ; Never move if not registered in new-backend yet.
2735	       ;; move if new-backend comes later in vc-handled-backends
2736	       (or (memq new-backend (memq old-backend vc-handled-backends))
2737		   (y-or-n-p "Final transfer? "))))
2738	 (comment nil))
2739    (if (eq old-backend new-backend)
2740	(error "%s is the current backend of %s" new-backend file))
2741    (if registered
2742	(set-file-modes file (logior (file-modes file) 128))
2743      ;; `registered' might have switched under us.
2744      (vc-switch-backend file old-backend)
2745      (let* ((rev (vc-workfile-version file))
2746	     (modified-file (and edited (make-temp-file file)))
2747	     (unmodified-file (and modified-file (vc-version-backup-file file))))
2748	;; Go back to the base unmodified file.
2749	(unwind-protect
2750	    (progn
2751	      (when modified-file
2752		(copy-file file modified-file 'ok-if-already-exists)
2753		;; If we have a local copy of the unmodified file, handle that
2754		;; here and not in vc-revert-file because we don't want to
2755		;; delete that copy -- it is still useful for OLD-BACKEND.
2756		(if unmodified-file
2757		    (copy-file unmodified-file file
2758			       'ok-if-already-exists 'keep-date)
2759		  (if (y-or-n-p "Get base version from master? ")
2760		      (vc-revert-file file))))
2761	      (vc-call-backend new-backend 'receive-file file rev))
2762	  (when modified-file
2763	    (vc-switch-backend file new-backend)
2764	    (unless (eq (vc-checkout-model file) 'implicit)
2765	      (vc-checkout file t nil))
2766	    (rename-file modified-file file 'ok-if-already-exists)
2767	    (vc-file-setprop file 'vc-checkout-time nil)))))
2768    (when move
2769      (vc-switch-backend file old-backend)
2770      (setq comment (vc-call comment-history file))
2771      (vc-call unregister file))
2772    (vc-switch-backend file new-backend)
2773    (when (or move edited)
2774      (vc-file-setprop file 'vc-state 'edited)
2775      (vc-mode-line file)
2776      (vc-checkin file nil comment (stringp comment)))))
2777
2778(defun vc-default-unregister (backend file)
2779  "Default implementation of `vc-unregister', signals an error."
2780  (error "Unregistering files is not supported for %s" backend))
2781
2782(defun vc-default-receive-file (backend file rev)
2783  "Let BACKEND receive FILE from another version control system."
2784  (vc-call-backend backend 'register file rev ""))
2785
2786(defun vc-rename-master (oldmaster newfile templates)
2787  "Rename OLDMASTER to be the master file for NEWFILE based on TEMPLATES."
2788  (let* ((dir (file-name-directory (expand-file-name oldmaster)))
2789	 (newdir (or (file-name-directory newfile) ""))
2790	 (newbase (file-name-nondirectory newfile))
2791	 (masters
2792	  ;; List of potential master files for `newfile'
2793	  (mapcar
2794	   (lambda (s) (vc-possible-master s newdir newbase))
2795	   templates)))
2796    (if (or (file-symlink-p oldmaster)
2797	    (file-symlink-p (file-name-directory oldmaster)))
2798	(error "This is unsafe in the presence of symbolic links"))
2799    (rename-file
2800     oldmaster
2801     (catch 'found
2802       ;; If possible, keep the master file in the same directory.
2803       (dolist (f masters)
2804	 (if (and f (string= (file-name-directory (expand-file-name f)) dir))
2805	     (throw 'found f)))
2806       ;; If not, just use the first possible place.
2807       (dolist (f masters)
2808	 (and f (or (not (setq dir (file-name-directory f)))
2809		    (file-directory-p dir))
2810	      (throw 'found f)))
2811       (error "New file lacks a version control directory")))))
2812
2813(defun vc-delete-file (file)
2814  "Delete file and mark it as such in the version control system."
2815  (interactive "fVC delete file: ")
2816  (let ((buf (get-file-buffer file))
2817        (backend (vc-backend file)))
2818    (unless backend
2819      (error "File %s is not under version control"
2820             (file-name-nondirectory file)))
2821    (unless (vc-find-backend-function backend 'delete-file)
2822      (error "Deleting files under %s is not supported in VC" backend))
2823    (if (and buf (buffer-modified-p buf))
2824	(error "Please save files before deleting them"))
2825    (unless (y-or-n-p (format "Really want to delete %s? "
2826			      (file-name-nondirectory file)))
2827      (error "Abort!"))
2828    (unless (or (file-directory-p file) (null make-backup-files))
2829      (with-current-buffer (or buf (find-file-noselect file))
2830	(let ((backup-inhibited nil))
2831	  (backup-buffer))))
2832    (vc-call delete-file file)
2833    ;; If the backend hasn't deleted the file itself, let's do it for him.
2834    (if (file-exists-p file) (delete-file file))))
2835
2836(defun vc-default-rename-file (backend old new)
2837  (condition-case nil
2838      (add-name-to-file old new)
2839    (error (rename-file old new)))
2840  (vc-delete-file old)
2841  (with-current-buffer (find-file-noselect new)
2842    (vc-register)))
2843
2844;;;###autoload
2845(defun vc-rename-file (old new)
2846  "Rename file OLD to NEW, and rename its master file likewise."
2847  (interactive "fVC rename file: \nFRename to: ")
2848  (let ((oldbuf (get-file-buffer old)))
2849    (if (and oldbuf (buffer-modified-p oldbuf))
2850	(error "Please save files before moving them"))
2851    (if (get-file-buffer new)
2852	(error "Already editing new file name"))
2853    (if (file-exists-p new)
2854	(error "New file already exists"))
2855    (let ((state (vc-state old)))
2856      (unless (memq state '(up-to-date edited))
2857	(error "Please %s files before moving them"
2858	       (if (stringp state) "check in" "update"))))
2859    (vc-call rename-file old new)
2860    (vc-file-clearprops old)
2861    ;; Move the actual file (unless the backend did it already)
2862    (if (file-exists-p old) (rename-file old new))
2863    ;; ?? Renaming a file might change its contents due to keyword expansion.
2864    ;; We should really check out a new copy if the old copy was precisely equal
2865    ;; to some checked in version.  However, testing for this is tricky....
2866    (if oldbuf
2867	(with-current-buffer oldbuf
2868	  (let ((buffer-read-only buffer-read-only))
2869	    (set-visited-file-name new))
2870	  (vc-backend new)
2871	  (vc-mode-line new)
2872	  (set-buffer-modified-p nil)))))
2873
2874;;;###autoload
2875(defun vc-update-change-log (&rest args)
2876  "Find change log file and add entries from recent version control logs.
2877Normally, find log entries for all registered files in the default
2878directory.
2879
2880With prefix arg of \\[universal-argument], only find log entries for the current buffer's file.
2881
2882With any numeric prefix arg, find log entries for all currently visited
2883files that are under version control.  This puts all the entries in the
2884log for the default directory, which may not be appropriate.
2885
2886From a program, any ARGS are assumed to be filenames for which
2887log entries should be gathered."
2888  (interactive
2889   (cond ((consp current-prefix-arg)	;C-u
2890	  (list buffer-file-name))
2891	 (current-prefix-arg		;Numeric argument.
2892	  (let ((files nil)
2893		(buffers (buffer-list))
2894		file)
2895	    (while buffers
2896	      (setq file (buffer-file-name (car buffers)))
2897	      (and file (vc-backend file)
2898		   (setq files (cons file files)))
2899	      (setq buffers (cdr buffers)))
2900	    files))
2901	 (t
2902          ;; Don't supply any filenames to backend; this means
2903          ;; it should find all relevant files relative to
2904          ;; the default-directory.
2905	  nil)))
2906  (dolist (file (or args (list default-directory)))
2907    (if (eq (string-match tramp-file-name-regexp file) 0)
2908        (error "Sorry, vc-update-change-log does not work over Tramp")))
2909  (vc-call-backend (vc-responsible-backend default-directory)
2910                   'update-changelog args))
2911
2912(defun vc-default-update-changelog (backend files)
2913  "Default implementation of update-changelog.
2914Uses `rcs2log' which only works for RCS and CVS."
2915  ;; FIXME: We (c|sh)ould add support for cvs2cl
2916  (let ((odefault default-directory)
2917	(changelog (find-change-log))
2918	;; Presumably not portable to non-Unixy systems, along with rcs2log:
2919	(tempfile (make-temp-file
2920		   (expand-file-name "vc"
2921				     (or small-temporary-file-directory
2922					 temporary-file-directory))))
2923        (login-name (or user-login-name
2924                        (format "uid%d" (number-to-string (user-uid)))))
2925	(full-name (or add-log-full-name
2926		       (user-full-name)
2927		       (user-login-name)
2928		       (format "uid%d" (number-to-string (user-uid)))))
2929	(mailing-address (or add-log-mailing-address
2930			     user-mail-address)))
2931    (find-file-other-window changelog)
2932    (barf-if-buffer-read-only)
2933    (vc-buffer-sync)
2934    (undo-boundary)
2935    (goto-char (point-min))
2936    (push-mark)
2937    (message "Computing change log entries...")
2938    (message "Computing change log entries... %s"
2939	     (unwind-protect
2940		 (progn
2941		   (setq default-directory odefault)
2942		   (if (eq 0 (apply 'call-process
2943                                    (expand-file-name "rcs2log"
2944                                                      exec-directory)
2945                                    nil (list t tempfile) nil
2946                                    "-c" changelog
2947                                    "-u" (concat login-name
2948                                                 "\t" full-name
2949                                                 "\t" mailing-address)
2950                                    (mapcar
2951                                     (lambda (f)
2952                                       (file-relative-name
2953                                        (if (file-name-absolute-p f)
2954                                            f
2955                                          (concat odefault f))))
2956                                     files)))
2957                       "done"
2958		     (pop-to-buffer (get-buffer-create "*vc*"))
2959		     (erase-buffer)
2960		     (insert-file-contents tempfile)
2961		     "failed"))
2962	       (setq default-directory (file-name-directory changelog))
2963	       (delete-file tempfile)))))
2964
2965;; Annotate functionality
2966
2967;; Declare globally instead of additional parameter to
2968;; temp-buffer-show-function (not possible to pass more than one
2969;; parameter).  The use of annotate-ratio is deprecated in favor of
2970;; annotate-mode, which replaces it with the more sensible "span-to
2971;; days", along with autoscaling support.
2972(defvar vc-annotate-ratio nil "Global variable.")
2973
2974;; internal buffer-local variables
2975(defvar vc-annotate-backend nil)
2976(defvar vc-annotate-parent-file nil)
2977(defvar vc-annotate-parent-rev nil)
2978(defvar vc-annotate-parent-display-mode nil)
2979
2980(defconst vc-annotate-font-lock-keywords
2981  ;; The fontification is done by vc-annotate-lines instead of font-lock.
2982  '((vc-annotate-lines)))
2983
2984(define-derived-mode vc-annotate-mode fundamental-mode "Annotate"
2985  "Major mode for output buffers of the `vc-annotate' command.
2986
2987You can use the mode-specific menu to alter the time-span of the used
2988colors.  See variable `vc-annotate-menu-elements' for customizing the
2989menu items."
2990  (set (make-local-variable 'truncate-lines) t)
2991  (set (make-local-variable 'font-lock-defaults)
2992       '(vc-annotate-font-lock-keywords t))
2993  (view-mode 1))
2994
2995(defun vc-annotate-display-default (ratio)
2996  "Display the output of \\[vc-annotate] using the default color range.
2997The color range is given by `vc-annotate-color-map', scaled by RATIO.
2998The current time is used as the offset."
2999  (interactive (progn (kill-local-variable 'vc-annotate-color-map) '(1.0)))
3000  (message "Redisplaying annotation...")
3001  (vc-annotate-display ratio)
3002  (message "Redisplaying annotation...done"))
3003
3004(defun vc-annotate-oldest-in-map (color-map)
3005  "Return the oldest time in the COLOR-MAP."
3006  ;; Since entries should be sorted, we can just use the last one.
3007  (caar (last color-map)))
3008
3009(defun vc-annotate-display-autoscale (&optional full)
3010  "Highlight the output of \\[vc-annotate] using an autoscaled color map.
3011Autoscaling means that the map is scaled from the current time to the
3012oldest annotation in the buffer, or, with prefix argument FULL, to
3013cover the range from the oldest annotation to the newest."
3014  (interactive "P")
3015  (let ((newest 0.0)
3016	(oldest 999999.)		;Any CVS users at the founding of Rome?
3017	(current (vc-annotate-convert-time (current-time)))
3018	date)
3019    (message "Redisplaying annotation...")
3020    ;; Run through this file and find the oldest and newest dates annotated.
3021    (save-excursion
3022      (goto-char (point-min))
3023      (while (setq date (prog1 (vc-call-backend vc-annotate-backend
3024                                                'annotate-time)
3025                          (forward-line 1)))
3026	(if (> date newest)
3027	    (setq newest date))
3028	(if (< date oldest)
3029	    (setq oldest date))))
3030    (vc-annotate-display
3031     (/ (- (if full newest current) oldest)
3032        (vc-annotate-oldest-in-map vc-annotate-color-map))
3033     (if full newest))
3034    (message "Redisplaying annotation...done \(%s\)"
3035	     (if full
3036		 (format "Spanned from %.1f to %.1f days old"
3037			 (- current oldest)
3038			 (- current newest))
3039	       (format "Spanned to %.1f days old" (- current oldest))))))
3040
3041;; Menu -- Using easymenu.el
3042(easy-menu-define vc-annotate-mode-menu vc-annotate-mode-map
3043  "VC Annotate Display Menu"
3044  `("VC-Annotate"
3045    ["By Color Map Range" (unless (null vc-annotate-display-mode)
3046                 (setq vc-annotate-display-mode nil)
3047                 (vc-annotate-display-select))
3048     :style toggle :selected (null vc-annotate-display-mode)]
3049    ,@(let ((oldest-in-map (vc-annotate-oldest-in-map vc-annotate-color-map)))
3050        (mapcar (lambda (element)
3051                  (let ((days (* element oldest-in-map)))
3052                    `[,(format "Span %.1f days" days)
3053                      (vc-annotate-display-select nil ,days)
3054                      :style toggle :selected
3055                      (eql vc-annotate-display-mode ,days) ]))
3056                vc-annotate-menu-elements))
3057    ["Span ..."
3058     (vc-annotate-display-select
3059      nil (float (string-to-number (read-string "Span how many days? "))))]
3060    "--"
3061    ["Span to Oldest"
3062     (unless (eq vc-annotate-display-mode 'scale)
3063       (vc-annotate-display-select nil 'scale))
3064     :style toggle :selected
3065     (eq vc-annotate-display-mode 'scale)]
3066    ["Span Oldest->Newest"
3067     (unless (eq vc-annotate-display-mode 'fullscale)
3068       (vc-annotate-display-select nil 'fullscale))
3069     :style toggle :selected
3070     (eq vc-annotate-display-mode 'fullscale)]
3071    "--"
3072    ["Annotate previous revision" vc-annotate-prev-version]
3073    ["Annotate next revision" vc-annotate-next-version]
3074    ["Annotate revision at line" vc-annotate-revision-at-line]
3075    ["Annotate revision previous to line" vc-annotate-revision-previous-to-line]
3076    ["Annotate latest revision" vc-annotate-workfile-version]
3077    ["Show log of revision at line" vc-annotate-show-log-revision-at-line]
3078    ["Show diff of revision at line" vc-annotate-show-diff-revision-at-line]))
3079
3080(defun vc-annotate-display-select (&optional buffer mode)
3081  "Highlight the output of \\[vc-annotate].
3082By default, the current buffer is highlighted, unless overridden by
3083BUFFER.  `vc-annotate-display-mode' specifies the highlighting mode to
3084use; you may override this using the second optional arg MODE."
3085  (interactive)
3086  (if mode (setq vc-annotate-display-mode mode))
3087  (pop-to-buffer (or buffer (current-buffer)))
3088  (cond ((null vc-annotate-display-mode)
3089         ;; The ratio is global, thus relative to the global color-map.
3090         (kill-local-variable 'vc-annotate-color-map)
3091	 (vc-annotate-display-default (or vc-annotate-ratio 1.0)))
3092        ;; One of the auto-scaling modes
3093	((eq vc-annotate-display-mode 'scale)
3094	 (vc-annotate-display-autoscale))
3095	((eq vc-annotate-display-mode 'fullscale)
3096	 (vc-annotate-display-autoscale t))
3097	((numberp vc-annotate-display-mode) ; A fixed number of days lookback
3098	 (vc-annotate-display-default
3099	  (/ vc-annotate-display-mode
3100             (vc-annotate-oldest-in-map vc-annotate-color-map))))
3101	(t (error "No such display mode: %s"
3102		  vc-annotate-display-mode))))
3103
3104;;;###autoload
3105(defun vc-annotate (file rev &optional display-mode buf)
3106  "Display the edit history of the current file using colors.
3107
3108This command creates a buffer that shows, for each line of the current
3109file, when it was last edited and by whom.  Additionally, colors are
3110used to show the age of each line--blue means oldest, red means
3111youngest, and intermediate colors indicate intermediate ages.  By
3112default, the time scale stretches back one year into the past;
3113everything that is older than that is shown in blue.
3114
3115With a prefix argument, this command asks two questions in the
3116minibuffer.  First, you may enter a version number; then the buffer
3117displays and annotates that version instead of the current version
3118\(type RET in the minibuffer to leave that default unchanged).  Then,
3119you are prompted for the time span in days which the color range
3120should cover.  For example, a time span of 20 days means that changes
3121over the past 20 days are shown in red to blue, according to their
3122age, and everything that is older than that is shown in blue.
3123
3124Customization variables:
3125
3126`vc-annotate-menu-elements' customizes the menu elements of the
3127mode-specific menu. `vc-annotate-color-map' and
3128`vc-annotate-very-old-color' defines the mapping of time to
3129colors. `vc-annotate-background' specifies the background color."
3130  (interactive
3131   (save-current-buffer
3132     (vc-ensure-vc-buffer)
3133     (list buffer-file-name
3134	   (let ((def (vc-workfile-version buffer-file-name)))
3135	     (if (null current-prefix-arg) def
3136	       (read-string
3137		(format "Annotate from version (default %s): " def)
3138		nil nil def)))
3139	   (if (null current-prefix-arg)
3140	       vc-annotate-display-mode
3141	     (float (string-to-number
3142		     (read-string "Annotate span days (default 20): "
3143				  nil nil "20")))))))
3144  (vc-ensure-vc-buffer)
3145  (setq vc-annotate-display-mode display-mode) ;Not sure why.  --Stef
3146  (let* ((temp-buffer-name (format "*Annotate %s (rev %s)*" (buffer-name) rev))
3147         (temp-buffer-show-function 'vc-annotate-display-select)
3148         ;; If BUF is specified, we presume the caller maintains current line,
3149         ;; so we don't need to do it here.  This implementation may give
3150         ;; strange results occasionally in the case of REV != WORKFILE-REV.
3151         (current-line (unless buf (line-number-at-pos))))
3152    (message "Annotating...")
3153    ;; If BUF is specified it tells in which buffer we should put the
3154    ;; annotations.  This is used when switching annotations to another
3155    ;; revision, so we should update the buffer's name.
3156    (if buf (with-current-buffer buf
3157	      (rename-buffer temp-buffer-name t)
3158	      ;; In case it had to be uniquified.
3159	      (setq temp-buffer-name (buffer-name))))
3160    (with-output-to-temp-buffer temp-buffer-name
3161      (vc-call annotate-command file (get-buffer temp-buffer-name) rev)
3162      ;; we must setup the mode first, and then set our local
3163      ;; variables before the show-function is called at the exit of
3164      ;; with-output-to-temp-buffer
3165      (with-current-buffer temp-buffer-name
3166        (if (not (equal major-mode 'vc-annotate-mode))
3167            (vc-annotate-mode))
3168        (set (make-local-variable 'vc-annotate-backend) (vc-backend file))
3169        (set (make-local-variable 'vc-annotate-parent-file) file)
3170        (set (make-local-variable 'vc-annotate-parent-rev) rev)
3171        (set (make-local-variable 'vc-annotate-parent-display-mode)
3172             display-mode)))
3173    (when current-line
3174      (goto-line current-line temp-buffer-name))
3175    (message "Annotating... done")))
3176
3177(defun vc-annotate-prev-version (prefix)
3178  "Visit the annotation of the version previous to this one.
3179
3180With a numeric prefix argument, annotate the version that many
3181versions previous."
3182  (interactive "p")
3183  (vc-annotate-warp-version (- 0 prefix)))
3184
3185(defun vc-annotate-next-version (prefix)
3186  "Visit the annotation of the version after this one.
3187
3188With a numeric prefix argument, annotate the version that many
3189versions after."
3190  (interactive "p")
3191  (vc-annotate-warp-version prefix))
3192
3193(defun vc-annotate-workfile-version ()
3194  "Visit the annotation of the workfile version of this file."
3195  (interactive)
3196  (if (not (equal major-mode 'vc-annotate-mode))
3197      (message "Cannot be invoked outside of a vc annotate buffer")
3198    (let ((warp-rev (vc-workfile-version vc-annotate-parent-file)))
3199      (if (equal warp-rev vc-annotate-parent-rev)
3200	  (message "Already at version %s" warp-rev)
3201	(vc-annotate-warp-version warp-rev)))))
3202
3203(defun vc-annotate-extract-revision-at-line ()
3204  "Extract the revision number of the current line."
3205  ;; This function must be invoked from a buffer in vc-annotate-mode
3206  (vc-call-backend vc-annotate-backend 'annotate-extract-revision-at-line))
3207
3208(defun vc-annotate-revision-at-line ()
3209  "Visit the annotation of the version identified in the current line."
3210  (interactive)
3211  (if (not (equal major-mode 'vc-annotate-mode))
3212      (message "Cannot be invoked outside of a vc annotate buffer")
3213    (let ((rev-at-line (vc-annotate-extract-revision-at-line)))
3214      (if (not rev-at-line)
3215	  (message "Cannot extract revision number from the current line")
3216	(if (equal rev-at-line vc-annotate-parent-rev)
3217	    (message "Already at version %s" rev-at-line)
3218	  (vc-annotate-warp-version rev-at-line))))))
3219
3220(defun vc-annotate-revision-previous-to-line ()
3221  "Visit the annotation of the version before the version at line."
3222  (interactive)
3223  (if (not (equal major-mode 'vc-annotate-mode))
3224      (message "Cannot be invoked outside of a vc annotate buffer")
3225    (let ((rev-at-line (vc-annotate-extract-revision-at-line))
3226	  (prev-rev nil))
3227      (if (not rev-at-line)
3228	  (message "Cannot extract revision number from the current line")
3229	(setq prev-rev
3230	      (vc-call previous-version vc-annotate-parent-file rev-at-line))
3231	(vc-annotate-warp-version prev-rev)))))
3232
3233(defun vc-annotate-show-log-revision-at-line ()
3234  "Visit the log of the version at line."
3235  (interactive)
3236  (if (not (equal major-mode 'vc-annotate-mode))
3237      (message "Cannot be invoked outside of a vc annotate buffer")
3238    (let ((rev-at-line (vc-annotate-extract-revision-at-line)))
3239      (if (not rev-at-line)
3240	  (message "Cannot extract revision number from the current line")
3241	(vc-print-log rev-at-line)))))
3242
3243(defun vc-annotate-show-diff-revision-at-line ()
3244  "Visit the diff of the version at line from its previous version."
3245  (interactive)
3246  (if (not (equal major-mode 'vc-annotate-mode))
3247      (message "Cannot be invoked outside of a vc annotate buffer")
3248    (let ((rev-at-line (vc-annotate-extract-revision-at-line))
3249	  (prev-rev nil))
3250      (if (not rev-at-line)
3251	  (message "Cannot extract revision number from the current line")
3252	(setq prev-rev
3253	      (vc-call previous-version vc-annotate-parent-file rev-at-line))
3254	(if (not prev-rev)
3255	    (message "Cannot diff from any version prior to %s" rev-at-line)
3256	  (save-window-excursion
3257	    (vc-version-diff vc-annotate-parent-file prev-rev rev-at-line))
3258	  (switch-to-buffer "*vc-diff*"))))))
3259
3260(defun vc-annotate-warp-version (revspec)
3261  "Annotate the version described by REVSPEC.
3262
3263If REVSPEC is a positive integer, warp that many versions
3264forward, if possible, otherwise echo a warning message.  If
3265REVSPEC is a negative integer, warp that many versions backward,
3266if possible, otherwise echo a warning message.  If REVSPEC is a
3267string, then it describes a revision number, so warp to that
3268revision."
3269  (if (not (equal major-mode 'vc-annotate-mode))
3270      (message "Cannot be invoked outside of a vc annotate buffer")
3271    (let* ((buf (current-buffer))
3272	   (oldline (line-number-at-pos))
3273	   (revspeccopy revspec)
3274	   (newrev nil))
3275      (cond
3276       ((and (integerp revspec) (> revspec 0))
3277	(setq newrev vc-annotate-parent-rev)
3278	(while (and (> revspec 0) newrev)
3279	       (setq newrev (vc-call next-version
3280				     vc-annotate-parent-file newrev))
3281	       (setq revspec (1- revspec)))
3282	(if (not newrev)
3283	    (message "Cannot increment %d versions from version %s"
3284		     revspeccopy vc-annotate-parent-rev)))
3285       ((and (integerp revspec) (< revspec 0))
3286	(setq newrev vc-annotate-parent-rev)
3287	(while (and (< revspec 0) newrev)
3288	       (setq newrev (vc-call previous-version
3289				     vc-annotate-parent-file newrev))
3290	       (setq revspec (1+ revspec)))
3291	(if (not newrev)
3292	    (message "Cannot decrement %d versions from version %s"
3293		     (- 0 revspeccopy) vc-annotate-parent-rev)))
3294       ((stringp revspec) (setq newrev revspec))
3295       (t (error "Invalid argument to vc-annotate-warp-version")))
3296      (when newrev
3297	(vc-annotate vc-annotate-parent-file newrev
3298                     vc-annotate-parent-display-mode
3299                     buf)
3300	(goto-line (min oldline (progn (goto-char (point-max))
3301				       (previous-line)
3302				       (line-number-at-pos))) buf)))))
3303
3304(defun vc-annotate-compcar (threshold a-list)
3305  "Test successive cons cells of A-LIST against THRESHOLD.
3306Return the first cons cell with a car that is not less than THRESHOLD,
3307nil if no such cell exists."
3308 (let ((i 1)
3309       (tmp-cons (car a-list)))
3310   (while (and tmp-cons (< (car tmp-cons) threshold))
3311     (setq tmp-cons (car (nthcdr i a-list)))
3312     (setq i (+ i 1)))
3313   tmp-cons))				; Return the appropriate value
3314
3315(defun vc-annotate-convert-time (time)
3316  "Convert a time value to a floating-point number of days.
3317The argument TIME is a list as returned by `current-time' or
3318`encode-time', only the first two elements of that list are considered."
3319  (/ (+ (* (float (car time)) (lsh 1 16)) (cadr time)) 24 3600))
3320
3321(defun vc-annotate-difference (&optional offset)
3322  "Return the time span in days to the next annotation.
3323This calls the backend function annotate-time, and returns the
3324difference in days between the time returned and the current time,
3325or OFFSET if present."
3326   (let ((next-time (vc-call-backend vc-annotate-backend 'annotate-time)))
3327     (if next-time
3328	 (- (or offset
3329		(vc-call-backend vc-annotate-backend 'annotate-current-time))
3330	    next-time))))
3331
3332(defun vc-default-annotate-current-time (backend)
3333  "Return the current time, encoded as fractional days."
3334  (vc-annotate-convert-time (current-time)))
3335
3336(defvar vc-annotate-offset nil)
3337
3338(defun vc-annotate-display (ratio &optional offset)
3339  "Highlight `vc-annotate' output in the current buffer.
3340RATIO, is the expansion that should be applied to `vc-annotate-color-map'.
3341The annotations are relative to the current time, unless overridden by OFFSET."
3342  (if (/= ratio 1.0)
3343      (set (make-local-variable 'vc-annotate-color-map)
3344           (mapcar (lambda (elem) (cons (* (car elem) ratio) (cdr elem)))
3345                   vc-annotate-color-map)))
3346  (set (make-local-variable 'vc-annotate-offset) offset)
3347  (font-lock-mode 1))
3348
3349(defun vc-annotate-lines (limit)
3350  (let (difference)
3351    (while (and (< (point) limit)
3352		(setq difference (vc-annotate-difference vc-annotate-offset)))
3353      (let* ((color (or (vc-annotate-compcar difference vc-annotate-color-map)
3354			(cons nil vc-annotate-very-old-color)))
3355	     ;; substring from index 1 to remove any leading `#' in the name
3356	     (face-name (concat "vc-annotate-face-"
3357				(if (string-equal
3358				     (substring (cdr color) 0 1) "#")
3359				    (substring (cdr color) 1)
3360				  (cdr color))))
3361	     ;; Make the face if not done.
3362	     (face (or (intern-soft face-name)
3363		       (let ((tmp-face (make-face (intern face-name))))
3364			 (set-face-foreground tmp-face (cdr color))
3365			 (if vc-annotate-background
3366			     (set-face-background tmp-face
3367						  vc-annotate-background))
3368			 tmp-face)))	; Return the face
3369	     (point (point)))
3370	(forward-line 1)
3371	(put-text-property point (point) 'face face)))
3372    ;; Pretend to font-lock there were no matches.
3373    nil))
3374
3375;; Collect back-end-dependent stuff here
3376
3377(defalias 'vc-default-logentry-check 'ignore)
3378
3379(defun vc-check-headers ()
3380  "Check if the current file has any headers in it."
3381  (interactive)
3382  (vc-call-backend (vc-backend buffer-file-name) 'check-headers))
3383
3384(defun vc-default-check-headers (backend)
3385  "Default implementation of check-headers; always returns nil."
3386  nil)
3387
3388;; Back-end-dependent stuff ends here.
3389
3390;; Set up key bindings for use while editing log messages
3391
3392(defun vc-log-edit (file)
3393  "Set up `log-edit' for use with VC on FILE."
3394  (setq default-directory
3395	(if file (file-name-directory file)
3396	  (with-current-buffer vc-parent-buffer default-directory)))
3397  (log-edit 'vc-finish-logentry nil
3398	    (if file `(lambda () ',(list (file-name-nondirectory file)))
3399	      ;; If FILE is nil, we were called from vc-dired.
3400	      (lambda ()
3401		(with-current-buffer vc-parent-buffer
3402		  (dired-get-marked-files t)))))
3403  (set (make-local-variable 'vc-log-file) file)
3404  (make-local-variable 'vc-log-version)
3405  (set-buffer-modified-p nil)
3406  (setq buffer-file-name nil))
3407
3408;; These things should probably be generally available
3409
3410(defun vc-file-tree-walk (dirname func &rest args)
3411  "Walk recursively through DIRNAME.
3412Invoke FUNC f ARGS on each VC-managed file f underneath it."
3413  (vc-file-tree-walk-internal (expand-file-name dirname) func args)
3414  (message "Traversing directory %s...done" dirname))
3415
3416(defun vc-file-tree-walk-internal (file func args)
3417  (if (not (file-directory-p file))
3418      (if (vc-backend file) (apply func file args))
3419    (message "Traversing directory %s..." (abbreviate-file-name file))
3420    (let ((dir (file-name-as-directory file)))
3421      (mapcar
3422       (lambda (f) (or
3423		    (string-equal f ".")
3424		    (string-equal f "..")
3425		    (member f vc-directory-exclusion-list)
3426		    (let ((dirf (expand-file-name f dir)))
3427		      (or
3428		       (file-symlink-p dirf);; Avoid possible loops
3429		       (vc-file-tree-walk-internal dirf func args)))))
3430       (directory-files dir)))))
3431
3432(provide 'vc)
3433
3434;; DEVELOPER'S NOTES ON CONCURRENCY PROBLEMS IN THIS CODE
3435;;
3436;; These may be useful to anyone who has to debug or extend the package.
3437;; (Note that this information corresponds to versions 5.x. Some of it
3438;; might have been invalidated by the additions to support branching
3439;; and RCS keyword lookup. AS, 1995/03/24)
3440;;
3441;; A fundamental problem in VC is that there are time windows between
3442;; vc-next-action's computations of the file's version-control state and
3443;; the actions that change it.  This is a window open to lossage in a
3444;; multi-user environment; someone else could nip in and change the state
3445;; of the master during it.
3446;;
3447;; The performance problem is that rlog/prs calls are very expensive; we want
3448;; to avoid them as much as possible.
3449;;
3450;; ANALYSIS:
3451;;
3452;; The performance problem, it turns out, simplifies in practice to the
3453;; problem of making vc-state fast.  The two other functions that call
3454;; prs/rlog will not be so commonly used that the slowdown is a problem; one
3455;; makes snapshots, the other deletes the calling user's last change in the
3456;; master.
3457;;
3458;; The race condition implies that we have to either (a) lock the master
3459;; during the entire execution of vc-next-action, or (b) detect and
3460;; recover from errors resulting from dispatch on an out-of-date state.
3461;;
3462;; Alternative (a) appears to be infeasible.  The problem is that we can't
3463;; guarantee that the lock will ever be removed.  Suppose a user starts a
3464;; checkin, the change message buffer pops up, and the user, having wandered
3465;; off to do something else, simply forgets about it?
3466;;
3467;; Alternative (b), on the other hand, works well with a cheap way to speed up
3468;; vc-state.  Usually, if a file is registered, we can read its locked/
3469;; unlocked state and its current owner from its permissions.
3470;;
3471;; This shortcut will fail if someone has manually changed the workfile's
3472;; permissions; also if developers are munging the workfile in several
3473;; directories, with symlinks to a master (in this latter case, the
3474;; permissions shortcut will fail to detect a lock asserted from another
3475;; directory).
3476;;
3477;; Note that these cases correspond exactly to the errors which could happen
3478;; because of a competing checkin/checkout race in between two instances of
3479;; vc-next-action.
3480;;
3481;; For VC's purposes, a workfile/master pair may have the following states:
3482;;
3483;; A. Unregistered.  There is a workfile, there is no master.
3484;;
3485;; B. Registered and not locked by anyone.
3486;;
3487;; C. Locked by calling user and unchanged.
3488;;
3489;; D. Locked by the calling user and changed.
3490;;
3491;; E. Locked by someone other than the calling user.
3492;;
3493;; This makes for 25 states and 20 error conditions.  Here's the matrix:
3494;;
3495;; VC's idea of state
3496;;  |
3497;;  V  Actual state   RCS action              SCCS action          Effect
3498;;    A  B  C  D  E
3499;;  A .  1  2  3  4   ci -u -t-          admin -fb -i<file>      initial admin
3500;;  B 5  .  6  7  8   co -l              get -e                  checkout
3501;;  C 9  10 .  11 12  co -u              unget; get              revert
3502;;  D 13 14 15 .  16  ci -u -m<comment>  delta -y<comment>; get  checkin
3503;;  E 17 18 19 20 .   rcs -u -M -l       unget -n ; get -g       steal lock
3504;;
3505;; All commands take the master file name as a last argument (not shown).
3506;;
3507;; In the discussion below, a "self-race" is a pathological situation in
3508;; which VC operations are being attempted simultaneously by two or more
3509;; Emacsen running under the same username.
3510;;
3511;; The vc-next-action code has the following windows:
3512;;
3513;; Window P:
3514;;    Between the check for existence of a master file and the call to
3515;; admin/checkin in vc-buffer-admin (apparent state A).  This window may
3516;; never close if the initial-comment feature is on.
3517;;
3518;; Window Q:
3519;;    Between the call to vc-workfile-unchanged-p in and the immediately
3520;; following revert (apparent state C).
3521;;
3522;; Window R:
3523;;    Between the call to vc-workfile-unchanged-p in and the following
3524;; checkin (apparent state D).  This window may never close.
3525;;
3526;; Window S:
3527;;    Between the unlock and the immediately following checkout during a
3528;; revert operation (apparent state C).  Included in window Q.
3529;;
3530;; Window T:
3531;;    Between vc-state and the following checkout (apparent state B).
3532;;
3533;; Window U:
3534;;    Between vc-state and the following revert (apparent state C).
3535;; Includes windows Q and S.
3536;;
3537;; Window V:
3538;;    Between vc-state and the following checkin (apparent state
3539;; D).  This window may never be closed if the user fails to complete the
3540;; checkin message.  Includes window R.
3541;;
3542;; Window W:
3543;;    Between vc-state and the following steal-lock (apparent
3544;; state E).  This window may never close if the user fails to complete
3545;; the steal-lock message.  Includes window X.
3546;;
3547;; Window X:
3548;;    Between the unlock and the immediately following re-lock during a
3549;; steal-lock operation (apparent state E).  This window may never close
3550;; if the user fails to complete the steal-lock message.
3551;;
3552;; Errors:
3553;;
3554;; Apparent state A ---
3555;;
3556;; 1. File looked unregistered but is actually registered and not locked.
3557;;
3558;;    Potential cause: someone else's admin during window P, with
3559;; caller's admin happening before their checkout.
3560;;
3561;;    RCS: Prior to version 5.6.4, ci fails with message
3562;;         "no lock set by <user>".  From 5.6.4 onwards, VC uses the new
3563;;         ci -i option and the message is "<file>,v: already exists".
3564;;    SCCS: admin will fail with error (ad19).
3565;;
3566;;    We can let these errors be passed up to the user.
3567;;
3568;; 2. File looked unregistered but is actually locked by caller, unchanged.
3569;;
3570;;    Potential cause: self-race during window P.
3571;;
3572;;    RCS: Prior to version 5.6.4, reverts the file to the last saved
3573;;         version and unlocks it.  From 5.6.4 onwards, VC uses the new
3574;;         ci -i option, failing with message "<file>,v: already exists".
3575;;    SCCS: will fail with error (ad19).
3576;;
3577;;    Either of these consequences is acceptable.
3578;;
3579;; 3. File looked unregistered but is actually locked by caller, changed.
3580;;
3581;;    Potential cause: self-race during window P.
3582;;
3583;;    RCS: Prior to version 5.6.4, VC registers the caller's workfile as
3584;;         a delta with a null change comment (the -t- switch will be
3585;;         ignored). From 5.6.4 onwards, VC uses the new ci -i option,
3586;;         failing with message "<file>,v: already exists".
3587;;    SCCS: will fail with error (ad19).
3588;;
3589;; 4. File looked unregistered but is locked by someone else.
3590;;;
3591;;    Potential cause: someone else's admin during window P, with
3592;; caller's admin happening *after* their checkout.
3593;;
3594;;    RCS: Prior to version 5.6.4, ci fails with a
3595;;         "no lock set by <user>" message.  From 5.6.4 onwards,
3596;;         VC uses the new ci -i option, failing with message
3597;;         "<file>,v: already exists".
3598;;    SCCS: will fail with error (ad19).
3599;;
3600;;    We can let these errors be passed up to the user.
3601;;
3602;; Apparent state B ---
3603;;
3604;; 5. File looked registered and not locked, but is actually unregistered.
3605;;
3606;;    Potential cause: master file got nuked during window P.
3607;;
3608;;    RCS: will fail with "RCS/<file>: No such file or directory"
3609;;    SCCS: will fail with error ut4.
3610;;
3611;;    We can let these errors be passed up to the user.
3612;;
3613;; 6. File looked registered and not locked, but is actually locked by the
3614;; calling user and unchanged.
3615;;
3616;;    Potential cause: self-race during window T.
3617;;
3618;;    RCS: in the same directory as the previous workfile, co -l will fail
3619;; with "co error: writable foo exists; checkout aborted".  In any other
3620;; directory, checkout will succeed.
3621;;    SCCS: will fail with ge17.
3622;;
3623;;    Either of these consequences is acceptable.
3624;;
3625;; 7. File looked registered and not locked, but is actually locked by the
3626;; calling user and changed.
3627;;
3628;;    As case 6.
3629;;
3630;; 8. File looked registered and not locked, but is actually locked by another
3631;; user.
3632;;
3633;;    Potential cause: someone else checks it out during window T.
3634;;
3635;;    RCS: co error: revision 1.3 already locked by <user>
3636;;    SCCS: fails with ge4 (in directory) or ut7 (outside it).
3637;;
3638;;    We can let these errors be passed up to the user.
3639;;
3640;; Apparent state C ---
3641;;
3642;; 9. File looks locked by calling user and unchanged, but is unregistered.
3643;;
3644;;    As case 5.
3645;;
3646;; 10. File looks locked by calling user and unchanged, but is actually not
3647;; locked.
3648;;
3649;;    Potential cause: a self-race in window U, or by the revert's
3650;; landing during window X of some other user's steal-lock or window S
3651;; of another user's revert.
3652;;
3653;;    RCS: succeeds, refreshing the file from the identical version in
3654;; the master.
3655;;    SCCS: fails with error ut4 (p file nonexistent).
3656;;
3657;;    Either of these consequences is acceptable.
3658;;
3659;; 11. File is locked by calling user.  It looks unchanged, but is actually
3660;; changed.
3661;;
3662;;    Potential cause: the file would have to be touched by a self-race
3663;; during window Q.
3664;;
3665;;    The revert will succeed, removing whatever changes came with
3666;; the touch.  It is theoretically possible that work could be lost.
3667;;
3668;; 12. File looks like it's locked by the calling user and unchanged, but
3669;; it's actually locked by someone else.
3670;;
3671;;    Potential cause: a steal-lock in window V.
3672;;
3673;;    RCS: co error: revision <rev> locked by <user>; use co -r or rcs -u
3674;;    SCCS: fails with error un2
3675;;
3676;;    We can pass these errors up to the user.
3677;;
3678;; Apparent state D ---
3679;;
3680;; 13. File looks like it's locked by the calling user and changed, but it's
3681;; actually unregistered.
3682;;
3683;;    Potential cause: master file got nuked during window P.
3684;;
3685;;    RCS: Prior to version 5.6.4, checks in the user's version as an
3686;;         initial delta.  From 5.6.4 onwards, VC uses the new ci -j
3687;;         option, failing with message "no such file or directory".
3688;;    SCCS: will fail with error ut4.
3689;;
3690;;    This case is kind of nasty.  Under RCS prior to version 5.6.4,
3691;; VC may fail to detect the loss of previous version information.
3692;;
3693;; 14. File looks like it's locked by the calling user and changed, but it's
3694;; actually unlocked.
3695;;
3696;;    Potential cause: self-race in window V, or the checkin happening
3697;; during the window X of someone else's steal-lock or window S of
3698;; someone else's revert.
3699;;
3700;;    RCS: ci will fail with "no lock set by <user>".
3701;;    SCCS: delta will fail with error ut4.
3702;;
3703;; 15. File looks like it's locked by the calling user and changed, but it's
3704;; actually locked by the calling user and unchanged.
3705;;
3706;;    Potential cause: another self-race --- a whole checkin/checkout
3707;; sequence by the calling user would have to land in window R.
3708;;
3709;;    SCCS: checks in a redundant delta and leaves the file unlocked as usual.
3710;;    RCS: reverts to the file state as of the second user's checkin, leaving
3711;; the file unlocked.
3712;;
3713;;    It is theoretically possible that work could be lost under RCS.
3714;;
3715;; 16. File looks like it's locked by the calling user and changed, but it's
3716;; actually locked by a different user.
3717;;
3718;;    RCS: ci error: no lock set by <user>
3719;;    SCCS: unget will fail with error un2
3720;;
3721;;    We can pass these errors up to the user.
3722;;
3723;; Apparent state E ---
3724;;
3725;; 17. File looks like it's locked by some other user, but it's actually
3726;; unregistered.
3727;;
3728;;    As case 13.
3729;;
3730;; 18. File looks like it's locked by some other user, but it's actually
3731;; unlocked.
3732;;
3733;;    Potential cause: someone released a lock during window W.
3734;;
3735;;    RCS: The calling user will get the lock on the file.
3736;;    SCCS: unget -n will fail with cm4.
3737;;
3738;;    Either of these consequences will be OK.
3739;;
3740;; 19. File looks like it's locked by some other user, but it's actually
3741;; locked by the calling user and unchanged.
3742;;
3743;;    Potential cause: the other user relinquishing a lock followed by
3744;; a self-race, both in window W.
3745;;
3746;;     Under both RCS and SCCS, both unlock and lock will succeed, making
3747;; the sequence a no-op.
3748;;
3749;; 20. File looks like it's locked by some other user, but it's actually
3750;; locked by the calling user and changed.
3751;;
3752;;     As case 19.
3753;;
3754;; PROBLEM CASES:
3755;;
3756;;    In order of decreasing severity:
3757;;
3758;;    Cases 11 and 15 are the only ones that potentially lose work.
3759;; They would require a self-race for this to happen.
3760;;
3761;;    Case 13 in RCS loses information about previous deltas, retaining
3762;; only the information in the current workfile.  This can only happen
3763;; if the master file gets nuked in window P.
3764;;
3765;;    Case 3 in RCS and case 15 under SCCS insert a redundant delta with
3766;; no change comment in the master.  This would require a self-race in
3767;; window P or R respectively.
3768;;
3769;;    Cases 2, 10, 19 and 20 do extra work, but make no changes.
3770;;
3771;;    Unfortunately, it appears to me that no recovery is possible in these
3772;; cases.  They don't yield error messages, so there's no way to tell that
3773;; a race condition has occurred.
3774;;
3775;;    All other cases don't change either the workfile or the master, and
3776;; trigger command errors which the user will see.
3777;;
3778;;    Thus, there is no explicit recovery code.
3779
3780;; arch-tag: ca82c1de-3091-4e26-af92-460abc6213a6
3781;;; vc.el ends here
3782