Initial Commit
[packages] / xemacs-packages / vc-cc / vc-cc.el
1 ;;; vc-cc.el --- ClearCase version of vc.el
2
3 ;; Copyright (C) 1992, 1993, 1994 Free Software Foundation, Inc.
4 ;; Copyright (C) 1995 Tinker Systems and INS Engineering Corp.
5
6 ;; Author: Eric S. Raymond <esr@snark.thyrsus.com>
7 ;; Maintainer: ttn@netcom.com
8 ;; Version: 5.6
9
10 ;; This file is part of XEmacs.
11
12 ;; XEmacs is free software; you can redistribute it and/or modify it
13 ;; under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; XEmacs is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with XEmacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Synched up with: It's not clear at this point.
28 ;;; mly synched this with FSF at version 5.4.  Stig did a whole lot
29 ;;; of stuff to it since then, and so has the FSF.
30
31 ;;; ################## NOTE:
32
33 ;;; ################## This is NOT the standard vc.el, and it
34 ;;; conflicts with vc.el.  If you want to use this, you need to
35 ;;; explicitly load it using `M-x load-library vc-cc', *BEFORE* doing
36 ;;; anything that loads vc.el. (It might work if loaded after vc.el,
37 ;;; but we make no guarantees.) You can ensure this by putting a line
38 ;;; like this in your init file:
39
40 ;;; (load-library "vc-cc")
41
42 ;;; If you want to be really cool, merge the ClearCase changes in this
43 ;;; file into vc.el.
44
45
46 ;;; Commentary:
47
48 ;; This mode is fully documented in the Emacs user's manual.
49 ;;
50 ;; This was designed and implemented by Eric Raymond <esr@snark.thyrsus.com>.
51 ;; Paul Eggert <eggert@twinsun.com>, Sebastian Kremer <sk@thp.uni-koeln.de>,
52 ;; and Richard Stallman contributed valuable criticism, support, and testing.
53 ;; CVS support was added by Per Cederqvist <ceder@lysator.liu.se>
54 ;; in Jan-Feb 1994.
55 ;;
56 ;; XEmacs fixes, CVS fixes, and general improvements
57 ;; by Jonathan Stigelman <Stig@hackvan.com>
58 ;;
59 ;; Merged ClearCase features from ClearCase extensions version: 2.2.3 and
60 ;; added highlighting and menubar access to vc-dired-mode by Chris Felaco
61 ;; <felaco@iatcmail.ed.ray.com>.
62 ;;
63 ;; Supported version-control systems presently include SCCS, RCS, and CVS.
64 ;; The RCS lock-stealing code doesn't work right unless you use RCS 5.6.2
65 ;; or newer.  Currently (January 1994) that is only a beta test release.
66 ;; Even initial checkins will fail if your RCS version is so old that ci
67 ;; doesn't understand -t-; this has been known to happen to people running
68 ;; NExTSTEP 3.0.
69 ;;
70 ;; The RCS code assumes strict locking.  You can support the RCS -x option
71 ;; by adding pairs to the vc-master-templates list.
72 ;;
73 ;; Proper function of the SCCS diff commands requires the shellscript vcdiff
74 ;; to be installed somewhere on Emacs's path for executables.
75 ;;
76 ;; If your site uses the ChangeLog convention supported by Emacs, the
77 ;; function vc-comment-to-change-log should prove a useful checkin hook.
78 ;;
79 ;; This code depends on call-process passing back the subprocess exit
80 ;; status.  Thus, you need Emacs 18.58 or later to run it.  For the
81 ;; vc-directory command to work properly as documented, you need 19.
82 ;; You also need Emacs 19's ring.el.
83 ;;
84 ;; The vc code maintains some internal state in order to reduce expensive
85 ;; version-control operations to a minimum.  Some names are only computed
86 ;; once.  If you perform version control operations with RCS/SCCS/CVS while
87 ;; vc's back is turned, or move/rename master files while vc is running,
88 ;; vc may get seriously confused.  Don't do these things!
89 ;;
90 ;; Developer's notes on some concurrency issues are included at the end of
91 ;; the file.
92
93 ;;; Code:
94
95 (require 'vc-cc-hooks)
96 (require 'ring)
97 (eval-when-compile (require 'dired))    ; for dired-map-over-marks macro
98
99 (put 'vc-backend-dispatch 'lisp-indent-hook 0)
100 (require 'comint)
101 (require 'tq) ;; For ClearCase support
102
103 (defconst cc-vc-version "2.2.3")
104 (defconst cc-vc-maintainer-address "bug-cc-vc@bloom-beacon.mit.edu")
105
106 (defun cc-vc-submit-bug-report ()
107    "Submit via mail a bug report on ClearCase VC"
108    (interactive)
109    (require 'reporter)
110    (and (y-or-n-p "Do you really want to submit a report on CC-VC? ")
111         (reporter-submit-bug-report
112           cc-vc-maintainer-address
113           (concat "vc.el " cc-vc-version)
114           '(vc-diff-on-checkin vc-keep-workfiles vc-default-back-end
115                                vc-master-templates))))
116
117 (defvar vc-alternate-lsvtree nil
118   "*Use an alternate external program instead of xlsvtree")
119
120 (defvar vc-diff-on-checkin nil
121   "*Display diff on checkin to help you compose the checkin comment.")
122
123 (if (not (assoc 'vc-parent-buffer minor-mode-alist))
124     (setq minor-mode-alist
125           (cons '(vc-parent-buffer vc-parent-buffer-name)
126                 minor-mode-alist)))
127
128 ;; General customization
129
130 (defvar vc-default-back-end nil
131   "*Back-end actually used by this interface; may be SCCS or RCS.
132 The value is only computed when needed to avoid an expensive search.")
133 (defvar vc-suppress-confirm nil
134   "*If non-nil, treat user as expert; suppress yes-no prompts on some things.")
135 (defvar vc-keep-workfiles t
136   "*If non-nil, don't delete working files after registering changes.
137 If the back-end is CVS, workfiles are always kept, regardless of the
138 value of this flag.")
139 (defvar vc-initial-comment nil
140   "*Prompt for initial comment when a file is registered.")
141 (defvar vc-command-messages nil
142   "*Display run messages from back-end commands.")
143 (defvar vc-mistrust-permissions 'file-symlink-p
144   "*Don't assume that permissions and ownership track version-control status.")
145 (defvar vc-checkin-switches nil
146   "*Extra switches passed to the checkin program by \\[vc-checkin].")
147 (defvar vc-default-comment "[no seeded comment]"
148   "*Default comment for when no checkout comment is available, or
149 for those version control systems which don't support checkout comments.")
150 (defvar vc-checkin-on-register nil
151   "*If t, file will be checked-in when first registered.
152 This only applies to version control systems that by default leave files
153 checked-out when first registered.")
154 (defvar vc-suppress-checkout-comments nil
155   "*Suppress prompts for checkout comments for those version control
156 systems which use them.")
157 (defvar vc-checkout-switches nil
158   "*Extra switches passed to the checkout program by \\[vc-checkout].")
159 (defvar vc-directory-exclusion-list '("SCCS" "RCS" "lost+found")
160   "*Directory names ignored by functions that recursively walk file trees.")
161
162 (defvar vc-dired-highlight t
163   "*If non-nil, highlight registered and reserved files in vc-dired buffers.")
164
165 (defvar vc-checkout-dir-on-register 'ask
166   "*If t, automatically checkout the directory (if needed) when registering files.
167 If nil, don't checkout the directory and cancel the registration.
168 If `ask', prompt before checking out the directory.
169
170 This only applies to version control systems with versioned directories (namely
171 ClearCase.")
172
173 (defconst vc-maximum-comment-ring-size 32
174   "Maximum number of saved comments in the comment ring.")
175
176 ;;; XEmacs - This is dumped into loaddefs.el already.
177 ;(defvar diff-switches "-c"
178 ;  "*A string or list of strings specifying switches to be passed to diff.")
179
180 ;;;dont ###autoload, it conflicts with vc.el
181 (defvar vc-checkin-hook nil
182   "*List of functions called after a checkin is done.  See `run-hooks'.")
183
184 ;;;dont ###autoload, it conflicts with vc.el
185 (defvar vc-before-checkin-hook nil
186   "*List of functions called before a checkin is done.  See `run-hooks'.")
187
188 (defvar vc-make-buffer-writable-hook nil
189   "*List of functions called when a buffer is made writable.  See `run-hooks.'
190 This hook is only used when the version control system is CVS.  It
191 might be useful for sites who uses locking with CVS, or who uses link
192 farms to gold trees.")
193
194 ;; Header-insertion hair
195
196 (defvar vc-header-alist
197   '((SCCS "\%W\%") (RCS "\$Id\$") (CVS "\$Id\$"))
198   "*Header keywords to be inserted when `vc-insert-headers' is executed.")
199 (defvar vc-static-header-alist
200   '(("\\.c$" .
201      "\n#ifndef lint\nstatic char vcid[] = \"\%s\";\n#endif /* lint */\n"))
202   "*Associate static header string templates with file types.  A \%s in the
203 template is replaced with the first string associated with the file's
204 version-control type in `vc-header-alist'.")
205
206 (defvar vc-comment-alist
207   '((nroff-mode ".\\\"" ""))
208   "*Special comment delimiters to be used in generating vc headers only.
209 Add an entry in this list if you need to override the normal comment-start
210 and comment-end variables.  This will only be necessary if the mode language
211 is sensitive to blank lines.")
212
213 ;; Default is to be extra careful for super-user.
214 (defvar vc-checkout-carefully (= (user-uid) 0) ; #### - this prevents preloading!
215   "*Non-nil means be extra-careful in checkout.
216 Verify that the file really is not locked
217 and that its contents match what the master file says.")
218
219 ;; Variables the user doesn't need to know about.
220 (defvar vc-log-entry-mode nil)
221 (defvar vc-log-operation nil)
222 (defvar vc-log-after-operation-hook nil)
223 (defvar vc-log-writable nil)
224 (defvar vc-checkout-writable-buffer-hook 'vc-checkout-writable-buffer)
225 ;; In a log entry buffer, this is a local variable
226 ;; that points to the buffer for which it was made
227 ;; (either a file, or a VC dired buffer).
228 (defvar vc-parent-buffer nil)
229 (defvar vc-parent-buffer-name nil)
230
231 (defvar vc-log-file)
232 (defvar vc-log-version)
233
234 (defconst vc-name-assoc-file "VC-names")
235
236 (defvar vc-comment-ring nil)
237 (defvar vc-comment-ring-index nil)
238 (defvar vc-last-comment-match nil)
239 (defvar vc-window-config nil)
240
241 (defvar vc-cleartool-path
242   "/usr/atria/bin/cleartool"
243   "Path to ClearCase cleartool")
244
245 (defvar vc-cleardiff-command nil
246   "*Name of ClearCase differencing tool; if nil, use cleardiff as default.
247 If not nil, the command specified is expected to handle one or two
248 filename arguments just as cleardiff would.")
249
250 ;; File property caching
251
252 (defun vc-clear-context ()
253   "Clear all cached file properties and the comment ring."
254   (interactive)
255   (fillarray vc-file-prop-obarray nil)
256   ;; Note: there is potential for minor lossage here if there is an open
257   ;; log buffer with a nonzero local value of vc-comment-ring-index.
258   (setq vc-comment-ring nil))
259
260 ;; Random helper functions
261
262 (defun vc-registration-error (file)
263   (if file
264       (error "File %s is not under version control" file)
265     (error "Buffer %s is not associated with a file" (buffer-name))))
266
267 (defvar vc-binary-assoc nil)
268
269 (defun vc-find-binary (name)
270   "Look for a command anywhere on the subprocess-command search path."
271   (or (cdr (assoc name vc-binary-assoc))
272       ;; XEmacs - use locate-file
273       (let ((full (locate-file name exec-path nil 1)))
274         (if full
275             (setq vc-binary-assoc (cons (cons name full) vc-binary-assoc)))
276         full)))
277
278 (defun vc-do-command (okstatus command file last &rest flags)
279   "Execute a version-control command, notifying user and checking for errors.
280 The command is successful if its exit status does not exceed OKSTATUS.
281 Output from COMMAND goes to buffer *vc*.  The last argument of the command is
282 the master name of FILE if LAST is 'MASTER, or the workfile of FILE if LAST is
283 'WORKFILE; this is appended to an optional list of FLAGS."
284   (setq file (expand-file-name file))
285   (let ((camefrom (current-buffer))
286         (pwd (file-name-directory (expand-file-name file)))
287         (squeezed nil)
288         (vc-file (and file (vc-name file)))
289         status)
290 ;;; #### - don't know why this code was here...to beautify the echo message?
291 ;;;        the version of code below doesn't break default-directory, but it
292 ;;;        still might mess up CVS and RCS because they like to operate on
293 ;;;        files in the current directory. --Stig
294 ;;;
295 ;;;     (if (string-match (concat "^" (regexp-quote pwd)) file)
296 ;;;         (setq file (substring file (match-end 0)))
297 ;;;       (setq pwd (file-name-directory file)))
298     (if vc-command-messages
299         (message "Running %s on %s..." command file))
300     (set-buffer (get-buffer-create "*vc*"))
301     (setq default-directory pwd
302           file (file-name-nondirectory file))
303
304     (set (make-local-variable 'vc-parent-buffer) camefrom)
305     (set (make-local-variable 'vc-parent-buffer-name)
306          (concat " from " (buffer-name camefrom)))
307
308     (erase-buffer)
309
310     (mapcar
311      (function (lambda (s) (and s (setq squeezed (append squeezed (list s))))))
312      flags)
313     (if (and vc-file (eq last 'MASTER))
314         (setq squeezed (append squeezed (list vc-file))))
315     (if (eq last 'WORKFILE)
316         (setq squeezed (append squeezed (list file))))
317     (let ((exec-path (if vc-path (append vc-path exec-path) exec-path))
318           ;; Add vc-path to PATH for the execution of this command.
319           (process-environment (copy-sequence process-environment)))
320       (setenv "PATH" (mapconcat 'identity exec-path ":"))
321       (setq status (apply 'call-process command nil t nil squeezed)))
322     (goto-char (point-max))
323     (set-buffer-modified-p nil)         ; XEmacs - fsf uses `not-modified'
324     (forward-line -1)
325     (if (or (not (integerp status)) (< okstatus status))
326         (progn
327           (pop-to-buffer "*vc*")
328           (goto-char (point-min))
329           (shrink-window-if-larger-than-buffer)
330           (error "Running %s...FAILED (%s)" command
331                  (if (integerp status)
332                      (format "status %d" status)
333                    status))
334           )
335       (if vc-command-messages
336           (message "Running %s...OK" command))
337       )
338     (set-buffer camefrom)
339     status)
340   )
341
342 ;;; Save a bit of the text around POSN in the current buffer, to help
343 ;;; us find the corresponding position again later.  This works even
344 ;;; if all markers are destroyed or corrupted.
345 (defun vc-position-context (posn)
346   (list posn
347         (buffer-size)
348         (buffer-substring posn
349                           (min (point-max) (+ posn 100)))))
350
351 ;;; Return the position of CONTEXT in the current buffer, or nil if we
352 ;;; couldn't find it.
353 (defun vc-find-position-by-context (context)
354   (let ((context-string (nth 2 context)))
355     (if (equal "" context-string)
356         (point-max)
357       (save-excursion
358         (let ((diff (- (nth 1 context) (buffer-size))))
359           (if (< diff 0) (setq diff (- diff)))
360           (goto-char (nth 0 context))
361           (if (or (search-forward context-string nil t)
362                   ;; Can't use search-backward since the match may continue
363                   ;; after point.
364                   (progn (goto-char (- (point) diff (length context-string)))
365                          ;; goto-char doesn't signal an error at
366                          ;; beginning of buffer like backward-char would
367                          (search-forward context-string nil t)))
368               ;; to beginning of OSTRING
369               (- (point) (length context-string))))))))
370
371 (defun vc-revert-buffer1 (&optional arg no-confirm)
372   ;; Most of this was shamelessly lifted from Sebastian Kremer's rcs.el mode.
373   ;; Revert buffer, try to keep point and mark where user expects them in spite
374   ;; of changes because of expanded version-control key words.
375   ;; This is quite important since otherwise typeahead won't work as expected.
376   (interactive "P")
377   (widen)
378   (let ((point-context (vc-position-context (point)))
379         ;; Use mark-marker to avoid confusion in transient-mark-mode.
380         ;; XEmacs - mark-marker t
381         (mark-context  (if (eq (marker-buffer (mark-marker t)) (current-buffer))
382                            (vc-position-context (mark-marker t))))
383         ;; We may want to reparse the compilation buffer after revert
384         (reparse (and (boundp 'compilation-error-list) ;compile loaded
385                       ;; Construct a list; each elt is nil or a buffer
386                       ;; iff that buffer is a compilation output buffer
387                       ;; that contains markers into the current buffer.
388                       (save-excursion
389                         (mapcar (function
390                                  (lambda (buffer)
391                                    (set-buffer buffer)
392                                    (let ((errors (or
393                                                   (symbol-value 'compilation-old-error-list)
394                                                   (symbol-value 'compilation-error-list)))
395                                          (buffer-error-marked-p nil))
396                                      (while (and (consp errors)
397                                                  (not buffer-error-marked-p))
398                                        (and (markerp (cdr (car errors)))
399                                             (eq buffer
400                                                 (marker-buffer
401                                                  (cdr (car errors))))
402                                             (setq buffer-error-marked-p t))
403                                        (setq errors (cdr errors)))
404                                      (if buffer-error-marked-p buffer))))
405                                 (buffer-list))))))
406
407     ;; The FSF version intentionally runs font-lock here.  That
408     ;; usually just leads to a correctly font-locked buffer being
409     ;; redone.  #### We should detect the cases where the font-locking
410     ;; may be incorrect (such as on reverts).  We know that it is fine
411     ;; during regular checkin and checkouts.
412
413     ;; the actual revisit
414     (revert-buffer arg no-confirm)
415
416     ;; Reparse affected compilation buffers.
417     (while reparse
418       (if (car reparse)
419           (save-excursion
420             (set-buffer (car reparse))
421             (let ((compilation-last-buffer (current-buffer)) ;select buffer
422                   ;; Record the position in the compilation buffer of
423                   ;; the last error next-error went to.
424                   (error-pos (marker-position
425                               (car (car-safe compilation-error-list)))))
426               ;; Reparse the error messages as far as they were parsed before.
427               (if (fboundp 'compile-reinitialize-errors)
428                   (if vc-elucidated
429                       (compile-reinitialize-errors '(4))
430                     (compile-reinitialize-errors '(4) compilation-parsing-end)))
431               ;; Move the pointer up to find the error we were at before
432               ;; reparsing.  Now next-error should properly go to the next one.
433               (while (and compilation-error-list
434                           (/= error-pos (car (car compilation-error-list))))
435                 (setq compilation-error-list (cdr compilation-error-list))))))
436       (setq reparse (cdr reparse)))
437
438     ;; Restore point and mark
439     (let ((new-point (vc-find-position-by-context point-context)))
440       (if new-point (goto-char new-point)))
441     (if mark-context
442         (let ((new-mark (vc-find-position-by-context mark-context)))
443           (if new-mark (set-mark new-mark))))))
444
445
446 (defun vc-buffer-sync (&optional not-urgent)
447   ;; Make sure the current buffer and its working file are in sync
448   ;; NOT-URGENT means it is ok to continue if the user says not to save.
449   (if (buffer-modified-p)
450       (if (or vc-suppress-confirm
451               (y-or-n-p (format "Buffer %s modified; save it? " (buffer-name))))
452           (save-buffer)
453         (if not-urgent
454             nil
455           (error "Aborted")))))
456
457 ;;;dont ###autoload, it conflicts with vc.el
458 (defun vc-file-status ()
459   "Display the current status of the file being visited.
460 Currently, this is only defined for CVS and ClearCase.
461 The information provided in the modeline is generally sufficient for
462 RCS and SCCS."
463   ;; by Stig@hackvan.com
464   (interactive)
465
466   (let* ((file (if vc-dired-mode (dired-get-filename)
467                    (vc-buffer-sync t) buffer-file-name))
468          (type (vc-backend-deduce file)))
469     (cond ((null type)
470            (if file
471                (message "`%s' is not registered with a version control system."
472                         file)
473              (ding)
474              (message "Buffer `%s' has no associated file."
475                       (buffer-name (current-buffer)))))
476           ((eq 'CVS type)
477            (vc-do-command 0 "cvs" file 'WORKFILE "status" "-v")
478            (set-buffer "*vc*")
479            (set-buffer-modified-p nil)
480            ;; reparse the status information, since we have it handy...
481            (vc-parse-buffer '("Status: \\(.*\\)") file '(vc-cvs-status))
482            (goto-char (point-min))
483            (shrink-window-if-larger-than-buffer
484             (display-buffer (current-buffer))))
485           ((eq '@@ type)
486            (vc-do-command 0 "cleartool" file 'WORKFILE "describe")
487            (set-buffer "*vc*")
488            (set-buffer-modified-p nil)
489            (goto-char (point-min))
490            (shrink-window-if-larger-than-buffer
491             (display-buffer (current-buffer))))
492           (t
493            (ding)
494            (message "Operation not yet defined for RCS or SCCS.")))
495     ))
496
497 (defun vc-workfile-unchanged-p (file &optional want-differences-if-changed)
498   ;; Has the given workfile changed since last checkout?
499   (cond ((and (eq 'CVS (vc-backend-deduce file))
500               (not want-differences-if-changed))
501
502          (let ((status (vc-file-getprop file 'vc-cvs-status)))
503            ;; #### - should this have some kind of timeout?  how often does
504            ;; this get called?  possibly the cached information should be
505            ;; flushed out of hand.  The only concern is the VC menu, which
506            ;; may indirectly call this function.
507            (or status                   ; #### - caching is error-prone
508                (setq status (car (vc-log-info "cvs" file 'WORKFILE '("status")
509                                               '("Status: \\(.*\\)")
510                                               '(vc-cvs-status)))))
511            (string= status "Up-to-date")))
512         (t
513          (let ((checkout-time (vc-file-getprop file 'vc-checkout-time))
514                (lastmod (nth 5 (file-attributes file)))
515                unchanged)
516            (or (equal checkout-time lastmod)
517                (and (or (not checkout-time) want-differences-if-changed)
518                     (setq unchanged
519                           (zerop (vc-backend-diff file nil nil
520                                                   (not want-differences-if-changed))))
521                     ;; 0 stands for an unknown time; it can't match any mod time.
522                     (vc-file-setprop file 'vc-checkout-time (if unchanged lastmod 0))
523                     unchanged))))))
524
525 (defun vc-owner-equal (o1 o2)
526   (let ((len1 (length o1))
527         (len2 (length o2)))
528     (string-equal (substring o1 0 (min len1 8))
529                   (substring o2 0 (min len2 8)))))
530
531 (defun vc-next-action-on-file (file verbose &optional comment)
532   ;;; If comment is specified, it will be used as an admin or checkin comment.
533   (let ((vc-file (vc-name file))
534         (vc-type (vc-backend-deduce file))
535         owner version)
536     (cond
537
538      ;; if there is no master file corresponding, create one
539      ((not vc-file)
540       (vc-register verbose comment))
541
542      ;; if there is no lock on the file, assert one and get it
543      ((and (not (eq vc-type 'CVS))      ;There are no locks in CVS.
544            (not (setq owner (vc-locking-user file))))
545       (if (and vc-checkout-carefully
546                (not (vc-workfile-unchanged-p file t)))
547           (if (save-window-excursion
548                 (pop-to-buffer "*vc*")
549                 (goto-char (point-min))
550                 (insert (format "Changes to %s since last lock:\n\n" file))
551                 (not (beep))
552                 (yes-or-no-p
553                  "File has unlocked changes, claim lock retaining changes? "))
554               (progn (vc-backend-steal file)
555                      (vc-mode-line file))
556             (if (not (yes-or-no-p "Revert to checked-in version, instead? "))
557                 (error "Checkout aborted.")
558               (vc-revert-buffer1 t t)
559               (vc-checkout-writable-buffer file))
560             )
561         (vc-checkout-writable-buffer file)))
562
563      ;; a checked-out version exists, but the user may not own the lock
564      ((and (not (eq vc-type 'CVS))      ;There are no locks in CVS.
565            (not (string-equal owner (user-login-name))))
566       (if comment
567           (error "Sorry, you can't steal the lock on %s this way" file))
568       (vc-steal-lock
569        file
570        (and verbose (read-string "Version to steal: "))
571        owner))
572
573      ;; changes to the master file needs to be merged back into the
574      ;; working file
575      ((and (eq vc-type 'CVS)
576            ;; "0" means "added, but not yet committed"
577            (not (string= (vc-file-getprop file 'vc-your-latest-version) "0"))
578            (progn
579              (vc-fetch-properties file)
580              (not (string= (vc-file-getprop file 'vc-your-latest-version)
581                            (vc-file-getprop file 'vc-latest-version)))))
582       (vc-buffer-sync)
583       (if (yes-or-no-p (format "%s is not up-to-date.  Merge in changes now? "
584                                (buffer-name)))
585           (progn
586             (if (and (buffer-modified-p)
587                      (not (yes-or-no-p
588                            (format
589                             "Buffer %s modified; merge file on disc anyhow? "
590                             (buffer-name)))))
591                 (error "Merge aborted"))
592             (if (not (zerop (vc-backend-merge-news file)))
593                 ;; Overlaps detected - what now?  Should use some
594                 ;; fancy RCS conflict resolving package, or maybe
595                 ;; emerge, but for now, simply warn the user with a
596                 ;; message.
597                 (message "Conflicts detected!"))
598             (vc-resynch-window file t (not (buffer-modified-p))))
599
600         (error "%s needs update" (buffer-name))))
601
602      ((and buffer-read-only (eq vc-type 'CVS))
603       (toggle-read-only)
604       ;; Sites who make link farms to a read-only gold tree (or
605       ;; something similar) can use the hook below to break the
606       ;; sym-link.
607       (run-hooks 'vc-make-buffer-writable-hook))
608
609      ;; OK, user owns the lock on the file (or we are running CVS)
610      (t
611       (find-file file)
612
613       ;; give luser a chance to save before checking in.
614       (vc-buffer-sync)
615
616       ;; Revert if file is unchanged and buffer is too.
617       ;; If buffer is modified, that means the user just said no
618       ;; to saving it; in that case, don't revert,
619       ;; because the user might intend to save
620       ;; after finishing the log entry.
621       (if (and (vc-workfile-unchanged-p file)
622                (not (buffer-modified-p)))
623           (progn
624             (if (eq vc-type 'CVS)
625                 (message "No changes to %s" file)
626
627               (vc-backend-revert file)
628               ;; DO NOT revert the file without asking the user!
629               (vc-resynch-window file t nil)))
630
631         ;; user may want to set nonstandard parameters
632         (if verbose
633             (setq version (read-string "New version level: ")))
634
635         ;; OK, let's do the checkin
636         (vc-checkin file version comment)
637         )))
638     ))
639
640 (defun vc-next-action-on-dir (dirname verbose &optional comment)
641   ;;; If comment is specified, it will be used as an admin or checkin comment.
642   (let ((vc-file (vc-name dirname))
643         (vc-type (vc-backend-deduce dirname))
644         owner version)
645     (cond
646
647      ;; if there is no master file corresponding, create one
648      ((not vc-file)
649       (vc-register verbose comment))
650
651      ;; if there is no lock on the file, assert one and get it
652      ((not (setq owner (vc-locking-user dirname)))
653       (vc-checkout-writable-buffer dirname))
654
655      ;; a checked-out version exists, but the user may not own the lock
656      ((not (string-equal owner (user-login-name)))
657
658       (if comment
659           (error "Sorry, you can't steal the lock on %s this way" dirname))
660       (vc-steal-lock
661        dirname
662        (and verbose (read-string "Version to steal: "))
663        owner))
664
665      ;; OK, user owns the lock on the file
666      (t
667       ;; TODO: figure out how to check if directory is unchanged
668
669       ;; user may want to set nonstandard parameters
670       (if verbose
671           (setq version (read-string "New version level: ")))
672
673       ;; OK, let's do the checkin
674       (vc-checkin dirname version comment)
675       ))
676     ))
677
678 (defun vc-next-action-dired (file &optional writable rev workfile comment)
679   ;; We've accepted a log comment, now do a vc-next-action using it on all
680   ;; marked files.
681   (set-buffer vc-parent-buffer)
682   (dired-map-over-marks
683      (save-window-excursion
684      ;;; !!! dired-get-filename doesn't  DTRT if the filename entry is
685      ;;; an absolute pathname..
686      (let ((file (dired-get-filename)))
687        (message "Processing %s..." file)
688        (save-window-excursion
689          (vc-next-action-on-file file nil comment)
690          (message "Processing %s...done" file))))
691    nil t)
692   )
693
694 (defun vc-next-dir-action (verbose)
695   (let* ((file default-directory)
696          (owner (vc-locking-user file)))
697     (cond
698      ((not owner)
699       (vc-checkout-writable-buffer file))
700      ((vc-owner-equal owner (user-login-name))
701       (vc-checkin file nil nil))
702      (t
703       (error "Now what do we do?")))))
704
705 ;; Here's the major entry point.
706
707 ;;;dont ###autoload, it conflicts with vc.el
708 (defun vc-next-action (verbose)
709   "Do the next logical checkin or checkout operation on the current file.
710
711 For RCS and SCCS files:
712    If the file is not already registered, this registers it for version
713 control and then retrieves a writable, locked copy for editing.
714    If the file is registered and not locked by anyone, this checks out
715 a writable and locked file ready for editing.
716    If the file is checked out and locked by the calling user, this
717 first checks to see if the file has changed since checkout.  If not,
718 it performs a revert.
719    If the file has been changed, this pops up a buffer for entry
720 of a log message; when the message has been entered, it checks in the
721 resulting changes along with the log message as change commentary.  If
722 the variable `vc-keep-workfiles' is non-nil (which is its default), a
723 read-only copy of the changed file is left in place afterwards.
724    If the file is registered and locked by someone else, you are given
725 the option to steal the lock.
726
727 For CVS files:
728    If the file is not already registered, this registers it for version
729 control.  This does a \"cvs add\", but no \"cvs commit\".
730    If the file is added but not committed, it is committed.
731    If the file has not been changed, neither in your working area or
732 in the repository, a message is printed and nothing is done.
733    If your working file is changed, but the repository file is
734 unchanged, this pops up a buffer for entry of a log message; when the
735 message has been entered, it checks in the resulting changes along
736 with the logmessage as change commentary.  A writable file is retained.
737    If the repository file is changed, you are asked if you want to
738 merge in the changes into your working copy.
739
740 The following is true regardless of which version control system you
741 are using:
742
743    If you call this from within a VC dired buffer with no files marked,
744 it will operate on the file in the current line.
745    If you call this from within a VC dired buffer, and one or more
746 files are marked, it will accept a log message and then operate on
747 each one.  The log message will be used as a comment for any register
748 or checkin operations, but ignored when doing checkouts.  Attempted
749 lock steals will raise an error.
750
751    For checkin, a prefix argument lets you specify the version number to use."
752   (interactive "P")
753   (catch 'nogo
754     (if (or vc-dired-mode
755             (and (eq major-mode 'dired-mode)
756                  (string= "\C-xvv" (if vc-elucidated
757                                        (events-to-keys (this-command-keys))
758                                      (this-command-keys)))))
759         (let ((files (dired-get-marked-files)))
760           (if (= (length files) 1)
761               (if (file-directory-p (car files))
762                   (let* ((dirname (car files))
763                          (registered (vc-registered dirname)))
764                     (if (and registered (eq '@@ (cdr registered)))
765                         (progn (vc-next-action-on-dir dirname nil)
766                                (throw 'nogo nil)))
767                     (vc-registration-error nil))
768                 (find-file-other-window (car files)))
769             (vc-start-entry nil nil nil
770                             "Enter a change comment for the marked files."
771                             'vc-next-action-dired
772                             nil
773                             nil         ;after-hook could be used here??
774                             )
775             (throw 'nogo nil))))
776     (while vc-parent-buffer
777       (pop-to-buffer vc-parent-buffer))
778     (if buffer-file-name
779         (vc-next-action-on-file buffer-file-name verbose)
780       ;; TODO: Add code to operate on ClearCase directories here.
781       (vc-registration-error nil))))
782
783 ;;; These functions help the vc-next-action entry point
784
785 (defun vc-checkout-writable-buffer (&optional file)
786   "Retrieve a writable copy of the latest version of the current buffer's file."
787   (if (and (vc-file-getprop file 'vc-need-pre-checkout-message)
788            (not vc-suppress-checkout-comments))
789       (progn
790         (vc-start-entry file nil nil "Enter a checkout comment." 'vc-backend-checkout t 'vc-checkout))
791     (vc-checkout (or file (buffer-file-name)) t)))
792
793 ;;;dont ###autoload, it conflicts with vc.el
794 (defun vc-register (&optional override comment)
795   "Register the current file into your version-control system."
796   (interactive "P")
797   (let ((master (vc-name buffer-file-name)))
798     (and master (file-exists-p master)
799          (error "This file is already registered"))
800     (and master
801          (not (y-or-n-p "Previous master file has vanished.  Make a new one? "))
802          (error "This file is already registered")))
803   ;; Watch out for new buffers of size 0: the corresponding file
804   ;; does not exist yet, even though buffer-modified-p is nil.
805   (if (and (not (buffer-modified-p))
806            (zerop (buffer-size))
807            (not (file-exists-p buffer-file-name)))
808       (set-buffer-modified-p t))
809   (vc-buffer-sync)
810   (vc-admin
811    buffer-file-name
812    (and override
813         (read-string
814          (format "Initial version level for %s: " buffer-file-name)))
815    comment)
816   )
817
818 (defun vc-resynch-window (file &optional keep noquery)
819   ;; If the given file is in the current buffer,
820   ;; either revert on it so we see expanded keyworks,
821   ;; or unvisit it (depending on vc-keep-workfiles)
822   ;; NOQUERY if non-nil inhibits confirmation for reverting.
823   ;; NOQUERY should be t *only* if it is known the only difference
824   ;; between the buffer and the file is due to RCS rather than user editing!
825   (and (string= buffer-file-name file)
826        (if keep
827            (progn
828              (vc-revert-buffer1 t noquery)
829              (vc-mode-line buffer-file-name))
830          (progn
831            (delete-window)
832            (kill-buffer (current-buffer))))))
833
834 (defsubst vc-log-buffer-name (file-name)
835   (format "*Log-%s*" (or file-name "Marked")))
836
837 (defun vc-start-entry (file rev comment msg action &optional writable after-hook before-hook)
838   ;; Accept a comment for an operation on FILE revision REV.  If COMMENT
839   ;; is nil, pop up a VC-log buffer, emit MSG, and set the
840   ;; action on close to ACTION; otherwise, do action immediately.
841   ;; Remember the file's buffer in vc-parent-buffer (current one if no file).
842   ;; AFTER-HOOK specifies the local value for vc-log-operation-hook.
843   ;; BEFORE-HOOK specifies a hook to run before even asking for the
844   ;; checkin comments.
845   (let* ((parent (if file (find-file-noselect file) (current-buffer)))
846          (log-buffer-name (vc-log-buffer-name (if file (file-name-nondirectory file))))
847          (log-buffer (get-buffer-create log-buffer-name)))
848     (when before-hook
849       (save-excursion
850         (set-buffer parent)
851         (run-hooks before-hook)))
852     (if comment
853         (set-buffer log-buffer)
854       (let ((old-window-config (current-window-configuration)))
855         (pop-to-buffer log-buffer)
856         (set (make-local-variable 'vc-window-config) old-window-config)))
857     (set (make-local-variable 'vc-parent-buffer) parent)
858 ;;    (set (make-local-variable 'vc-parent-buffer-name)
859 ;;       (concat " from " (buffer-name vc-parent-buffer)))
860     (vc-mode-line (or file " (no file)"))
861     ;; If file is not checked out, the log buffer will be read-only
862     (setq buffer-read-only nil)
863     (vc-log-mode)
864     (make-local-variable 'vc-log-after-operation-hook)
865     (if after-hook
866         (setq vc-log-after-operation-hook after-hook))
867     (setq vc-log-operation action)
868     (setq vc-log-file file)
869     (setq vc-log-version rev)
870     (setq vc-log-writable writable)
871     (if comment
872         (progn
873           (erase-buffer)
874           (if (eq comment t)
875               (vc-finish-logentry t)
876             (insert comment)
877             (vc-finish-logentry nil)))
878       (or writable
879           (vc-backend-fetch-default-comment file rev))
880       (message "%s  Type C-c C-c when done." msg))))
881
882 (defun vc-admin (file rev &optional comment)
883   "Check a file into your version-control system.
884 FILE is the unmodified name of the file.  REV should be the base version
885 level to check it in under.  COMMENT, if specified, is the checkin comment."
886
887   ;; For ClearCase, we need to checkout the directory
888   (let ((filedir (file-name-directory file)) user)
889     (if (eq (vc-backend-deduce filedir) '@@)
890         (progn
891           (setq user (vc-locking-user filedir))
892           (if user
893               (if (not (equal user (user-login-name)))
894                   (error "Directory is locked by %s." user))
895             (if (cond
896                  ((eq vc-checkout-dir-on-register 'ask)
897                   (y-or-n-p (format "Checkout directory %s " filedir)))
898                  (vc-checkout-dir-on-register)
899                  (t nil))
900                 (vc-backend-checkout filedir t rev nil comment)
901               (error "Can't register file unless directory is reserved.")
902               )))))
903
904   (vc-start-entry file rev
905                   (or comment (not vc-initial-comment))
906                   "Enter initial comment." 'vc-backend-admin
907                   nil nil 'vc-before-checkin-hook))
908
909 ;;;dont ###autoload, it conflicts with vc.el
910 (defun vc-checkout (file &optional writable)
911   "Retrieve a copy of the latest version of the given file."
912   ;; XEmacs - ftp is suppressed by the check for a filename handler in
913   ;;          vc-registered, so this is needless surplussage
914   ;; If ftp is on this system and the name matches the ange-ftp format
915   ;; for a remote file, the user is trying something that won't work.
916   ;;   (if (and (string-match "^/[^/:]+:" file) (vc-find-binary "ftp"))
917   ;;       (error "Sorry, you can't check out files over FTP"))
918   (vc-backend-checkout file writable)
919   (if (string-equal file buffer-file-name)
920       (vc-resynch-window file t t))
921   )
922
923 (defun vc-steal-lock (file rev &optional owner)
924   "Steal the lock on the current workfile."
925   (let (file-description)
926     (if (not owner)
927         (setq owner (vc-locking-user file)))
928     (if rev
929         (setq file-description (format "%s:%s" file rev))
930       (setq file-description file))
931     (if (not (y-or-n-p (format "Take the lock on %s from %s? "
932                                file-description owner)))
933         (error "Steal cancelled"))
934     (pop-to-buffer (get-buffer-create "*VC-mail*"))
935     (setq default-directory (expand-file-name "~/"))
936     (auto-save-mode auto-save-default)
937     (mail-mode)
938     (erase-buffer)
939     (mail-setup owner (format "Stolen lock on %s" file-description) nil nil nil
940                 (list (list 'vc-finish-steal file rev)))
941     (goto-char (point-max))
942     (insert
943      (format "I stole the lock on %s, " file-description)
944      (current-time-string)
945      ".\n")
946     (message "Please explain why you stole the lock.  Type C-c C-c when done.")))
947
948 ;; This is called when the notification has been sent.
949 (defun vc-finish-steal (file version)
950   (vc-backend-steal file version)
951   (if (get-file-buffer file)
952       (save-excursion
953         (set-buffer (get-file-buffer file))
954         (vc-resynch-window file t t))))
955
956 (defun vc-checkin (file &optional rev comment)
957   "Check in the file specified by FILE.
958 The optional argument REV may be a string specifying the new version level
959 \(if nil increment the current level).  The file is either retained with write
960 permissions zeroed, or deleted (according to the value of `vc-keep-workfiles').
961 If the back-end is CVS, a writable workfile is always kept.
962 COMMENT is a comment string; if omitted, a buffer is
963 popped up to accept a comment."
964   (vc-start-entry file rev comment
965                   "Enter a change comment." 'vc-backend-checkin
966                   nil 'vc-checkin-hook 'vc-before-checkin-hook)
967   (if (and (not comment) (not (file-directory-p file)) vc-diff-on-checkin)
968       (save-excursion
969         (let ((tmp-buffer (current-buffer)))
970           (message "Running diff...")
971           (vc-diff nil)
972           (message "Running diff...done")
973           (set-buffer "*vc*")
974           (if (get-buffer "*vc-diff*")
975               (kill-buffer "*vc-diff*"))
976           (rename-buffer "*vc-diff*")
977           (pop-to-buffer tmp-buffer)))))
978
979 ;;; Here is a checkin hook that may prove useful to sites using the
980 ;;; ChangeLog facility supported by Emacs.
981 (defun vc-comment-to-change-log (&optional whoami file-name)
982   "Enter last VC comment into change log file for current buffer's file.
983 Optional arg (interactive prefix) non-nil means prompt for user name and site.
984 Second arg is file name of change log.  \
985 If nil, uses `change-log-default-name'."
986   (interactive (if current-prefix-arg
987                    (list current-prefix-arg
988                          (prompt-for-change-log-name))))
989   ;; Make sure the defvar for add-log-current-defun-function has been executed
990   ;; before binding it.
991   (require 'add-log)
992   (let (;; Extract the comment first so we get any error before doing anything.
993         (comment (ring-ref vc-comment-ring 0))
994         ;; Don't let add-change-log-entry insert a defun name.
995         (add-log-current-defun-function 'ignore)
996         end)
997     ;; Call add-log to do half the work.
998     (add-change-log-entry whoami file-name t t)
999     ;; Insert the VC comment, leaving point before it.
1000     (setq end (save-excursion (insert comment) (point-marker)))
1001     (if (looking-at "\\s *\\s(")
1002         ;; It starts with an open-paren, as in "(foo): Frobbed."
1003         ;; So remove the ": " add-log inserted.
1004         (delete-char -2))
1005     ;; Canonicalize the white space between the file name and comment.
1006     (just-one-space)
1007     ;; Indent rest of the text the same way add-log indented the first line.
1008     (let ((indentation (current-indentation)))
1009       (save-excursion
1010         (while (< (point) end)
1011           (forward-line 1)
1012           (indent-to indentation))
1013         (setq end (point))))
1014     ;; Fill the inserted text, preserving open-parens at bol.
1015     (let ((paragraph-separate (concat paragraph-separate "\\|^\\s *\\s("))
1016           (paragraph-start (concat paragraph-start "\\|^\\s *\\s(")))
1017       (beginning-of-line)
1018       (fill-region (point) end))
1019     ;; Canonicalize the white space at the end of the entry so it is
1020     ;; separated from the next entry by a single blank line.
1021     (skip-syntax-forward " " end)
1022     (delete-char (- (skip-syntax-backward " ")))
1023     (or (eobp) (looking-at "\n\n")
1024         (insert "\n"))))
1025
1026
1027 (defun vc-cc-save-logentry (comment buffer)
1028   (save-excursion
1029     (set-buffer buffer)
1030     (let* ((file (buffer-file-name))
1031            (target (concat (vc-latest-version file))))
1032       (cond ((string-match "/CHECKEDOUT$" target)
1033              (vc-do-cleartool-command "chevent"
1034                                       (vc-cc-build-version file target)
1035                                       (vc-cleanup-comment comment) "-replace"))
1036             (t
1037              (error "Can't change comment of checked-in version with this interface"))))))
1038
1039 (defun vc-save-logentry ()
1040   "Checkpoint currently entered comment"
1041   (interactive)
1042   (let ((comment-string (buffer-string))
1043         (parent-buffer vc-parent-buffer))
1044     (if (not (buffer-modified-p))
1045         (message "(No changes need to be saved)")
1046       (progn
1047         (save-excursion
1048           (set-buffer parent-buffer)
1049           (vc-backend-dispatch buffer-file-name
1050             (error "Logentry saves not supported under SCCS")
1051             (error "Logentry saves not supported under RCS")
1052             (error "Logentry saves not supported under CVS")
1053             (vc-cc-save-logentry comment-string parent-buffer)))
1054         (set-buffer-modified-p nil)))))
1055
1056 (defun vc-num-num-error ()
1057   (interactive)
1058   (message "Perhaps you wanted to type C-c C-c instead?"))
1059
1060 (defun vc-finish-logentry (&optional nocomment)
1061   "Complete the operation implied by the current log entry."
1062   (interactive)
1063   ;; Check and record the comment, if any.
1064   (let ((log-buffer (current-buffer)))
1065     (if (not nocomment)
1066         (progn
1067           (goto-char (point-max))
1068           (if (not (bolp))
1069               (newline))
1070           ;; Comment too long?
1071           (vc-backend-logentry-check vc-log-file)
1072           ;; Record the comment in the comment ring
1073           (if (null vc-comment-ring)
1074               (setq vc-comment-ring (make-ring vc-maximum-comment-ring-size)))
1075           (ring-insert vc-comment-ring (buffer-string))
1076           ))
1077     ;; Sync parent buffer in case the user modified it while editing the comment.
1078     ;; But not if it is a vc-dired buffer.
1079     (save-excursion
1080       (set-buffer vc-parent-buffer)
1081       (or vc-dired-mode
1082           (vc-buffer-sync)))
1083     ;; OK, do it to it
1084     (if vc-log-operation
1085         (save-excursion
1086           (funcall vc-log-operation
1087                    vc-log-file
1088                    vc-log-writable
1089                    vc-log-version
1090                    nil
1091                    (buffer-string)))
1092       (error "No log operation is pending"))
1093     ;; Return to "parent" buffer of this checkin and remove checkin window
1094     ;; save the vc-log-after-operation-hook of log buffer
1095     (let ((after-hook vc-log-after-operation-hook)
1096           (old-window-config vc-window-config))
1097       (pop-to-buffer vc-parent-buffer)
1098       (delete-windows-on log-buffer)
1099       (kill-buffer log-buffer)
1100       (if old-window-config (set-window-configuration old-window-config))
1101       ;; Now make sure we see the expanded headers
1102       (if buffer-file-name
1103           (vc-resynch-window buffer-file-name vc-keep-workfiles t))
1104       (if (and (not (eq vc-log-operation 'vc-next-action-dired))
1105                (eq major-mode 'dired-mode))
1106           (revert-buffer t t))
1107       (run-hooks after-hook))))
1108
1109 ;; Code for access to the comment ring
1110
1111 (defun vc-previous-comment (arg)
1112   "Cycle backwards through comment history."
1113   (interactive "*p")
1114   (let ((len (ring-length vc-comment-ring)))
1115     (cond ((or (not len) (<= len 0))    ; XEmacs change from Barry Warsaw
1116            (message "Empty comment ring")
1117            (ding))
1118           (t
1119            (erase-buffer)
1120            ;; Initialize the index on the first use of this command
1121            ;; so that the first M-p gets index 0, and the first M-n gets
1122            ;; index -1.
1123            (if (null vc-comment-ring-index)
1124                (setq vc-comment-ring-index
1125                      (if (> arg 0) -1
1126                        (if (< arg 0) 1 0))))
1127            (setq vc-comment-ring-index
1128                  (mod (+ vc-comment-ring-index arg) len))
1129            (message "%d" (1+ vc-comment-ring-index))
1130            (insert (ring-ref vc-comment-ring vc-comment-ring-index))))))
1131
1132 (defun vc-next-comment (arg)
1133   "Cycle forwards through comment history."
1134   (interactive "*p")
1135   (vc-previous-comment (- arg)))
1136
1137 (defun vc-comment-search-reverse (str)
1138   "Searches backwards through comment history for substring match."
1139   (interactive "sComment substring: ")
1140   (if (string= str "")
1141       (setq str vc-last-comment-match)
1142     (setq vc-last-comment-match str))
1143   (if (null vc-comment-ring-index)
1144       (setq vc-comment-ring-index -1))
1145   (let ((str (regexp-quote str))
1146         (len (ring-length vc-comment-ring))
1147         (n (1+ vc-comment-ring-index)))
1148     (while (and (< n len) (not (string-match str (ring-ref vc-comment-ring n))))
1149       (setq n (+ n 1)))
1150     (cond ((< n len)
1151            (vc-previous-comment (- n vc-comment-ring-index)))
1152           (t (error "Not found")))))
1153
1154 (defun vc-comment-search-forward (str)
1155   "Searches forwards through comment history for substring match."
1156   (interactive "sComment substring: ")
1157   (if (string= str "")
1158       (setq str vc-last-comment-match)
1159     (setq vc-last-comment-match str))
1160   (if (null vc-comment-ring-index)
1161       (setq vc-comment-ring-index 0))
1162   (let ((str (regexp-quote str))
1163         (n vc-comment-ring-index))
1164     (while (and (>= n 0) (not (string-match str (ring-ref vc-comment-ring n))))
1165       (setq n (- n 1)))
1166     (cond ((>= n 0)
1167            (vc-next-comment (- n vc-comment-ring-index)))
1168           (t (error "Not found")))))
1169
1170 ;; Additional entry points for examining version histories
1171
1172 ;;;dont ###autoload, it conflicts with vc.el
1173 (defun vc-diff (historic &optional not-urgent)
1174   "Display diffs between file versions.
1175 Normally this compares the current file and buffer with the most recent
1176 checked in version of that file.  This uses no arguments.
1177 With a prefix argument, it reads the file name to use
1178 and two version designators specifying which versions to compare."
1179   (interactive "P")
1180   (if vc-dired-mode
1181       (set-buffer (find-file-noselect (dired-get-filename))))
1182   (while vc-parent-buffer
1183     (pop-to-buffer vc-parent-buffer))
1184   (if historic
1185       (call-interactively 'vc-version-diff)
1186     (if (or (null buffer-file-name) (null (vc-name buffer-file-name)))
1187         (error
1188          "There is no version-control master associated with this buffer"))
1189     (let ((file buffer-file-name)
1190           unchanged)
1191       (or (and file (vc-name file))
1192           (vc-registration-error file))
1193       (vc-buffer-sync not-urgent)
1194       (setq unchanged (vc-workfile-unchanged-p buffer-file-name))
1195       (if unchanged
1196           (message "No changes to %s since latest version." file)
1197         (vc-backend-diff file)
1198         ;; Ideally, we'd like at this point to parse the diff so that
1199         ;; the buffer effectively goes into compilation mode and we
1200         ;; can visit the old and new change locations via next-error.
1201         ;; Unfortunately, this is just too painful to do.  The basic
1202         ;; problem is that the `old' file doesn't exist to be
1203         ;; visited.  This plays hell with numerous assumptions in
1204         ;; the diff.el and compile.el machinery.
1205         (pop-to-buffer "*vc*")
1206         (setq default-directory (file-name-directory file))
1207         (if (= 0 (buffer-size))
1208             (progn
1209               (setq unchanged t)
1210               (message "No changes to %s since latest version." file))
1211           (goto-char (point-min))
1212           (shrink-window-if-larger-than-buffer)))
1213       (not unchanged))))
1214
1215 ;;;dont ###autoload, it conflicts with vc.el
1216 (defun vc-version-diff (file rel1 rel2)
1217   "For FILE, report diffs between two stored versions REL1 and REL2 of it.
1218 If FILE is a directory, generate diffs between versions for all registered
1219 files in or below it."
1220   (interactive
1221    (progn
1222      (let ((file (read-file-name "File or directory to diff: "
1223                                  default-directory nil t nil)))
1224        (if (file-directory-p file)
1225            (let ((r1 (read-string "Older version: "))
1226                  (r2 (read-string "Newer version: ")))
1227              (list file r1 r2))
1228          (let ((r1 (vc-read-version
1229                     (format "Older version of %s: "
1230                             (file-name-nondirectory file))
1231                     file))
1232                (r2 (vc-read-version
1233                     (format "Newer version of %s: "
1234                             (file-name-nondirectory file))
1235                     file)))
1236            (list file r1 r2))))))
1237   (if (string-equal rel1 "") (setq rel1 nil))
1238   (if (string-equal rel2 "") (setq rel2 nil))
1239   (if (file-directory-p file)
1240       (let ((camefrom (current-buffer)))
1241         (set-buffer (get-buffer-create "*vc-status*"))
1242         (set (make-local-variable 'vc-parent-buffer) camefrom)
1243         (set (make-local-variable 'vc-parent-buffer-name)
1244              (concat " from " (buffer-name camefrom)))
1245         (erase-buffer)
1246         (insert "Diffs between "
1247                 (or rel1 "last version checked in")
1248                 " and "
1249                 (or rel2 "current workfile(s)")
1250                 ":\n\n")
1251         (set-buffer (get-buffer-create "*vc*"))
1252         (cd file)
1253         (vc-file-tree-walk
1254          (function (lambda (f)
1255                      (message "Looking at %s" f)
1256                      (and
1257                       (not (file-directory-p f))
1258                       (vc-registered f)
1259                       (vc-backend-diff f rel1 rel2)
1260                       (append-to-buffer "*vc-status*" (point-min) (point-max)))
1261                      )))
1262         (pop-to-buffer "*vc-status*")
1263         (insert "\nEnd of diffs.\n")
1264         (goto-char (point-min))
1265         (set-buffer-modified-p nil)
1266         )
1267     (if (zerop (vc-backend-diff file rel1 rel2))
1268         (message "No changes to %s between %s and %s." file rel1 rel2)
1269       (pop-to-buffer "*vc*"))))
1270
1271 (defun vc-read-version (prompt file)
1272   (vc-backend-dispatch file
1273       (read-string prompt (vc-latest-version file))
1274       (read-string prompt (vc-latest-version file))
1275       (read-string prompt (vc-latest-version file))
1276       ;; For ClearCase, use the version-extended path
1277       (let* (;; Don't show the whole gory path
1278              (insert-default-directory nil)
1279              ;; Fetch the latest version for defaults - it's not critical that
1280              ;; it be up-to-date, so try the property-list first.
1281              (latest (or (vc-file-getprop file 'vc-latest-version)
1282                          (vc-latest-version file)))
1283              (default (vc-cc-build-version file latest))
1284              ;; Make the current directory the branch of the latest version
1285              ;; This is the only way that read-file-name will work properly, if
1286              ;; I pass in this directory, it doesn't complete properly when
1287              ;; subdirectories are used.
1288              (default-directory (expand-file-name
1289                                 (vc-cc-build-version file
1290                                                      (file-name-directory latest))))
1291              )
1292         ;; Extract just version name, but still complete
1293         (vc-cc-version-name
1294          (expand-file-name
1295           (read-file-name (format "%s (default %s): " prompt latest)
1296                           nil
1297                           default
1298                           t
1299                           nil
1300                           ))
1301          )
1302 ;;        ;; The completing-read method safer, but slower
1303 ;;        (completing-read prompt (vc-cc-enumerate-versions file) nil t
1304 ;;                         (or (vc-cc-version-name file) (vc-latest-version file)))
1305         )
1306       ))
1307
1308 ;;;dont ###autoload, it conflicts with vc.el
1309 (defun vc-version-other-window (rev)
1310   "Visit version REV of the current buffer in another window.
1311 If the current buffer is named `F', the version is named `F.~REV~'.
1312 If `F.~REV~' already exists, it is used instead of being re-created.
1313
1314 ClearCase uses the normal version-extended naming convention instead."
1315   (interactive
1316    (list
1317     (progn
1318       (if vc-dired-mode
1319           (set-buffer (find-file-noselect (dired-get-filename))))
1320       (while vc-parent-buffer
1321         (pop-to-buffer vc-parent-buffer))
1322       (vc-read-version (format "Version of %s to visit: "
1323                                (file-name-nondirectory buffer-file-name))
1324                        buffer-file-name))))
1325
1326   (if (and buffer-file-name (vc-name buffer-file-name))
1327       (let* ((version (if (string-equal rev "")
1328                           (vc-latest-version buffer-file-name)
1329                         rev))
1330              (filename (vc-backend-dispatch
1331                         buffer-file-name
1332                         (concat buffer-file-name ".~" version" ~")      ;; SCCS
1333                         (concat buffer-file-name ".~" version" ~")      ;; RCS
1334                         (concat buffer-file-name ".~" version" ~")      ;; CVS
1335                         (vc-cc-build-version
1336                          (vc-cc-element-name buffer-file-name)
1337                                  version) ;; ClearCase
1338                         )))
1339          (or (file-exists-p filename)
1340              (vc-backend-checkout buffer-file-name nil version filename nil))
1341          (find-file-other-window filename))
1342     (vc-registration-error buffer-file-name)))
1343
1344 ;; Header-insertion code
1345
1346 ;;;dont ###autoload, it conflicts with vc.el
1347 (defun vc-insert-headers ()
1348   "Insert headers in a file for use with your version-control system.
1349 Headers desired are inserted at the start of the buffer, and are pulled from
1350 the variable `vc-header-alist'."
1351   (interactive)
1352   (if vc-dired-mode
1353       (find-file-other-window (dired-get-filename)))
1354   (while vc-parent-buffer
1355     (pop-to-buffer vc-parent-buffer))
1356   (save-excursion
1357     (save-restriction
1358       (widen)
1359       (if (or (not (vc-check-headers))
1360               (y-or-n-p "Version headers already exist.  Insert another set? "))
1361           (progn
1362             (let* ((delims (cdr (assq major-mode vc-comment-alist)))
1363                    (comment-start-vc (or (car delims) comment-start "#"))
1364                    (comment-end-vc (or (car (cdr delims)) comment-end ""))
1365                    (hdstrings (cdr (assoc (vc-backend-deduce (buffer-file-name)) vc-header-alist))))
1366               (mapcar (function (lambda (s)
1367                                   (insert comment-start-vc s
1368                                           comment-end-vc "\n")))
1369                       hdstrings)
1370               (if vc-static-header-alist
1371                   (mapcar (function (lambda (f)
1372                               (if (and buffer-file-name
1373                                        (string-match (car f) buffer-file-name))
1374                                   (insert (format (cdr f) (car hdstrings))))))
1375                           vc-static-header-alist))
1376               )
1377             )))))
1378
1379 ;; The VC directory submode.  Coopt Dired for this.
1380 ;; All VC commands get mapped into logical equivalents.
1381
1382 (defvar vc-dired-prefix-map (make-sparse-keymap))
1383 (define-key vc-dired-prefix-map "\C-xv" vc-prefix-map)
1384
1385 (if (not (fboundp 'set-keymap-name))
1386     (defun set-keymap-name (&rest args)
1387       nil))
1388
1389 (set-keymap-name vc-dired-prefix-map 'vc-dired-prefix-map)
1390
1391 (or (not (boundp 'minor-mode-map-alist))
1392     (assq 'vc-dired-mode (symbol-value 'minor-mode-map-alist))
1393     (setq minor-mode-map-alist
1394           (cons (cons 'vc-dired-mode vc-dired-prefix-map)
1395                 minor-mode-map-alist)))
1396
1397 ;;;dont ###autoload, it conflicts with vc.el
1398 (defun vc-dired-mode (&optional arg)
1399   "The augmented Dired minor mode used in VC directory buffers.
1400 All Dired commands operate normally.  Users currently locking listed files
1401 are listed in place of the file's owner and group.
1402 Keystrokes bound to VC commands will execute as though they had been called
1403 on a buffer attached to the file named in the current Dired buffer line."
1404   (interactive "P")
1405
1406   ;; Behave like a proper minor-mode
1407   (setq vc-dired-mode
1408         (if (interactive-p)
1409             (if (null arg)
1410                 (not vc-dired-mode)
1411               ;; Check if the numeric arg is positive
1412               (> (prefix-numeric-value arg) 0)
1413               )
1414           ;; else
1415           ;; Use the car if it's a list
1416           (if (consp arg) (setq arg (car arg)))
1417
1418           (if (symbolp arg)
1419               (if (null arg)
1420                   (not vc-dired-mode)  ;; toggle mode switch
1421                 (not (eq '- arg))) ;; True if symbol is not '-
1422             ;; else
1423             ;; assume it's a number and check that
1424             (> arg 0)
1425             )))
1426
1427   (if (or (not (eq major-mode 'dired-mode)))
1428       (setq vc-dired-mode nil))
1429
1430   (if (and vc-dired-mode vc-dired-highlight)
1431       (progn
1432         (vc-reformat-dired-buffer)
1433         (setq vc-mode " under VC")
1434         )
1435     (setq vc-mode ""))
1436   )
1437
1438 ;;(defvar vc-dired-width 15
1439 ;;  "Field width of locking-user information inserted into dired buffer")
1440
1441 ;; Create a face for highlighting checked out files in vc-dired
1442 (if (not (memq 'vc-dired-checkedout-face (face-list)))
1443     (progn
1444       (make-face 'vc-dired-checkedout-face)
1445       (set-face-doc-string 'vc-dired-checkedout-face
1446                            "Checked out files in VC dired buffers")
1447       (set-face-foreground 'vc-dired-checkedout-face "yellow")))
1448
1449 ;; Create a face for highlighting registered files in vc-dired
1450 (if (not (memq 'vc-dired-registered-face (face-list)))
1451     (progn
1452       (make-face 'vc-dired-registered-face)
1453       (set-face-doc-string 'vc-dired-registered-face
1454                            "Registered files in VC dired buffers")
1455       (set-face-foreground 'vc-dired-registered-face "#6920ac")))
1456
1457 ;;;dont ###autoload, it conflicts with vc.el
1458 (defun vc-reformat-dired-buffer (&optional filelist)
1459   "Reformats the current dired buffer using the given file alist."
1460   (let* ((givenlist filelist)
1461          (directory default-directory)
1462          subdir)
1463     (save-excursion
1464       (goto-char (point-min))
1465
1466       (while (not (eobp))
1467         (cond
1468          ;; Look for directory markers
1469          ((setq subdir (dired-get-subdir))
1470           (setq directory subdir)
1471           ;; If no filelist was passed in, look up the checkouts.
1472           ;; The routine vc-list-registered-files is optimized (at least for
1473           ;; SCCS and ClearCase) to return the checked out files quickly.
1474           ;; This routine should be much faster than checking each file.
1475           (if (not givenlist)
1476               (setq filelist (vc-list-registered-files 'all nil directory)))
1477           ;; If no registered files are found, we don't need to check each
1478           ;; file, and it's very slow.  The filelist should contain something
1479           ;; so it doesn't attempt to do this.
1480           (if (null filelist) (setq filelist '(nil)))
1481           (message "Reformatting %s..." directory))
1482
1483          ;; Look for files (the safest way to get the filename)
1484          ((setq fullpath (dired-get-filename nil t))
1485           ;; Expand it to get rid of . and .. entries
1486           (setq fullpath (expand-file-name fullpath))
1487           (looking-at
1488            "..\\([drwxlts-]+ \\) *[0-9]+ \\(.+\\) +[0-9]+\\( [^ 0-9]+ [0-9 ][0-9] .*\\)")
1489           (let* ((file-registered (assoc fullpath filelist))
1490                  (owner (if file-registered (cdr file-registered)
1491                           ;; If a filelist was not specified, try to find the
1492                           ;; locking user.  The only time this should happen
1493                           ;; is when we are updating a single file entry.  For
1494                           ;; whole subdirectories, the filelist should have
1495                           ;; been generated.
1496                           (save-match-data
1497                             (and (null filelist)
1498                                  (vc-registered fullpath)
1499                                  (vc-locking-user fullpath)))))
1500                  (info-length (- (match-end 2) (match-beginning 2)))
1501                  (rep (format "%-8s RESERVED" owner))
1502                  )
1503
1504             ;; Remove this element from the alist (in case multiple users have
1505             ;; a file checked out)
1506             (if (consp file-registered) (setcar file-registered nil))
1507
1508             ;; Highlight the line if the file is reserved
1509             (if owner
1510                 (progn
1511                   (goto-char (match-beginning 2))
1512                   ;; Replace the user/group with user/RESERVED
1513                   (let ((buffer-read-only nil))
1514                     (cond ((>= info-length 17) (setq info-length 17))
1515                           ((>= info-length 8) (setq info-length 8))
1516                           (t (error "Bad format.")))
1517
1518                     (delete-char info-length)
1519                     (insert (substring rep 0 info-length))
1520                     )
1521
1522                   ;; Highlight the checked out files sort of like xclearcase
1523                   (if (featurep 'text-props)
1524                       (put-text-property (match-beginning 2) (match-end 2)
1525                                          'face 'vc-dired-checkedout-face)))
1526               ;; Else if it is registered, but not checked out
1527               (if (or file-registered
1528                       (and (not filelist)
1529                            (save-match-data (vc-registered fullpath))))
1530                   ;; Highlight the registered files
1531                   (if (featurep 'text-props)
1532                       (put-text-property (match-beginning 2) (match-end 2)
1533                                          'face 'vc-dired-registered-face)))
1534               ))))
1535         (forward-line 1))       ;; go to next line
1536       ))
1537   (message "Reformatting...Done")
1538   )
1539
1540 (defvar vc-dired-listing-switches (concat dired-listing-switches "d"))
1541
1542 (defun vc-list-registered-files (verbose recurse &optional directory)
1543   "Returns an alist of files to users in the directory."
1544   (or directory (setq directory default-directory))
1545   (let ((filelist nil) (default-directory directory))
1546     (cond
1547      ;; ClearCase
1548      ((eq (vc-backend-deduce directory) '@@)
1549
1550       (message "Listing ClearCase checkouts...")
1551
1552       ;; File-tree walk is too slow to use for ClearCase
1553       (setq filelist (vc-cc-list-checkouts directory verbose recurse))
1554
1555       ;; Check if the directory itself is checked-out
1556       (let* ((dirname (directory-file-name directory))
1557              (user (vc-locking-user dirname)))
1558         (if user (setq filelist (cons (cons dirname user) filelist)))
1559         ;; Check the parent too, he's in the list
1560         (setq dirname (directory-file-name (expand-file-name (concat directory "..")))
1561               user (vc-locking-user dirname))
1562         (if user (setq filelist (cons (cons dirname user) filelist))))
1563
1564       ;; List all registered files if requested
1565       (if (eq verbose 'all)
1566           ;; Add all the rest of the non-private files to the list
1567           (let ((tree-walk-function
1568                  (function (lambda (file)
1569                              (let ((fullpath (expand-file-name file directory)))
1570                                (if (and (not (assoc fullpath filelist))
1571                                         (clearcase-element-p file))
1572                                    (setq filelist (cons (cons fullpath nil)
1573                                                         filelist))
1574                                  ))))))
1575             ;; Add all the rest of the non-private files to the list
1576             (if recurse
1577                 (vc-file-tree-walk tree-walk-function)
1578               (vc-dir-all-files tree-walk-function))
1579             ))
1580       (message "Listing ClearCase checkouts...done")
1581       )
1582      ;; SCCS
1583      ((or (file-directory-p "SCCS") (eq vc-default-back-end 'SCCS))
1584
1585       (message "Listing SCCS checkouts...")
1586
1587       ;; If recursive was requested, use vc-subdir-tree-walk
1588       (if recurse
1589           (vc-subdir-tree-walk 'vc-sccs-info-list verbose)
1590         (vc-sccs-info-list directory verbose))
1591
1592       ;; List all registered files if requested
1593       (if (eq verbose 'all)
1594           (let ((tree-walk-function
1595                  (function (lambda (file)
1596                              (let ((fullpath (expand-file-name file directory)))
1597                                (if (and (not (file-directory-p fullpath))
1598                                         (not (assoc fullpath filelist))
1599                                         ;; Cut to the chase
1600                                         (file-exists-p
1601                                          (format
1602                                           "%sSCCS/s.%s"
1603                                           (file-name-directory file)
1604                                           (file-name-nondirectory file)))
1605                                         )
1606                                    (setq filelist (cons (cons fullpath nil)
1607                                                         filelist))
1608                                  ))))))
1609             ;; Add all the rest of the registered files to the list
1610             (if recurse
1611                 (vc-file-tree-walk tree-walk-function)
1612               (vc-dir-all-files tree-walk-function))
1613             ))
1614
1615       (message "Listing SCCS checkouts...done")
1616       )
1617      (t
1618       ;; All other VC systems... this may be too slow for comfort
1619       (let ((tree-walk-function
1620              (function (lambda (f)
1621                          (if (vc-registered f)
1622                              (let ((user (vc-locking-user f)))
1623                                (if (cond ((null verbose))
1624                                          ((eq verbose 'all))
1625                                          ((eq verbose 'yours) (string-equal user (user-login-name))))
1626                                    (setq filelist
1627                                          (cons (cons f user) filelist)))))))))
1628         (if recurse
1629             (vc-file-tree-walk tree-walk-function)
1630           (vc-dir-all-files tree-walk-function)))
1631       )
1632      )
1633     ;; Return the filelist
1634     filelist
1635     ))
1636
1637 (defun vc-cc-list-checkouts (directory verbose &optional recurse)
1638   (or directory (setq directory default-directory))
1639   (vc-cc-cd directory)
1640
1641   (let* (;; Trim off the view specifier
1642          (reldir (vc-cc-relpath directory))
1643          ;; Don't use avobs, it takes way too long
1644          (cmd (concat
1645                "lsco -fmt \"%n %u %Tf\\n\""
1646                (if (eq verbose 'yours) " -me" "")
1647                ;; If recursive list requested, use "-r", otherwise,
1648                ;; assume the request is for a single vc-dired-mode
1649                ;; directory, and use "-cview" to restrict list to
1650                ;; checkouts in the current view.
1651                (if recurse " -r" " -cview")
1652                ;; Put the directory so all names will be fullpaths
1653                ;; For some reason ClearCase adds an extra slash if you leave
1654                ;; the trailing slash on the directory, so we need to remove it.
1655                " " (directory-file-name (or reldir directory))))
1656          (string (vc-cleartool-cmd (or reldir directory) cmd))
1657          (tmplist (split-string string "\n")))
1658     ;; Return the reversed alist constructed from the file/version pairs
1659     (cdr (nreverse
1660           (mapcar (function
1661                    (lambda (string)
1662                      (let* ((split-list (split-string string " "))
1663                             (fullname (vc-cc-build-version
1664                                        (car split-list) nil
1665                                        (if (or reldir recurse)
1666                                            (caddr split-list))))
1667                             (locking-user (cadr split-list)))
1668                        ;; Record the locking user for future operations
1669                        (vc-file-setprop fullname 'vc-locking-user locking-user)
1670                        (cons fullname locking-user))
1671                      ))
1672                   tmplist)))
1673     ))
1674
1675 ;; This assumes that the caller has defined the variable filelist.
1676 ;; Should be used only by vc-list-registered-files.
1677 (defun vc-sccs-info-list (directory verbose)
1678   "List the SCCS checked out files in the given directory."
1679
1680   (if (file-directory-p (concat directory "SCCS/"))
1681       (save-excursion
1682         ;; Call sccs info to list all checked out files
1683         (apply 'vc-do-command 0 "sccs" directory nil
1684                "info" (if (eq verbose 'yours) '("-U") nil))
1685         (set-buffer "*vc*")
1686         (beginning-of-buffer)
1687
1688         ;; Find all lines matching the format and create a filelist
1689         (while (re-search-forward
1690                 "^[ \t]*\\([^ \t\n]*\\): being edited: \\([0-9.]+\\) \\([0-9.]+\\) \\([^ \t\n]+\\) .*$"
1691                 nil t)
1692           (let* ((file (match-string 1))
1693                  (user (match-string 4))
1694                  (fullpath (expand-file-name file directory)))
1695
1696             ;; Add the entry to the filelist if not there already
1697             (if (not (assoc fullpath filelist))
1698                 (setq filelist (cons (cons fullpath user) filelist)))
1699
1700             ;; Record the locking user for future operations
1701             (vc-file-setprop (expand-file-name file directory)
1702                              'vc-locking-user user)
1703           ))
1704         )
1705     ))
1706
1707 ;; This is a very useful function, and I'm surprised that I couldn't find an
1708 ;; equivalent
1709 (defun find-base-dir (dirlist)
1710   "Find the base directory of the given list of directories."
1711   (let ((dirlist (mapcar (function (lambda (x) (split-string x "/"))) 
1712                          dirlist))
1713         prelist first postlist)
1714     (setq postlist
1715           (catch 'done
1716             (while t
1717               (setq 
1718                first nil
1719                dirlist (mapcar (function (lambda (list)
1720                                            (if first
1721                                                (if (not (string-equal first (car list)))
1722                                                    (throw 'done prelist))
1723                                              (setq first (car list)))
1724                                            (if (consp list) (cdr list) list)))
1725                                dirlist))
1726               (setq prelist (append prelist (list first)))
1727               )))
1728     (if postlist
1729         (concat (mapconcat 'identity postlist "/") "/")
1730       "/")
1731     ))
1732
1733
1734 ;;; Note in Emacs 18 the following defun gets overridden
1735 ;;; with the symbol 'vc-directory-18.  See below.
1736 ;;;dont ###autoload, it conflicts with vc.el
1737 (defun vc-directory (dir verbose)
1738   "Show version-control status of all files under the directory DIR.
1739 With a single prefix argument, all registered files are listed.
1740 With two prefix arguments, only files you have checked out are listed.
1741
1742 Files are listed in a dired buffer, in `vc-dired-mode'."
1743   (interactive "DVC status of directory: \nP")
1744
1745   ;; Determine value of verbose flag from prefix arg
1746   (setq verbose (cond ((equal '(4) verbose) 'all)
1747                       ((equal '(16) verbose) 'yours)
1748                       (t nil)))
1749
1750   (if (null dir) (setq dir default-directory))
1751
1752   (let* (nonempty
1753          dired-buf
1754          (default-directory dir)
1755          (filelist (vc-list-registered-files verbose t)))
1756     (if filelist
1757         (save-excursion
1758           ;; This uses a semi-documented feature of dired; giving a switch
1759           ;; argument forces the buffer to refresh each time.
1760           (message "Reading directory entries...")
1761           ;; Because ClearCase lists the views the files were found in, the
1762           ;; top-level of the directory tree must be root.
1763           (let ((uniquify-buffer-name-style nil)
1764                 (files (mapcar 'car filelist))) ;; shut off uniquify temporarily
1765             (dired (cons (find-base-dir files)
1766                          (nreverse files))
1767                    vc-dired-listing-switches))
1768           (message "Reading directory entries...done")
1769           (setq dired-buf (current-buffer))
1770           (rename-buffer (generate-new-buffer-name 
1771                           (concat "VC:" (or (vc-cc-relpath dir) dir))))
1772           (setq nonempty (not (zerop (buffer-size))))))
1773     (if nonempty
1774         (progn
1775           (pop-to-buffer dired-buf)
1776           (setq vc-dired-mode t
1777                 vc-mode " under VC")
1778           (vc-reformat-dired-buffer filelist)
1779           )
1780
1781       (message "No files are currently %s under %s"
1782                (cond ((eq 'all verbose) "registered")
1783                      ((eq 'yours verbose) "locked by you")
1784                      (t "locked"))
1785                default-directory))
1786     ))
1787
1788 ;; Emacs 18 version
1789 (defun vc-directory-18 (dir verbose)
1790   "Show version-control status of all files under the directory DIR.
1791 With a single prefix argument, all registered files are listed.
1792 With two prefix arguments, only files you have checked out are listed.
1793
1794 Files are listed in a plain buffer, with the name of the locking user."
1795   (interactive "DVC status of directory: \nP")
1796
1797   ;; Determine value of verbose flag from prefix arg
1798   (setq verbose (cond ((equal '(4) verbose) 'all)
1799                       ((equal '(16) verbose) 'yours)
1800                       (t nil)))
1801
1802   (if (null dir) (setq dir default-directory))
1803
1804   (let ((default-directory dir)
1805         (action (cond ((eq 'all verbose) "registered")
1806                       ((eq 'yours verbose) "locked by you")
1807                       (t "locked"))))
1808     (save-excursion
1809       (set-buffer (get-buffer-create "*vc-status*"))
1810       (erase-buffer)
1811       (cd dir)
1812       (insert "Files " action " under " default-directory "\n\n")
1813       (display-buffer "*vc-status*")
1814       (sit-for 0)
1815
1816       ;; Map over the file list and print
1817       (let ((filelist (vc-list-registered-files verbose t default-directory)))
1818         (if filelist
1819             (progn
1820               (mapcar
1821                (function (lambda (f)
1822                            (let ((user (cdr f)) (f (car f)))
1823                              (if (cond ((null verbose) user)
1824                                        ((eq verbose 'all))
1825                                        ((eq verbose 'yours) (equal user (user-login-name))))
1826                                  (progn
1827                                    (insert (format
1828                                             "%s      %s\n"
1829                                             (concat user) f)))))))
1830                filelist)
1831
1832               (pop-to-buffer "*vc-status*" t)
1833               (goto-char (point-min))
1834               (shrink-window-if-larger-than-buffer))
1835           (message "No files are currently %s under %s"
1836                    action default-directory)))
1837       )))
1838
1839 (cond ((string-lessp emacs-version "18")
1840        (fset 'vc-directory 'vc-directory-18)
1841        ;; Emacs 18 also lacks these.
1842        (or (boundp 'compilation-old-error-list)
1843            (setq compilation-old-error-list nil))
1844        )
1845       ;; XEmacs with efs does work
1846       ((and (string-match "Lucid" emacs-version)
1847             (or (and
1848                  (= emacs-major-version 19)
1849                  (<= emacs-minor-version 14))
1850                 (< emacs-major-version 19)))
1851        ;; lucid emacs does not have the new dired yet
1852        (fset 'vc-directory 'vc-directory-18)
1853        )
1854       )
1855
1856 ;; Named-configuration support for SCCS
1857
1858 (defun vc-add-triple (name file rev)
1859   (save-excursion
1860     (find-file (concat (vc-backend-subdirectory-name file) "/" vc-name-assoc-file))
1861     (goto-char (point-max))
1862     (insert name "\t:\t" file "\t" rev "\n")
1863     (basic-save-buffer)
1864     (kill-buffer (current-buffer))
1865     ))
1866
1867 (defun vc-record-rename (file newname)
1868   (save-excursion
1869     (find-file (concat (vc-backend-subdirectory-name file) "/" vc-name-assoc-file))
1870     (goto-char (point-min))
1871     ;; (replace-regexp (concat ":" (regexp-quote file) "$") (concat ":" newname))
1872     (while (re-search-forward (concat ":" (regexp-quote file) "$") nil t)
1873       (replace-match (concat ":" newname) nil nil))
1874     (basic-save-buffer)
1875     (kill-buffer (current-buffer))
1876     ))
1877
1878 (defun vc-lookup-triple (file name)
1879   ;; Return the numeric version corresponding to a named snapshot of file
1880   ;; If name is nil or a version number string it's just passed through
1881   (cond ((null name) name)
1882         ((let ((firstchar (aref name 0)))
1883            (and (>= firstchar ?0) (<= firstchar ?9)))
1884          name)
1885         (t
1886          (car (vc-master-info
1887                (concat (vc-backend-subdirectory-name file) "/" vc-name-assoc-file)
1888                (list (concat name "\t:\t" file "\t\\(.+\\)"))))
1889          )))
1890
1891 ;; Named-configuration entry points
1892
1893 (defun vc-locked-example ()
1894   ;; Return an example of why the current directory is not ready to be snapshot
1895   ;; or nil if no such example exists.
1896   (catch 'vc-locked-example
1897     (vc-file-tree-walk
1898      (function (lambda (f)
1899                  (if (and (vc-registered f) (vc-locking-user f))
1900                      (throw 'vc-locked-example f)))))
1901     nil))
1902
1903 ;;;dont ###autoload, it conflicts with vc.el
1904 (defun vc-create-snapshot (name)
1905   "Make a snapshot called NAME.
1906 The snapshot is made from all registered files at or below the current
1907 directory.  For each file, the version level of its latest
1908 version becomes part of the named configuration."
1909   (interactive "sNew snapshot name: ")
1910   (let ((locked (vc-locked-example)))
1911     (if locked
1912         (error "File %s is locked" locked)
1913       (progn
1914         (vc-backend-define-name default-directory name)
1915         (vc-file-tree-walk
1916           (function (lambda (f) (and
1917                                  (vc-name f)
1918                                  (vc-backend-assign-name f name)))))
1919       ))))
1920
1921 ;;;dont ###autoload, it conflicts with vc.el
1922 (defun vc-assign-name (name)
1923   "Assign a NAME to the current file version.
1924 In vc-dired-mode all marked files are labeled."
1925   (interactive (list (vc-read-label "Label: ")))
1926   (let ((filelist
1927          (if vc-dired-mode (dired-get-marked-files)
1928                 (list (buffer-file-name))))
1929         file)
1930     (while filelist
1931       (setq file (car filelist) filelist (cdr filelist))
1932       (if (and (vc-registered file) (vc-locking-user file))
1933           (error "File %s is locked" file)
1934         (vc-backend-assign-name file name))
1935       )))
1936
1937 (defun vc-read-label (prompt)
1938   "Read a label name."
1939   (if (eq (vc-backend-deduce default-directory) '@@)
1940       (let* ((string (vc-cleartool-cmd default-directory
1941                                        "lstype -kind lbtype -short"))
1942              labels)
1943         (mapcar (function (lambda (arg)
1944                             (if (string-match "(locked)" arg)
1945                                 nil
1946                               (setq labels (cons (list arg) labels)))))
1947                 (split-string string "\n"))
1948         (completing-read prompt labels nil t))
1949     ;; Otherwise, just read any string
1950     (read-string prompt)
1951     ))
1952
1953 ;;;dont ###autoload, it conflicts with vc.el
1954 (defun vc-retrieve-snapshot (name)
1955   "Retrieve the snapshot called NAME.
1956 This function fails if any files are locked at or below the current directory
1957 Otherwise, all registered files are checked out (unlocked) at their version
1958 levels in the snapshot."
1959   (interactive "sSnapshot name to retrieve: ")
1960   (let ((locked (vc-locked-example)))
1961     (if locked
1962         (error "File %s is locked" locked)
1963       (vc-file-tree-walk
1964        (function (lambda (f) (and
1965                               (vc-name f)
1966                               (vc-error-occurred
1967                                (vc-backend-checkout f nil name))))))
1968       )))
1969
1970 ;; Miscellaneous other entry points
1971
1972 ;;;dont ###autoload, it conflicts with vc.el
1973 (defun vc-print-log ()
1974   "List the change log of the current buffer in a window."
1975   (interactive)
1976   (if vc-dired-mode
1977       (set-buffer (find-file-noselect (dired-get-filename))))
1978   (while vc-parent-buffer
1979     (pop-to-buffer vc-parent-buffer))
1980   (if (and buffer-file-name (vc-name buffer-file-name))
1981       (let ((file buffer-file-name))
1982         (vc-backend-print-log file)
1983         (pop-to-buffer (get-buffer-create "*vc*"))
1984         (setq default-directory (file-name-directory file))
1985         (while (looking-at "=*\n")
1986           (delete-char (- (match-end 0) (match-beginning 0)))
1987           (forward-line -1))
1988         (goto-char (point-min))
1989         (if (looking-at "[\b\t\n\v\f\r ]+")
1990             (delete-char (- (match-end 0) (match-beginning 0))))
1991         (shrink-window-if-larger-than-buffer)
1992         )
1993     (vc-registration-error buffer-file-name)))
1994
1995 ;;;dont ###autoload, it conflicts with vc.el
1996 (defun vc-revert-buffer ()
1997   "Revert the current buffer's file back to the latest checked-in version.
1998 This asks for confirmation if the buffer contents are not identical
1999 to that version.
2000 If the back-end is CVS, this will give you the most recent revision of
2001 the file on the branch you are editing."
2002   (interactive)
2003   (while vc-parent-buffer
2004     (pop-to-buffer vc-parent-buffer))
2005   (let (filelist file changed keep-buffer new-buffer
2006         (obuf (current-buffer)))
2007
2008     (if vc-dired-mode
2009         (setq filelist (dired-get-marked-files))
2010       (setq filelist (list (buffer-file-name))))
2011
2012     (while filelist
2013       (setq file (car filelist) filelist (cdr filelist)
2014             changed nil)
2015
2016       (if (file-directory-p file)
2017           (setq new-buffer nil keep-buffer t)
2018
2019         ;; Otherwise find the file
2020         (setq new-buffer (find-buffer-visiting file))
2021
2022         (if new-buffer
2023             (setq keep-buffer t)
2024           (setq new-buffer (find-file-noselect file)
2025                 keep-buffer nil))
2026
2027         (set-buffer new-buffer)
2028         )
2029
2030       (if (or
2031            (not (vc-name file))
2032            (not (equal (vc-locking-user file) (user-login-name)))
2033            (and (not (file-directory-p file))
2034                 (setq changed (vc-diff nil t))
2035                 (or vc-suppress-confirm
2036                     (not (yes-or-no-p "Discard changes? ")))))
2037           (progn
2038             (unless keep-buffer (kill-buffer new-buffer))
2039             (message "Revert of %s cancelled" file))
2040         (set-buffer obuf)
2041         (if changed
2042             (delete-window))
2043         (vc-backend-revert file)
2044         (vc-resynch-window file t t)
2045         (if keep-buffer
2046             (if new-buffer (progn (set-buffer new-buffer) (revert-buffer nil t)))
2047           (kill-buffer new-buffer))
2048
2049         ;; See if we can keep dired up-to-date
2050         (if (fboundp 'dired-relist-file)
2051             (dired-relist-file file)
2052           ))
2053       )))
2054
2055 ;;;dont ###autoload, it conflicts with vc.el
2056 (defun vc-cancel-version (norevert)
2057   "Get rid of most recently checked in version of this file.
2058 A prefix argument means do not revert the buffer afterwards."
2059   (interactive "P")
2060   (if vc-dired-mode
2061       (find-file-other-window (dired-get-filename)))
2062   (while vc-parent-buffer
2063     (pop-to-buffer vc-parent-buffer))
2064   (let* ((target (concat (vc-latest-version (buffer-file-name))))
2065          (yours (concat (vc-your-latest-version (buffer-file-name))))
2066          (prompt (if (string-equal yours target)
2067                      "Remove your version %s from master? "
2068                    "Version %s was not your change.  Remove it anyway? ")))
2069     (if (null (yes-or-no-p (format prompt target)))
2070         nil
2071       (vc-backend-uncheck (buffer-file-name) target)
2072       (if (or norevert
2073               (not (yes-or-no-p "Revert buffer to most recent remaining version? ")))
2074           (vc-mode-line (buffer-file-name))
2075         (vc-checkout (buffer-file-name) nil)))
2076     ))
2077
2078 ;;;dont ###autoload, it conflicts with vc.el
2079 (defun vc-rename-file (old new)
2080   "Rename file OLD to NEW, and rename its master file likewise."
2081   (interactive "fVC rename file: \nFRename to: ")
2082   ;; There are several ways of renaming files under CVS 1.3, but they all
2083   ;; have serious disadvantages.  See the FAQ (available from think.com in
2084   ;; pub/cvs/).  I'd rather send the user an error, than do something he might
2085   ;; consider to be wrong.  When the famous, long-awaited rename database is
2086   ;; implemented things might change for the better.  This is unlikely to occur
2087   ;; until CVS 2.0 is released.  --ceder 1994-01-23 21:27:51
2088   (if (eq (vc-backend-deduce old) 'CVS)
2089       (error "Renaming files under CVS is dangerous and not supported in VC."))
2090   (if (eq (vc-backend-deduce old) '@@)
2091       (error "VC's ClearCase support cannot rename files."))
2092   (let ((oldbuf (get-file-buffer old)))
2093     (if (and oldbuf (buffer-modified-p oldbuf))
2094         (error "Please save files before moving them"))
2095     (if (get-file-buffer new)
2096         (error "Already editing new file name"))
2097     (if (file-exists-p new)
2098         (error "New file already exists"))
2099     (let ((oldmaster (vc-name old)))
2100       (if oldmaster
2101           (progn
2102             (if (vc-locking-user old)
2103                 (error "Please check in files before moving them"))
2104             (if (or (file-symlink-p oldmaster)
2105                     ;; This had FILE, I changed it to OLD. -- rms.
2106                     (file-symlink-p (vc-backend-subdirectory-name old)))
2107                 (error "This is not a safe thing to do in the presence of symbolic links"))
2108             (rename-file
2109              oldmaster
2110              (let ((backend (vc-backend-deduce old))
2111                    (newdir (or (file-name-directory new) ""))
2112                    (newbase (file-name-nondirectory new)))
2113                (catch 'found
2114                  (mapcar
2115                   (function
2116                    (lambda (s)
2117                      (if (eq backend (cdr s))
2118                          (let* ((newmaster (format (car s) newdir newbase))
2119                                 (newmasterdir (file-name-directory newmaster)))
2120                            (if (or (not newmasterdir)
2121                                    (file-directory-p newmasterdir))
2122                                (throw 'found newmaster))))))
2123                   vc-master-templates)
2124                  (error "New file lacks a version control directory"))))))
2125       (if (or (not oldmaster) (file-exists-p old))
2126           (rename-file old new)))
2127     ;; ?? Renaming a file might change its contents due to keyword expansion.
2128     ;; We should really check out a new copy if the old copy was precisely equal
2129     ;; to some checked in version.  However, testing for this is tricky....
2130     (if oldbuf
2131         (save-excursion
2132           (set-buffer oldbuf)
2133           (set-visited-file-name new)
2134           (set-buffer-modified-p nil))))
2135   ;; This had FILE, I changed it to OLD. -- rms.
2136   (vc-backend-dispatch old
2137     (vc-record-rename old new)          ;SCCS
2138     ;; #### - This CAN kinda be done for both rcs and
2139     ;; cvs.  It needs to be implemented. -- Stig
2140     nil                                 ;RCS
2141     nil                                 ;CVS
2142     nil                                 ;CC
2143     )
2144   )
2145
2146 ;;;dont ###autoload, it conflicts with vc.el
2147 (defun vc-update-change-log (&rest args)
2148   "Find change log file and add entries from recent RCS logs.
2149 The mark is left at the end of the text prepended to the change log.
2150 With prefix arg of C-u, only find log entries for the current buffer's file.
2151 With any numeric prefix arg, find log entries for all files currently visited.
2152 Otherwise, find log entries for all registered files in the default directory.
2153 >From a program, any arguments are passed to the `rcs2log' script."
2154   (interactive
2155    (cond ((consp current-prefix-arg)    ;C-u
2156           (list buffer-file-name))
2157          (current-prefix-arg            ;Numeric argument.
2158           (let ((files nil)
2159                 (buffers (buffer-list))
2160                 file)
2161             (while buffers
2162               (setq file (buffer-file-name (car buffers)))
2163               (and file (vc-backend-deduce file)
2164                    (setq files (cons file files)))
2165               (setq buffers (cdr buffers)))
2166             files))
2167          (t
2168           (let ((RCS (concat default-directory "RCS")))
2169             (and (file-directory-p RCS)
2170                  (mapcar (function
2171                           (lambda (f)
2172                             (if (string-match "\\(.*\\),v$" f)
2173                                 (substring f 0 (match-end 1))
2174                               f)))
2175                          (directory-files RCS nil "...\\|^[^.]\\|^.[^.]")))))))
2176   (let ((odefault default-directory))
2177     (find-file-other-window (find-change-log))
2178     (barf-if-buffer-read-only)
2179     (vc-buffer-sync)
2180     (undo-boundary)
2181     (goto-char (point-min))
2182     (push-mark)
2183     (message "Computing change log entries...")
2184     (message "Computing change log entries... %s"
2185              (if (or (null args)
2186                      (eq 0 (apply 'call-process "rcs2log" nil t nil
2187                                   "-n"
2188                                   (user-login-name)
2189                                   (user-full-name)
2190                                   user-mail-address
2191                                   (mapcar (function
2192                                            (lambda (f)
2193                                              (file-relative-name
2194                                               (if (file-name-absolute-p f)
2195                                                   f
2196                                                 (concat odefault f)))))
2197                                           args))))
2198                  "done" "failed"))))
2199
2200 ;; Functions for querying the master and lock files.
2201
2202 (defun vc-match-substring (bn)
2203   (buffer-substring (match-beginning bn) (match-end bn)))
2204
2205 (defun vc-parse-buffer (patterns &optional file properties nodates)
2206   ;; Each pattern is of the form:
2207   ;;    regex                ; subex is 1, and date-subex is 2 (or nil)
2208   ;;    (regex subex date-subex)
2209   ;;
2210   ;; Use PATTERNS to parse information out of the current buffer by matching
2211   ;; each REGEX in the list and the returning the string matched by SUBEX.
2212   ;; If a DATE-SUBEX is present, then the SUBEX from the match with the
2213   ;; highest value for DATE-SUBEX (string comparison is used) will be
2214   ;; returned.
2215   ;;
2216   ;; If FILE and PROPERTIES are given, the latter must be a list of
2217   ;; properties of the same length as PATTERNS; each property is assigned
2218   ;; the corresponding value.
2219   (mapcar (function (lambda (p)
2220              (goto-char (point-min))
2221              (if (and (not nodates) (string-match "\\\\(.*\\\\(" p))
2222                  (let ((latest-date "") (latest-val))
2223                    (while (re-search-forward p nil t)
2224                      (let ((date (vc-match-substring 2)))
2225                        (if (string< latest-date date)
2226                            (progn
2227                              (setq latest-date date)
2228                              (setq latest-val
2229                                    (vc-match-substring 1))))))
2230                    latest-val))
2231              (prog1
2232                  (let ((value nil))
2233                    (if (re-search-forward p nil t)
2234                        (setq value (vc-match-substring 1)))
2235                         (if file
2236                             (vc-file-setprop file (car properties) value))
2237                    value)
2238                (setq properties (cdr properties)))))
2239           patterns)
2240   )
2241
2242 (defun vc-master-info (file fields &optional rfile properties)
2243   ;; Search for information in a master file.
2244   (if (and file (file-exists-p file))
2245       (save-excursion
2246         (let ((buf))
2247           (setq buf (create-file-buffer file))
2248           (set-buffer buf))
2249         (erase-buffer)
2250         (insert-file-contents file nil)
2251         (set-buffer-modified-p nil)
2252         (auto-save-mode nil)
2253         (prog1
2254             (vc-parse-buffer fields rfile properties)
2255           (kill-buffer (current-buffer)))
2256         )
2257     (if rfile
2258         (mapcar
2259          (function (lambda (p) (vc-file-setprop rfile p nil)))
2260          properties))
2261     )
2262   )
2263
2264 (defun vc-log-info (command file last flags patterns &optional properties nodates)
2265   ;; Search for information in log program output
2266   (if (and file (file-exists-p file))
2267       (save-excursion
2268         (let ((buf))
2269           (setq buf (get-buffer-create "*vc*"))
2270           (set-buffer buf)
2271           ;; Special case for cleartool commands
2272           (if (string-equal command "cleartool")
2273               (insert (vc-cleartool-cmd file
2274                        ;; Concatenate each flag and the file name into a
2275                        ;; single space separated string.
2276                        (mapconcat 'identity (nconc flags (list file)) " ")))
2277             (apply 'vc-do-command 0 command file last flags))
2278           (set-buffer-modified-p nil)
2279           (prog1
2280               (vc-parse-buffer patterns file properties nodates)
2281             (kill-buffer buf))))
2282     (if file
2283         (mapcar
2284          (function (lambda (p) (vc-file-setprop file p nil)))
2285          properties))))
2286
2287 ;;;dont ###autoload, it conflicts with vc.el
2288 (defun vc-locking-user (file)
2289   "Return the name of the person currently holding a lock on FILE.
2290 Return nil if there is no such person.
2291 Under CVS, a file is considered locked if it has been modified since it
2292 was checked out...even though it may well be writable by you."
2293   (setq file (expand-file-name file))   ; use full pathname
2294   (cond ((eq (vc-backend-deduce file) 'CVS)
2295          (if (vc-workfile-unchanged-p file t)
2296              nil
2297            ;; XEmacs - ahead of the pack...
2298            (user-login-name (nth 2 (file-attributes file)))))
2299         (t
2300          ;; #### - this can probably be cleaned up as a result of the changes to
2301          ;; user-login-name...
2302          (if (or (not vc-keep-workfiles)
2303                  (eq vc-mistrust-permissions 't)
2304                  (and vc-mistrust-permissions
2305                       (funcall vc-mistrust-permissions (vc-backend-subdirectory-name
2306                                                         file)))
2307                  (vc-file-newer file))
2308              (vc-true-locking-user file)
2309            ;; This implementation assumes that any file which is under version
2310            ;; control and has -rw-r--r-- is locked by its owner.  This is true
2311            ;; for both RCS and SCCS, which keep unlocked files at -r--r--r--.
2312            ;; We have to be careful not to exclude files with execute bits on;
2313            ;; scripts can be under version control too.  Also, we must ignore
2314            ;; the group-read and other-read bits, since paranoid users turn them off.
2315            ;; This hack wins because calls to the very expensive vc-fetch-properties
2316            ;; function only have to be made if (a) the file is locked by someone
2317            ;; other than the current user, or (b) some untoward manipulation
2318            ;; behind vc's back has changed the owner or the `group' or `other'
2319            ;; write bits.
2320            (let ((attributes (file-attributes file)))
2321              (cond ((string-match ".r-..-..-." (nth 8 attributes))
2322                     nil)
2323