view lisp/vc-arch.el @ 96044:c1ef445563bb

2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-colview.el (org-columns-next-allowed-value): Bug fix. * org-colview-xemacs.el (org-columns-next-allowed-value): Bug fix. * org-agenda.el (org-agenda-get-closed): Get the end time into the agenda prefix as well. * org-publish.el (org-publish-org-index): Make a properly indented list. * org.el (org-calendar-agenda-action-key): New option. (org-get-cursor-date): New function. (org-mark-entry-for-agenda-action): New command. (org-overriding-default-time): New variable. (org-read-date): Respect `org-overriding-default-time'. * org-remember.el (org-remember-apply-template): Respect the ovverriding default time. * org-agenda.el (org-agenda-action-marker): New variable. (org-agenda-action): New command. (org-agenda-do-action): New function. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-schedule, org-deadline): Protect scheduled and deadline tasks against changes that accidently remove the repeater. Also show a message with the new date when done. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-beginning-of-line): Cater for the case when there are tags but no headline text. (org-align-tags-here): Convert to tabs only when indent-tabs-mode it set. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-mhe.el (org-mhe-get-message-folder-from-index): Make sure the return value is nil instead of "nil" when there is no match. * org-exp.el (org-insert-centered): Use fill-column instead of 80. (org-export-as-ascii): Use string-width to measure the width of the heading. * org.el (org-diary-to-ical-string): No longer kill buffer FROMBUF, this is now done by the caller. * org-exp.el (org-print-icalendar-entries): Move the call to `org-diary-to-ical-string' out of the loop, and kill the buffer afterwords. * org-remember.el (org-remember-visit-immediately): Position cursor after moving to the note. (org-remember-apply-template): Use a text property to record the cursor position. (org-remember-handler): Align tags after pasting the note. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-bbdb.el (org-bbdb-follow-anniversary-link): New function. * org-agenda.el (org-agenda-open-link): If there is an org-bbdb-name property in the current line, jump to that bbdb entry. * org-bbdb.el (org-bbdb-anniversaries): Add the bbdb-name as a text property, so that the agenda knows where this entry comes from. * org-agenda.el (org-agenda-clock-in): Fixed bug in the interaction between clocking-in from the agenda, and automatic task state switching. * org-macs.el (org-with-point-at): Bug fix in macro defintion. * org.el (org-beginning-of-line, org-end-of-line): Make sure the zmacs-region stays after this command in XEmacs. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-scan-tags): Allow new values for ACTION parameter. * org-remember.el (org-remember-templates): Fix bug in customization type definition. * org.el (org-map-entries): New function. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-agenda.el (org-agenda-skip-comment-trees): New option. (org-agenda-skip): Respect `org-agenda-skip-comment-trees'. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-remember.el (org-jump-to-target-location): New variable. (org-remember-apply-template): Set `org-remember-apply-template' if requested by template. (org-remember-handler): Start an idle timer to jump to remember location. * org-exp.el (org-get-current-options): Add the FILETAGS setting. * org.el (org-set-regexps-and-options): Fix bug with parsing of file tags. (org-get-tags-at): Add the content of `org-file-tags'. * org-exp.el (org-export-handle-comments): Fix bug with several comment lines after each other. (org-number-to-roman, org-number-to-counter): New functions. (org-export-section-number-format): New option. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-exp.el (org-export-protect-examples): Catch the case of a missing end_example line. * org.el (org-set-regexps-and-options): Set `org-file-properties' and `org-file-tags' to nil. * org-colview.el (org-columns-next-allowed-value): Handle next argument NTH to directly select a value. * org-colview-xemacs.el (org-columns-next-allowed-value): Handle next argument NTH to directly select a value. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-agenda.el (org-agenda-scheduled-leaders): Fix docstring. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-columns-ellipses): New option. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-colview.el (org-columns-add-ellipses): New function. (org-columns-compact-links): New function. (org-columns-cleanup-item): Call `org-columns-compact-links'. (org-columns-display-here): Call `org-agenda-columns-cleanup-item' when in agenda. (org-columns-edit-value): Fixed bug with editing values from agenda column view. (org-columns-redo): Also redo the agenda itself. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-agenda.el (org-agenda-columns-remove-prefix-from-item): New option. * org-colview.el (org-agenda-columns-cleanup-item): New function. * org-exp.el (org-export-ascii-preprocess): Renamed from `org-export-ascii-clean-string'. (org-export-kill-licensed-text) (org-export-define-heading-targets) (org-export-handle-invisible-targets) (org-export-target-internal-links) (org-export-remove-or-extract-drawers) (org-export-remove-archived-trees) (org-export-protect-quoted-subtrees) (org-export-protect-verbatim, org-export-protect-examples) (org-export-select-backend-specific-text) (org-export-mark-blockquote-and-verse) (org-export-remove-comment-blocks-and-subtrees) (org-export-handle-comments, org-export-mark-radio-links) (org-export-remove-special-table-lines) (org-export-normalize-links) (org-export-concatenate-multiline-links) (org-export-concatenate-multiline-emphasis): New functions, obtained from spliiting the export preprocessor. * org-table.el (org-table-recalculate): Improve error message if the row number is invalid. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-archive.el (org-archive-save-context-info): Fix bugs in customization setup and docstring. * org-exp.el (org-export-html-style): Changed the size of in the <pre> element to 90%. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-find-src-example-start): Function removed. (org-edit-src-find-region-and-lang): New function. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-edit-src-exit): New function. (org-exit-edit-mode): New minor mode. * org-exp.el (org-export-preprocess-string): Fix bug with removing comment-like lines from protected examples. * org.el (org-edit-src-example, org-find-src-example-start) (org-protect-source-example, org-edit-special): New functions. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-publish.el (org-publish-project-alist): Fix typo in docstring. (org-publish-project-alist): Handle :index-title property. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-export-latex.el (org-export-as-latex): Make sure region bounds are correct. Parse subtree properties relating to export. * org-exp.el (org-export-add-options-to-plist): New function. (org-infile-export-plist): Use `org-export-add-options-to-plist'. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-default-properties): Add EXPORT_FILE_NAME and EXPORT_TITLE. * org-exp.el (org-export-get-title-from-subtree) (org-export-as-ascii, org-export-as-html): Make sure the original region-beginning and region-end are used, even after moving point. (org-export-get-title-from-subtree): Also try the EXPORT_TITLE property. * org-remember.el (org-remember-last-stored-marker): New variable. (org-remember-goto-last-stored): Use `org-goto-marker-or-bmk'. (org-remember-handler): Also use marker to remember last-stored position. * org.el (org-goto-marker-or-bmk): New function. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-file-properties): Renamed from `org-local-properties'. (org-scan-tags): Take file tags into account. (org-tags-match-list-sublevels): Default changed to t. * org-exp.el (org-export-as-html): Close paragraph after a footnote. * org.el (org-update-parent-todo-statistics): New function. * org-exp.el (org-icalendar-store-UID): New option. (org-icalendar-force-UID): Option removed. (org-print-icalendar-entries): IMplement UIDs. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-mhe.el (org-mhe-follow-link): Fix bug in mhe searches. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-faces.el (org-column): Document how this face is being used and why sometimes the background faces shine through. * org-mhe.el (org-mhe-follow-link): Improve handling of searches. * org-publish.el (org-publish-attachment): Create publishing directory if it does not yet exist. * org-table.el (org-calc-default-modes): Change default number format to (float 8). * org.el (org-olpath-completing-read): New function. (org-time-clocksum-format): New option. (org-minutes-to-hh:mm-string): Use `org-time-clocksum-format'. * org-clock.el (org-clock-display, org-clock-out) (org-update-mode-line): Use `org-time-clocksum-format'. * org-colview-xemacs.el (org-columns-number-to-string): Use `org-time-clocksum-format'. * org-colview.el (org-columns-number-to-string): Use `org-time-clocksum-format'. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-id.el: New file, move from contrib to core. * org-exp.el (org-icalendar-force-UID): New option. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-exp.el (org-print-icalendar-entries): Make sure DTEND is shifted by one day if theere is a date range without an end time. * org.el (org-try-structure-completion): New function. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-set-font-lock-defaults): Improve fontification of description lists. (org-insert-item): Handle description lists. (org-adaptive-fill-function): Improve auto indentation in description lists. * org-exp.el (org-export-as-html, org-export-preprocess-string): Implement VERSE environment. (org-export-preprocess-string): Implement the COMMENT environment. * org-export-latex.el (org-export-latex-preprocess): Implement VERSE environment. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-jsinfo.el (org-infojs-opts-table): Add entry for FIXED_TOC option. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-table.el (orgtbl-to-tsv, orgtbl-to-csv): New functions. * org.el (org-quote-csv-field): New functions. * org-table.el (org-table-export-default-format): Remove :splice from default format, we get the same effect by not specifying :tstart and :tend. (org-table-export): Improve setup, distinguish better between interactive and non-interactive use, allow specifying the format on the fly, better protection against wrong file names. (orgtbl-to-generic): Fix documentation. Do not require :tstart and :tend when :splice is omitted. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-clock.el (org-clock-select-task): Make sure the selection letters are 1-9 and A-Z, no special characters. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-exp.el (org-export-htmlize): New group. (org-export-htmlize-output-type) (org-export-htmlize-css-font-prefix): New options. (org-export-htmlize-region-for-paste): New function. (org-export-htmlize-generate-css): New command. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-set-visibility-according-to-property): New function. (org-ctrl-c-ctrl-c): Do not restart org-mode, just get the options and compute the regular expressions, and update font-lock. (org-property-re): Allow a dash in property names. * org-archive.el (org-extract-archive-file): Insert the file name without the path into the format, to allow the location format to contain a subdirectory. * org-agenda.el (org-agenda-post-command-hook): If point is at end of buffer, and the `org-agenda-type' property undefined, use the value from the character before. * org.el (org-add-planning-info): Don't let indentation for would-be timestamp become extra whitespace at the end of headline. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-remove-double-quotes, org-file-contents): New functions. * org-exp.el (org-infile-export-plist): Also parse the contents of #+SETUPFILE files, recursively. * org.el (org-set-regexps-and-options): Also parse the contents of #+SETUPFILE files, recursively. * org-exp.el (org-export-handle-include-files): New function. (org-export-preprocess-string): Call `org-export-handle-include-files'. * org.el (org-delete-property-globally) (org-delete-property, org-set-property): Ignore case during completion. (org-set-property): Use `org-completing-read' instead of `completing-read'. * org.el (org-complete-expand-structure-template): New, experimental function. (org-structure-template-alist): New, experimental option. (org-complete): Call `org-complete-expand-structure-template'. 2008-06-17 Bastien Guerry <bzg@altern.org> * org-export-latex.el (org-export-latex-preprocess): Added support for blockquotes. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-read-date-analyze): Catch the case where only a weekday is given. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-set-font-lock-defaults): Make the description tag bold. * org-exp.el (org-export-as-html, org-close-li): Implement description lists. 2008-06-17 Jason Riedy <jason@acm.org> * org-table.el (*orgtbl-default-fmt*): New variable. (orgtbl-format-line): Use the value of *orgtbl-default-fmt* when there is no other fmt available. (orgtbl-to-generic): Allow an explicitly nil :tstart or :tend to suppress the appropriate string. (orgtbl-to-orgtbl): New function for translating to another orgtbl table. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.el (org-read-date-analyze): "." as an alias for "+0" in read date. * org-clock.el (org-clock-save-markers-for-cut-and-paste): New function. * org-agenda.el (org-agenda-save-markers-for-cut-and-paste): New function. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-clock.el (org-clock-find-position): Don't include notes into clock drawer. * org-archive.el (org-archive-subtree): No longer remove an extra line after cutting the subtree. `org-cut-subtree' already takes care of this. * org-remember.el (org-remember-handler): Only kill the target buffer if it does not contain the running clock. * org.el (org-markers-to-move): New variable. (org-save-markers-in-region, org-check-and-save-marker) (org-reinstall-markers-in-region): New function. (org-move-subtree-down, org-copy-subtree): Remember relative marker positions before cutting. (org-move-subtree-down, org-paste-subtree): Restore relative marker positions after pasting. * org-remember.el (org-remember-clock-out-on-exit): New option. (org-remember-finalize): Clock out only if the setting in `org-remember-clock-out-on-exit' requires it. (org-remember-handler): Do the cleanup in the buffer, to make sure that the clock marker remains in tact. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-clock.el (org-clock-goto): Widen buffer if necessary. (org-clock-in): Make sure that also tasks outside the narrowed region will be clocked in correctly. (org-clock-insert-selection-line): Widen the buffer so that we can find the correct task heading. * org.el (org-base-buffer): New function. * org-exp.el (org-icalendar-cleanup-string): Make sure '," and ";" are escaped. (org-print-icalendar-entries): Also apply `org-icalendar-cleanup-string' to the headline, not only to the summary property. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org-exp.el (org-export-preprocess-hook): New hook. (org-export-preprocess-string): Call `org-export-preprocess-hook'. * org.el (org-font-lock-hook): New variable. (org-font-lock-hook): New function. (org-set-font-lock-defaults): Call `org-font-lock-hook'. 2008-06-17 Carsten Dominik <dominik@science.uva.nl> * org.texi: Modify license to no longer include back- and front cover matters. (Using the mapping API): New section. (Agenda column view): New section. (Moving subtrees): Document archiving to the archive sibling. (Agenda commands): Document columns view in the agenda. (Using the property API): Document the API for multi-valued properties.
author Carsten Dominik <dominik@science.uva.nl>
date Tue, 17 Jun 2008 15:22:00 +0000
parents 5e64dca662f0
children 7df3d9a17631
line wrap: on
line source

;;; vc-arch.el --- VC backend for the Arch version-control system

;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.

;; Author:      FSF (see vc.el for full credits)
;; Maintainer:  Stefan Monnier <monnier@gnu.org>

;; 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 3 of the License, 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
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;; The home page of the Arch version control system is at
;;
;;      http://www.gnuarch.org/
;;
;; This is derived from vc-mcvs.el as follows:
;; - cp vc-mcvs.el vc-arch.el and then M-% mcvs RET arch RET
;;
;; Then of course started the hacking.
;;
;; What has been partly tested:
;; - Open a file.
;; - C-x v =  without any prefix arg.
;; - C-x v v  to commit a change to a single file.

;; Bugs:

;; - *VC-log*'s initial content lacks the `Summary:' lines.
;; - All files under the tree are considered as "under Arch's control"
;;   without regards to =tagging-method and such.
;; - Files are always considered as `edited'.
;; - C-x v l does not work.
;; - C-x v i does not work.
;; - C-x v ~ does not work.
;; - C-x v u does not work.
;; - C-x v s does not work.
;; - C-x v r does not work.
;; - VC directory listings do not work.
;; - And more...

;;; Code:

(eval-when-compile (require 'vc) (require 'cl))

;;; Properties of the backend

(defun vc-arch-revision-granularity () 'repository)
(defun vc-arch-checkout-model (files) 'implicit)

;;;
;;; Customization options
;;;

(defvar vc-arch-command
  (let ((candidates '("tla" "baz")))
    (while (and candidates (not (executable-find (car candidates))))
      (setq candidates (cdr candidates)))
    (or (car candidates) "tla")))

;; Clear up the cache to force vc-call to check again and discover
;; new functions when we reload this file.
(put 'Arch 'vc-functions nil)

;;;###autoload (defun vc-arch-registered (file)
;;;###autoload   (if (vc-find-root file "{arch}/=tagging-method")
;;;###autoload       (progn
;;;###autoload         (load "vc-arch")
;;;###autoload         (vc-arch-registered file))))

(defun vc-arch-add-tagline ()
  "Add an `arch-tag' to the end of the current file."
  (interactive)
  (comment-normalize-vars)
  (goto-char (point-max))
  (forward-comment -1)
  (skip-chars-forward " \t\n")
  (cond
   ((not (bolp)) (insert "\n\n"))
   ((not (eq ?\n (char-before (1- (point))))) (insert "\n")))
  (let ((beg (point))
	(idfile (and buffer-file-name
		     (expand-file-name
		      (concat ".arch-ids/"
			      (file-name-nondirectory buffer-file-name)
			      ".id")
		      (file-name-directory buffer-file-name)))))
    (insert "arch-tag: ")
    (if (and idfile (file-exists-p idfile))
	;; If the file is unreadable, we do want to get an error here.
	(progn
	  (insert-file-contents idfile)
	  (forward-line 1)
	  (delete-file idfile))
      (condition-case nil
	  (call-process "uuidgen" nil t)
	(file-error (insert (format "%s <%s> %s"
				    (current-time-string)
				    user-mail-address
				    (+ (nth 2 (current-time))
				       (buffer-size)))))))
    (comment-region beg (point))))

(defconst vc-arch-tagline-re "^\\W*arch-tag:[ \t]*\\(.*[^ \t\n]\\)")

(defmacro vc-with-current-file-buffer (file &rest body)
  (declare (indent 2) (debug t))
  `(let ((-kill-buf- nil)
         (-file- ,file))
     (with-current-buffer (or (find-buffer-visiting -file-)
                              (setq -kill-buf- (generate-new-buffer " temp")))
       ;; Avoid find-file-literally since it can do many undesirable extra
       ;; things (among which, call us back into an infinite loop).
       (if -kill-buf- (insert-file-contents -file-))
       (unwind-protect
           (progn ,@body)
         (if (buffer-live-p -kill-buf-) (kill-buffer -kill-buf-))))))

(defun vc-arch-file-source-p (file)
  "Can return nil, `maybe' or a non-nil value.
Only the value `maybe' can be trusted :-(."
  ;; FIXME: Check the tag and name of parent dirs.
  (unless (string-match "\\`[,+]" (file-name-nondirectory file))
    (or (string-match "\\`{arch}/"
		      (file-relative-name file (vc-arch-root file)))
	(file-exists-p
	 ;; Check the presence of an ID file.
	 (expand-file-name
	  (concat ".arch-ids/" (file-name-nondirectory file) ".id")
	  (file-name-directory file)))
	;; Check the presence of a tagline.
	(vc-with-current-file-buffer file
	  (save-excursion
	    (goto-char (point-max))
	    (or (re-search-backward vc-arch-tagline-re (- (point) 1000) t)
		(progn
		  (goto-char (point-min))
		  (re-search-forward vc-arch-tagline-re (+ (point) 1000) t)))))
	;; FIXME: check =tagging-method to see whether untagged files might
	;; be source or not.
	(with-current-buffer
	    (find-file-noselect (expand-file-name "{arch}/=tagging-method"
						  (vc-arch-root file)))
	  (let ((untagged-source t))	;Default is `names'.
	    (save-excursion
	      (goto-char (point-min))
	      (if (re-search-forward "^[ \t]*\\(\\(tagline\\|implicit\\|names\\)\\|explicit\\)" nil t)
		  (setq untagged-source (match-end 2)))
	      (if (re-search-forward "^[ \t]*untagged-source[ \t]+\\(\\(source\\)\\|precious\\|backup\\|junk\\|unrecognized\\)" nil t)
		  (setq untagged-source (match-end 2))))
	    (if untagged-source 'maybe))))))

(defun vc-arch-file-id (file)
  ;; Don't include the kind of ID this is because it seems to be too messy.
  (let ((idfile (expand-file-name
		 (concat ".arch-ids/" (file-name-nondirectory file) ".id")
		 (file-name-directory file))))
    (if (file-exists-p idfile)
	(with-temp-buffer
	  (insert-file-contents idfile)
	  (looking-at ".*[^ \n\t]")
	  (match-string 0))
      (with-current-buffer (find-file-noselect file)
	(save-excursion
	  (goto-char (point-max))
	  (if (or (re-search-backward vc-arch-tagline-re (- (point) 1000) t)
		  (progn
		    (goto-char (point-min))
		    (re-search-forward vc-arch-tagline-re (+ (point) 1000) t)))
	      (match-string 1)
	    (concat "./" (file-relative-name file (vc-arch-root file)))))))))

(defun vc-arch-tagging-method (file)
  (with-current-buffer
      (find-file-noselect
       (expand-file-name "{arch}/=tagging-method" (vc-arch-root file)))
    (save-excursion
      (goto-char (point-min))
      (if (re-search-forward
	   "^[ \t]*\\(tagline\\|implicit\\|names\\|explicit\\)" nil t)
	  (intern (match-string 1))
	'names))))

(defun vc-arch-root (file)
  "Return the root directory of a Arch project, if any."
  (or (vc-file-getprop file 'arch-root)
      ;; Check the =tagging-method, in case someone naively manually
      ;; creates a {arch} directory somewhere.
      (let ((root (vc-find-root file "{arch}/=tagging-method")))
	(when root
	  (vc-file-setprop
	   file 'arch-root root)))))

(defun vc-arch-register (files &optional rev comment)
  (if rev (error "Explicit initial revision not supported for Arch"))
  (dolist (file files)
    (let ((tagmet (vc-arch-tagging-method file)))
      (if (and (memq tagmet '(tagline implicit)) comment-start)
	  (with-current-buffer (find-file-noselect file)
	    (if (buffer-modified-p)
		(error "Save %s first" (buffer-name)))
	    (vc-arch-add-tagline)
	    (save-buffer)))))
  (vc-arch-command nil 0 files "add"))

(defun vc-arch-registered (file)
  ;; Don't seriously check whether it's source or not.  Checking would
  ;; require running TLA, so it's better to not do it, so it also works if
  ;; TLA is not installed.
  (and (vc-arch-root file)
       (vc-arch-file-source-p file)))

(defun vc-arch-default-version (file)
  (or (vc-file-getprop (vc-arch-root file) 'arch-default-version)
      (let* ((root (vc-arch-root file))
	     (f (expand-file-name "{arch}/++default-version" root)))
	(if (file-readable-p f)
	    (vc-file-setprop
	     root 'arch-default-version
	     (with-temp-buffer
	       (insert-file-contents f)
	       ;; Strip the terminating newline.
	       (buffer-substring (point-min) (1- (point-max)))))))))

(defun vc-arch-workfile-unchanged-p (file)
  "Check if FILE is unchanged by diffing against the master version.
Return non-nil if FILE is unchanged."
  nil)

(defun vc-arch-state (file)
  ;; There's no checkout operation and merging is not done from VC
  ;; so the only operation that's state dependent that VC supports is commit
  ;; which is only activated if the file is `edited'.
  (let* ((root (vc-arch-root file))
	 (ver (vc-arch-default-version file))
	 (pat (concat "\\`" (subst-char-in-string ?/ ?% ver)))
	 (dir (expand-file-name ",,inode-sigs/"
				(expand-file-name "{arch}" root)))
	 (sigfile nil))
    (dolist (f (if (file-directory-p dir) (directory-files dir t pat)))
      (if (or (not sigfile) (file-newer-than-file-p f sigfile))
	  (setq sigfile f)))
    (if (not sigfile)
	'edited				;We know nothing.
      (let ((id (vc-arch-file-id file)))
	(setq id (replace-regexp-in-string "[ \t]" "_" id))
	(with-current-buffer (find-file-noselect sigfile)
	  (goto-char (point-min))
	  (while (and (search-forward id nil 'move)
		      (save-excursion
			(goto-char (- (match-beginning 0) 2))
			;; For `names', the lines start with `?./foo/bar'.
			;; For others there's 2 chars before the ./foo/bar.
			(or (not (or (bolp) (looking-at "\n?")))
			    ;; Ignore E_ entries used for foo.id files.
			    (looking-at "E_")))))
	  (if (eobp)
	      ;; ID not found.
	      (if (equal (file-name-nondirectory sigfile)
			 (subst-char-in-string
			  ?/ ?% (vc-arch-working-revision file)))
		  'added
		;; Might be `added' or `up-to-date' as well.
		;; FIXME: Check in the patch logs to find out.
		'edited)
	    ;; Found the ID, let's check the inode.
	    (if (not (re-search-forward
		      "\t.*mtime=\\([0-9]+\\):size=\\([0-9]+\\)"
		      (line-end-position) t))
		;; Buh?  Unexpected format.
		'edited
	      (let ((ats (file-attributes file)))
		(if (and (eq (nth 7 ats) (string-to-number (match-string 2)))
			 (equal (format-time-string "%s" (nth 5 ats))
				(match-string 1)))
		    'up-to-date
		  'edited)))))))))

(defun vc-arch-working-revision (file)
  (let* ((root (expand-file-name "{arch}" (vc-arch-root file)))
	 (defbranch (vc-arch-default-version file)))
    (when (and defbranch (string-match "\\`\\(.+@[^/\n]+\\)/\\(\\(\\(.*?\\)\\(?:--.*\\)?\\)--.*\\)\\'" defbranch))
      (let* ((archive (match-string 1 defbranch))
	     (category (match-string 4 defbranch))
	     (branch (match-string 3 defbranch))
	     (version (match-string 2 defbranch))
	     (sealed nil) (rev-nb 0)
	     (rev nil)
	     logdir tmp)
	(setq logdir (expand-file-name category root))
	(setq logdir (expand-file-name branch logdir))
	(setq logdir (expand-file-name version logdir))
	(setq logdir (expand-file-name archive logdir))
	(setq logdir (expand-file-name "patch-log" logdir))
	(dolist (file (if (file-directory-p logdir) (directory-files logdir)))
	  ;; Revision names go: base-0, patch-N, version-0, versionfix-M.
	  (when (and (eq (aref file 0) ?v) (not sealed))
	    (setq sealed t rev-nb 0))
	  (if (and (string-match "-\\([0-9]+\\)\\'" file)
		   (setq tmp (string-to-number (match-string 1 file)))
		   (or (not sealed) (eq (aref file 0) ?v))
		   (>= tmp rev-nb))
	      (setq rev-nb tmp rev file)))
	;; Use "none-000" if the tree hasn't yet been committed on the
	;; default branch.  We'll then get "Arch:000[branch]" on the mode-line.
	(concat defbranch "--" (or rev "none-000"))))))


(defcustom vc-arch-mode-line-rewrite
  '(("\\`.*--\\(.*--.*\\)--\\(v?\\).*-\\([0-9]+\\)\\'" . "\\2\\3[\\1]"))
  "Rewrite rules to shorten Arch's revision names on the mode-line."
  :type '(repeat (cons regexp string))
  :group 'vc)

(defun vc-arch-mode-line-string (file)
  "Return string for placement in modeline by `vc-mode-line' for FILE."
  (let ((rev (vc-working-revision file)))
    (dolist (rule vc-arch-mode-line-rewrite)
      (if (string-match (car rule) rev)
	  (setq rev (replace-match (cdr rule) t nil rev))))
    (format "Arch%c%s"
	    (case (vc-state file)
	      ((up-to-date needs-update) ?-)
	      (added ?@)
	      (t ?:))
	    rev)))

(defun vc-arch-diff3-rej-p (rej)
  (let ((attrs (file-attributes rej)))
    (and attrs (< (nth 7 attrs) 60)
	 (with-temp-buffer
	   (insert-file-contents rej)
	   (goto-char (point-min))
	   (looking-at "Conflicts occured, diff3 conflict markers left in file\\.")))))

(defun vc-arch-delete-rej-if-obsolete ()
  "For use in `after-save-hook'."
  (save-excursion
    (let ((rej (concat buffer-file-name ".rej")))
      (when (and buffer-file-name (vc-arch-diff3-rej-p rej))
	(unless (re-search-forward "^<<<<<<< " nil t)
	  ;; The .rej file is obsolete.
	  (condition-case nil (delete-file rej) (error nil))
	  ;; Remove the hook so that it is not called multiple times.
	  (remove-hook 'after-save-hook 'vc-arch-delete-rej-if-obsolete t))))))

(defun vc-arch-find-file-hook ()
  (let ((rej (concat buffer-file-name ".rej")))
    (when (and buffer-file-name (file-exists-p rej))
      (if (vc-arch-diff3-rej-p rej)
	  (save-excursion
	    (goto-char (point-min))
	    (if (not (re-search-forward "^<<<<<<< " nil t))
		;; The .rej file is obsolete.
		(condition-case nil (delete-file rej) (error nil))
	      (smerge-mode 1)
	      (add-hook 'after-save-hook
			'vc-arch-delete-rej-if-obsolete nil t)
	      (message "There are unresolved conflicts in this file")))
	(message "There are unresolved conflicts in %s"
		 (file-name-nondirectory rej))))))

(defun vc-arch-checkin (files rev comment)
  (if rev (error "Committing to a specific revision is unsupported"))
  ;; FIXME: This implementation probably only works for singleton filesets
  (let ((summary (file-relative-name (car files) (vc-arch-root (car files)))))
    ;; Extract a summary from the comment.
    (when (or (string-match "\\`Summary:[ \t]*\\(.*[^ \t\n]\\)\\([ \t]*\n\\)*" comment)
	      (string-match "\\`[ \t]*\\(.*[^ \t\n]\\)[ \t]*\\(\n?\\'\\|\n\\([ \t]*\n\\)+\\)" comment))
      (setq summary (match-string 1 comment))
      (setq comment (substring comment (match-end 0))))
    (vc-arch-command nil 0 files "commit" "-s" summary "-L" comment "--"
		     (vc-switches 'Arch 'checkin))))

(defun vc-arch-diff (files &optional oldvers newvers buffer)
  "Get a difference report using Arch between two versions of FILES."
  ;; FIXME: This implementation only works for singleton filesets.  To make
  ;; it work for more cases, we have to either call `file-diffs' manually on
  ;; each and every `file' in the fileset, or use `changes --diffs' (and
  ;; variants) and maybe filter the output with `filterdiff' to only include
  ;; the files in which we're interested.
  (let ((file (car files)))
    (if (and newvers
             (vc-up-to-date-p file)
             (equal newvers (vc-working-revision file)))
        ;; Newvers is the base revision and the current file is unchanged,
        ;; so we can diff with the current file.
        (setq newvers nil))
    (if newvers
        (error "Diffing specific revisions not implemented")
      (let* ((async (not vc-disable-async-diff))
             ;; Run the command from the root dir.
             (default-directory (vc-arch-root file))
             (status
              (vc-arch-command
               (or buffer "*vc-diff*")
               (if async 'async 1)
               nil "file-diffs"
               ;; Arch does not support the typical flags.
               ;; (vc-switches 'Arch 'diff)
               (file-relative-name file)
               (if (equal oldvers (vc-working-revision file))
                   nil
                 oldvers))))
        (if async 1 status)))))	       ; async diff, pessimistic assumption.

(defun vc-arch-delete-file (file)
  (vc-arch-command nil 0 file "rm"))

(defun vc-arch-rename-file (old new)
  (vc-arch-command nil 0 new "mv" (file-relative-name old)))

(defalias 'vc-arch-responsible-p 'vc-arch-root)

(defun vc-arch-command (buffer okstatus file &rest flags)
  "A wrapper around `vc-do-command' for use in vc-arch.el."
  (apply 'vc-do-command (or buffer "*vc*") okstatus vc-arch-command file flags))

(defun vc-arch-init-revision () nil)

;;; Completion of versions and revisions.

(defun vc-arch--version-completion-table (root string)
  (delq nil
	(mapcar
	 (lambda (d)
	   (when (string-match "/\\([^/]+\\)/\\([^/]+\\)\\'" d)
	     (concat (match-string 2 d) "/" (match-string 1 d))))
	 (let ((default-directory root))
	   (file-expand-wildcards
	    (concat "*/*/"
		    (if (string-match "/" string)
			(concat (substring string (match-end 0))
				"*/" (substring string 0 (match-beginning 0)))
		      (concat "*/" string))
		    "*"))))))

(defun vc-arch-revision-completion-table (files)
  (lexical-let ((files files))
    (lambda (string pred action)
      ;; FIXME: complete revision patches as well.
      (let* ((root (expand-file-name "{arch}" (vc-arch-root (car files))))
             (table (vc-arch--version-completion-table root string)))
	(complete-with-action action table string pred)))))

;;; Trimming revision libraries.

;; This code is not directly related to VC and there are many variants of
;; this functionality available as scripts, but I like this version better,
;; so maybe others will like it too.

(defun vc-arch-trim-find-least-useful-rev (revs)
  (let* ((first (pop revs))
         (second (pop revs))
         (third (pop revs))
         ;; We try to give more importance to recent revisions.  The idea is
         ;; that it's OK if checking out a revision 1000-patch-old is ten
         ;; times slower than checking out a revision 100-patch-old.  But at
         ;; the same time a 2-patch-old rev isn't really ten times more
         ;; important than a 20-patch-old, so we use an arbitrary constant
         ;; "100" to reduce this effect for recent revisions.  Making this
         ;; constant a float has the side effect of causing the subsequent
         ;; computations to be done as floats as well.
         (max (+ 100.0 (car (or (car (last revs)) third))))
         (cost (lambda () (/ (- (car third) (car first)) (- max (car second)))))
         (minrev second)
         (mincost (funcall cost)))
    (while revs
      (setq first second)
      (setq second third)
      (setq third (pop revs))
      (when (< (funcall cost) mincost)
        (setq minrev second)
        (setq mincost (funcall cost))))
    minrev))

(defun vc-arch-trim-make-sentinel (revs)
  (if (null revs) (lambda (proc msg) (message "VC-Arch trimming ... done"))
    `(lambda (proc msg)
       (message "VC-Arch trimming %s..." ',(file-name-nondirectory (car revs)))
       (rename-file ,(car revs) ,(concat (car revs) "*rm*"))
       (setq proc (start-process "vc-arch-trim" nil
                                 "rm" "-rf" ',(concat (car revs) "*rm*")))
       (set-process-sentinel proc (vc-arch-trim-make-sentinel ',(cdr revs))))))

(defun vc-arch-trim-one-revlib (dir)
  "Delete half of the revisions in the revision library."
  (interactive "Ddirectory: ")
  (let ((revs
         (sort (delq nil
                     (mapcar
                      (lambda (f)
                        (when (string-match "-\\([0-9]+\\)\\'" f)
                          (cons (string-to-number (match-string 1 f)) f)))
                      (directory-files dir nil nil 'nosort)))
               'car-less-than-car))
        (subdirs nil))
    (when (cddr revs)
      (dotimes (i (/ (length revs) 2))
        (let ((minrev (vc-arch-trim-find-least-useful-rev revs)))
          (setq revs (delq minrev revs))
          (push minrev subdirs)))
      (funcall (vc-arch-trim-make-sentinel
                (mapcar (lambda (x) (expand-file-name (cdr x) dir)) subdirs))
               nil nil))))

(defun vc-arch-trim-revlib ()
  "Delete half of the revisions in the revision library."
  (interactive)
  (let ((rl-dir (with-output-to-string
                  (call-process vc-arch-command nil standard-output nil
                                "my-revision-library"))))
    (while (string-match "\\(.*\\)\n" rl-dir)
      (let ((dir (match-string 1 rl-dir)))
        (setq rl-dir
              (if (and (file-directory-p dir) (file-writable-p dir))
                  dir
                (substring rl-dir (match-end 0))))))
    (unless (file-writable-p rl-dir)
      (error "No writable revlib directory found"))
    (message "Revlib at %s" rl-dir)
    (let* ((archives (directory-files rl-dir 'full "[^.]\\|..."))
           (categories
            (apply 'append
                   (mapcar (lambda (dir)
                             (when (file-directory-p dir)
                               (directory-files dir 'full "[^.]\\|...")))
                           archives)))
           (branches
            (apply 'append
                   (mapcar (lambda (dir)
                             (when (file-directory-p dir)
                               (directory-files dir 'full "[^.]\\|...")))
                           categories)))
           (versions
            (apply 'append
                   (mapcar (lambda (dir)
                             (when (file-directory-p dir)
                               (directory-files dir 'full "--.*--")))
                           branches))))
      (mapc 'vc-arch-trim-one-revlib versions))
    ))

(defvar vc-arch-extra-menu-map
  (let ((map (make-sparse-keymap)))
    (define-key map [add-tagline]
      '(menu-item "Add tagline" vc-arch-add-tagline))
    map))

(defun vc-arch-extra-menu () vc-arch-extra-menu-map)
  

;;; Less obvious implementations.

(defun vc-arch-find-revision (file rev buffer)
  (let ((out (make-temp-file "vc-out")))
    (unwind-protect
        (progn
          (with-temp-buffer
            (vc-arch-command (current-buffer) 1 nil "file-diffs" file rev)
            (call-process-region (point-min) (point-max)
                                 "patch" nil nil nil "-R" "-o" out file))
          (with-current-buffer buffer
            (insert-file-contents out)))
      (delete-file out))))

(provide 'vc-arch)

;; arch-tag: a35c7c1c-5237-429d-88ef-3d718fd2e704
;;; vc-arch.el ends here