Remove old and crusty tooltalk pkg
[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                    ((and (= (nth 2 attributes) (user-uid))
2324                          (string-match ".rw..-..-." (nth 8 attributes)))
2325                     (user-login-name))
2326                    (t
2327                     (vc-true-locking-user file)))) ; #### - this looks recursive!!!
2328            ))))
2329
2330 (defun vc-true-locking-user (file)
2331   ;; The slow but reliable version
2332   (vc-fetch-properties file)
2333   (vc-file-getprop file 'vc-locking-user))
2334
2335 ;;;dont ###autoload, it conflicts with vc.el
2336 (defun vc-latest-version (file)
2337   ;; Return version level of the latest version of FILE
2338   (vc-fetch-properties file)
2339   (vc-file-getprop file 'vc-latest-version))
2340
2341 (defun vc-your-latest-version (file)
2342   ;; Return version level of the latest version of FILE checked in by you
2343   (vc-fetch-properties file)
2344   (vc-file-getprop file 'vc-your-latest-version))
2345
2346 (defun vc-cc-previous-version (file version)
2347   (let ((ext-name (if version
2348                       (vc-cc-build-version file version)
2349                     file)))
2350     (vc-fetch-properties ext-name )
2351     (vc-file-getprop ext-name 'vc-pred-version)))
2352
2353 ;; Collect back-end-dependent stuff here
2354 ;;
2355 ;; Everything eventually funnels through these functions.  To implement
2356 ;; support for a new version-control system, add another branch to the
2357 ;; vc-backend-dispatch macro and fill it in in each call.  The variable
2358 ;; vc-master-templates in vc-hooks.el will also have to change.
2359
2360 (put 'vc-backend-dispatch 'lisp-indent-function 'defun)
2361
2362 (defmacro vc-backend-dispatch (f s r c a)
2363   "Execute FORM1, FORM2, FORM3 or FORM4 depending whether we're using
2364 SCCS, RCS, CVS or ClearCase.
2365 If FORM3 is RCS, use FORM2 even if we are using CVS.  (CVS shares some code
2366 with RCS)."
2367   (list 'let (list (list 'type (list 'vc-backend-deduce f)))
2368         (list 'cond
2369               (list (list 'eq 'type (quote 'SCCS)) s) ; SCCS
2370               (list (list 'eq 'type (quote 'RCS)) r) ; RCS
2371               (list (list 'eq 'type (quote 'CVS)) ; CVS
2372                     (if (eq c 'RCS) r c))
2373               (list (list 'eq 'type (quote '@@)) a) ; CC
2374               )))
2375
2376 (defun vc-lock-file (file)
2377   ;; Generate lock file name corresponding to FILE
2378   (let ((master (vc-name file)))
2379     (and
2380      master
2381      (string-match "\\(.*/\\)s\\.\\(.*\\)" master)
2382      (concat
2383       (substring master (match-beginning 1) (match-end 1))
2384       "p."
2385       (substring master (match-beginning 2) (match-end 2))))))
2386
2387
2388 (defun vc-fetch-properties (file)
2389   ;; Re-fetch all properties associated with the given file.
2390   ;; Currently these properties are:
2391   ;;   vc-locking-user
2392   ;;   vc-locked-version
2393   ;;   vc-latest-version
2394   ;;   vc-your-latest-version
2395   ;;   vc-cvs-status (cvs only)
2396   ;;   vc-cc-predecessor (ClearCase only)
2397   (vc-backend-dispatch
2398     file
2399     ;; SCCS
2400     (progn
2401       (vc-master-info (vc-lock-file file)
2402                       (list
2403                        "^[^ ]+ [^ ]+ \\([^ ]+\\)"
2404                        "^\\([^ ]+\\)")
2405                       file
2406                       '(vc-locking-user vc-locked-version))
2407       (vc-master-info (vc-name file)
2408                       (list
2409                        "^\001d D \\([^ ]+\\)"
2410                        (concat "^\001d D \\([^ ]+\\) .* "
2411                                (regexp-quote (user-login-name)) " ")
2412                        )
2413                       file
2414                       '(vc-latest-version vc-your-latest-version))
2415       )
2416     ;; RCS
2417     (vc-log-info "rlog" file 'MASTER nil
2418                  (list
2419                   "^locks: strict\n\t\\([^:]+\\)"
2420                   "^locks: strict\n\t[^:]+: \\(.+\\)"
2421                   "^revision[\t ]+\\([0-9.]+\\).*\ndate: \\([ /0-9:]+\\);"
2422                   (concat
2423                    "^revision[\t ]+\\([0-9.]+\\)\n.*author: "
2424                    (regexp-quote (user-login-name))
2425                    ";"))
2426                  '(vc-locking-user vc-locked-version
2427                                    vc-latest-version vc-your-latest-version))
2428     ;; CVS
2429     ;; Don't fetch vc-locking-user and vc-locked-version here, since they
2430     ;; should always be nil anyhow.  Don't fetch vc-your-latest-version, since
2431     ;; that is done in vc-find-cvs-master.
2432     (vc-log-info
2433      "cvs" file 'WORKFILE '("status")
2434      ;; CVS 1.3 says "RCS Version:", other releases "RCS Revision:",
2435      ;; and CVS 1.4a1 says "Repository revision:".  The regexp below
2436      ;; matches much more, but because of the way vc-log-info is
2437      ;; implemented it is impossible to use additional groups.
2438      '(("\\(RCS Version\\|RCS Revision\\|Repository revision\\):[\t ]+\\([0-9.]+\\)" 2)
2439        "Status: \\(.*\\)")
2440      '(vc-latest-version
2441        vc-cvs-status))
2442     ;; CC
2443    (progn
2444      (vc-file-setprop file 'vc-need-pre-checkout-message t)
2445      (vc-log-info "cleartool" file nil (list "describe" file)
2446                   (list
2447                    "checked out .* by .* (\\([^ .]+\\)..*@.*)"
2448                    "from \\([^ ]+\\) (reserved)"
2449                    "version [^\"]*\".*@@\\([^ ]+\\)\""
2450 ;;                   "version [^\"]*\".*@@\\([^ ]+\\)\""
2451                    "predecessor version: \\([^ ]+\\)\n")
2452                   '(vc-locking-user
2453                     vc-locked-version
2454                     vc-latest-version
2455 ;;                    vc-your-latest-version
2456                     vc-cc-predecessor))
2457      ;; Rather than search twice, why not just set the property manually
2458      (vc-file-setprop file 'vc-your-latest-version
2459                       (vc-file-getprop file 'vc-latest-version))
2460      )
2461    ))
2462
2463
2464 (defun vc-backend-subdirectory-name (&optional file)
2465   ;; Where the master and lock files for the current directory are kept
2466   (let ((backend
2467          (or
2468           (and file (vc-backend-deduce file))
2469           vc-default-back-end
2470           (setq vc-default-back-end (if (vc-find-binary "rcs") 'RCS 'SCCS)))))
2471     (cond
2472      ((eq backend 'SCCS) "SCCS")
2473      ((eq backend 'RCS)  "RCS")
2474      ((eq backend 'CVS)  "CVS")
2475      ((eq backend '@@)   "@@"))
2476     ))
2477
2478 (defun vc-backend-admin (file &optional writable rev workfile comment)
2479   ;; Register a file into the version-control system
2480   ;; Automatically retrieves a read-only version of the file with
2481   ;; keywords expanded if vc-keep-workfiles is non-nil, otherwise
2482   ;; it deletes the workfile.
2483   (vc-file-clearprops file)
2484   (or vc-default-back-end
2485       (setq vc-default-back-end (if (vc-find-binary "rcs") 'RCS 'SCCS)))
2486   (message "Registering %s..." file)
2487   (let ((backend
2488          (cond
2489           ((file-exists-p (vc-backend-subdirectory-name)) vc-default-back-end)
2490           ((file-exists-p "RCS") 'RCS)
2491           ((file-exists-p "SCCS") 'SCCS)
2492           ((file-exists-p "CVS") 'CVS)
2493           ((file-exists-p "@@") '@@)
2494           (t vc-default-back-end))))
2495     (cond ((eq backend 'SCCS)
2496            (vc-do-command 0 "admin" file 'MASTER ; SCCS
2497                           (and rev (concat "-r" rev))
2498                           "-fb"
2499                           (concat "-i" file)
2500                           (and comment (concat "-y" comment))
2501                           (format
2502                            (car (rassq 'SCCS vc-master-templates))
2503                            (or (file-name-directory file) "")
2504                            (file-name-nondirectory file)))
2505            (delete-file file)
2506            (if vc-keep-workfiles
2507                (vc-do-command 0 "get" file 'MASTER)))
2508           ((eq backend 'RCS)
2509            (vc-do-command 0 "ci" file 'MASTER ; RCS
2510                           (concat (if vc-keep-workfiles "-u" "-r") rev)
2511                           (and comment (concat "-t-" comment))
2512                           file))
2513           ((eq backend 'CVS)
2514            ;; #### - should maybe check to see if the master file is
2515            ;; already in the repository...in which case we need to add the
2516            ;; appropriate branch tag and do  an update.
2517            ;; #### - note that adding a file is a 2 step process in CVS...
2518            (vc-do-command 0 "cvs" file 'WORKFILE "add")
2519            (vc-do-command 0 "cvs" file 'WORKFILE "commit"
2520                           (and comment (not (string= comment ""))
2521                                (concat "-m" comment)))
2522            )
2523           ((eq backend '@@)
2524            (if vc-checkin-on-register
2525                (vc-do-cleartool-command "mkelem" file comment "-ci")
2526              (vc-do-cleartool-command "mkelem" file comment)
2527              ;; clearcase mkelem leaves file checked out!
2528              (vc-file-setprop file 'vc-checkout-time '(0 . 0))))
2529           (t (error "Backend %s unknown!" backend))))
2530   (message "Registering %s...done" file)
2531   ;; See if we can keep dired up-to-date
2532   (if (fboundp 'dired-relist-file)
2533       (dired-relist-file file))
2534   )
2535
2536 (defun vc-backend-checkout (file &optional writable rev workfile comment)
2537   ;; Retrieve a copy of a saved version into a workfile
2538   (let ((filename (or workfile file)))
2539     (message "Checking out %s..." filename)
2540     (save-excursion
2541       ;; Clean up comment prior to checkout (in case user ci's outside vc-cc)
2542       (setq comment (vc-cleanup-comment comment nil))
2543       ;; Change buffers to get local value of vc-checkout-switches.
2544       (set-buffer (or (get-file-buffer file) (current-buffer)))
2545       (vc-backend-dispatch
2546         file
2547         ;; SCCS
2548         (if workfile
2549             ;; Some SCCS implementations allow checking out directly to a
2550             ;; file using the -G option, but then some don't so use the
2551             ;; least common denominator approach and use the -p option
2552             ;; ala RCS.
2553             (let ((vc-modes (logior (file-modes (vc-name file))
2554                                     (if writable 128 0)))
2555                   (failed t))
2556               (unwind-protect
2557                   (progn
2558                     (apply 'vc-do-command
2559                            0 "/bin/sh" file 'MASTER "-c"
2560                            ;; Some shells make the "" dummy argument into $0
2561                            ;; while others use the shell's name as $0 and
2562                            ;; use the "" as $1.  The if-statement
2563                            ;; converts the latter case to the former.
2564                            (format "if [ x\"$1\" = x ]; then shift; fi; \
2565                               umask %o; exec >\"$1\" || exit; \
2566                                shift; umask %o; exec get \"$@\""
2567                                    (logand 511 (lognot vc-modes))
2568                                    (logand 511 (lognot (default-file-modes))))
2569                            ""           ; dummy argument for shell's $0
2570                            filename
2571                            (if writable "-e")
2572                            "-p" (and rev
2573                                      (concat "-r" (vc-lookup-triple file rev)))
2574                            vc-checkout-switches)
2575                     (setq failed nil))
2576                 (and failed (file-exists-p filename) (delete-file filename))))
2577           (apply 'vc-do-command 0 "get" file 'MASTER ; SCCS
2578                  (if writable "-e")
2579                  (and rev (concat "-r" (vc-lookup-triple file rev)))
2580                  vc-checkout-switches))
2581         ;; RCS
2582         (if workfile
2583             ;; RCS doesn't let us check out into arbitrary file names directly.
2584             ;; Use `co -p' and make stdout point to the correct file.
2585             (let ((vc-modes (logior (file-modes (vc-name file))
2586                                     (if writable 128 0)))
2587                   (failed t))
2588               (unwind-protect
2589                   (progn
2590                     (apply 'vc-do-command
2591                            0 "/bin/sh" file 'MASTER "-c"
2592                            ;; See the SCCS case, above, regarding the
2593                            ;; if-statement.
2594                            (format "if [ x\"$1\" = x ]; then shift; fi; \
2595                               umask %o; exec >\"$1\" || exit; \
2596                                shift; umask %o; exec co \"$@\""
2597                                    (logand 511 (lognot vc-modes))
2598                                    (logand 511 (lognot (default-file-modes))))
2599                            ""           ; dummy argument for shell's $0
2600                            filename
2601                            (if writable "-l")
2602                            (concat "-p" rev)
2603                            vc-checkout-switches)
2604                     (setq failed nil))
2605                 (and failed (file-exists-p filename) (delete-file filename))))
2606           (apply 'vc-do-command 0 "co" file 'MASTER
2607                  (if writable "-l")
2608                  (and rev (concat "-r" rev))
2609                  vc-checkout-switches))
2610         ;; CVS
2611         (if workfile
2612             ;; CVS is much like RCS
2613             (let ((failed t))
2614               (unwind-protect
2615                   (progn
2616                     (apply 'vc-do-command
2617                            0 "/bin/sh" file 'WORKFILE "-c"
2618                            "exec >\"$1\" || exit; shift; exec cvs update \"$@\""
2619                            ""           ; dummy argument for shell's $0
2620                            workfile
2621                            (concat "-r" rev)
2622                            "-p"
2623                            vc-checkout-switches)
2624                     (setq failed nil))
2625                 (and failed (file-exists-p filename) (delete-file filename))))
2626           (apply 'vc-do-command 0 "cvs" file 'WORKFILE
2627                  "update"
2628                  (and rev (concat "-r" rev))
2629                  file
2630                  vc-checkout-switches))
2631         ;; CC
2632        (if writable
2633             (vc-do-cleartool-command "co" file
2634                       comment
2635                       (and rev "-branch")
2636                       rev
2637                       vc-checkout-switches))
2638         ))
2639     (or workfile
2640         (vc-file-setprop file
2641                          'vc-checkout-time (nth 5 (file-attributes file))))
2642     (message "Checking out %s...done" filename))
2643   ;; See if we can keep dired up-to-date
2644   (if (fboundp 'dired-relist-file)
2645       (dired-relist-file file))
2646   )
2647
2648
2649 (defun vc-backend-logentry-check (file)
2650   (vc-backend-dispatch file
2651     (if (>= (buffer-size) 512)          ; SCCS
2652         (progn
2653           (goto-char 512)
2654           (error
2655            "Log must be less than 512 characters; point is now at pos 512")))
2656     nil                                 ; RCS
2657     nil                                 ; CVS
2658     nil)                                ; CC
2659   )
2660
2661 (defun vc-backend-checkin (file &optional writable rev workfile comment)
2662   ;; Register changes to FILE as level REV with explanatory COMMENT.
2663   ;; Automatically retrieves a read-only version of the file with
2664   ;; keywords expanded if vc-keep-workfiles is non-nil, otherwise
2665   ;; it deletes the workfile.
2666   (message "Checking in %s..." file)
2667   (save-excursion
2668     (setq comment (vc-cleanup-comment comment nil))
2669     ;; Change buffers to get local value of vc-checkin-switches.
2670     (set-buffer (or (get-file-buffer file) (current-buffer)))
2671     (vc-backend-dispatch file
2672       ;; SCCS
2673       (progn
2674         (apply 'vc-do-command 0 "delta" file 'MASTER
2675                (if rev (concat "-r" rev))
2676                (if comment (concat "-y" comment))
2677                vc-checkin-switches)
2678         (if vc-keep-workfiles
2679             (vc-do-command 0 "get" file 'MASTER))
2680         )
2681       ;; RCS
2682       (apply 'vc-do-command 0 "ci" file 'MASTER
2683              (concat (if vc-keep-workfiles "-u" "-r") rev)
2684              (if comment (concat "-m" comment))
2685              vc-checkin-switches)
2686       ;; CVS
2687       (progn
2688         (apply 'vc-do-command 0 "cvs" file 'WORKFILE
2689                "ci"
2690                (if comment (concat "-m" comment))
2691                vc-checkin-switches)
2692         (vc-file-setprop file 'vc-checkout-time
2693                          (nth 5 (file-attributes file))))
2694       ;; ClearCase
2695       (progn
2696         (apply 'vc-do-cleartool-command "ci" file comment
2697                vc-checkin-switches)
2698         (vc-file-setprop file 'vc-checkout-time
2699                          (nth 5 (file-attributes file))))
2700       ))
2701   (vc-file-setprop file 'vc-locking-user nil)
2702   (message "Checking in %s...done" file)
2703   ;; See if we can keep dired up-to-date
2704   (if (fboundp 'dired-relist-file)
2705       (dired-relist-file file))
2706   )
2707
2708 (defun vc-backend-revert (file)
2709   ;; Revert file to latest checked-in version.
2710   (message "Reverting %s..." file)
2711   (vc-backend-dispatch
2712     file
2713     (progn                              ; SCCS
2714       (vc-do-command 0 "unget" file 'MASTER nil)
2715       (vc-do-command 0 "get" file 'MASTER nil))
2716     (vc-do-command 0 "co" file 'MASTER  ; RCS.  This deletes the work file.
2717                    "-f" "-u")
2718     (progn                              ; CVS
2719       (delete-file file)
2720       (vc-do-command 0 "cvs" file 'WORKFILE "update"))
2721     (vc-do-cleartool-command "unco" file 'unused "-rm") ;CC
2722     )
2723   (vc-file-setprop file 'vc-locking-user nil)
2724   (message "Reverting %s...done" file)
2725   )
2726
2727 (defun vc-backend-steal (file &optional rev)
2728   ;; Steal the lock on the current workfile.  Needs RCS 5.6.2 or later for -M.
2729   (message "Stealing lock on %s..." file)
2730   (vc-backend-dispatch file
2731     (progn                              ; SCCS
2732       (vc-do-command 0 "unget" file 'MASTER "-n" (if rev (concat "-r" rev)))
2733       (vc-do-command 0 "get" file 'MASTER "-g" (if rev (concat "-r" rev)))
2734       )
2735     (vc-do-command 0 "rcs" file 'MASTER ; RCS
2736                    "-M" (concat "-u" rev) (concat "-l" rev))
2737     (error "You cannot steal a CVS lock; there are no CVS locks to steal.") ; CVS
2738     (error "VC's ClearCase support cannot steal locks.") ; CC
2739     )
2740   (vc-file-setprop file 'vc-locking-user (user-login-name))
2741   (message "Stealing lock on %s...done" file)
2742   )
2743
2744 (defun vc-backend-uncheck (file target)
2745   ;; Undo the latest checkin.  Note: this code will have to get a lot
2746   ;; smarter when we support multiple branches.
2747   (message "Removing last change from %s..." file)
2748   (vc-backend-dispatch file
2749     (vc-do-command 0 "rmdel" file 'MASTER (concat "-r" target))
2750     (vc-do-command 0 "rcs" file 'MASTER (concat "-o" target))
2751     (error "Unchecking files under CVS is dangerous and not supported in VC.")
2752     (let ((vc-command-messages t))
2753      (cond ((string-match "/CHECKEDOUT$" target)
2754             (vc-do-cleartool-command "unco" file 'unused "-rm"))
2755            ((string-match "/0$" target)
2756             (vc-do-cleartool-command
2757              "rmbranch"
2758              (vc-cc-build-version file
2759                          (substring target 0 (match-beginning 0)))
2760              "Removing empty branch"
2761              "-force"))
2762            (t
2763             (vc-do-cleartool-command "rmver"
2764                                      (vc-cc-build-version file target)
2765                                      nil "-force"))))
2766     )
2767   (message "Removing last change from %s...done" file)
2768   ;; See if we can keep dired up-to-date
2769   (if (fboundp 'dired-relist-file)
2770       (dired-relist-file file))
2771   )
2772
2773 (defun vc-backend-print-log (file)
2774   ;; Print change log associated with FILE to buffer *vc*.
2775   (vc-backend-dispatch
2776     file
2777     (vc-do-command 0 "prs" file 'MASTER)
2778     (vc-do-command 0 "rlog" file 'MASTER)
2779     (vc-do-command 0 "cvs" file 'WORKFILE "log")
2780     (vc-do-cleartool-command "lshistory" file 'unused))
2781   )
2782
2783 (defun vc-backend-define-name (file name)
2784   ;; Under directory FILE, allow NAME as a version name.
2785   (vc-backend-dispatch file
2786    nil
2787    nil
2788    nil
2789    (vc-do-cleartool-command "mklbtype" nil nil "-vob" file name)))
2790
2791 (defun vc-backend-assign-name (file name)
2792   ;; Assign to a FILE's latest version a given NAME.
2793   (vc-backend-dispatch file
2794     (vc-add-triple name file (vc-latest-version file)) ; SCCS
2795     (vc-do-command 0 "rcs" file 'MASTER (concat "-n" name ":")) ; RCS
2796     (vc-do-command 0 "cvs" file 'WORKFILE "tag" name) ; CVS
2797     (vc-do-cleartool-command "mklabel" file nil "-replace" name) ; CC
2798     )
2799   )
2800
2801 (defun vc-backend-diff (file &optional oldvers newvers cmp)
2802   ;; Get a difference report between two versions of FILE.
2803   ;; Get only a brief comparison report if CMP, a difference report otherwise.
2804   (let ((backend (vc-backend-deduce file)))
2805     (cond
2806      ((eq backend 'SCCS)
2807       (setq oldvers (vc-lookup-triple file oldvers))
2808       (setq newvers (vc-lookup-triple file newvers))))
2809     (cond
2810      ;; SCCS and RCS shares a lot of code.
2811      ((or (eq backend 'SCCS) (eq backend 'RCS))
2812       (let* ((command (if (eq backend 'SCCS)
2813                           "vcdiff"
2814                         "rcsdiff"))
2815              (mode (if (eq backend 'RCS) 'WORKFILE 'MASTER))
2816              (options (append (list (and cmp "--brief")
2817                                     "-q"
2818                                     (and oldvers (concat "-r" oldvers))
2819                                     (and newvers (concat "-r" newvers)))
2820                               (and (not cmp)
2821                                    (if (listp diff-switches)
2822                                        diff-switches
2823                                      (list diff-switches)))))
2824              (status (apply 'vc-do-command 2 command file mode options)))
2825         ;; Some RCS versions don't understand "--brief"; work around this.
2826         (if (eq status 2)
2827             (apply 'vc-do-command 1 command file 'WORKFILE
2828                    (if cmp (cdr options) options))
2829           status)))
2830      ;; CVS is different.
2831      ;; cmp is not yet implemented -- we always do a full diff.
2832      ((eq backend 'CVS)
2833       (if (string= (vc-file-getprop file 'vc-your-latest-version) "0") ; CVS
2834           ;; This file is added but not yet committed; there is no master file.
2835           ;; diff it against /dev/null.
2836           (if (or oldvers newvers)
2837               (error "No revisions of %s exists" file)
2838             (apply 'vc-do-command
2839                    1 "diff" file 'WORKFILE "/dev/null"
2840                    (if (listp diff-switches)
2841                        diff-switches
2842                      (list diff-switches))))
2843         (apply 'vc-do-command
2844                1 "cvs" file 'WORKFILE "diff"
2845                (and oldvers (concat "-r" oldvers))
2846                (and newvers (concat "-r" newvers))
2847                (if (listp diff-switches)
2848                    diff-switches
2849                  (list diff-switches)))))
2850      ;; ClearCase is completely different.
2851      ((eq backend '@@)
2852       (let
2853           ((cmd (or vc-cleardiff-command "cleardiff")))
2854         (apply 'vc-do-command 2 cmd file nil
2855                (unless vc-cleardiff-command
2856              (if cmp "-status_only")
2857
2858              ;; Like the "-w" flag to diff
2859              "-blank_ignore"
2860
2861              ;; Display as much as possible of the file
2862                  "-columns" (format "%d" (window-width)))
2863              (vc-cc-build-version file
2864                                   (or oldvers
2865                                       (vc-file-getprop file 'vc-cc-predecessor)))
2866              (if newvers
2867                  (concat file "@@" newvers) file)
2868              nil
2869                )))
2870      (t
2871       (vc-registration-error file)))))
2872
2873 (defun vc-backend-merge-news (file)
2874   ;; Merge in any new changes made to FILE.
2875   (vc-backend-dispatch
2876     file
2877     (error "vc-backend-merge-news not meaningful for SCCS files") ; SCCS
2878     (error "vc-backend-merge-news not meaningful for RCS files") ; RCS
2879     (vc-do-command 1 "cvs" file 'WORKFILE "update") ; CVS
2880     (error "vc-backend-merge-news not meaningful for ClearCase files") ; CC
2881     ))
2882
2883 (defun vc-backend-fetch-default-comment (file rev)
2884   "Fetch default comment, if any, and insert into the current buffer"
2885   (vc-backend-dispatch file
2886                        (insert vc-default-comment)      ;; SCCS
2887                        (insert vc-default-comment)      ;; RCS
2888                        (insert vc-default-comment)      ;; CVS
2889                        (vc-clearcase-fetch-default-comment file)))
2890
2891 (defun vc-cleanup-comment (string &optional from-describe)
2892   (if string
2893       (let (tmpbuf)
2894         (unwind-protect
2895             (progn
2896               (setq tmpbuf (get-buffer-create " *vc-cleanup*"))
2897               (set-buffer tmpbuf)
2898               (erase-buffer)
2899               (insert string)
2900               (if from-describe
2901                   (progn
2902                     (goto-char (point-min))
2903                     (while (re-search-forward "^   " nil t)
2904                       (replace-match ""))))
2905               (goto-char (point-min))
2906               (while (re-search-forward "[ \t]+$" nil t)
2907                 (replace-match ""))
2908               (goto-char (point-max))
2909               (skip-chars-backward " \n\t")
2910               (delete-region (point) (point-max))
2911               (if (= (point) (point-min))
2912                   nil
2913                 (buffer-string)))
2914           (if tmpbuf
2915               (kill-buffer tmpbuf))))))
2916
2917 (defun vc-clearcase-fetch-default-comment (file)
2918   "Fetch default comment, if any, and insert into current buffer."
2919   (insert
2920    (save-excursion
2921      (let ((vc-command-messages t))
2922        ;; Use the fmt feature to get just the comment
2923        (or (vc-file-getprop file 'vc-old-comment)
2924            (vc-file-setprop file 'vc-old-comment
2925                             (vc-cleanup-comment
2926                              (vc-cleartool-cmd (or (file-name-directory file) default-directory)
2927                                                (format "describe -fmt %%c %s" file)) t))
2928            vc-default-comment
2929            )))))
2930
2931 (defun vc-check-headers ()
2932   "Check if the current file has any headers in it."
2933   (interactive)
2934   (save-excursion
2935     (goto-char (point-min))
2936     (vc-backend-dispatch buffer-file-name
2937       (re-search-forward  "%[MIRLBSDHTEGUYFPQCZWA]%" nil t) ; SCCS
2938       (re-search-forward "\\$[A-Za-z\300-\326\330-\366\370-\377]+\\(: [\t -#%-\176\240-\377]*\\)?\\$" nil t) ; RCS
2939       'RCS ; CVS works like RCS in this regard.
2940       nil ; ClearCase does not recognise headers.
2941       )
2942     ))
2943
2944 ;; Back-end-dependent stuff ends here.
2945
2946 ;; Set up key bindings for use while editing log messages
2947
2948 (defun vc-log-mode ()
2949   "Minor mode for driving version-control tools.
2950 These bindings are added to the global keymap when you enter this mode:
2951 \\[vc-next-action]              perform next logical version-control operation on current file
2952 \\[vc-register]                 register current file
2953 \\[vc-toggle-read-only]         like next-action, but won't register files
2954 \\[vc-insert-headers]           insert version-control headers in current file
2955 \\[vc-print-log]                display change history of current file
2956 \\[vc-revert-buffer]            revert buffer to latest version
2957 \\[vc-cancel-version]           undo latest checkin
2958 \\[vc-diff]                     show diffs between file versions
2959 \\[vc-version-other-window]             visit old version in another window
2960 \\[vc-directory]                show all files locked by any user in or below .
2961 \\[vc-update-change-log]        add change log entry from recent checkins
2962
2963 While you are entering a change log message for a version, the following
2964 additional bindings will be in effect.
2965
2966 \\[vc-finish-logentry]   proceed with check in, ending log message entry
2967
2968 Whenever you do a checkin, your log comment is added to a ring of
2969 saved comments.  These can be recalled as follows:
2970
2971 \\[vc-next-comment]     replace region with next message in comment ring
2972 \\[vc-previous-comment] replace region with previous message in comment ring
2973 \\[vc-comment-search-reverse]   search backward for regexp in the comment ring
2974 \\[vc-comment-search-forward]   search backward for regexp in the comment ring
2975
2976 Entry to the change-log submode calls the value of text-mode-hook, then
2977 the value of vc-log-mode-hook.
2978
2979 Global user options:
2980  vc-initial-comment      If non-nil, require user to enter a change
2981                          comment upon first checkin of the file.
2982
2983  vc-keep-workfiles       Non-nil value prevents workfiles from being
2984                          deleted when changes are checked in
2985
2986  vc-suppress-confirm     Suppresses some confirmation prompts,
2987                          notably for reversions.
2988
2989  vc-header-alist         Which keywords to insert when adding headers
2990                          with \\[vc-insert-headers].  Defaults to
2991                          '(\"\%\W\%\") under SCCS, '(\"\$Id\$\") under
2992                          RCS and CVS.
2993
2994  vc-static-header-alist  By default, version headers inserted in C files
2995                          get stuffed in a static string area so that
2996                          ident(RCS/CVS) or what(SCCS) can see them in
2997                          the compiled object code.  You can override
2998                          this by setting this variable to nil, or change
2999                          the header template by changing it.
3000
3001  vc-command-messages     if non-nil, display run messages from the
3002                          actual version-control utilities (this is
3003                          intended primarily for people hacking vc
3004                          itself).
3005 "
3006   (interactive)
3007   (set-syntax-table text-mode-syntax-table)
3008   (use-local-map vc-log-entry-mode)
3009   (setq local-abbrev-table text-mode-abbrev-table)
3010   (setq major-mode 'vc-log-mode)
3011   (setq mode-name "VC-Log")
3012   (make-local-variable 'vc-log-file)
3013   (make-local-variable 'vc-log-version)
3014   (make-local-variable 'vc-comment-ring-index)
3015   (make-local-variable 'vc-log-writable)
3016   (set-buffer-modified-p nil)
3017   (setq buffer-file-name nil)
3018   (run-hooks 'text-mode-hook 'vc-log-mode-hook)
3019   )
3020
3021 ;; Initialization code, to be done just once at load-time
3022 (if vc-log-entry-mode
3023     nil
3024   (setq vc-log-entry-mode (make-sparse-keymap))
3025   (define-key vc-log-entry-mode "\M-n" 'vc-next-comment)
3026   (define-key vc-log-entry-mode "\M-p" 'vc-previous-comment)
3027   (define-key vc-log-entry-mode "\M-r" 'vc-comment-search-reverse)
3028   (define-key vc-log-entry-mode "\M-s" 'vc-comment-search-forward)
3029   (define-key vc-log-entry-mode "\C-c\C-c" 'vc-finish-logentry)
3030   (define-key vc-log-entry-mode "\C-x\C-s" 'vc-save-logentry)
3031   (define-key vc-log-entry-mode "\C-x\C-q" 'vc-num-num-error)
3032   )
3033
3034 ;;; These things should probably be generally available
3035
3036 (defun vc-file-tree-walk (func &rest args)
3037   "Walk recursively through default directory.
3038 Invoke FUNC f ARGS on each non-directory file f underneath it."
3039   (vc-file-tree-walk-internal default-directory func args nil)
3040   (message "Traversing directory %s...done" default-directory))
3041
3042 (defun vc-file-tree-walk-internal (file func args quiet)
3043   (if (not (file-directory-p file))
3044       (apply func file args)
3045     (or quiet
3046         (message "Traversing directory %s..." file))
3047     (let ((dir (file-name-as-directory file)))
3048       (mapcar
3049        (function
3050         (lambda (f) (or
3051                      (string-equal f ".")
3052                      (string-equal f "..")
3053                      (member f vc-directory-exclusion-list)
3054                      (let ((dirf (concat dir f)))
3055                         (or
3056                          (file-symlink-p dirf) ;; Avoid possible loops
3057                          (vc-file-tree-walk-internal dirf func args quiet))))))
3058        (directory-files dir)))))
3059
3060 (defun vc-subdir-tree-walk (func &rest args)
3061   "Walk recursively through default directory.
3062 Invoke FUNC f ARGS on each subdirectory underneath it."
3063   (vc-subdir-tree-walk-internal default-directory func args nil)
3064   (message "Traversing directory %s...done" default-directory))
3065
3066 (defun vc-subdir-tree-walk-internal (file func args quiet)
3067   (if (file-directory-p file)
3068       (let ((dir (file-name-as-directory file)))
3069         (apply func dir args)
3070         (or quiet
3071             (message "Traversing directory %s..." file))
3072         (mapcar
3073          (function
3074           (lambda (f) (or
3075                        (string-equal f ".")
3076                        (string-equal f "..")
3077                        (member f vc-directory-exclusion-list)
3078                        (let ((dirf (concat dir f)))
3079                          (or
3080                             (file-symlink-p dirf) ;; Avoid possible loops
3081                             (vc-subdir-tree-walk-internal dirf func args quiet))))))
3082          (directory-files dir)))
3083     ))
3084
3085 (defun vc-dir-all-files (func &rest args)
3086   "Invoke FUNC f ARGS on each regular file f in default directory."
3087   (let ((dir default-directory))
3088     (message "Scanning directory %s..." dir)
3089     (mapcar (function (lambda (f)
3090                         (let ((dirf (expand-file-name f dir)))
3091                           (apply func dirf args))))
3092             (directory-files dir))
3093     (message "Scanning directory %s...done" dir)))
3094
3095 ;;; Lucid Emacs-specific code.
3096 (defun vc-file-newer (file)
3097   (or (null file)
3098       (let ((vc-file (vc-file-getprop file 'vc-name)))
3099         (or (null vc-file)
3100             (let ((time (vc-file-getprop file 'vc-file-timestamp)))
3101               (or (null time)
3102                   (> time (nth 5 (file-attributes vc-file)))))))))
3103
3104 (defun vc-revision-diff (arg)
3105   "Compare the version being edited with the last checked-in revision.
3106 With a prefix argument prompt for revision to compare with."
3107   (interactive "P")
3108   (save-excursion
3109     (if vc-dired-mode
3110         (set-buffer (find-file-noselect (dired-get-filename))))
3111     ;; check that the file is not modified
3112     (if (and (buffer-modified-p)
3113              (or
3114               (y-or-n-p (format "%s has been modified. Write it out? "
3115                                 (buffer-name)))))
3116         (save-buffer))
3117     (if arg
3118         (vc-version-diff buffer-file-name
3119                          (vc-read-version "Revision to compare against: "
3120                                           (buffer-file-name))
3121                          ())
3122       (vc-diff ())))
3123   )
3124
3125 (defun vc-diff-since-revision ()
3126   (interactive)
3127   (vc-revision-diff '(4)))
3128
3129 (defun vc-backend-checkout-in-buffer (file rev)
3130   ;; Retrieve a copy of a saved version into the current buffer
3131   (message "Checking out %s..." file)
3132   (vc-backend-dispatch file
3133    (progn
3134      (vc-do-command 0 "get" file 'WORKFILE       ;; SCCS
3135                     "-p" "-s"
3136                     (and rev (concat "-r" (vc-lookup-triple file rev))))
3137      )
3138    (vc-do-command 0 "co" file 'WORKFILE  ;; RCS
3139                   "-p" "-q"
3140                   (and rev (concat "-r" rev)))
3141    (error "Command not yet supported in CVS.")
3142    (error "Just use ClearCase extended naming.")
3143    )
3144   (message "Checking out %s...done" file)
3145   )
3146
3147
3148 ;;;(defun vc-visit-previous-revision (revision)
3149 ;;;  "Show a previous revision of the current file"
3150 ;;;  (interactive "sShow previous revision number: ")
3151 ;;;  (if (not buffer-file-name)
3152 ;;;      (error "There is no file associated with buffer %s" (buffer-name)))
3153 ;;;  (let* ((file buffer-file-name)
3154 ;;;      (other-file
3155 ;;;       (make-temp-name
3156 ;;;        (concat (or revision "current") "-" (file-name-nondirectory file)
3157 ;;;                "-")))
3158 ;;;      (buffer-name (concat (file-name-nondirectory file)
3159 ;;;                           "<" (vc-backend-deduce file) " " revision ">")))
3160 ;;;    (vc-backend-checkout-in-buffer file revision)
3161 ;;;    (save-excursion
3162 ;;;      (set-buffer "*vc*")
3163 ;;;      (write-region (point-min) (point-max) other-file t 0)
3164 ;;;      (erase-buffer))
3165 ;;;    (pop-to-buffer (get-buffer-create buffer-name))
3166 ;;;    (erase-buffer)
3167 ;;;    (insert-file other-file)
3168 ;;;    ;; get the same major mode as the original file
3169 ;;;    (setq buffer-file-name file)
3170 ;;;    (normal-mode)
3171 ;;;    (setq buffer-file-name ())
3172 ;;;    (set-buffer-modified-p ())
3173 ;;;    (toggle-read-only)
3174 ;;;    (delete-file other-file)))
3175
3176 ;;;dont ###autoload, it conflicts with vc.el
3177 (defun vc-rename-this-file (new)
3178   "Rename the file of the current buffer.
3179 It also renames the source control archive with it"
3180   (interactive "FVC rename file to: ")
3181   (if (and (buffer-modified-p)
3182            (y-or-n-p (format "%s has been modified. Write it out? "
3183                              (buffer-name))))
3184       (save-buffer))
3185   (vc-rename-file buffer-file-name new)
3186   (let ((old-buffer (current-buffer))
3187         (new-buffer (find-file-noselect new)))
3188     (set-window-buffer (selected-window) new-buffer)
3189     (pop-to-buffer (current-buffer))
3190     (bury-buffer old-buffer)))
3191
3192 (defun vc-update-directory ()
3193   "Updates the current directory by getting the latest copies of the files"
3194   (interactive)
3195   (save-some-buffers)
3196   (let ((failed ())
3197         (any-updated ())
3198         (dir default-directory))
3199     (save-excursion
3200       (set-buffer (get-buffer-create "*vc-update*"))
3201       (setq default-directory dir)
3202       (erase-buffer)
3203       (insert "Updating " default-directory "\n\n")
3204       (display-buffer (current-buffer))
3205       (sit-for 0)
3206       (condition-case ()
3207           (vc-file-tree-walk
3208            (function (lambda (f)
3209                        (if (and f (vc-registered f))
3210                            (progn
3211                              (cond ((file-newer-than-file-p f (vc-name f)))
3212                                    ((equal (vc-locking-user f)
3213                                            (user-login-name)))
3214                                    ((not (zerop (vc-backend-diff f nil)))
3215                                     (vc-backend-checkout f nil nil nil nil)
3216                                     (insert "updated  " f "\n")
3217                                     (setq any-updated t)
3218                                     (sit-for 0))))))))
3219         (error (setq failed t)))
3220       (if (null any-updated)
3221           (insert "No files needed to be updated\n")
3222         (goto-char (point-max))
3223         (insert "\ndone\n")))
3224     (if failed
3225         (save-excursion
3226           (set-buffer "*vc*")
3227           (append-to-buffer "*vc-update*" (point-min) (point-max)))
3228         (save-excursion
3229           (set-buffer "*vc*")
3230           (goto-char (point-min))))
3231     (pop-to-buffer "*vc-update*")
3232     (if failed
3233         (error "update failed"))))
3234
3235 (provide 'vc-cc)
3236
3237 ;;; DEVELOPER'S NOTES ON CONCURRENCY PROBLEMS IN THIS CODE
3238 ;;;
3239 ;;; These may be useful to anyone who has to debug or extend the package.
3240 ;;;
3241 ;;; A fundamental problem in VC is that there are time windows between
3242 ;;; vc-next-action's computations of the file's version-control state and
3243 ;;; the actions that change it.  This is a window open to lossage in a
3244 ;;; multi-user environment; someone else could nip in and change the state
3245 ;;; of the master during it.
3246 ;;;
3247 ;;; The performance problem is that rlog/prs calls are very expensive; we want
3248 ;;; to avoid them as much as possible.
3249 ;;;
3250 ;;; ANALYSIS:
3251 ;;;
3252 ;;; The performance problem, it turns out, simplifies in practice to the
3253 ;;; problem of making vc-locking-user fast.  The two other functions that call
3254 ;;; prs/rlog will not be so commonly used that the slowdown is a problem; one
3255 ;;; makes snapshots, the other deletes the calling user's last change in the
3256 ;;; master.
3257 ;;;
3258 ;;; The race condition implies that we have to either (a) lock the master
3259 ;;; during the entire execution of vc-next-action, or (b) detect and
3260 ;;; recover from errors resulting from dispatch on an out-of-date state.
3261 ;;;
3262 ;;; Alternative (a) appears to be unfeasible.  The problem is that we can't
3263 ;;; guarantee that the lock will ever be removed.  Suppose a user starts a
3264 ;;; checkin, the change message buffer pops up, and the user, having wandered
3265 ;;; off to do something else, simply forgets about it?
3266 ;;;
3267 ;;; Alternative (b), on the other hand, works well with a cheap way to speed up
3268 ;;; vc-locking-user.  Usually, if a file is registered, we can read its locked/
3269 ;;; unlocked state and its current owner from its permissions.
3270 ;;;
3271 ;;; This shortcut will fail if someone has manually changed the workfile's
3272 ;;; permissions; also if developers are munging the workfile in several
3273 ;;; directories, with symlinks to a master (in this latter case, the
3274 ;;; permissions shortcut will fail to detect a lock asserted from another
3275 ;;; directory).
3276 ;;;
3277 ;;; Note that these cases correspond exactly to the errors which could happen
3278 ;;; because of a competing checkin/checkout race in between two instances of
3279 ;;; vc-next-action.
3280 ;;;
3281 ;;; For VC's purposes, a workfile/master pair may have the following states:
3282 ;;;
3283 ;;; A. Unregistered.  There is a workfile, there is no master.
3284 ;;;
3285 ;;; B. Registered and not locked by anyone.
3286 ;;;
3287 ;;; C. Locked by calling user and unchanged.
3288 ;;;
3289 ;;; D. Locked by the calling user and changed.
3290 ;;;
3291 ;;; E. Locked by someone other than the calling user.
3292 ;;;
3293 ;;; This makes for 25 states and 20 error conditions.  Here's the matrix:
3294 ;;;
3295 ;;; VC's idea of state
3296 ;;;  |
3297 ;;;  V  Actual state   RCS action              SCCS action          Effect
3298 ;;;    A  B  C  D  E
3299 ;;;  A .  1  2  3  4   ci -u -t-          admin -fb -i<file>      initial admin
3300 ;;;  B 5  .  6  7  8   co -l              get -e                  checkout
3301 ;;;  C 9  10 .  11 12  co -u              unget; get              revert
3302 ;;;  D 13 14 15 .  16  ci -u -m<comment>  delta -y<comment>; get  checkin
3303 ;;;  E 17 18 19 20 .   rcs -u -M ; rcs -l unget -n ; get -g       steal lock
3304 ;;;
3305 ;;; All commands take the master file name as a last argument (not shown).
3306 ;;;
3307 ;;; In the discussion below, a "self-race" is a pathological situation in
3308 ;;; which VC operations are being attempted simultaneously by two or more
3309 ;;; Emacsen running under the same username.
3310 ;;;
3311 ;;; The vc-next-action code has the following windows:
3312 ;;;
3313 ;;; Window P:
3314 ;;;    Between the check for existence of a master file and the call to
3315 ;;; admin/checkin in vc-buffer-admin (apparent state A).  This window may
3316 ;;; never close if the initial-comment feature is on.
3317 ;;;
3318 ;;; Window Q:
3319 ;;;    Between the call to vc-workfile-unchanged-p in and the immediately
3320 ;;; following revert (apparent state C).
3321 ;;;
3322 ;;; Window R:
3323 ;;;    Between the call to vc-workfile-unchanged-p in and the following
3324 ;;; checkin (apparent state D).  This window may never close.
3325 ;;;
3326 ;;; Window S:
3327 ;;;    Between the unlock and the immediately following checkout during a
3328 ;;; revert operation (apparent state C).  Included in window Q.
3329 ;;;
3330 ;;; Window T:
3331 ;;;    Between vc-locking-user and the following checkout (apparent state B).
3332 ;;;
3333 ;;; Window U:
3334 ;;;    Between vc-locking-user and the following revert (apparent state C).
3335 ;;; Includes windows Q and S.
3336 ;;;
3337 ;;; Window V:
3338 ;;;    Between vc-locking-user and the following checkin (apparent state
3339 ;;; D).  This window may never be closed if the user fails to complete the
3340 ;;; checkin message.  Includes window R.
3341 ;;;
3342 ;;; Window W:
3343 ;;;    Between vc-locking-user and the following steal-lock (apparent
3344 ;;; state E).  This window may never close if the user fails to complete
3345 ;;; the steal-lock message.  Includes window X.
3346 ;;;
3347 ;;; Window X:
3348 ;;;    Between the unlock and the immediately following re-lock during a
3349 ;;; steal-lock operation (apparent state E).  This window may never cloce
3350 ;;; if the user fails to complete the steal-lock message.
3351 ;;;
3352 ;;; Errors:
3353 ;;;
3354 ;;; Apparent state A ---
3355 ;;;
3356 ;;; 1. File looked unregistered but is actually registered and not locked.
3357 ;;;
3358 ;;;    Potential cause: someone else's admin during window P, with
3359 ;;; caller's admin happening before their checkout.
3360 ;;;
3361 ;;;    RCS: ci will fail with a "no lock set by <user>" message.
3362 ;;;    SCCS: admin will fail with error (ad19).
3363 ;;;
3364 ;;;    We can let these errors be passed up to the user.
3365 ;;;
3366 ;;; 2. File looked unregistered but is actually locked by caller, unchanged.
3367 ;;;
3368 ;;;    Potential cause: self-race during window P.
3369 ;;;
3370 ;;;    RCS: will revert the file to the last saved version and unlock it.
3371 ;;;    SCCS: will fail with error (ad19).
3372 ;;;
3373 ;;;    Either of these consequences is acceptable.
3374 ;;;
3375 ;;; 3. File looked unregistered but is actually locked by caller, changed.
3376 ;;;
3377 ;;;    Potential cause: self-race during window P.
3378 ;;;
3379 ;;;    RCS: will register the caller's workfile as a delta with a
3380 ;;; null change comment (the -t- switch will be ignored).
3381 ;;;    SCCS: will fail with error (ad19).
3382 ;;;
3383 ;;; 4. File looked unregistered but is locked by someone else.
3384 ;;;
3385 ;;;    Potential cause: someone else's admin during window P, with
3386 ;;; caller's admin happening *after* their checkout.
3387 ;;;
3388 ;;;    RCS: will fail with a "no lock set by <user>" message.
3389 ;;;    SCCS: will fail with error (ad19).
3390 ;;;
3391 ;;;    We can let these errors be passed up to the user.
3392 ;;;
3393 ;;; Apparent state B ---
3394 ;;;
3395 ;;; 5. File looked registered and not locked, but is actually unregistered.
3396 ;;;
3397 ;;;    Potential cause: master file got nuked during window P.
3398 ;;;
3399 ;;;    RCS: will fail with "RCS/<file>: No such file or directory"
3400 ;;;    SCCS: will fail with error ut4.
3401 ;;;
3402 ;;;    We can let these errors be passed up to the user.
3403 ;;;
3404 ;;; 6. File looked registered and not locked, but is actually locked by the
3405 ;;; calling user and unchanged.
3406 ;;;
3407 ;;;    Potential cause: self-race during window T.
3408 ;;;
3409 ;;;    RCS: in the same directory as the previous workfile, co -l will fail
3410 ;;; with "co error: writable foo exists; checkout aborted".  In any other
3411 ;;; directory, checkout will succeed.
3412 ;;;    SCCS: will fail with ge17.
3413 ;;;
3414 ;;;    Either of these consequences is acceptable.
3415 ;;;
3416 ;;; 7. File looked registered and not locked, but is actually locked by the
3417 ;;; calling user and changed.
3418 ;;;
3419 ;;;    As case 6.
3420 ;;;
3421 ;;; 8. File looked registered and not locked, but is actually locked by another
3422 ;;; user.
3423 ;;;
3424 ;;;    Potential cause: someone else checks it out during window T.
3425 ;;;
3426 ;;;    RCS: co error: revision 1.3 already locked by <user>
3427 ;;;    SCCS: fails with ge4 (in directory) or ut7 (outside it).
3428 ;;;
3429 ;;;    We can let these errors be passed up to the user.
3430 ;;;
3431 ;;; Apparent state C ---
3432 ;;;
3433 ;;; 9. File looks locked by calling user and unchanged, but is unregistered.
3434 ;;;
3435 ;;;    As case 5.
3436 ;;;
3437 ;;; 10. File looks locked by calling user and unchanged, but is actually not
3438 ;;; locked.
3439 ;;;
3440 ;;;    Potential cause: a self-race in window U, or by the revert's
3441 ;;; landing during window X of some other user's steal-lock or window S
3442 ;;; of another user's revert.
3443 ;;;
3444 ;;;    RCS: succeeds, refreshing the file from the identical version in
3445 ;;; the master.
3446 ;;;    SCCS: fails with error ut4 (p file nonexistent).
3447 ;;;
3448 ;;;    Either of these consequences is acceptable.
3449 ;;;
3450 ;;; 11. File is locked by calling user.  It looks unchanged, but is actually
3451 ;;; changed.
3452 ;;;
3453 ;;;    Potential cause: the file would have to be touched by a self-race
3454 ;;; during window Q.
3455 ;;;
3456 ;;;    The revert will succeed, removing whatever changes came with
3457 ;;; the touch.  It is theoretically possible that work could be lost.
3458 ;;;
3459 ;;; 12. File looks like it's locked by the calling user and unchanged, but
3460 ;;; it's actually locked by someone else.
3461 ;;;
3462 ;;;    Potential cause: a steal-lock in window V.
3463 ;;;
3464 ;;;    RCS: co error: revision <rev> locked by <user>; use co -r or rcs -u
3465 ;;;    SCCS: fails with error un2
3466 ;;;
3467 ;;;    We can pass these errors up to the user.
3468 ;;;
3469 ;;; Apparent state D ---
3470 ;;;
3471 ;;; 13. File looks like it's locked by the calling user and changed, but it's
3472 ;;; actually unregistered.
3473 ;;;
3474 ;;;    Potential cause: master file got nuked during window P.
3475 ;;;
3476 ;;;    RCS: Checks in the user's version as an initial delta.
3477 ;;;    SCCS: will fail with error ut4.
3478 ;;;
3479 ;;;    This case is kind of nasty.  It means VC may fail to detect the
3480 ;;; loss of previous version information.
3481 ;;;
3482 ;;; 14. File looks like it's locked by the calling user and changed, but it's
3483 ;;; actually unlocked.
3484 ;;;
3485 ;;;    Potential cause: self-race in window V, or the checkin happening
3486 ;;; during the window X of someone else's steal-lock or window S of
3487 ;;; someone else's revert.
3488 ;;;
3489 ;;;    RCS: ci will fail with "no lock set by <user>".
3490 ;;;    SCCS: delta will fail with error ut4.
3491 ;;;
3492 ;;; 15. File looks like it's locked by the calling user and changed, but it's
3493 ;;; actually locked by the calling user and unchanged.
3494 ;;;
3495 ;;;    Potential cause: another self-race --- a whole checkin/checkout
3496 ;;; sequence by the calling user would have to land in window R.
3497 ;;;
3498 ;;;    SCCS: checks in a redundant delta and leaves the file unlocked as usual.
3499 ;;;    RCS: reverts to the file state as of the second user's checkin, leaving
3500 ;;; the file unlocked.
3501 ;;;
3502 ;;;    It is theoretically possible that work could be lost under RCS.
3503 ;;;
3504 ;;; 16. File looks like it's locked by the calling user and changed, but it's
3505 ;;; actually locked by a different user.
3506 ;;;
3507 ;;;    RCS: ci error: no lock set by <user>
3508 ;;;    SCCS: unget will fail with error un2
3509 ;;;
3510 ;;;    We can pass these errors up to the user.
3511 ;;;
3512 ;;; Apparent state E ---
3513 ;;;
3514 ;;; 17. File looks like it's locked by some other user, but it's actually
3515 ;;; unregistered.
3516 ;;;
3517 ;;;    As case 13.
3518 ;;;
3519 ;;; 18. File looks like it's locked by some other user, but it's actually
3520 ;;; unlocked.
3521 ;;;
3522 ;;;    Potential cause: someone released a lock during window W.
3523 ;;;
3524 ;;;    RCS: The calling user will get the lock on the file.
3525 ;;;    SCCS: unget -n will fail with cm4.
3526 ;;;
3527 ;;;    Either of these consequences will be OK.
3528 ;;;
3529 ;;; 19. File looks like it's locked by some other user, but it's actually
3530 ;;; locked by the calling user and unchanged.
3531 ;;;
3532 ;;;    Potential cause: the other user relinquishing a lock followed by
3533 ;;; a self-race, both in window W.
3534 ;;;
3535 ;;;     Under both RCS and SCCS, both unlock and lock will succeed, making
3536 ;;; the sequence a no-op.
3537 ;;;
3538 ;;; 20. File looks like it's locked by some other user, but it's actually
3539 ;;; locked by the calling user and changed.
3540 ;;;
3541 ;;;     As case 19.
3542 ;;;
3543 ;;; PROBLEM CASES:
3544 ;;;
3545 ;;;    In order of decreasing severity:
3546 ;;;
3547 ;;;    Cases 11 and 15 under RCS are the only one that potentially lose work.
3548 ;;; They would require a self-race for this to happen.
3549 ;;;
3550 ;;;    Case 13 in RCS loses information about previous deltas, retaining
3551 ;;; only the information in the current workfile.  This can only happen
3552 ;;; if the master file gets nuked in window P.
3553 ;;;
3554 ;;;    Case 3 in RCS and case 15 under SCCS insert a redundant delta with
3555 ;;; no change comment in the master.  This would require a self-race in
3556 ;;; window P or R respectively.
3557 ;;;
3558 ;;;    Cases 2, 10, 19 and 20 do extra work, but make no changes.
3559 ;;;
3560 ;;;    Unfortunately, it appears to me that no recovery is possible in these
3561 ;;; cases.  They don't yield error messages, so there's no way to tell that
3562 ;;; a race condition has occurred.
3563 ;;;
3564 ;;;    All other cases don't change either the workfile or the master, and
3565 ;;; trigger command errors which the user will see.
3566 ;;;
3567 ;;;    Thus, there is no explicit recovery code.
3568
3569 ;;; ClearCase extensions:
3570
3571 ;;; vc-edit-config
3572
3573 (defvar vc-config-edit-mode nil)
3574
3575 (defvar vc-tag-name nil
3576   "Name of view tag which is currently being edited")
3577
3578 (if vc-config-edit-mode
3579     nil
3580   (setq vc-config-edit-mode (make-sparse-keymap))
3581   (define-key vc-config-edit-mode "\C-c\C-c" 'vc-finish-config)
3582   (define-key vc-config-edit-mode "\C-x\C-s" 'vc-save-config))
3583
3584 (defsubst vc-temp-filename ()
3585   (make-temp-name "/tmp/VC-"))
3586
3587 (defun vc-save-config ()
3588   (interactive)
3589   (if (not (buffer-modified-p))
3590       (message "Configuration not changed since last saved")
3591     (let ((tmp (vc-temp-filename)))
3592       (unwind-protect
3593           (progn
3594             (message "Setting configuration for %s..." vc-tag-name)
3595             (write-region (point-min) (point-max) tmp nil 'dont-mention-it)
3596             (let ((vc-command-messages t))
3597               (vc-cleartool-cmd default-directory
3598                                 (format "setcs -tag %s %s" vc-tag-name tmp)))
3599             (set-buffer-modified-p nil)
3600             (message "Setting configuration for %s...done" vc-tag-name))
3601         (if (file-exists-p tmp)
3602             (delete-file tmp))))))
3603
3604 (defun vc-finish-config ()
3605   (interactive)
3606   (let ((old-buffer (current-buffer)))
3607     (vc-save-config)
3608     (bury-buffer nil)
3609 ;;    (if (bufferp vc-parent-buffer)
3610 ;;      (pop-to-buffer vc-parent-buffer))
3611     (kill-buffer old-buffer)))
3612
3613 (defun vc-config-edit-mode ()
3614   (interactive)
3615   (set-syntax-table text-mode-syntax-table)
3616   (use-local-map vc-config-edit-mode)
3617   (setq major-mode 'vc-config-edit-mode)
3618   (setq mode-name "VC-Config")
3619   (make-variable-buffer-local 'vc-parent-buffer)
3620   (set-buffer-modified-p nil)
3621   (setq buffer-file-name nil)
3622   (run-hooks 'text-mode-hook 'vc-config-edit-mode-hook))
3623
3624 (defun vc-cc-tagname (str)
3625   "Extract the view tag name from a view-extended-pathname"
3626   (and str
3627        (stringp str)
3628        (string-match "^/view/\\([^/]+\\)" str)
3629        (substring str
3630                   (match-beginning 1)
3631                   (match-end 1))))
3632
3633 ;;;dont ###autoload, it conflicts with vc.el
3634 (defun vc-cc-pwv (path)
3635   (or (vc-cc-tagname path)
3636       (vc-cc-tagname (getenv "CLEARCASE_ROOT"))))
3637
3638 (defvar vc-tag-history ()
3639   "History of view tags used in vc-edit-config")
3640
3641 ;;;dont ###autoload, it conflicts with vc.el
3642 (defun vc-edit-config (tag-name)
3643   "Edit a ClearCase configuration specification"
3644   (interactive
3645    (let ((vxname (vc-cc-pwv default-directory)))
3646      (list (directory-file-name
3647             (completing-read "View Tag: "
3648                             (vc-cc-get-view-cache-noslash)
3649                             nil
3650                             'fascist
3651                             vxname
3652                             'vc-tag-history)))))
3653   (let ((start (current-buffer))
3654         (buffer-name (format "*VC-Config-%s*" tag-name)))
3655     (kill-buffer (get-buffer-create buffer-name))
3656     (pop-to-buffer (get-buffer-create buffer-name))
3657     (auto-save-mode auto-save-default)
3658     (erase-buffer)
3659     (insert (vc-cleartool-cmd default-directory
3660                               (format "catcs -tag %s" tag-name)))
3661     (goto-char (point-min))
3662     (re-search-forward "^[^#\n]" nil 'end)
3663     (beginning-of-line)
3664     (vc-config-edit-mode)
3665     (setq vc-parent-buffer start)
3666     (make-local-variable 'vc-tag-name)
3667     (setq vc-tag-name tag-name))
3668   )
3669
3670 (defun vc-nosupport (which op)
3671   (error (format "%s does not support %s" which op)))
3672
3673 ;;;dont ###autoload, it conflicts with vc.el
3674 (defun vc-graph-history (arg)
3675   "Display a graph of a file's history"
3676   (interactive "p")
3677   (let ((pathname (cond (vc-dired-mode (dired-get-filename))
3678                         (buffer-file-name)
3679                         (default-directory)))
3680         (vtreearg (cond ((eq arg 1) nil)
3681                         ((eq arg 4) "-all ")
3682                         ((eq arg 16) "-nmerge ")))
3683         (debug-on-error t))
3684     (vc-backend-dispatch
3685      pathname
3686      (vc-nosupport 'SCCS 'graph-history)
3687      (vc-nosupport 'RCS 'graph-history)
3688      (vc-nosupport 'CVS 'graph-history)
3689      (progn
3690        (if vc-alternate-lsvtree
3691            (start-process "lsvtree" (get-buffer-create "*lsvtree*")
3692                           vc-alternate-lsvtree pathname)
3693          (vc-cleartool-cmd pathname
3694                            (concat "xlsvtree " vtreearg pathname)))
3695        (message "xlsvtree window for %s should appear shortly" pathname)))))
3696
3697 (defvar cleartool-tq nil
3698   "Transaction queue to talk to ClearTool in a subprocess")
3699
3700 (defvar vc-return nil
3701   "Return value when we're involved in a blocking call")
3702
3703 (defvar cleartool-view ""
3704   "Current view of cleartool subprocess, or the empty string if none")
3705
3706 (defvar cleartool-wdir ""
3707   "Current working directory of cleartool subprocess, or the empty string if none")
3708
3709 (defvar vc-running nil)
3710
3711 (defconst vc-subproc-timeout 30
3712   "Timeout on calls to subprocess")
3713
3714 (defun vc-accept-process-output (proc timeout)
3715   (if vc-elucidated
3716       (accept-process-output proc)
3717     (accept-process-output proc timeout)))
3718
3719 (defun vc-start-cleartool ()
3720   (interactive)
3721   (let ((process-environment (append '("ATRIA_NO_BOLD=1"
3722                                         "ATRIA_FORCE_GUI=1")
3723                                      ;;; emacs is a GUI, right? :-)
3724                                      process-environment)))
3725     (let ((cleartool-process (start-process "cleartool" "*cleartool*" vc-cleartool-path)))
3726       (process-kill-without-query cleartool-process)
3727       (setq cleartool-view "")
3728       (setq cleartool-tq (tq-create cleartool-process))
3729       (tq-enqueue cleartool-tq "" "[.\n]*cleartool> " 'vc-running 'set)
3730       (while (not vc-running)
3731         (message "waiting for cleartool to start...")
3732         (vc-accept-process-output (tq-process cleartool-tq) vc-subproc-timeout))
3733       (message "waiting for cleartool to start...done"))))
3734
3735 (defun vc-kill-cleartool ()
3736   "Kill off cleartool subprocess.  If another one is needed,
3737 it will be restarted.  This may be useful if you're debugging clearcase."
3738   (interactive)
3739   (vc-kill-tq))
3740
3741 (defun vc-callback (arg val)
3742   (setq vc-return (substring val 0 -11)))
3743
3744 ;;(defun vc-foo (cmd)
3745 ;;  (interactive)
3746 ;;  (tq-enqueue cleartool-tq cmd "[.\n]*\ncleartool> " nil 'vc-callback)
3747 ;;  )
3748
3749 (defvar vc-cc-uninteresting-commands "\\(describe\\|lsview\\)")
3750
3751 (defun vc-do-cleartool-command (command file comment &rest flags)
3752   "Execute a cleartool version-control command, notifying user and checking for errors.
3753 Output from COMMAND goes to buffer *vc*.  The last argument of the command is
3754 the master name of FILE; this is appended to an optional list of FLAGS."
3755   (if file
3756       (setq file (expand-file-name file)))
3757   (if (listp command)
3758 ;;      (progn
3759 ;;      (setq flags (append (cdr command) flags))
3760 ;;      (setq command (car command)))
3761       (error "command must not be a list"))
3762   (if vc-command-messages
3763       (message "Running %s on %s..." command file))
3764   (let ((obuf (current-buffer)) (camefrom (current-buffer))
3765         (squeezed nil)
3766         (vc-file (and file (or (vc-name file) file)))
3767         status)
3768     (set-buffer (get-buffer-create "*vc*"))
3769     (set (make-local-variable 'vc-parent-buffer) camefrom)
3770     (set (make-local-variable 'vc-parent-buffer-name)
3771          (concat " from " (buffer-name camefrom)))
3772     (erase-buffer)
3773     ;; This is so that command arguments typed in the *vc* buffer will
3774     ;; have reasonable defaults.
3775     (if file
3776         (setq default-directory (file-name-directory file)))
3777
3778     (mapcar
3779      (function (lambda (s)
3780                  (and s
3781                       (setq squeezed
3782                             (concat squeezed " " s)))))
3783      flags)
3784     (let ((tmpfile (vc-temp-filename)))
3785       (unwind-protect
3786           (progn
3787             (if (not (eq comment 'unused))
3788                 (if comment
3789                     (progn
3790                       (write-region comment nil tmpfile nil 'noprint)
3791                       (setq squeezed (concat squeezed " -cfile " tmpfile)))
3792                   (setq squeezed (concat squeezed " -nc"))))
3793             (if vc-file
3794                 (setq squeezed (concat squeezed " " vc-file)))
3795             (let ((default-directory (file-name-directory
3796                                       (or file default-directory))))
3797               (vc-cc-cd default-directory)
3798               (if vc-command-messages
3799                   (message "Running %s %s..." command squeezed))
3800               (insert
3801                (vc-cleartool-cmd file (concat command " " squeezed)))
3802               (if vc-command-messages
3803                   (message "Running %s %s...done" command squeezed))))
3804         (if (file-exists-p tmpfile)
3805             (delete-file tmpfile))))
3806     (goto-char (point-min))
3807     (if (re-search-forward "^cleartool: Error:.*$" nil t)
3808         (progn
3809           (setq status (buffer-substring (match-beginning 0) (match-end 0)))
3810           (pop-to-buffer "*vc*")
3811           (goto-char (point-min))
3812           (shrink-window-if-larger-than-buffer)
3813           (error "Running %s...FAILED (%s)" squeezed status))
3814       (if vc-command-messages
3815           (message "Running %s...OK" command)))
3816     (set-buffer obuf)
3817     status))
3818
3819 (defun vc-cc-cd (dir)
3820   (if (or (not dir)
3821           (string= dir cleartool-wdir))
3822       cleartool-wdir
3823     (vc-setview (vc-cc-pwv dir))
3824     (let ((ret (vc-cleartool-blocking-call (format "cd %s" dir))))
3825       (if (string-match "cleartool: Error:" ret)
3826           (error (substring ret (match-end 0)))
3827         (setq cleartool-wdir dir)))))
3828
3829 (defun vc-setview (view)
3830   "Set the cleartool subprocess to a named view"
3831   (if (or (not view)
3832           (string= view cleartool-view))
3833       cleartool-view
3834     (let ((ret (vc-cleartool-blocking-call (format "setview %s" view))))
3835       (if (string-match "cleartool: Error:" ret)
3836           (error (substring ret (match-end 0)))
3837         (setq cleartool-view view)))))
3838
3839 (defun vc-cleartool-cmd (path cmd)
3840   (vc-setview (vc-cc-pwv path))
3841   (vc-cleartool-blocking-call cmd))
3842
3843 (defun vc-cleartool-blocking-call (cmd)
3844   (interactive)
3845   (save-excursion
3846     (setq vc-return nil)
3847     (if (not cleartool-tq)
3848         (vc-start-cleartool))
3849     (unwind-protect
3850         (progn
3851           (tq-enqueue cleartool-tq (concat cmd "\n") "[.\n]*cleartool> " nil 'vc-callback)
3852           (while (not vc-return)
3853             (vc-accept-process-output (tq-process cleartool-tq) vc-subproc-timeout)))
3854       (while (tq-queue cleartool-tq)
3855         (tq-queue-pop cleartool-tq))))
3856   vc-return)
3857
3858 (defun vc-kill-tq ()
3859   (process-send-eof (tq-process cleartool-tq))
3860   (kill-process (tq-process cleartool-tq))
3861   (setq vc-running nil)
3862   (setq cleartool-tq nil))
3863
3864 (defun vc-what-the-hey ()
3865  (let ((kill-buffer-hook nil))
3866    (if (eq (current-buffer) (tq-buffer cleartool-tq))
3867        (error "Don't kill TQ buffer %s, use `vc-kill-tq'" (current-buffer)))
3868    ))
3869 ;;    (debug nil "Killing TQ buffer" (current-buffer)))))
3870 (add-hook 'kill-buffer-hook 'vc-what-the-hey)
3871
3872 (defun vc-split-string (pat str &optional indir suffix)
3873   (let ((ret nil)
3874         (start 0)
3875         (last (length str)))
3876     (while (< start last)
3877       (if (string-match pat str start)
3878           (progn
3879             (let ((tmp (substring str start (match-beginning 0))))
3880               (if suffix (setq tmp (concat tmp suffix)))
3881               (setq ret (cons (if indir (cons tmp nil)
3882                                 tmp)
3883                           ret)))
3884             (setq start (match-end 0)))
3885         (setq start last)
3886         (setq ret (cons (substring str start) ret))))
3887     (nreverse ret)))
3888
3889 ;;;dont ###autoload, it conflicts with vc.el
3890 (defun vc-mkbrtype (typename comment)
3891   (interactive "sBranch type name: \nsBranch type comment: ")
3892   (message "%s" (vc-cleartool-cmd default-directory
3893                                   (format "mkbrtype -vob %s -c '%s' %s"
3894                                           default-directory comment typename))))
3895
3896 ;;; warn when editing files which *should* be under change
3897 ;;; control, but aren't.
3898 ;;;
3899
3900 (defvar vc-controlled-trees ()
3901   "*A list of regexps; if any of these match buffer-file name, and
3902 the file in question is not under version control, an error will be signalled")
3903
3904 (defun vc-edit-warn ()
3905   (let ((need-work
3906          (and buffer-file-name
3907               buffer-file-number
3908               (not vc-mode)
3909               (let ((paths vc-controlled-trees))
3910                 (catch 'break
3911                   (while paths
3912                     (if (string-match (car paths) buffer-file-name)
3913                         (throw 'break t))
3914                     (setq paths (cdr paths))))))))
3915     (if need-work
3916         (progn
3917           (vc-register)
3918           (if buffer-read-only
3919               (vc-toggle-read-only))))))
3920
3921 ;; This causes XEmacs 19.15 VM MIME to fail.
3922 ;; (add-hook 'first-change-hook 'vc-edit-warn)
3923
3924 ;;; completions, view autostart in /view given view registry
3925
3926 (defvar vc-cc-known-view-cache nil
3927   "Cache of views known to the local system.")
3928
3929 (defvar vc-cc-view-cache-timeout 300
3930   "*Default timeout of view list cache, in seconds.")
3931
3932 (defun vc-timeout (delay function arg)
3933   (if (fboundp 'start-itimer)
3934       (start-itimer "VC-CC-Cache" function delay)
3935     (if (fboundp 'run-at-time)
3936         (run-at-time (format "%s sec" delay) nil function arg)
3937       (error "vc-timeout: don't know how to set a timeout function"))))
3938
3939 (defun vc-cc-known-views  ()
3940   (message "Fetching view names...")
3941   (let ((raw-views (vc-cleartool-blocking-call "lsview -short")))
3942     (prog1
3943         (vc-split-string "\n *" raw-views t "/")
3944       (message "Fetching view names...done"))))
3945
3946 (defun vc-cc-get-view-cache ()
3947   (or vc-cc-known-view-cache
3948       (progn
3949         (let ((default-directory "/"))
3950           (vc-timeout vc-cc-view-cache-timeout
3951                        (function (lambda (&rest ignore)
3952                                    (setq vc-cc-known-view-cache nil)))
3953                        nil))
3954         (setq vc-cc-known-view-cache (vc-cc-known-views)))))
3955
3956 (defun vc-cc-get-view-cache-noslash ()
3957   (let ((cache (vc-cc-get-view-cache)))
3958     (mapcar (lambda (vn)
3959               (let ((tmp (car vn)))
3960                 (cons (substring tmp 0 (- (length tmp) 1))
3961                       (cdr vn))))
3962             cache)))
3963
3964 (defun vc-cc-start-view (view-tag)
3965   (let ((tagfile (file-name-as-directory view-tag)))
3966     (if (assoc tagfile (vc-cc-get-view-cache))
3967         (let ((tagname (directory-file-name view-tag)))
3968           (message "Starting view server for %s..." tagname)
3969           (vc-cleartool-blocking-call (format "startview %s"
3970                                     (directory-file-name tagname)))
3971           (message "Starting view server for %s...done" tagname)))))
3972
3973 (defun vc-syslog (buf value)
3974   (save-excursion
3975     (let ((tmpbuf (get-buffer buf)))
3976       (if (bufferp tmpbuf)
3977           (progn
3978             (set-buffer buf)
3979             (goto-char (point-max))
3980             (insert (format "%s\n" value)))))))
3981
3982 (defun vc-cc-dedouble (pathname)
3983   (let ((root (file-name-as-directory (or (getenv "CLEARCASE_ROOT") ""))))
3984     (if (stringp pathname)
3985         (cond ((string-match "^/view/[^/]+\\(/view/\\)" pathname)
3986                (vc-cc-dedouble (substring pathname (match-beginning 1))))
3987               ((string= root "/")
3988                pathname)
3989               ((and (< (length root) (length pathname))
3990                     (string= root (substring pathname 0 (length root))))
3991                (vc-cc-dedouble (substring pathname (- (length root) 1))))
3992               (t
3993                pathname)))))
3994
3995 ;;;dont ###autoload, it conflicts with vc.el
3996 (defun vc-cc-file-handler (operation &rest args)
3997   (save-match-data
3998     (let* ((file-name-handler-alist nil)
3999            (path (vc-cc-dedouble (car args)))
4000            (tag (vc-cc-tagname path)))
4001       (setq default-directory (vc-cc-dedouble default-directory))
4002       (vc-syslog "*FH*" (cons operation args))
4003       (if tag
4004           (or (file-exists-p (format "/view/%s" tag))
4005               (vc-cc-start-view tag)))
4006       (apply operation args))))
4007
4008 (defun vc-view-completion (file dir)
4009   (try-completion file (vc-cc-get-view-cache)))
4010
4011 (defun vc-view-completions (file dir)
4012   (all-completions file (vc-cc-get-view-cache)))
4013
4014 ;;;dont ###autoload, it conflicts with vc.el
4015 (defun vc-cc-view-handler (operation &rest args)
4016   (save-match-data
4017     (vc-syslog "*FH*" (cons "VIEW:" (cons operation args)))
4018     (let ((file-name-handler-alist nil))
4019       (cond ((eq operation 'file-name-completion)
4020              (apply 'vc-view-completion args))
4021             ((eq operation 'file-name-all-completions)
4022              (apply 'vc-view-completions args))
4023             (t (apply operation args))))))
4024
4025 ;; vc-cc-what
4026
4027 ;;;dont ###autoload, it conflicts with vc.el
4028 (defun vc-cc-what-rule (file)
4029   (interactive (list (cond (vc-dired-mode (dired-get-filename))
4030                            (buffer-file-name)
4031                            (default-directory))))
4032
4033   ;; File should not have a version extension, it will not have a rule!
4034   (setq file (vc-cc-element-name file))
4035
4036   (let ((result (vc-cleartool-cmd file (format "ls -d %s" file))))
4037     (if (string-match "Rule: \\(.*\\)\n" result)
4038         (message (substring result
4039                             ;; Be a little more verbose
4040                             (match-beginning 0) (match-end 1)))
4041       (error result)
4042       )))
4043
4044 ;;(defun vc-cc-enumerate-versions (file)
4045 ;;  "Produce an alist, suitable for the completion functions, of the
4046 ;;versions of the element named by FILE"
4047 ;;  (message "Finding versions of %s..." file)
4048 ;;  (let ((versions nil))
4049 ;;    (vc-file-tree-walk-internal
4050 ;;     (vc-cc-build-version file "")
4051 ;;     (function (lambda (f &rest args)
4052 ;;               (if (not (string-match "/CHECKEDOUT[^/]*$" f))
4053 ;;                   (setq versions
4054 ;;                         (cons (list (vc-cc-version-name f))
4055 ;;                               versions)))))
4056 ;;     nil
4057 ;;     t)
4058 ;;    (message "Finding versions of %s...done" file)
4059 ;;    (nreverse versions)))
4060
4061 (defun vc-cc-enumerate-versions (file)
4062   "Produce an alist, suitable for the completion functions, of the
4063 versions of the element named by FILE"
4064   (message "Finding versions of %s..." file)
4065   (let ((raw-info (vc-cleartool-cmd
4066                    default-directory
4067                    (format "lsvtree -all -nco -short %s" file))))
4068     (prog1
4069         (mapcar (function (lambda (x)
4070                             (list (vc-cc-version-name x))))
4071                 (vc-split-string "\n" raw-info))
4072       (message "Finding versions of %s...done" file))))
4073
4074 (defsubst vc-buffer-match (tag)
4075   (buffer-substring (match-beginning tag)
4076                     (match-end tag)))
4077
4078 (defun vc-extract-environ-from-view-1 (tag)
4079   (let ((tmp-buffer (generate-new-buffer " *env temp*"))
4080         ret)
4081     (unwind-protect
4082         (save-excursion
4083           (set-buffer tmp-buffer)
4084           (insert (vc-cleartool-blocking-call (format "catcs -tag %s" tag)))
4085           (goto-char (point-min))
4086           (keep-lines "%ENV%")
4087           (goto-char (point-min))
4088           (while (re-search-forward "^.*%ENV%[ \t]\\(.*\\)=\\(.*\\)$" nil t)
4089             (setq ret (cons (format "%s=%s"
4090                                     (vc-buffer-match 1)
4091                                     (vc-buffer-match 2))
4092                             ret)))
4093           ret)
4094       (kill-buffer tmp-buffer))))
4095
4096 (defun vc-add-env (env var)
4097   (catch 'return
4098     (let ((a env)
4099           (vname (substring var 0
4100                             (and (string-match "=" var)
4101                                  (match-end 0)))))
4102       (let ((vnl (length vname)))
4103         (while a
4104           (if (and (> (length (car a)) vnl)
4105                    (string= (substring (car a) 0 vnl)
4106                             vname))
4107               (throw 'return env))
4108           (setq a (cdr a)))
4109         (cons var env)))))
4110
4111 (defun vc-extract-environ-from-view (old-env tag &optional add-ons)
4112   (let ((newenv nil)
4113         (cc-env (vc-extract-environ-from-view-1 tag)))
4114     (while add-ons
4115       (setq newenv (vc-add-env newenv (car add-ons)))
4116       (setq add-ons (cdr add-ons)))
4117     (while cc-env
4118       (setq newenv (vc-add-env newenv (car cc-env)))
4119       (setq cc-env (cdr cc-env)))
4120     (while old-env
4121       (setq newenv (vc-add-env newenv (car old-env)))
4122       (setq old-env (cdr old-env)))
4123     newenv))
4124
4125 (defsubst vc-setview-arglist (dir args)
4126   (let ((r (concat (if dir (format "cd %s; " dir) "")
4127                    "exec "
4128                    (mapconcat 'identity args " "))))
4129     (insert r "\n")
4130     r))
4131
4132 (if (not (fboundp 'dired-get-filename))
4133 (defun dired-get-filename (&optional localp no-error-if-not-filep)
4134   "In dired, return name of file mentioned on this line.
4135 Value returned normally includes the directory name.
4136 Optional arg LOCALP with value `no-dir' means don't include directory
4137   name in result.  A value of t means construct name relative to
4138   `default-directory', which still may contain slashes if in a subdirectory.
4139 Optional arg NO-ERROR-IF-NOT-FILEP means return nil if no filename on
4140   this line, otherwise an error occurs."
4141   (let (case-fold-search file p1 p2)
4142     (save-excursion
4143       (if (setq p1 (dired-move-to-filename (not no-error-if-not-filep)))
4144           (setq p2 (dired-move-to-end-of-filename no-error-if-not-filep))))
4145     ;; nil if no file on this line, but no-error-if-not-filep is t:
4146     (if (setq file (and p1 p2 (format "%s" (buffer-substring p1 p2))))
4147         ;; Check if ls quoted the names, and unquote them.
4148         ;; Using read to unquote is much faster than substituting
4149         ;; \007 (4 chars) -> ^G  (1 char) etc. in a lisp loop.
4150         (cond ((string-match "b" dired-actual-switches) ; System V ls
4151                ;; This case is about 20% slower than without -b.
4152                (setq file
4153                      (read
4154                       (concat "\""
4155                               ;; some ls -b don't escape quotes, argh!
4156                               ;; This is not needed for GNU ls, though.
4157                               (or (dired-string-replace-match
4158                                    "\\([^\\]\\)\"" file "\\1\\\\\"")
4159                                   file)
4160                               "\""))))
4161               ;; If you do this, update dired-insert-subdir-validate too
4162               ;; ((string-match "Q" dired-actual-switches) ; GNU ls
4163               ;;  (setq file (read file)))
4164               ))
4165     (if (or (eq localp 'no-dir) (null file) (eq (aref file 0) ?/))
4166         file
4167       (concat (dired-current-directory localp) file)))))
4168
4169 ;;;dont ###autoload, it conflicts with vc.el
4170 (defun vc-cc-browse-versions ()
4171   (interactive)
4172   (let ((file (cond (vc-dired-mode (dired-get-filename))
4173                     (buffer-file-name)
4174                     (default-directory))))
4175     (if (clearcase-element-p file)
4176         (if (boundp 'vc-mode)
4177             (let* ((clearcase-extended-name
4178                     (concat (vc-cc-element-name file)
4179                             "@@"
4180                             (or (vc-cc-version-name file)
4181                                 (vc-latest-version file))))
4182                    (dired-listing-switches (concat dired-listing-switches
4183                                                    "tr"))
4184 ;;                   (file-name-handler-alist nil) ;; shut off my special handler
4185                    (clearcase-branch (file-name-directory clearcase-extended-name)))
4186               (if (file-exists-p clearcase-extended-name)
4187                   (progn
4188                     ;; Invoke dired on the directory of the version branch
4189                     (dired clearcase-branch)
4190
4191                     (if (re-search-forward (concat "[ \t]+"
4192                                                    "\\("
4193                                                    (regexp-quote clearcase-branch)
4194                                                    "\\)"
4195                                                    "$")
4196                                        nil
4197                                        t)
4198                         (goto-char (match-beginning 1))))
4199                 (dired (concat file "@@")))))
4200       (error "Not a Clearcase element"))))
4201
4202 ;;----------------------------------------------------------------------------
4203 ;; Advise various other functions to properly handle ClearCase extended paths
4204 ;;----------------------------------------------------------------------------
4205 (defadvice gud-find-file (before vc-gud-find-file protect activate)
4206   "Sets the current view and comint-file-name-prefix if necessary for ClearCase support."
4207   (let ((tag (and (string-match "^\\(/view/[^/]+\\)" default-directory)
4208                   (substring default-directory
4209                              (match-beginning 1)
4210                              (match-end 1)))))
4211     (and tag
4212          (ad-set-arg 0 (concat tag (ad-get-arg 0))))))
4213
4214 (defadvice comint-exec-1 (around vc-comint-exec-1 protect activate)
4215   "Sets the current view and comint-file-name-prefix if necessary for ClearCase support."
4216   (let ((tag (vc-cc-pwv default-directory))
4217         (view-rel (vc-cc-relpath default-directory))
4218         (wdir-in-clearcase (file-directory-p ".@@/main")))
4219     (if (or (not (or (string-match "^/view/" default-directory)
4220                      wdir-in-clearcase))
4221             (string= tag (vc-cc-pwv (getenv "CLEARCASE_ROOT"))))
4222         ad-do-it
4223       (let ((process-environment
4224              ;; If using termcap, we specify `emacs' as the terminal type
4225              ;; because that lets us specify a width.
4226              ;; If using terminfo, we specify `unknown' because that is
4227              ;; a defined terminal type.  `emacs' is not a defined terminal
4228              ;; type and there is no way for us to define it here.
4229              ;; Some programs that use terminfo get very confused
4230              ;; if TERM is not a valid terminal type.
4231              (vc-extract-environ-from-view process-environment tag
4232                                            (if (and (boundp 'system-uses-terminfo)
4233                                                     (symbol-value 'system-uses-terminfo))
4234                                                (list "EMACS=t" "TERM=unknown"
4235                                                      (format "COLUMNS=%d" (frame-width)))
4236                                              (list "EMACS=t" "TERM=emacs"
4237                                                    (format "TERMCAP=emacs:co#%d:tc=unknown" (frame-width)))))))
4238         (insert "setview " tag "\n")
4239         (make-variable-buffer-local 'comint-file-name-prefix)
4240         (setq comint-file-name-prefix (format "/view/%s" tag))
4241         (setq ad-return-value
4242               (start-process name buffer vc-cleartool-path
4243                              "setview" "-exec"
4244
4245                      (vc-setview-arglist view-rel (cons command switches))
4246                              tag))))))
4247
4248 (defadvice start-process-shell-command (around vc-spsc protect activate)
4249   "Sets the current view and comint-file-name-prefix if necessary for ClearCase support."
4250   (let ((tag (vc-cc-pwv default-directory))
4251         (view-rel (vc-cc-relpath default-directory))
4252         (wdir-in-clearcase (file-directory-p ".@@/main")))
4253     (if (null wdir-in-clearcase)
4254         ad-do-it
4255       (let ((process-environment (vc-extract-environ-from-view process-environment tag)))
4256         (if (string= tag (vc-cc-pwv (getenv "CLEARCASE_ROOT")))
4257             ad-do-it
4258           (progn
4259             (insert "setview " tag "\n")
4260             (make-variable-buffer-local 'comint-file-name-prefix)
4261             (setq comint-file-name-prefix (format "/view/%s" tag))
4262
4263             (setq ad-return-value
4264                   (start-process name buffer vc-cleartool-path
4265                                  "setview" "-exec"
4266                                  (vc-setview-arglist view-rel args)
4267                                  tag))))))))
4268
4269 ;;; Hook into jka-compr so it knows a little about clearcase
4270 ;;; version-extended names..
4271
4272 (defvar vc-jka-compr-hook-installed nil
4273   "Is hook for vc installed in jka-compr?")
4274
4275 (if (and (not vc-jka-compr-hook-installed)
4276          (fboundp 'jka-compr-installed-p)
4277          (jka-compr-installed-p))
4278     (progn
4279       (jka-compr-uninstall)
4280       (setq jka-compr-compression-info-list
4281             (append '(["\\.gz\\(@@.*\\)\\'"
4282                        "zipping" "gzip" ("-c" "-q")
4283                        "unzipping" "gzip" ("-c" "-q" "-d") nil t])
4284                     jka-compr-compression-info-list))
4285       (setq auto-mode-alist
4286             (append '(("\\.gz\\(~\\|\\.~[0-9]+~\\)?\\'" nil jka-compr))
4287                     auto-mode-alist))
4288       (setq vc-jka-compr-hook-installed t)
4289       (jka-compr-install)))
4290
4291 ;;; vc-cc.el ends here
4292