vc.el 113 KB
Newer Older
Eric S. Raymond's avatar
Eric S. Raymond committed
1 2
;;; vc.el --- drive a version-control system from within Emacs

3
;; Copyright (C) 1992,93,94,95,96,97,98,2000  Free Software Foundation, Inc.
Eric S. Raymond's avatar
Eric S. Raymond committed
4

5 6
;; Author:     FSF (see below for full credits)
;; Maintainer: Andre Spiegel <spiegel@gnu.org>
Eric S. Raymond's avatar
Eric S. Raymond committed
7

8
;; $Id: vc.el,v 1.1 2000/09/04 19:35:57 gerd Exp gerd $
9

Eric S. Raymond's avatar
Eric S. Raymond committed
10 11 12 13 14 15 16 17 18 19 20 21 22
;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
Erik Naggum's avatar
Erik Naggum committed
23 24 25
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
Eric S. Raymond's avatar
Eric S. Raymond committed
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
;;; Credits:

;; VC was initially designed and implemented by Eric S. Raymond
;; <esr@snark.thyrsus.com>.  Over the years, many people have
;; contributed substantial amounts of work to VC.  These include:
;;   Per Cederqvist <ceder@lysator.liu.se>
;;   Paul Eggert <eggert@twinsun.com>
;;   Sebastian Kremer <sk@thp.uni-koeln.de>
;;   Martin Lorentzson <martinl@gnu.org>
;;   Dave Love <d.love@dl.ac.uk>
;;   Stefan Monnier <monnier@cs.yale.edu>
;;   Andre Spiegel <spiegel@gnu.org>
;;   Richard Stallman <rms@gnu.org>
;;   ttn@netcom.com

Eric S. Raymond's avatar
Eric S. Raymond committed
42 43
;;; Commentary:

44 45
;; This mode is fully documented in the Emacs user's manual.
;;
46
;; Supported version-control systems presently include SCCS, RCS, and CVS.
47 48 49
;;
;; Some features will not work with old RCS versions.  Where
;; appropriate, VC finds out which version you have, and allows or
50
;; disallows those features (stealing locks, for example, works only
51
;; from 5.6.2 onwards).
52 53
;; Even initial checkins will fail if your RCS version is so old that ci
;; doesn't understand -t-; this has been known to happen to people running
54
;; NExTSTEP 3.0.
Eric S. Raymond's avatar
Eric S. Raymond committed
55
;;
56
;; You can support the RCS -x option by customizing vc-rcs-master-templates.
Eric S. Raymond's avatar
Eric S. Raymond committed
57 58 59 60
;;
;; Proper function of the SCCS diff commands requires the shellscript vcdiff
;; to be installed somewhere on Emacs's path for executables.
;;
61
;; If your site uses the ChangeLog convention supported by Emacs, the
62
;; function vc-comment-to-change-log should prove a useful checkin hook.
63
;;
Eric S. Raymond's avatar
Eric S. Raymond committed
64 65
;; The vc code maintains some internal state in order to reduce expensive
;; version-control operations to a minimum.  Some names are only computed
66
;; once.  If you perform version control operations with RCS/SCCS/CVS while
Eric S. Raymond's avatar
Eric S. Raymond committed
67 68 69 70 71 72 73 74
;; vc's back is turned, or move/rename master files while vc is running,
;; vc may get seriously confused.  Don't do these things!
;;
;; Developer's notes on some concurrency issues are included at the end of
;; the file.

;;; Code:

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
;;;;;;;;;;;;;;;;; Backend-specific functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; for each operation FUN, the backend should provide a function vc-BACKEND-FUN.
;; Operations marked with a `-' instead of a `*' have a sensible default
;; behavior.

;; * registered (file)
;; * state (file)
;; - state-heuristic (file)
;;     The default behavior delegates to `state'.
;; - dir-state (dir)
;; * checkout-model (file)
;; - mode-line-string (file)
;; * workfile-version (file)
;; * revert (file)
;; * merge-news (file)
;; * merge (file rev1 rev2)
;; * steal-lock (file &optional version)
;; * register (file rev comment)
;; * responsible-p (file)
;;     Should also work if FILE is a directory (ends with a slash).
;; - could-register (file)
;; * checkout (file writable &optional rev destfile)
;;     Checkout revision REV of FILE into DESTFILE.
;;     DESTFILE defaults to FILE.
;;     The file should be made writable if WRITABLE is non-nil.
;;     REV can be nil (BASE) or "" (HEAD) or any other revision.
;; * checkin (file rev comment)
;; - logentry-check ()
;; * diff (file &optional rev1 rev2)
;;     Insert the diff for FILE into the current buffer.
;;     REV1 should default to workfile-version.
;;     REV2 should default to the current workfile
;;     Return a status of either 0 (i.e. no diff) or 1 (i.e. either non-empty
;;     diff or the diff is run asynchronously).
;; - workfile-unchanged-p (file)
;;     Return non-nil if FILE is unchanged from its current workfile version.
;;     This function should do a brief comparison of FILE's contents
;;     with those of the master version.  If the backend does not have
;;     such a brief-comparison feature, the default implementation of this
;;     function can be used, which delegates to a full vc-BACKEND-diff.
;; - clear-headers ()
;; * check-headers ()
;; - dired-state-info (file)
;; - create-snapshot (dir name branchp)
;;     Take a snapshot of the current state of files under DIR and name it NAME.
;;     This should make sure that files are up-to-date before proceeding
;;     with the action.
;;     DIR can also be a file and if BRANCHP is specified, NAME
;;     should be created as a branch and DIR should be checked out under
;;     this new branch.  The default behavior does not support branches
;;     but does a sanity check, a tree traversal and for each file calls
;;     `assign-name'.
;; * assign-name (file name)
;;     Give name NAME to the current version of FILE, assuming it is
;;     up-to-date.  Only used by the default version of `create-snapshot'.
;; - retrieve-snapshot (dir name update)
;;     Retrieve a named snapshot of all registered files at or below DIR.
;;     If UPDATE is non-nil, then update buffers of any files in the snapshot 
;;     that are currently visited.
;; * print-log (file)
;;     Insert the revision log of FILE into the current buffer.
;; - show-log-entry (version)
;; - update-changelog (files)
;;     Find changelog entries for FILES, or for all files at or below
;;     the default-directory if FILES is nil.
;; * latest-on-branch-p (file)
;;     Only used for sanity check before calling `uncheck'.
;; * uncheck (file target)
;; * rename-file (old new)
;; * annotate-command (file buf)
;; * annotate-difference (pos)

Eric S. Raymond's avatar
Eric S. Raymond committed
148
(require 'vc-hooks)
149
(require 'ring)
150 151 152
(eval-when-compile
  (require 'compile)
  (require 'dired))	; for dired-map-over-marks macro
153 154 155 156 157

(if (not (assoc 'vc-parent-buffer minor-mode-alist))
    (setq minor-mode-alist
	  (cons '(vc-parent-buffer vc-parent-buffer-name)
		minor-mode-alist)))
Eric S. Raymond's avatar
Eric S. Raymond committed
158 159 160

;; General customization

161 162 163 164 165 166 167 168 169
(defgroup vc nil
  "Version-control system in Emacs."
  :group 'tools)

(defcustom vc-suppress-confirm nil
  "*If non-nil, treat user as expert; suppress yes-no prompts on some things."
  :type 'boolean
  :group 'vc)

170 171 172 173 174 175 176 177
(defcustom vc-delete-logbuf-window t
  "*If non-nil, delete the *VC-log* buffer and window after each logical action.
If nil, bury that buffer instead.
This is most useful if you have multiple windows on a frame and would like to
preserve the setting."
  :type 'boolean
  :group 'vc)

178 179 180 181 182
(defcustom vc-initial-comment nil
  "*If non-nil, prompt for initial comment when a file is registered."
  :type 'boolean
  :group 'vc)

183 184
(defcustom vc-default-init-version "1.1"
  "*A string used as the default version number when a new file is registered.
185
This can be overridden by giving a prefix argument to \\[vc-register]."
186
  :type 'string
Dan Nicolaescu's avatar
Dan Nicolaescu committed
187 188
  :group 'vc
  :version "20.3")
189

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
(defcustom vc-command-messages nil
  "*If non-nil, display run messages from back-end commands."
  :type 'boolean
  :group 'vc)

(defcustom vc-checkin-switches nil
  "*A string or list of strings specifying extra switches for checkin.
These are passed to the checkin program by \\[vc-checkin]."
  :type '(choice (const :tag "None" nil)
		 (string :tag "Argument String")
		 (repeat :tag "Argument List"
			 :value ("")
			 string))
  :group 'vc)

(defcustom vc-checkout-switches nil
  "*A string or list of strings specifying extra switches for checkout.
These are passed to the checkout program by \\[vc-checkout]."
  :type '(choice (const :tag "None" nil)
		 (string :tag "Argument String")
		 (repeat :tag "Argument List"
			 :value ("")
			 string))
  :group 'vc)

(defcustom vc-register-switches nil
  "*A string or list of strings; extra switches for registering a file.
These are passed to the checkin program by \\[vc-register]."
  :type '(choice (const :tag "None" nil)
		 (string :tag "Argument String")
		 (repeat :tag "Argument List"
			 :value ("")
			 string))
  :group 'vc)

225 226 227 228 229 230
(defcustom vc-dired-listing-switches "-al"
  "*Switches passed to `ls' for vc-dired.  MUST contain the `l' option."
  :type 'string
  :group 'vc
  :version "21.0")

231 232 233 234 235 236 237 238 239 240 241 242
(defcustom vc-dired-recurse t
  "*If non-nil, show directory trees recursively in VC Dired."
  :type 'boolean
  :group 'vc
  :version "20.3")

(defcustom vc-dired-terse-display t
  "*If non-nil, show only locked files in VC Dired."
  :type 'boolean
  :group 'vc
  :version "20.3")

243 244 245 246
(defcustom vc-directory-exclusion-list '("SCCS" "RCS" "CVS")
  "*List of directory names to be ignored while recursively walking file trees."
  :type '(repeat string)
  :group 'vc)
247

248 249 250
(defconst vc-maximum-comment-ring-size 32
  "Maximum number of saved comments in the comment ring.")

251 252
;;; This is duplicated in diff.el.
(defvar diff-switches "-c"
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
  "*A string or list of strings specifying switches to be passed to diff.")

;;;###autoload
(defcustom vc-checkin-hook nil
  "*Normal hook (list of functions) run after a checkin is done.
See `run-hooks'."
  :type 'hook
  :options '(vc-comment-to-change-log)
  :group 'vc)

;;;###autoload
(defcustom vc-before-checkin-hook nil
  "*Normal hook (list of functions) run before a file gets checked in.
See `run-hooks'."
  :type 'hook
  :group 'vc)

(defcustom vc-logentry-check-hook nil
  "*Normal hook run by `vc-backend-logentry-check'.
Use this to impose your own rules on the entry in addition to any the
version control backend imposes itself."
  :type 'hook
  :group 'vc)
276

277
;; Annotate customization
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
(defcustom vc-annotate-color-map
  '(( 26.3672 . "#FF0000")
    ( 52.7344 . "#FF3800")
    ( 79.1016 . "#FF7000")
    (105.4688 . "#FFA800")
    (131.8359 . "#FFE000")
    (158.2031 . "#E7FF00")
    (184.5703 . "#AFFF00")
    (210.9375 . "#77FF00")
    (237.3047 . "#3FFF00")
    (263.6719 . "#07FF00")
    (290.0391 . "#00FF31")
    (316.4063 . "#00FF69")
    (342.7734 . "#00FFA1")
    (369.1406 . "#00FFD9")
    (395.5078 . "#00EEFF")
    (421.8750 . "#00B6FF")
    (448.2422 . "#007EFF"))
  "*Association list of age versus color, for \\[vc-annotate].
Ages are given in units of 2**-16 seconds.
Default is eighteen steps using a twenty day increment."
299
  :type 'alist
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
  :group 'vc)

(defcustom vc-annotate-very-old-color "#0046FF"
  "*Color for lines older than CAR of last cons in `vc-annotate-color-map'."
  :type 'string
  :group 'vc)

(defcustom vc-annotate-background "black"
  "*Background color for \\[vc-annotate].
Default color is used if nil."
  :type 'string
  :group 'vc)

(defcustom vc-annotate-menu-elements '(2 0.5 0.1 0.01)
  "*Menu elements for the mode-specific menu of VC-Annotate mode.
List of factors, used to expand/compress the time scale.  See `vc-annotate'."
316
  :type '(repeat number)
317 318
  :group 'vc)

319 320 321
;; vc-annotate functionality (CVS only).
(defvar vc-annotate-mode nil
  "Variable indicating if VC-Annotate mode is active.")
322

323 324 325 326 327
(defvar vc-annotate-mode-map
  (let ((m (make-sparse-keymap)))
    (define-key m [menu-bar] (make-sparse-keymap "VC-Annotate"))
    m)
  "Local keymap used for VC-Annotate mode.")
328

329 330
(defvar vc-annotate-mode-menu nil
  "Local keymap used for VC-Annotate mode's menu bar menu.")
331

Eric S. Raymond's avatar
Eric S. Raymond committed
332 333
;; Header-insertion hair

334
(defcustom vc-static-header-alist
Eric S. Raymond's avatar
Eric S. Raymond committed
335 336
  '(("\\.c$" .
     "\n#ifndef lint\nstatic char vcid[] = \"\%s\";\n#endif /* lint */\n"))
337 338 339
  "*Associate static header string templates with file types.
A \%s in the template is replaced with the first string associated with
the file's version-control type in `vc-header-alist'."
340 341 342 343
  :type '(repeat (cons :format "%v"
		       (regexp :tag "File Type")
		       (string :tag "Header String")))
  :group 'vc)
344

345
(defcustom vc-comment-alist
Eric S. Raymond's avatar
Eric S. Raymond committed
346 347 348 349
  '((nroff-mode ".\\\"" ""))
  "*Special comment delimiters to be used in generating vc headers only.
Add an entry in this list if you need to override the normal comment-start
and comment-end variables.  This will only be necessary if the mode language
350 351 352 353 354 355
is sensitive to blank lines."
  :type '(repeat (list :format "%v"
		       (symbol :tag "Mode")
		       (string :tag "Comment Start")
		       (string :tag "Comment End")))
  :group 'vc)
Eric S. Raymond's avatar
Eric S. Raymond committed
356

357
;; Default is to be extra careful for super-user.
358 359 360
;; TODO: This variable is no longer used; the corresponding checks  
;;       are always done now.  If that turns out to be fast enough, 
;;       the variable can be obsoleted.
361
(defcustom vc-checkout-carefully (= (user-uid) 0)
362 363
  "*Non-nil means be extra-careful in checkout.
Verify that the file really is not locked
364 365 366
and that its contents match what the master file says."
  :type 'boolean
  :group 'vc)
367

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388

;;; The main keymap

(defvar vc-prefix-map
  (let ((map (make-sparse-keymap)))
    (define-key map "a" 'vc-update-change-log)
    (define-key map "c" 'vc-cancel-version)
    (define-key map "d" 'vc-directory)
    (define-key map "g" 'vc-annotate)
    (define-key map "h" 'vc-insert-headers)
    (define-key map "i" 'vc-register)
    (define-key map "l" 'vc-print-log)
    (define-key map "m" 'vc-merge)
    (define-key map "r" 'vc-retrieve-snapshot)
    (define-key map "s" 'vc-create-snapshot)
    (define-key map "u" 'vc-revert-buffer)
    (define-key map "v" 'vc-next-action)
    (define-key map "=" 'vc-diff)
    (define-key map "~" 'vc-version-other-window)
    map))
(fset 'vc-prefix-map vc-prefix-map)
389

390 391 392 393 394 395 396 397 398 399 400
;; Initialization code, to be done just once at load-time
(defvar vc-log-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\M-n" 'vc-next-comment)
    (define-key map "\M-p" 'vc-previous-comment)
    (define-key map "\M-r" 'vc-comment-search-reverse)
    (define-key map "\M-s" 'vc-comment-search-forward)
    (define-key map "\C-c\C-c" 'vc-finish-logentry)
    map))
;; Compatibility with old name.  Should we bother ?
(defvar vc-log-entry-mode vc-log-mode-map)
401

402

Eric S. Raymond's avatar
Eric S. Raymond committed
403 404
;; Variables the user doesn't need to know about.
(defvar vc-log-operation nil)
405
(defvar vc-log-after-operation-hook nil)
406
(defvar vc-checkout-writable-buffer-hook 'vc-checkout-writable-buffer)
407 408 409 410
(defvar vc-annotate-buffers nil
  "An association list of current \"Annotate\" buffers and their
corresponding backends.  The keys are \(BUFFER . BACKEND\).  See also
`vc-annotate-get-backend'.")
Richard M. Stallman's avatar
Richard M. Stallman committed
411 412 413
;; In a log entry buffer, this is a local variable
;; that points to the buffer for which it was made
;; (either a file, or a VC dired buffer).
414
(defvar vc-parent-buffer nil)
415
(put 'vc-parent-buffer 'permanent-local t)
416
(defvar vc-parent-buffer-name nil)
417
(put 'vc-parent-buffer-name 'permanent-local t)
Eric S. Raymond's avatar
Eric S. Raymond committed
418

419 420 421
(defvar vc-log-file)
(defvar vc-log-version)

422
;; FIXME: only used in vc-sccs.el
Eric S. Raymond's avatar
Eric S. Raymond committed
423 424
(defconst vc-name-assoc-file "VC-names")

425
(defvar vc-dired-mode nil)
426 427
(make-variable-buffer-local 'vc-dired-mode)

428
(defvar vc-comment-ring (make-ring vc-maximum-comment-ring-size))
429
(defvar vc-comment-ring-index nil)
430
(defvar vc-last-comment-match "")
431

432 433 434
;;; functions that operate on RCS revision numbers.  This code should
;;; also be moved into the backends.  It stays for now, however, since
;;; it is used in code below.
435
(defun vc-trunk-p (rev)
436
  "Return t if REV is a revision on the trunk"
437 438
  (not (eq nil (string-match "\\`[0-9]+\\.[0-9]+\\'" rev))))

439
(defun vc-branch-p (rev)
440
  "Return t if REV is a branch revision"
441 442
  (not (eq nil (string-match "\\`[0-9]+\\(\\.[0-9]+\\.[0-9]+\\)*\\'" rev))))

443
(defun vc-branch-part (rev)
444
  "return the branch part of a revision number REV"
445 446
  (substring rev 0 (string-match "\\.[0-9]+\\'" rev)))

447
(defun vc-minor-part (rev)
448
  "Return the minor version number of a revision number REV"
449 450 451 452
  (string-match "[0-9]+\\'" rev)
  (substring rev (match-beginning 0) (match-end 0)))

(defun vc-previous-version (rev)
453
  "Guess the previous version number"
454 455 456 457 458 459 460 461 462 463 464 465 466
  (let ((branch (vc-branch-part rev))
        (minor-num (string-to-number (vc-minor-part rev))))
    (if (> minor-num 1)
        ;; version does probably not start a branch or release
        (concat branch "." (number-to-string (1- minor-num)))
      (if (vc-trunk-p rev)
          ;; we are at the beginning of the trunk --
          ;; don't know anything to return here
          ""
        ;; we are at the beginning of a branch --
        ;; return version of starting point
        (vc-branch-part branch)))))

Eric S. Raymond's avatar
Eric S. Raymond committed
467 468
;; File property caching

469 470 471 472 473 474
(defun vc-clear-context ()
  "Clear all cached file properties and the comment ring."
  (interactive)
  (fillarray vc-file-prop-obarray nil)
  ;; Note: there is potential for minor lossage here if there is an open
  ;; log buffer with a nonzero local value of vc-comment-ring-index.
475
  (setq vc-comment-ring (make-ring vc-maximum-comment-ring-size)))
476

Eric S. Raymond's avatar
Eric S. Raymond committed
477 478
;; Random helper functions

479 480 481 482
(defsubst vc-editable-p (file)
  (or (eq (vc-checkout-model file) 'implicit)
      (eq (vc-state file) 'edited)
      (eq (vc-state file) 'needs-merge)))
483

484 485 486
;;; Two macros for elisp programming
;;;###autoload
(defmacro with-vc-file (file comment &rest body)
487 488 489 490
  "Check out a writable copy of FILE if necessary and execute the body.
Check in FILE with COMMENT (a string) after BODY has been executed.
FILE is passed through `expand-file-name'; BODY executed within
`save-excursion'.  If FILE is not under version control, or locked by
491 492 493 494
somebody else, signal error."
  `(let ((file (expand-file-name ,file)))
     (or (vc-registered file)
	 (error (format "File not under version control: `%s'" file)))
495 496 497 498
     (unless (vc-editable-p file)
       (let ((state (vc-state file)))
	 (if (stringp state) (error (format "`%s' is locking `%s'" state file))
	   (vc-checkout file t))))
499 500 501 502 503 504
     (save-excursion
       ,@body)
     (vc-checkin file nil ,comment)))

;;;###autoload
(defmacro edit-vc-file (file comment &rest body)
505 506
  "Edit FILE under version control, executing body.
Checkin with COMMENT after executing BODY.
507 508 509 510 511 512 513 514
This macro uses `with-vc-file', passing args to it.
However, before executing BODY, find FILE, and after BODY, save buffer."
  `(with-vc-file
    ,file ,comment
    (find-file ,file)
    ,@body
    (save-buffer)))

515
(defun vc-ensure-vc-buffer ()
516 517
  "Make sure that the current buffer visits a version-controlled
file."
518 519 520 521 522 523 524 525
  (if vc-dired-mode
      (set-buffer (find-file-noselect (dired-get-filename)))
    (while vc-parent-buffer
      (pop-to-buffer vc-parent-buffer))
    (if (not (buffer-file-name))
	(error "Buffer %s is not associated with a file" (buffer-name))
      (if (not (vc-backend (buffer-file-name)))
	  (error "File %s is not under version control" (buffer-file-name))))))
526

Eric S. Raymond's avatar
Eric S. Raymond committed
527
(defvar vc-binary-assoc nil)
528 529 530 531
(defvar vc-binary-suffixes
  (if (memq system-type '(ms-dos windows-nt))
      '(".exe" ".com" ".bat" ".cmd" ".btm" "")
    '("")))
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

(defun vc-process-filter (p s)
  "An alternative output filter for async processes.
The only difference with the default filter is to insert S after markers."
  (with-current-buffer (process-buffer p)
    (save-excursion
      (let ((inhibit-read-only t))
	(goto-char (process-mark p))
	(insert s)
	(set-marker (process-mark p) (point))))))

(defun vc-setup-buffer (&optional buf)
  "prepare BUF for executing a VC command and make it the current buffer.
BUF defaults to \"*vc*\", can be a string and will be created if necessary."
  (unless buf (setq buf "*vc*"))
  (let ((camefrom (current-buffer))
	(olddir default-directory))
    (set-buffer (get-buffer-create buf))
    (kill-all-local-variables)
    (set (make-local-variable 'vc-parent-buffer) camefrom)
    (set (make-local-variable 'vc-parent-buffer-name)
	 (concat " from " (buffer-name camefrom)))
    (setq default-directory olddir)
    (let ((inhibit-read-only t))
      (erase-buffer))))

(defun vc-exec-after (code)
  "Eval CODE when the current buffer's process is done.
If the current buffer has no process, just evaluate CODE.
Else, add CODE to the process' sentinel."
  (let ((proc (get-buffer-process (current-buffer))))
    (cond
     ;; If there's no background process, just execute the code.
     ((null proc) (eval code))
     ;; If the background process has exited, reap it and try again
     ((eq (process-status proc) 'exit)
      (delete-process proc)
      (vc-exec-after code))
     ;; If a process is running, add CODE to the sentinel
     ((eq (process-status proc) 'run)
      (let ((sentinel (process-sentinel proc)))
	(set-process-sentinel proc
	  `(lambda (p s)
	     (with-current-buffer ',(current-buffer)
	       (goto-char (process-mark p))
	       ,@(append (cdr (cdr (cdr ;strip off `with-current-buffer buf 
                                        ;             (goto-char...)'
			   (car (cdr (cdr ;strip off `lambda (p s)'
			    sentinel))))))
			 (list `(vc-exec-after ',code))))))))
     (t (error "Unexpected process state"))))
  nil)

(defvar vc-post-command-functions nil
  "Hook run at the end of `vc-do-command'.
Each function is called inside the buffer in which the command was run
and is passed 3 argument: the COMMAND, the FILE and the FLAGS.")

(defun vc-do-command (buffer okstatus command file &rest flags)
Eric S. Raymond's avatar
Eric S. Raymond committed
591
  "Execute a version-control command, notifying user and checking for errors.
592 593
Output from COMMAND goes to BUFFER, or *vc* if BUFFER is nil or the current
buffer (which is assumed to be properly setup) if BUFFER is t.  The
594
command is considered successful if its exit status does not exceed
595 596
OKSTATUS (if OKSTATUS is nil, that means to ignore errors, if it is 'async,
that means not to wait for termination of the subprocess).  FILE is
597
the name of the working file (may also be nil, to execute commands
598 599
that don't expect a file name).  If an optional list of FLAGS is present, 
that is inserted into the command line before the filename."
600
  (and file (setq file (expand-file-name file)))
Eric S. Raymond's avatar
Eric S. Raymond committed
601
  (if vc-command-messages
602
      (message "Running %s on %s..." command file))
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
  (save-current-buffer
    (unless (eq buffer t) (vc-setup-buffer buffer))
    (let ((squeezed nil)
	  (inhibit-read-only t)
	  (status 0))
      (setq squeezed (delq nil (copy-sequence flags)))
      (when file
	;; FIXME: file-relative-name can return a bogus result because
	;; it doesn't look at the actual file-system to see if symlinks
	;; come into play.
	(setq squeezed (append squeezed (list (file-relative-name file)))))
      (let ((exec-path (append vc-path exec-path))
	    ;; Add vc-path to PATH for the execution of this command.
	    (process-environment
	     (cons (concat "PATH=" (getenv "PATH")
			   path-separator
			   (mapconcat 'identity vc-path path-separator))
		   process-environment))
	    (w32-quote-process-args t))
	(if (eq okstatus 'async)
	    (let ((proc (apply 'start-process command (current-buffer) command
			       squeezed)))
	      (message "Running %s in the background..." command)
	      ;;(set-process-sentinel proc (lambda (p msg) (delete-process p)))
	      (set-process-filter proc 'vc-process-filter)
	      (vc-exec-after
	       `(message "Running %s in the background... done" ',command)))
	  (setq status (apply 'call-process command nil t nil squeezed))
	  (when (or (not (integerp status)) (and okstatus (< okstatus status)))
	    (pop-to-buffer (current-buffer))
	    (goto-char (point-min))
	    (shrink-window-if-larger-than-buffer)
	    (error "Running %s...FAILED (%s)" command
		   (if (integerp status) (format "status %d" status) status))))
	(if vc-command-messages
	    (message "Running %s...OK" command)))
      (vc-exec-after
       `(run-hook-with-args 'vc-post-command-functions ',command ',file ',flags))
      status)))
Eric S. Raymond's avatar
Eric S. Raymond committed
642

643
(defun vc-position-context (posn)
644 645 646 647 648
  "Save a bit of the text around POSN in the current buffer, to help
us find the corresponding position again later.  This works even if
all markers are destroyed or corrupted."
  ;; A lot of this was shamelessly lifted from Sebastian Kremer's
  ;; rcs.el mode.
649 650 651 652 653 654
  (list posn
	(buffer-size)
	(buffer-substring posn
			  (min (point-max) (+ posn 100)))))

(defun vc-find-position-by-context (context)
655 656
  "Return the position of CONTEXT in the current buffer, or nil if we
couldn't find it."
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
  (let ((context-string (nth 2 context)))
    (if (equal "" context-string)
	(point-max)
      (save-excursion
	(let ((diff (- (nth 1 context) (buffer-size))))
	  (if (< diff 0) (setq diff (- diff)))
	  (goto-char (nth 0 context))
	  (if (or (search-forward context-string nil t)
		  ;; Can't use search-backward since the match may continue
		  ;; after point.
		  (progn (goto-char (- (point) diff (length context-string)))
			 ;; goto-char doesn't signal an error at
			 ;; beginning of buffer like backward-char would
			 (search-forward context-string nil t)))
	      ;; to beginning of OSTRING
	      (- (point) (length context-string))))))))

674
(defun vc-context-matches-p (posn context)
675
  "Returns t if POSN matches CONTEXT, nil otherwise."
676 677 678 679 680 681 682
  (let* ((context-string (nth 2 context))
	 (len (length context-string))
	 (end (+ posn len)))
    (if (> end (1+ (buffer-size)))
	nil
      (string= context-string (buffer-substring posn end)))))

683
(defun vc-buffer-context ()
684 685
  "Return a list '(point-context mark-context reparse); from which
vc-restore-buffer-context can later restore the context."
686
  (let ((point-context (vc-position-context (point)))
687 688 689 690
	;; Use mark-marker to avoid confusion in transient-mark-mode.
	(mark-context  (if (eq (marker-buffer (mark-marker)) (current-buffer))
			   (vc-position-context (mark-marker))))
	;; Make the right thing happen in transient-mark-mode.
691 692 693 694 695 696 697 698
	(mark-active nil)
	;; We may want to reparse the compilation buffer after revert
	(reparse (and (boundp 'compilation-error-list) ;compile loaded
		      (let ((curbuf (current-buffer)))
			;; Construct a list; each elt is nil or a buffer
			;; iff that buffer is a compilation output buffer
			;; that contains markers into the current buffer.
			(save-excursion
699
			  (mapcar (lambda (buffer)
700 701 702 703 704
				    (set-buffer buffer)
				    (let ((errors (or
						   compilation-old-error-list
						   compilation-error-list))
					  (buffer-error-marked-p nil))
705
				      (while (and (consp errors)
706
						  (not buffer-error-marked-p))
707
					(and (markerp (cdr (car errors)))
708 709
					     (eq buffer
						 (marker-buffer
710
						  (cdr (car errors))))
711
					     (setq buffer-error-marked-p t))
712
					(setq errors (cdr errors)))
713
				      (if buffer-error-marked-p buffer)))
714
				  (buffer-list)))))))
715 716 717
    (list point-context mark-context reparse)))

(defun vc-restore-buffer-context (context)
718 719
  "Restore point/mark, and reparse any affected compilation buffers.
CONTEXT is that which vc-buffer-context returns."
720 721 722
  (let ((point-context (nth 0 context))
	(mark-context (nth 1 context))
	(reparse (nth 2 context)))
723 724 725
    ;; Reparse affected compilation buffers.
    (while reparse
      (if (car reparse)
726
	  (with-current-buffer (car reparse)
727 728 729 730 731 732 733 734 735 736
	    (let ((compilation-last-buffer (current-buffer)) ;select buffer
		  ;; Record the position in the compilation buffer of
		  ;; the last error next-error went to.
		  (error-pos (marker-position
			      (car (car-safe compilation-error-list)))))
	      ;; Reparse the error messages as far as they were parsed before.
	      (compile-reinitialize-errors '(4) compilation-parsing-end)
	      ;; Move the pointer up to find the error we were at before
	      ;; reparsing.  Now next-error should properly go to the next one.
	      (while (and compilation-error-list
737
			  (/= error-pos (car (car compilation-error-list))))
738 739
		(setq compilation-error-list (cdr compilation-error-list))))))
      (setq reparse (cdr reparse)))
740

741 742 743 744
    ;; if necessary, restore point and mark
    (if (not (vc-context-matches-p (point) point-context))
	(let ((new-point (vc-find-position-by-context point-context)))
	  (if new-point (goto-char new-point))))
745 746 747 748 749
    (and mark-active
         mark-context
         (not (vc-context-matches-p (mark) mark-context))
         (let ((new-mark (vc-find-position-by-context mark-context)))
           (if new-mark (set-mark new-mark))))))
750

751
(defun vc-revert-buffer1 (&optional arg no-confirm)
752 753 754 755
  "Revert buffer, try to keep point and mark where user expects them
in spite of changes because of expanded version-control key words.
This is quite important since otherwise typeahead won't work as
expected."
756 757 758
  (interactive "P")
  (widen)
  (let ((context (vc-buffer-context)))
759 760
    ;; Use save-excursion here, because it may be able to restore point
    ;; and mark properly even in cases where vc-restore-buffer-context
761
    ;; would fail.  However, save-excursion might also get it wrong --
762 763
    ;; in this case, vc-restore-buffer-context gives it a second try.
    (save-excursion
764
      ;; t means don't call normal-mode;
765 766
      ;; that's to preserve various minor modes.
      (revert-buffer arg no-confirm t))
767 768
    (vc-restore-buffer-context context)))

Eric S. Raymond's avatar
Eric S. Raymond committed
769

770
(defun vc-buffer-sync (&optional not-urgent)
771 772
  "Make sure the current buffer and its working file are in sync
NOT-URGENT means it is ok to continue if the user says not to save."
773
  (if (buffer-modified-p)
774 775 776
      (if (or vc-suppress-confirm
	      (y-or-n-p (format "Buffer %s modified; save it? " (buffer-name))))
	  (save-buffer)
777
	(unless not-urgent
778 779
	  (error "Aborted")))))

780 781
(defun vc-workfile-unchanged-p (file)
  "Has the given workfile changed since last checkout?"
Eric S. Raymond's avatar
Eric S. Raymond committed
782
  (let ((checkout-time (vc-file-getprop file 'vc-checkout-time))
783 784 785 786 787 788 789 790 791 792
        (lastmod (nth 5 (file-attributes file))))
    (if checkout-time
        (equal checkout-time lastmod)
      (let ((unchanged (vc-call workfile-unchanged-p file)))
        (vc-file-setprop file 'vc-checkout-time (if unchanged lastmod 0))
        unchanged))))
      
(defun vc-default-workfile-unchanged-p (file)
  "Default check whether workfile is unchanged: diff against master version."
  (zerop (vc-call diff file (vc-workfile-version file))))
Eric S. Raymond's avatar
Eric S. Raymond committed
793

794 795 796 797 798
(defun vc-recompute-state (file)
  "Force a recomputation of the version control state of FILE.
The state is computed using the exact, and possibly expensive
function `vc-BACKEND-state', not the heuristic."
  (vc-file-setprop file 'vc-state (vc-call state file)))
799

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
(defun vc-next-action-on-file (file verbose &optional comment)
  "Do The Right Thing for a given version-controlled FILE.
If COMMENT is specified, it will be used as an admin or checkin comment.
If VERBOSE is non-nil, query the user rather than using default parameters."
  (let ((visited (get-file-buffer file))
	state version)
    (when visited
      ;; Check relation of buffer and file, and make sure
      ;; user knows what he's doing.  First, finding the file
      ;; will check whether the file on disk is newer.
      (if vc-dired-mode
	  (find-file-other-window file)
	(find-file file))
      (if (not (verify-visited-file-modtime (current-buffer)))
	  (if (yes-or-no-p "Replace file on disk with buffer contents? ")
	      (write-file (buffer-file-name))
	    (error "Aborted"))
	;; Now, check if we have unsaved changes.
	(vc-buffer-sync t)
	(if (buffer-modified-p)
	    (or (y-or-n-p "Operate on disk file, keeping modified buffer? ")
		(error "Aborted")))))
    
    ;; Do the right thing
    (if (not (vc-registered file))
	(vc-register verbose comment)
      (vc-recompute-state file)
      (setq state (vc-state file))
      (cond
       ;; up-to-date
       ((or (eq state 'up-to-date)
	    (and verbose (eq state 'needs-patch)))
	(cond
	 (verbose
	  ;; go to a different version
	  (setq version (read-string "Branch or version to move to: "))
	  (vc-checkout file (eq (vc-checkout-model file) 'implicit) version))
	 ((not (eq (vc-checkout-model file) 'implicit))
	  ;; check the file out
	  (vc-checkout file t))
	 (t
	  ;; do nothing
	  (message "%s is up-to-date" file))))
       
       ;; Abnormal: edited but read-only
       ((and visited (eq state 'edited) buffer-read-only)
	;; Make the file+buffer read-write.  If the user really wanted to
	;; commit, he'll get a chance to do that next time around, anyway.
	(message "File is edited but read-only; making it writable")
	(set-file-modes buffer-file-name
			(logior (file-modes buffer-file-name) 128))
	(toggle-read-only -1))
       
       ;; edited
       ((eq state 'edited)
	(cond 
	 ;; For files with locking, if the file does not contain
	 ;; any changes, just let go of the lock, i.e. revert.
	 ((and (not (eq (vc-checkout-model file) 'implicit))
	       (vc-workfile-unchanged-p file)
	       ;; If buffer is modified, that means the user just
	       ;; said no to saving it; in that case, don't revert,
	       ;; because the user might intend to save after
	       ;; finishing the log entry.
	       (not (and visited (buffer-modified-p))))
	  ;; DO NOT revert the file without asking the user!
	  (if (not visited) (find-file-other-window file))
	  (if (yes-or-no-p "Revert to master version? ")
	      (vc-revert-buffer)))
	 (t ;; normal action
	  (if verbose (setq version (read-string "New version: ")))
	  (vc-checkin file version comment))))
       
       ;; locked by somebody else
       ((stringp state)
	(if comment
	    (error "Sorry, you can't steal the lock on %s this way"
		   (file-name-nondirectory file)))
	(vc-steal-lock file
                       (if verbose (read-string "Version to steal: ")
                         (vc-workfile-version file))
		       state))
       
       ;; needs-patch
       ((eq state 'needs-patch)
	(if (yes-or-no-p (format 
			  "%s is not up-to-date.  Get latest version? "
			  (file-name-nondirectory file)))
	    (vc-checkout file (eq (vc-checkout-model file) 'implicit) "")
	  (if (and (not (eq (vc-checkout-model file) 'implicit))
		   (yes-or-no-p "Lock this version? "))
	      (vc-checkout file t)
	    (error "Aborted"))))
       
       ;; needs-merge
       ((eq state 'needs-merge)
	(if (yes-or-no-p (format 
			  "%s is not up-to-date.  Merge in changes now? "
			  (file-name-nondirectory file)))
	    (vc-maybe-resolve-conflicts file (vc-call merge-news file))
	  (error "Aborted")))
       
       ;; unlocked-changes
       ((eq state 'unlocked-changes)
	(if (not visited) (find-file-other-window file))
	(if (save-window-excursion
	      (vc-version-diff file (vc-workfile-version file) nil)
	      (goto-char (point-min))
	      (insert-string (format "Changes to %s since last lock:\n\n"
				     file))
	      (not (beep))
	      (yes-or-no-p (concat "File has unlocked changes.  "
				   "Claim lock retaining changes? ")))
	    (progn (vc-call steal-lock file)
		   ;; Must clear any headers here because they wouldn't
		   ;; show that the file is locked now.
		   (vc-clear-headers file)
		   (vc-mode-line file))
	  (if (not (yes-or-no-p
		    "Revert to checked-in version, instead? "))
	      (error "Checkout aborted")
	    (vc-revert-buffer1 t t)
	    (vc-checkout file t))))))))
923

924 925
(defvar vc-dired-window-configuration)

926
(defun vc-next-action-dired (file rev comment)
927 928
  "Do a vc-next-action-on-file on all the marked files, possibly
passing on the log comment we've just entered."
929
  (let ((dired-buffer (current-buffer))
930
	(dired-dir default-directory))
931
    (dired-map-over-marks
932
     (let ((file (dired-get-filename)))
933
       (message "Processing %s..." file)
934 935
       (vc-next-action-on-file file nil comment)
       (set-buffer dired-buffer)
936
       (set-window-configuration vc-dired-window-configuration)
937
       (message "Processing %s...done" file))
938 939
    nil t))
  (dired-move-to-filename))
940

Jim Blandy's avatar
Jim Blandy committed
941
;; Here's the major entry point.
Eric S. Raymond's avatar
Eric S. Raymond committed
942

Jim Blandy's avatar
Jim Blandy committed
943
;;;###autoload
Eric S. Raymond's avatar
Eric S. Raymond committed
944 945
(defun vc-next-action (verbose)
  "Do the next logical checkin or checkout operation on the current file.
946 947

If you call this from within a VC dired buffer with no files marked,
948
it will operate on the file in the current line.
949 950

If you call this from within a VC dired buffer, and one or more
951 952 953 954
files are marked, it will accept a log message and then operate on
each one.  The log message will be used as a comment for any register
or checkin operations, but ignored when doing checkouts.  Attempted
lock steals will raise an error.
955 956

A prefix argument lets you specify the version number to use.
957 958

For RCS and SCCS files:
Eric S. Raymond's avatar
Eric S. Raymond committed
959
   If the file is not already registered, this registers it for version
960
control.
Eric S. Raymond's avatar
Eric S. Raymond committed
961
   If the file is registered and not locked by anyone, this checks out
962
a writable and locked file ready for editing.
Eric S. Raymond's avatar
Eric S. Raymond committed
963 964 965
   If the file is checked out and locked by the calling user, this
first checks to see if the file has changed since checkout.  If not,
it performs a revert.
966 967
   If the file has been changed, this pops up a buffer for entry
of a log message; when the message has been entered, it checks in the
Eric S. Raymond's avatar
Eric S. Raymond committed
968
resulting changes along with the log message as change commentary.  If
969
the variable `vc-keep-workfiles' is non-nil (which is its default), a
Eric S. Raymond's avatar
Eric S. Raymond committed
970 971
read-only copy of the changed file is left in place afterwards.
   If the file is registered and locked by someone else, you are given
972
the option to steal the lock.
973 974 975 976 977 978 979 980 981 982

For CVS files:
   If the file is not already registered, this registers it for version
control.  This does a \"cvs add\", but no \"cvs commit\".
   If the file is added but not committed, it is committed.
   If your working file is changed, but the repository file is
unchanged, this pops up a buffer for entry of a log message; when the
message has been entered, it checks in the resulting changes along
with the logmessage as change commentary.  A writable file is retained.
   If the repository file is changed, you are asked if you want to
983
merge in the changes into your working copy."
984

Eric S. Raymond's avatar
Eric S. Raymond committed
985
  (interactive "P")
986 987 988
  (catch 'nogo
    (if vc-dired-mode
	(let ((files (dired-get-marked-files)))
989 990
          (set (make-local-variable 'vc-dired-window-configuration)
               (current-window-configuration))
991
	  (if (string= ""
992
		 (mapconcat
993 994
	             (lambda (f)
		       (if (not (vc-up-to-date-p f)) "@" ""))
995 996 997 998 999
		     files ""))
		(vc-next-action-dired nil nil "dummy")
	      (vc-start-entry nil nil nil
			      "Enter a change comment for the marked files."
			      'vc-next-action-dired))
1000
	    (throw 'nogo nil)))
1001 1002 1003 1004 1005
    (while vc-parent-buffer
      (pop-to-buffer vc-parent-buffer))
    (if buffer-file-name
        (vc-next-action-on-file buffer-file-name verbose)
      (error "Buffer %s is not associated with a file" (buffer-name)))))
Eric S. Raymond's avatar
Eric S. Raymond committed
1006 1007 1008

;;; These functions help the vc-next-action entry point

1009
(defun vc-checkout-writable-buffer (&optional file rev)
1010
  "Retrieve a writable copy of the latest version of the current buffer's file."
1011
  (vc-checkout (or file (buffer-file-name)) t rev)
1012 1013
  )

Jim Blandy's avatar
Jim Blandy committed
1014
;;;###autoload
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
(defun vc-register (&optional set-version comment)
  "Register the current file into a version-control system.
With prefix argument SET-VERSION, allow user to specify initial version 
level.  If COMMENT is present, use that as an initial comment.

The version-control system to use is found by cycling through the list
`vc-handled-backends'.  The first backend in that list which declares
itself responsible for the file (usually because other files in that
directory are already registered under that backend) will be used to
register the file.  If no backend declares itself responsible, the
first backend that could register the file is used."
Eric S. Raymond's avatar
Eric S. Raymond committed
1026
  (interactive "P")
1027 1028
  (or buffer-file-name
      (error "No visited file"))
1029 1030 1031 1032 1033
  (when (vc-backend buffer-file-name)
    (if (vc-registered buffer-file-name)
	(error "This file is already registered")
      (unless (y-or-n-p "Previous master file has vanished.  Make a new one? ")
	(error "Aborted"))))
1034 1035 1036 1037 1038 1039
  ;; Watch out for new buffers of size 0: the corresponding file
  ;; does not exist yet, even though buffer-modified-p is nil.
  (if (and (not (buffer-modified-p))
	   (zerop (buffer-size))
	   (not (file-exists-p buffer-file-name)))
      (set-buffer-modified-p t))
Eric S. Raymond's avatar
Eric S. Raymond committed
1040
  (vc-buffer-sync)
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
  
  (vc-start-entry buffer-file-name
                  (if set-version
                      (read-string "Initial version level for %s: "
                                   (buffer-name))
                    ;; TODO: Use backend-specific init version.
                    vc-default-init-version)
                  (or comment (not vc-initial-comment))
                  "Enter initial comment."
		  (lambda (file rev comment)
		    (message "Registering %s... " file)
		    (let ((backend (vc-responsible-backend file)))
		      (vc-call-backend backend 'register file rev comment)
		      (vc-file-setprop file 'vc-backend backend)
		      (unless vc-make-backup-files
			(make-local-variable 'backup-inhibited)
			(setq backup-inhibited t)))
		    (message "Registering %s... done" file))))

(defun vc-responsible-backend (file &optional register)
  "Return the name of the backend system that is responsible for FILE.
If no backend in variable `vc-handled-backends' declares itself
responsible, the first backend in that list will be returned (if optional
arg REGISTER is non-nil, return the first backend that could register the 
file).
FILE can also be a directory name (ending with a slash)."
  (if (null vc-handled-backends)
      (error "Cannot register, no backends in `vc-handled-backends'"))
  (or (and (not (file-directory-p file)) (vc-backend file))
      (catch 'found
	(mapcar (lambda (backend)
		  (if (vc-call-backend backend 'responsible-p file)
		      (throw 'found backend)))
		vc-handled-backends)
	(if register
	    (mapcar (lambda (backend)
		      (if (vc-call-backend backend 'could-register file)
			  (throw 'found backend)))
		    vc-handled-backends)
	  (car vc-handled-backends)))))

(defun vc-default-could-register (backend file)
  "Return non-nil if BACKEND could be used to register FILE.  
The default implementation returns t for all files."
  t)
Eric S. Raymond's avatar
Eric S. Raymond committed
1086

1087
(defun vc-resynch-window (file &optional keep noquery)
1088 1089 1090 1091 1092 1093
  "If the given file is in the current buffer, either revert on it so
we see expanded keywords, or unvisit it (depending on
vc-keep-workfiles) NOQUERY if non-nil inhibits confirmation for
reverting.  NOQUERY should be t *only* if it is known the only
difference between the buffer and the file is due to version control
rather than user editing!"
Eric S. Raymond's avatar
Eric S. Raymond committed
1094 1095 1096
  (and (string= buffer-file-name file)
       (if keep
	   (progn
1097
	     (vc-revert-buffer1 t noquery)
1098 1099 1100
             ;; TODO: Adjusting view mode might no longer be necessary
             ;; after RMS change to files.el of 1999-08-08.  Investigate
             ;; this when we install the new VC.
1101 1102 1103 1104 1105 1106 1107 1108
             (and view-read-only
                  (if (file-writable-p file)
                      (and view-mode
                           (let ((view-old-buffer-read-only nil))
                             (view-mode-exit)))
                    (and (not view-mode)
                         (not (eq (get major-mode 'mode-class) 'special))
                         (view-mode-enter))))
Eric S. Raymond's avatar
Eric S. Raymond committed
1109
	     (vc-mode-line buffer-file-name))
1110
	 (kill-buffer (current-buffer)))))
Eric S. Raymond's avatar
Eric S. Raymond committed
1111

1112
(defun vc-resynch-buffer (file &optional keep noquery)
1113
  "If FILE is currently visited, resynch its buffer."
1114 1115 1116 1117
  (if (string= buffer-file-name file)
      (vc-resynch-window file keep noquery)
    (let ((buffer (get-file-buffer file)))
      (if buffer
1118 1119 1120
	  (with-current-buffer buffer
	    (vc-resynch-window file keep noquery)))))
  (vc-dired-resynch-file file))
1121

1122
(defun vc-start-entry (file rev comment msg action &optional after-hook)
1123 1124 1125 1126 1127
  "Accept a comment for an operation on FILE revision REV.  If COMMENT
is nil, pop up a VC-log buffer, emit MSG, and set the action on close
to ACTION; otherwise, do action immediately.  Remember the file's
buffer in vc-parent-buffer (current one if no file).  AFTER-HOOK
specifies the local value for vc-log-operation-hook."
1128
  (let ((parent (if file (find-file-noselect file) (current-buffer))))
1129 1130
    (if vc-before-checkin-hook
        (if file
1131
            (with-current-buffer parent
1132 1133
              (run-hooks 'vc-before-checkin-hook))
          (run-hooks 'vc-before-checkin-hook)))
1134 1135 1136
    (if comment
	(set-buffer (get-buffer-create "*VC-log*"))
      (pop-to-buffer (get-buffer-create "*VC-log*")))
1137 1138 1139
    (set (make-local-variable 'vc-parent-buffer) parent)
    (set (make-local-variable 'vc-parent-buffer-name)
	 (concat " from " (buffer-name vc-parent-buffer)))
1140
    (if file (vc-mode-line file))
1141
    (if (fboundp 'log-edit) (vc-log-edit file) (vc-log-mode file))
1142 1143 1144
    (make-local-variable 'vc-log-after-operation-hook)
    (if after-hook
	(setq vc-log-after-operation-hook after-hook))
1145 1146 1147 1148 1149
    (setq vc-log-operation action)
    (setq vc-log-version rev)
    (if comment
	(progn
	  (erase-buffer)
1150 1151 1152 1153
	  (if (eq comment t)
	      (vc-finish-logentry t)
	    (insert comment)
	    (vc-finish-logentry nil)))
1154
      (message "%s  Type C-c C-c when done" msg))))
1155

1156
(defun vc-checkout (file &optional writable rev)
1157
  "Retrieve a copy of the latest version of the given file."
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
  (condition-case err
      (vc-call checkout file writable rev)
    (file-error
     ;; Maybe the backend is not installed ;-(
     (when writable
       (let ((buf (get-file-buffer file)))
	 (when buf (with-current-buffer buf (toggle-read-only -1)))))
     (signal (car err) (cdr err))))
  (vc-file-setprop file 'vc-state
		   (if (or (eq (vc-checkout-model file) 'implicit)
			   (not writable))
		       (if (vc-call latest-on-branch-p file)
			   'up-to-date
			 'needs-patch)
		     'edited))
  (vc-file-setprop file 'vc-checkout-time (nth 5 (file-attributes file)))
1174
  (vc-resynch-buffer file t t))
Eric S. Raymond's avatar
Eric S. Raymond committed
1175

1176
(defun vc-steal-lock (file rev owner)
Eric S. Raymond's avatar
Eric S. Raymond committed
1177
  "Steal the lock on the current workfile."
1178 1179 1180 1181
  (let (file-description)
    (if rev
	(setq file-description (format "%s:%s" file rev))
      (setq file-description file))
1182 1183
    (if (not (yes-or-no-p (format "Steal the lock on %s from %s? "
				  file-description owner)))
1184 1185 1186 1187
	(error "Steal canceled"))
    (compose-mail owner (format "Stolen lock on %s" file-description)
		  nil nil nil nil
		  (list (list 'vc-finish-steal file rev)))
1188 1189 1190 1191 1192 1193 1194
    (setq default-directory (expand-file-name "~/"))
    (goto-char (point-max))
    (insert
     (format "I stole the lock on %s, " file-description)
     (current-time-string)
     ".\n")
    (message "Please explain why you stole the lock.  Type C-c C-c when done.")))
Eric S. Raymond's avatar
Eric S. Raymond committed
1195 1196

(defun vc-finish-steal (file version)
1197 1198 1199 1200 1201 1202
  ;; This is called when the notification has been sent.
  (message "Stealing lock on %s..." file)
  (vc-call steal-lock file version)
  (vc-file-setprop file 'vc-state 'edited)
  (vc-resynch-buffer file t t)
  (message "Stealing lock on %s...done" file))
Eric S. Raymond's avatar
Eric S. Raymond committed
1203 1204

(defun vc-checkin (file &optional rev comment)
1205 1206 1207 1208 1209 1210 1211
  "Check in FILE.  
The optional argument REV may be a string specifying the new version
level (if nil increment the current level).  COMMENT is a comment
string; if omitted, a buffer is popped up to accept a comment.

If `vc-keep-workfiles' is nil, FILE is deleted afterwards, provided
that the version control system supports this mode of operation.
Dave Love's avatar
Dave Love committed
1212 1213

Runs the normal hook `vc-checkin-hook'."
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
  (vc-start-entry 
   file rev comment
   "Enter a change comment." 
   (lambda (file rev comment)
     (message "Checking in %s..." file)
     ;; "This log message intentionally left almost blank".
     ;; RCS 5.7 gripes about white-space-only comments too.
     (or (and comment (string-match "[^\t\n ]" comment))
	 (setq comment "*** empty log message ***"))
     ;; Change buffers to get local value of vc-checkin-switches.
     (with-current-buffer (or (get-file-buffer file) (current-buffer))
       (vc-call checkin file rev comment))
     (vc-file-setprop file 'vc-state 'up-to-date)
     (vc-file-setprop file 'vc-checkout-time (nth 5 (file-attributes file)))
     (message "Checking in %s...done" file))
   'vc-checkin-hook))
Eric S. Raymond's avatar
Eric S. Raymond committed
1230

1231 1232 1233 1234
(defun vc-comment-to-change-log (&optional whoami file-name)
  "Enter last VC comment into change log file for current buffer's file.
Optional arg (interactive prefix) non-nil means prompt for user name and site.
Second arg is file name of change log.  \
Dave Love's avatar
Dave Love committed
1235 1236 1237
If nil, uses `change-log-default-name'.

May be useful as a `vc-checkin-hook' to update change logs automatically."
1238 1239 1240
  (interactive (if current-prefix-arg
		   (list current-prefix-arg
			 (prompt-for-change-log-name))))
1241 1242 1243
  ;; Make sure the defvar for add-log-current-defun-function has been executed
  ;; before binding it.
  (require 'add-log)
1244 1245
  (let (;; Extract the comment first so we get any error before doing anything.
	(comment (ring-ref vc-comment-ring 0))
1246
	;; Don't let add-change-log-entry insert a defun name.
1247 1248 1249
	(add-log-current-defun-function 'ignore)
	end)
    ;; Call add-log to do half the work.
1250
    (add-change-log-entry whoami file-name t t)
1251 1252 1253 1254
    ;; Insert the VC comment, leaving point before it.
    (setq end (save-excursion (insert comment) (point-marker)))
    (if (looking-at "\\s *\\s(")
	;; It starts with an open-paren, as in "(foo): Frobbed."
1255
	;; So remove the ": " add-log inserted.
1256 1257 1258 1259 1260 1261 1262 1263 1264
	(delete-char -2))
    ;; Canonicalize the white space between the file name and comment.
    (just-one-space)
    ;; Indent rest of the text the same way add-log indented the first line.
    (let ((indentation (current-indentation)))
      (save-excursion
	(while (< (point) end)
	  (forward-line 1)
	  (indent-to indentation))
1265
	(setq end (point))))
1266
    ;; Fill the inserted text, preserving open-parens at bol.
1267 1268
    (let ((paragraph-separate (concat paragraph-separate "\\|\\s *\\s("))
	  (paragraph-start (concat paragraph-start "\\|\\s *\\s(")))
1269
      (beginning-of-line)
1270 1271 1272 1273 1274 1275 1276
      (fill-region (point) end))
    ;; Canonicalize the white space at the end of the entry so it is
    ;; separated from the next entry by a single blank line.
    (skip-syntax-forward " " end)
    (delete-char (- (skip-syntax-backward " ")))
    (or (eobp) (looking-at "\n\n")
	(insert "\n"))))
1277

1278
(defun vc-finish-logentry (&optional nocomment)
Eric S. Raymond's avatar
Eric S. Raymond committed
1279 1280
  "Complete the operation implied by the current log entry."
  (interactive)
1281
  ;; Check and record the comment, if any.
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
  (unless nocomment
    ;; Comment too long?
    (vc-call-backend (or (and vc-log-file (vc-backend vc-log-file))
			 (vc-responsible-backend default-directory))
		     'logentry-check)
    (run-hooks 'vc-logentry-check-hook)
    ;; Record the comment in the comment ring
    (let ((comment (buffer-string)))
      (unless (and (ring-p vc-comment-ring)
		   (not (ring-empty-p vc-comment-ring))
		   (equal comment (ring-ref vc-comment-ring 0)))
	(ring-insert vc-comment-ring comment))))
1294
  ;; Sync parent buffer in case the user modified it while editing the comment.
1295
  ;; But not if it is a vc-dired buffer.
Gerd Moellmann's avatar