;;; xetla-core.el --- Core of xetla

;; Copyright (C) 2003-2004 by Stefan Reichoer (GPL)
;; Copyright (C) 2004 Steve Youngs (BSD)

;; Author:        Steve Youngs <steve@eicq.org>
;; Maintainer:    Steve Youngs <steve@eicq.org>
;; Created:       2004-11-25
;; Keywords:      arch archive tla

;; Based on xtla-core.el by: Stefan Reichoer, <stefan@xsteve.at>

;; This file is part of XEtla.

;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;;    notice, this list of conditions and the following disclaimer.
;;
;; 2. Redistributions in binary form must reproduce the above copyright
;;    notice, this list of conditions and the following disclaimer in the
;;    documentation and/or other materials provided with the distribution.
;;
;; 3. Neither the name of the author nor the names of any contributors
;;    may be used to endorse or promote products derived from this
;;    software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
;; BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
;; IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

;;; Commentary:

;; Contributions from:
;;    Matthieu Moy <Matthieu.Moy@imag.fr>
;;    Masatake YAMATO <jet@gyve.org>
;;    Milan Zamazal <pdm@zamazal.org>
;;    Martin Pool <mbp@sourcefrog.net>
;;    Robert Widhopf-Fenk <hack@robf.de>
;;    Mark Triggs <mst@dishevelled.net>


;; This file provides the low-level functions used by xetla.el


;;; Code:

(require 'xetla-defs)
(require 'ewoc)

;; --------------------------------------
;; Compatibility stuff
;; --------------------------------------
(eval-when-compile
  (require 'cl)
  (autoload 'read-passwd "passwd"))

(require 'pp)

(defvar xetla-buffer-type-alist
  '((changes   "*xetla-changes*"   root)
    (inventory "*xetla-inventory*" path)
    (missing   "*xetla-missing*"   single)
    (cat-log   "*xetla-cat-log(%s)*" string)
    (file-diff "*xetla-file-diff*" path)
    (changelog "*xetla-changelog*" root)
    (tree-lint "*xetla-tree-lint*" root)
    (logs      "*xetla-logs*"      root)
    (errors    "*xetla-error*"     multiple)
    (generic   "*xetla-process*"   multiple)
    (browse    "*xetla-browse*"    single)
    (changeset "*xetla-changeset(%s)*" string))
  "List of (type name mode) used to generate a name for a buffer.

TYPE is the type of buffer to create, passed as the first argument to
`xetla-get-buffer-create'.

NAME is a string, used as a name for the returned buffer.

MODE is a symbol defining the way to manage (value of
`default-directory' in the created buffer) paths for this type of
buffers. It can have the following values:

 * 'root: `default-directory' will be the tree-root of the specified
    directory.

 * 'path: `default-directory' will be the path specified.

For 'root and 'path, `xetla-get-buffer-create' will return the existing
buffer for this type and this path if it exists, or create a new one
otherwise.

 * 'single: There is only one buffer of this type for each Emacs
   instance. If a path is provided, `default-directory' is set to that
   path. Otherwise, the path is left unchanged when a buffer is
   reused, and set to the current directory on buffer creation.

 * 'multiple: `default-directory' is set to the path specified. A new
   buffer is returned anyway. (No buffer reuse).

 * 'string: The path specified is actually a string. It won't be used
   to set `default-directory'. The name of the created buffer will be
   (format name string).")

(defvar xetla-buffers-tree nil
  "Tree containing all xetla buffers.

Must be of the form
 ((type1 (\"path1\" buffer \"original name of buffer\")
         (\"path2\" buffer2 \"original name of buffer2\"))
  (type2 (\"path1\" buffer3 \"original name of buffer3\")
         (\"path3\" buffer4 \"original name of buffer4\")))
Used to keep track of all the xetla related buffers.")

(defun xetla-buffers-tree-remove (buffer)
  "Remove BUFFER from the buffers tree."
    (dolist (type-cons xetla-buffers-tree)
      (dolist (path-buffer (cdr type-cons))
        (when (eq (cadr path-buffer) buffer)
          (setcdr type-cons (delete path-buffer (cdr type-cons)))))))

(defun xetla-buffers-tree-add (type path buffer)
  "Add a buffer of TYPE visiting PATH to the buffers tree.
BUFFER should be the buffer to add."
  (let ((current-assoc (assoc type xetla-buffers-tree)))
    (if current-assoc
        (setcdr current-assoc
                (cons (list path buffer (buffer-name buffer))
                      (cdr current-assoc)))
      (setq xetla-buffers-tree
            (cons `(,type (,path ,buffer ,(buffer-name buffer))) xetla-buffers-tree)))))

(defvar xetla-temp-directory (temp-directory)
  "Temporary directory for some xetla operations.")

(defun xetla-make-temp-name (file)
  "Generate a temporary file name based on FILE.
The path for the file name can be set via `xetla-temp-directory'."
  (make-temp-name (concat (xetla-uniquify-file-name xetla-temp-directory) file)))

(defun xetla-uniquify-file-name (path)
  "Return a unique string designating PATH.
If PATH is a directory,the returned contains one and exactly one trailing
slash.  If PATH is nil, then nil is returned."
  (and path
       (let ((expanded (expand-file-name
                        (if (file-directory-p path)
                            (file-name-as-directory path)
                          path))))
         (if (featurep 'xemacs)
             (replace-regexp-in-string "/+$" "/" expanded)
           expanded))))

(defun xetla-config-file-full-path (file &optional create-config-dir)
  "Return the full path for the config file FILE.
FILE will be stored in the `xetla-config-directory'.
If CREATE-CONFIG-DIR is non nil, ensure that the `xetla-config-directory'
does exist."
  (let ((full-name (xetla-uniquify-file-name
                    (concat xetla-config-directory file))))
    (unless (file-exists-p xetla-config-directory)
      (when create-config-dir
        (make-directory xetla-config-directory t)
        (message "The config files of Xetla will be stored in %s!"
                 xetla-config-directory)
        (sit-for 5)))
    ;; TODO remove migration code as some time in the future
    (unless (file-exists-p (expand-file-name xetla-bookmarks-file-name
                                             xetla-config-directory))
      (let ((old-ones (list (list (expand-file-name xetla-bookmarks-file-name
                                                    xetla-config-directory)
                                  "~/.xetla-bookmarks.el"
                                  "~/.xetla/.xetla-bookmarks.el")))
            o olds n)
        (while old-ones
          (setq olds (car old-ones) old-ones (cdr old-ones))
          (if olds (setq n (car olds) olds (cdr olds)))
          (while olds
            (setq o (expand-file-name (car olds)) olds (cdr olds))
            (if (file-exists-p o)
                (if (yes-or-no-p (format "Migrate %s to %s? " o n))
                    (rename-file o n)
                  (if (yes-or-no-p (format "Delete %s? " o))
                      (delete-file o))))))))
    ;; return full-name
    full-name))

(defun xetla-stringise (uberstring &rest args)
  "Create a string from UBERSTRING.
I.e. you can pass 
- a string which evals to itself
- a variable whose value is a string
- a function which is called and should eval to a string
- a form which is evaluated and should return a string.

All results are run against `xetla-stringise' again
until finally a string is produced."
  (cond ((stringp uberstring)
         uberstring)
        ((and (symbolp uberstring)
              (boundp uberstring))
         (xetla-stringise (symbol-value uberstring)))
        ((and (symbolp uberstring)
              (fboundp uberstring))
         (xetla-stringise (apply uberstring args)))
        ((ignore-errors (xetla-stringise (eval uberstring))))
        ((ignore-errors (xetla-stringise (eval (cons 'progn uberstring)))))
        (t nil)))

;; this is useful since i can now have something like:
;;
;; (set-alist 'xetla-buffer-type-alist
;;            'inventory
;;            '((format "*xetla-inventory%s*"
;;                      (let ((dir (replace-regexp-in-string
;;                                  "^.+/\\([^/]+\\).?$"
;;                                  "\\1"
;;                                  (expand-file-name path))))
;;                        (if dir (format " (%s)" dir)
;;                          "")))))
;;
;; to always have the path in the buffer name of the inventory

(defun xetla-get-buffer-type (type)
  "Get entry in `xetla-buffer-type-alist' for given TYPE."
  (assoc type xetla-buffer-type-alist))

(defun xetla-get-buffer-name (type)
  "Get name part of `xetla-buffer-type-alist' for given TYPE."
  (let ((name (cadr (xetla-get-buffer-type type))))
    (xetla-stringise name)))

(defun xetla-get-buffer-mode (type)
  "Get name part of `xetla-buffer-type-alist' for given TYPE."
  (let ((mode (caddr (xetla-get-buffer-type type))))
    mode))

(eval-when-compile
  (autoload 'xetla-tree-root "xetla"))

(defun xetla-get-buffer-create (type &optional path)
  "Get a buffer of type TYPE for the path PATH.

Maybe reuse one if it exists, according to the value of
`xetla-buffer-type-alist' (see its docstring), or, call
`create-file-buffer' to create the buffer.

See also `xetla-get-buffer'"
  ;; Inspired from `cvs-get-buffer-create'
  (let* ((path (or path default-directory))
         (elem (assoc type xetla-buffer-type-alist))
         (mode (caddr elem)))
    (or (xetla-get-buffer type path mode)
        ;; Buffer couldn't be reused. Create one
        (let ((path (case mode
                      (root (xetla-uniquify-file-name
                             (xetla-tree-root path)))
                      (string path)
                      (t (xetla-uniquify-file-name path))))
              (name (xetla-get-buffer-name type)))
          (let ((buffer
                 (if (eq mode 'string)
                     (get-buffer-create (format name path))
                   (let ((default-directory (or path default-directory)))
                     (create-file-buffer (or name "*xetla-buffer*"))))))
            (with-current-buffer buffer
              (xetla-buffers-tree-add type path buffer)
              buffer))))))

(add-hook 'kill-buffer-hook 'xetla-kill-buffer-function)

(defun xetla-kill-buffer-function ()
  "Function run when a buffer is killed."
  (xetla-buffers-tree-remove (current-buffer))
  (xetla-kill-process-maybe (current-buffer)))

(defun xetla-get-buffer (type &optional path mode)
  "Get a buffer of type TYPE for the path PATH.

Maybe reuse one if it exists, depending on the value of MODE (see
`xetla-buffer-type-alist' 's third element), otherwise, return nil.  See
also `xetla-get-buffer-create'."
  (let ((mode (or mode (xetla-get-buffer-mode type)))
        (path (or path default-directory)))
    (if (eq mode 'single)
        ;; nothing to do about PATH. Reuse anyway
        (let* ((list-path (cdr (assoc type xetla-buffers-tree)))
               (first-elem (car list-path)))
          (if list-path
              (if (string= (buffer-name (cadr first-elem))
                           (caddr first-elem))
                  (cadr first-elem)
                (setcdr (assoc type xetla-buffers-tree) nil)
                nil)
            nil))
      (let ((path (and path
                       (case mode
                         (root (xetla-uniquify-file-name
                                (xetla-tree-root path)))
                         (string path)
                         (t (xetla-uniquify-file-name path))))))
        (if (eq mode 'multiple)
            ;; no need to search an existing buffer
            nil
          (let* ((list-path (assoc type xetla-buffers-tree))
                 (elem (assoc path (cdr list-path)))
                 (buffer (cadr elem)))
            (when buffer
              (if (and (buffer-live-p buffer)
                       ;; the buffer has not been renamed
                       (string= (buffer-name buffer)
                                (caddr elem)))
                  buffer
                ;; remove the buffer and try again
                (setcdr list-path
                        (delq (assoc path (cdr list-path))
                              (cdr list-path)))
                (xetla-get-buffer type path mode)))))))))

(defun xetla-add-buffer-type (type name)
  "Define a new TYPE of buffer whose buffer will be named NAME."
  (unless (assoc type xetla-buffer-type-alist)
    (push (list type name) xetla-buffer-type-alist)))

(defun xetla-position (item seq)
  "Position of ITEM in list, or nil if not found.
Return 0 if ITEM is the first element of SEQ"
  (let ((pos 0)
        (seq-int seq))
    (while (and seq-int
                (not (eq (car seq-int) item)))
      (setq seq-int (cdr seq-int))
      (setq pos (1+ pos)))
    (when seq-int pos)))


(defun xetla-last-visited-inventory-buffer ()
  "Return the last visited xetla's inventory buffer."
  (let ((inventories (remove nil (mapcar
                                  (lambda (elt)
                                    (when (buffer-live-p (cadr elt))
                                      elt))
                                  (cdr (assoc 'inventory xetla-buffers-tree)))))
        (bl (buffer-list)))
    (cadr (car (sort inventories (lambda (a b)
                                   (let ((aindex (xetla-position (cadr a) bl))
                                         (bindex (xetla-position (cadr b) bl)))
                                     (< aindex bindex))))))))

(defun xetla-show-inventory-buffer ()
  "Switch to the last visited inventory buffer."
  (interactive)
  (xetla-switch-to-buffer (xetla-last-visited-inventory-buffer)))

;; --------------------------------------
;; Process buffers
;; --------------------------------------

(defcustom xetla-process-buffer " *xetla-process*"
  "*Name of the process buffer."
  :type 'string
  :group 'xetla-internal)

(defcustom xetla-error-buffer " *xetla-errors*"
  "*Name of the buffer to which xetla's stderr is redirected."
  :type 'string
  :group 'xetla-internal)

(defcustom xetla-number-of-dead-process-buffer 20
  "*Number of process buffers to keep after process termination.
When the number of process buffers exceeds this number, the most ancient
is killed.  This includes both the process buffer and the error
buffer (to which stderr is redirected).

A nil value here means \"Never kill any process buffer\". Useful for
debugging, but this will eat the memory of your computer ;-)"
  :type 'integer
  :group 'xetla-internal)

(defcustom xetla-show-internal-buffers-on-menu nil
  "Toggle display of dead process buffers in the buffer menu."
  :type 'boolean
  :group 'xetla-internal)

(defvar xetla-dead-process-buffer-queue nil
  "List of process buffers belonging to terminated processes.
When the list is greater than `xetla-number-of-dead-process-buffer', the last
ones are killed.")

(defun xetla-kill-process-buffer (buffer)
  "Don't actually kill BUFFER, but add it to `xetla-dead-process-buffer-queue'.
It will eventually be killed when the number of buffers in
`xetla-dead-process-buffer-queue'exceeds `xetla-number-of-dead-process-buffer'."
  (add-to-list 'xetla-dead-process-buffer-queue buffer t)
  (setq xetla-dead-process-buffer-queue
        (remove-if-not #'buffer-live-p xetla-dead-process-buffer-queue))
  (when xetla-number-of-dead-process-buffer
    (while (> (length xetla-dead-process-buffer-queue)
              (max 2 xetla-number-of-dead-process-buffer))
      (let ((currbuf (car xetla-dead-process-buffer-queue)))
        ;; just to be completely certain
        (when (buffer-live-p currbuf)
          (kill-buffer currbuf))
        ;; now remove that killed buffer
        (setq xetla-dead-process-buffer-queue
              (cdr xetla-dead-process-buffer-queue))))))

(defvar xetla-last-process-buffer nil
  "The last created process buffer.")

(defvar xetla-last-error-buffer nil
  "The last created process buffer.")

(defun xetla-new-process-buffer (to-be-deleted)
  "Create a new process buffer.
If TO-BE-DELETED is non-nil, make this buffer a candidate for eventually
being deleted."
  (let ((buffer (create-file-buffer xetla-process-buffer)))
    (setq xetla-last-process-buffer buffer)
    (when to-be-deleted (xetla-kill-process-buffer buffer))
    buffer))

(defun xetla-new-error-buffer (to-be-deleted)
  "Create a new error buffer.
If TO-BE-DELETED is non-nil, make this buffer a candidate for eventually
being deleted."
  (let ((buffer (create-file-buffer xetla-error-buffer)))
    (setq xetla-last-error-buffer buffer)
    (when to-be-deleted (xetla-kill-process-buffer buffer))
    buffer))

;; --------------------------------------
;; Process management
;; --------------------------------------

;; Candidates for process handlers
(defun xetla-default-error-function (output error status arguments)
  "Default function called when a xetla process ends with a non-zero status.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (if (> (with-current-buffer error (point-max)) 1)
      (xetla-show-error-buffer error)
    (if (> (with-current-buffer output (point-max)) 1)
        (xetla-show-error-buffer output)
      (error "`tla %s' failed with code %d and no output!"
             (mapconcat 'identity arguments " ")
             status)))
  (error "`tla %s' failed with code %d"
         (mapconcat 'identity arguments " ")
         status))

(defvar xetla-default-killed-function-noerror 0
  "The number of killed processes we will ignore until throwing an error.
If the value is 0, `xetla-default-killed-function' will throw an error.
See `xetla-default-killed-function'.")

(defun xetla-default-killed-function (output error status arguments)
  "Default function called when a xetla process is killed.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (if (> xetla-default-killed-function-noerror 0)
      (setq xetla-default-killed-function-noerror
            (- xetla-default-killed-function-noerror 1))
    (xetla-switch-to-buffer error)
    (error "`tla %s' process killed !"
           (mapconcat 'identity arguments " "))))

(defun xetla-null-handler (output error status arguments)
  "Handle a finished process without doing anything.
Candidate as an argument for one of the keywords :finished, :error or :killed
in `xetla-run-tla-sync' or `xetla-run-tla-async'.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  nil)

(defun xetla-status-handler (output error status arguments)
  "Return an integer value that reflects the process status.
Candidate as an argument for one of the keywords :finished, :error or :killed
in `xetla-run-tla-sync' or `xetla-run-tla-async'.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (cond ((numberp status) status)
        ((string-match "^exited abnormally with code \\(.*\\)" status)
         (string-to-int (match-string 1)))
        (t (error status))))

(defun xetla-output-buffer-handler (output error status arguments)
  "Return the output of a finished process, stripping any trailing newline.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (xetla-buffer-content output))

(defun xetla-output-buffer-split-handler (output error status arguments)
  "Return the output of a finished process as a list of lines.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (split-string (xetla-buffer-content output) "\n"))

(defun xetla-default-finish-function (output error status arguments)
  "Default function called when a xetla process terminates.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (with-current-buffer output
    (xetla-process-buffer-mode))
  (xetla-switch-to-buffer output)
  (message "`tla %s' process finished !"
           (mapconcat 'identity arguments " "))
  status)

(defun xetla-finish-function-without-buffer-switch (output error status arguments)
  "Similar to `xetla-default-finish-function' but no buffer switch.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (message "`tla %s' process finished !"
           (mapconcat 'identity arguments " "))
  status)

(defvar xetla-log-cookie nil)

(defstruct (xetla-event) output-buffer error-buffer related-buffer
  command tree event time)

(defun xetla-strip-final-newline (string)
  "Strip the final newline from STRING if there's one."
  (if (eq (aref string (- (length string) 1)) ?\n)
      (substring string 0 (- (length string) 1))
    string))

(defsubst xetla-log-printer-print-buffer (buffer function)
  "Helper function for `xetla-log-printer'.
Print a buffer filed for BUFFER during printing a log event.
The printed name of BUFFER is mouse sensitive.  If the user
clicks it, FUNCTION is invoked."
  (xetla-face-add
   (or (buffer-name buffer)
       (pp-to-string buffer))
   'xetla-buffer
   (when (buffer-live-p buffer)
     (let ((map (make-sparse-keymap)))
       (define-key map [button2] function)
       map))
   nil
   "Show the buffer"))

(defun xetla-log-printer (elem)
  "XEtla event printer which prints ELEM."
  (let ((event (xetla-event-event elem))
        (p (point)))
    (insert
     "Command: " (xetla-event-command elem)
     "\nDirectory: " (xetla-face-add (xetla-event-tree elem)
                                    'xetla-local-directory)
     "\nDate: " (format-time-string "%c" (xetla-event-time elem))
     "\nRelated Buffer: " (xetla-log-printer-print-buffer
                           (xetla-event-related-buffer elem)
                           'xetla-switch-to-related-buffer-by-mouse)
     "\nOutput Buffer: "  (xetla-log-printer-print-buffer
                           (xetla-event-output-buffer elem)
                           'xetla-switch-to-output-buffer-by-mouse)
     "\nError Buffer: "   (xetla-log-printer-print-buffer
                           (xetla-event-error-buffer elem)
                           'xetla-switch-to-error-buffer-by-mouse)
     (if (not (string= event "started"))
         (concat "\nEvent: " event)
       "")
     "\n")
    ;; Reflect the point to `default-directory'.
    ;; NOTE: XEmacs doesn't have `point-entered' special text property.
    (put-text-property
     p (point)
     'point-entered (lambda (old new)
                      (setq default-directory
                            (xetla-event-tree
                             (ewoc-data
                              (ewoc-locate xetla-log-cookie))))))
    ))

(defvar xetla-process-running nil
  "List of xetla processes running.
A value of nil indicates no processes are running.

The list is a list of pairs (process event) where EVENT is the event
corresponding to the beginning of the execution of process.  It can be
used to get more info about the process.")

(defmacro xetla-switch-to-buffer-macro (function accessor)
  "Define a FUNCTION for switching to the buffer associated with some event.
ACCESSOR is a function for retrieving the appropriate buffer from a
`xetla-event'structure."
  `(defun ,function ()
     "In a log buffer, pops to the output or error buffer corresponding to the
process at point"
     (interactive)
     (let ((buffer (,accessor
                    (ewoc-data (ewoc-locate xetla-log-cookie)))))
       (cond ((buffer-live-p buffer)
              (xetla-switch-to-buffer buffer)
              (unless (member buffer
                              (mapcar (lambda (p)
                                        (process-buffer (car p)))
                                      xetla-process-running))
                (xetla-process-buffer-mode)))
             (t (error "Buffer has been killed"))))))

(xetla-switch-to-buffer-macro xetla-switch-to-output-buffer
                             xetla-event-output-buffer)

(xetla-switch-to-buffer-macro xetla-switch-to-error-buffer
                             xetla-event-error-buffer)

(xetla-switch-to-buffer-macro xetla-switch-to-related-buffer
                             xetla-event-related-buffer)

(defmacro xetla-make-bymouse-function (function)
  "Create a new function by adding mouse interface to FUNCTION.
The new function is named FUNCTION-by-mouse; and takes one argument,
a mouse click event.
Thew new function moves the point to the place where mouse is clicked
then invoke FUNCTION."
  `(defun ,(intern (concat (symbol-name function) "-by-mouse")) (event)
     ,(concat "`" (symbol-name function) "'" " with mouse interface.")
     (interactive "e")
     (mouse-set-point event)
     (,function)))

(xetla-make-bymouse-function xetla-switch-to-output-buffer)
(xetla-make-bymouse-function xetla-switch-to-error-buffer)
(xetla-make-bymouse-function xetla-switch-to-related-buffer)

(defun xetla-log-event (output error command tree event)
  "Log an event in the `xetla-log-buffer' buffer.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
COMMAND is the command that was executed.
TREE is the process's working directory.
EVENT is the event that occurred.
Returns that event."
  (unless (and xetla-log-cookie
               (buffer-live-p (ewoc-buffer xetla-log-cookie)))
    (with-current-buffer (get-buffer-create xetla-log-buffer)
      (setq xetla-log-cookie
            (ewoc-create 'xetla-log-printer))
      (xetla-log-buffer-mode)))
  (let ((related-buffer (current-buffer)))
    (with-current-buffer (ewoc-buffer xetla-log-cookie)
      (let ((elem (make-xetla-event :output-buffer output
                                   :error-buffer error
                                   :related-buffer related-buffer
                                   :command command
                                   :tree tree
                                   :event event
                                   :time (current-time)))
            buffer-read-only)
        (ewoc-enter-last xetla-log-cookie elem)
        (ewoc-refresh xetla-log-cookie)
        elem))))

(defun xetla-log-next ()
  "Move to the next log entry."
  (interactive)
  (let ((next (ewoc-next xetla-log-cookie
                         (ewoc-locate xetla-log-cookie))))
    (when next (goto-char (ewoc-location next)))))

(defun xetla-log-prev ()
  "Move to the previous log entry."
  (interactive)
  (let ((prev (ewoc-prev xetla-log-cookie
                         (ewoc-locate xetla-log-cookie))))
    (when prev (goto-char (ewoc-location prev)))))

(define-derived-mode xetla-log-buffer-mode fundamental-mode "XEtla Log"
  "Major mode for Xetla's internal log buffer. You can open this buffer
with `xetla-open-internal-log-buffer'."
  (toggle-read-only 1))

(define-derived-mode xetla-process-buffer-mode fundamental-mode
  "XEtla Process"
  "Major mode for process buffers. Mainly defines \\[bury-buffer]
to quit the buffer"
  (toggle-read-only 1))

(defmacro xetla-with-keywords (keywords plist &rest body)
  "Execute a body of code with keywords bound.
Each keyword listed in KEYWORDS is bound to its value from PLIST, then
BODY is evaluated."
  (flet ((keyword-to-symbol (keyword)
                            (intern (substring (symbol-name keyword) 1))))
    (let ((keyword (make-symbol "keyword"))
          (default (make-symbol "default")))
      `(let ,(mapcar (lambda (keyword-entry)
                       (keyword-to-symbol (if (consp keyword-entry)
                                              (car keyword-entry)
                                            keyword-entry)))
                     keywords)
         (dolist (keyword-entry ',keywords)
           (let ((,keyword (if (consp keyword-entry)
                               (car keyword-entry)
                             keyword-entry))
                 (,default (if (consp keyword-entry)
                               (cadr keyword-entry)
                             nil)))
             (set (intern (substring (symbol-name ,keyword) 1))
                  (or (cadr (member ,keyword ,plist))
                      ,default))))
         ,@body))))
(put 'xetla-with-keywords 'lisp-indent-function 1)

(defun xetla-build-xetla-command (list-args)
  "Build a shell command to run tla with args LIST-ARGS."
  (mapconcat 'shell-quote-argument
             (cons xetla-tla-executable
                   (delq nil list-args))
             " "))


(defcustom xetla-password-prompt-regexp
  "[Pp]ass\\(word\\|phrase\\).*:\\s *\\'"
  "*Regexp matching prompts for passwords in the inferior process.
This is used by `eshell-watch-for-password-prompt'."
  :type 'regexp
  :group 'xetla)

(defun xetla-process-filter (proc string)
  "Filter PROC's STRING.
Prompt for password with `read-passwd' if the output of PROC matches
`xetla-password-prompt-regexp'."
  (with-current-buffer (process-buffer proc)
    (insert (replace-regexp-in-string "\015" "\n" string))
    (when (string-match xetla-password-prompt-regexp string)
      (string-match "^\\([^\n]+\\)\n*\\'" string)
      (let ((passwd (read-passwd (match-string 1 string))))
        (process-send-string proc (concat passwd "\n"))))))

(defun xetla-run-tla-async (arguments &rest keys)
  "Run tla asynchronously.
ARGUMENTS is a list of arguments.  nil values in this list are removed.
KEYS is a list of keywords and values.  Possible keywords are:

 :finished ....... Function run when the process finishes.  If none
                   specified, `xetla-default-finish-function' is run.

 :killed ......... Function run when the process is killed.  If none
                   specified, `xetla-default-killed-function' is run.

 :error .......... Function run when the process exits with a non 0
                   status.  If none specified,
                   `xetla-default-error-function' is run.

All these functions take 4 arguments : output, error, status, and
arguments.

   - \"output\" is the output buffer
   - \"error\" is the buffer where standard error is redirected
   - \"status\" is the numeric exit-status or the signal number
   - \"arguments\" is the list of arguments, as a list of strings,
              like '(\"changes\" \"-diffs\")

   `xetla-null-handler' can be used here if there's nothing to do.

 :output-buffer .. Buffer where the output of the process should be
                   redirected.  If none specified, a new one is
                   created, and will be entered in
                   `xetla-dead-process-buffer-queue' to be killed
                   later.

 :error-buffer ... Buffer where the standard error of the process
                   should be redirected.

 :related-buffer . Defaults to `current-buffer'.  This is the buffer
                   where the result of the process will be used.  If
                   this buffer is killed before the end of the
                   execution, the user is prompted if he wants to kill
                   the process.

Example:
  (xetla-run-tla-async `(\"changes\" ,(unless arg \"-diffs\"))
                      :finished
                      (lambda (output error status arguments)
                        (message \"No changes in this working copy\"))
                      :error
                      (lambda (output error status arguments)
                        (xetla-show-changes-buffer output)))"
  (xetla-with-keywords
      (:finished :killed :error :output-buffer :error-buffer :related-buffer)
    keys
    (let* ((output-buf (or (and output-buffer (get-buffer-create output-buffer))
                           (xetla-new-process-buffer nil)))
           (error-buf  (or (and error-buffer (get-buffer-create error-buffer))
                           (xetla-new-error-buffer nil)))
           (error-file (xetla-make-temp-name "arch-errors"))
           (command (xetla-build-xetla-command arguments))
           ;; Make the `default-directory' unique. The trailing slash
           ;; may be necessary in some cases.
           (default-directory (xetla-uniquify-file-name default-directory))
           (process (start-process
                     xetla-tla-executable output-buf
                     "sh" "-c"
                     (format "%s 2> %s"
                             command error-file)))
           (process-event
            (list process
                  (xetla-log-event output-buf
                                  error-buf
                                  command
                                  default-directory "started"))))
      (with-current-buffer (or related-buffer (current-buffer))
        (message "running process `%s' in `%s'" command default-directory)
        (add-to-list 'xetla-process-running process-event)
        (set-process-filter process 'xetla-process-filter)
        (set-process-sentinel
         process
         `(lambda (process event)
            (let ((default-directory ,default-directory))
              (xetla-log-event ,output-buf ,error-buf ,command
                              ,default-directory
                              (xetla-strip-final-newline event))
              (setq xetla-process-running
                    (delq ',process-event xetla-process-running))
              (when (file-exists-p ,error-file)
                (with-current-buffer ,error-buf
                  (insert-file-contents ,error-file))
                (delete-file ,error-file))
              (let ((state (process-status process))
                    (status (process-exit-status process)))
                (unwind-protect
                    (cond ((and (eq state 'exit) (= status 0))
                           (funcall (or (quote ,finished)
                                        'xetla-default-finish-function)
                                    ,output-buf ,error-buf
                                    status (quote ,arguments)))
                          ((eq state 'signal)
                           (funcall (or (quote ,killed)
                                        'xetla-default-killed-function)
                                    ,output-buf ,error-buf status
                                    (quote ,arguments)))
                          ((eq state 'exit) ;; status != 0
                           (funcall (or (quote ,error)
                                        'xetla-default-error-function)
                                    ,output-buf ,error-buf status
                                    (quote ,arguments)))))
                ;; Schedule any buffers we created for killing
                (unless ,output-buffer (xetla-kill-process-buffer ,output-buf))
                (unless ,error-buffer (xetla-kill-process-buffer ,error-buf))))))
        process))))

(defun xetla-run-tla-sync (arguments &rest keys)
  "Run tla synchronously.
See `xetla-run-tla-async' for details on possible ARGUMENTS and KEYS."
  (xetla-with-keywords
      (:finished :killed :error :output-buffer :error-buffer :related-buffer)
    keys
    (let ((output-buf (or (and output-buffer (get-buffer-create output-buffer))
                          (xetla-new-process-buffer t)))
          (error-buf  (or (and error-buffer (get-buffer-create error-buffer))
                          (xetla-new-error-buffer t)))
          (command (xetla-build-xetla-command arguments))
          (error-file (xetla-make-temp-name "arch-errors"))
          ;; Make the `default-directory' unique. The trailing slash
          ;; may be necessary in some cases.
          (default-directory (xetla-uniquify-file-name default-directory)))
      (with-current-buffer (or related-buffer (current-buffer))
        (xetla-log-event output-buf error-buf command default-directory "started")
        (let ((status (call-process "sh" nil output-buf nil "-c"
                                    (format "%s 2> %s"
                                            command
                                            error-file))))
          (when (file-exists-p error-file)
            (with-current-buffer error-buf
              (insert-file-contents error-file))
            (delete-file error-file))
          (unwind-protect
              (cond ((stringp status)
                     (when (string= status "Terminated")
                       (funcall (or killed 'xetla-default-killed-function)
                                output-buf error-buf status arguments)))
                    ((numberp status)
                     (if (zerop status)
                         (funcall (or finished 'xetla-default-finish-function)
                                  output-buf error-buf status arguments)
                       (funcall (or error 'xetla-default-error-function)
                                output-buf error-buf status arguments)))
                    (t (message "Unknown status - %s" status)))
            ;; Schedule any buffers we created for killing
            (unless output-buffer (xetla-kill-process-buffer output-buf))
            (unless error-buffer (xetla-kill-process-buffer error-buf))))))))

(defun xetla-kill-process-maybe (buffer)
  "Prompts and possibly kill process whose related buffer is BUFFER."
  (let ((process-list nil))
    (dolist (process-buffer xetla-process-running)
      (when (eq (xetla-event-related-buffer (cadr process-buffer))
                buffer)
        (add-to-list 'process-list (car process-buffer))))
    (let ((l (length process-list)))
      (when (and process-list
                 (y-or-n-p (format "%s process%s running in buffer %s.  Kill %s? "
                                   l (if (> l 1) "es" "")
                                   (buffer-name buffer)
                                   (if (> l 1) "Them" "it"))))
        (dolist (process process-list)
          (setq xetla-default-killed-function-noerror
                (1+ xetla-default-killed-function-noerror))
          (if (eq (process-status process) 'run)
              (kill-process process)))))))

;;;###autoload
(add-to-list 'minor-mode-alist
             '(xetla-process-running
               (:eval (if (equal (length xetla-process-running) 1)
                          " tla running"
                        (concat " tla running("
                                (int-to-string (length xetla-process-running))
                                ")")))))

(eval-when-compile
  (autoload 'xetla-flash-line "xetla"))

(defun xetla-open-internal-log-buffer ()
  "Switch to the XEtla's internal log buffer.
This buffer contains a list of all the tla commands previously executed.
The buffer uses the mode `xetla-log-buffer-mode'"
  (interactive)
  (let ((buffer-name (buffer-name)))
    (xetla-switch-to-buffer xetla-log-buffer)
    (goto-char (point-max))
    (when (re-search-backward (concat " Buffer: "
                                      (regexp-quote buffer-name)
                                      "$")
                              nil t)
      (xetla-flash-line))))

(defun xetla-clear-log-buffer ()
  "Kill the log buffer."
  (when (bufferp (get-buffer xetla-log-buffer))
    (kill-buffer xetla-log-buffer)))

(defun xetla-buffer-content (buffer)
  "Return the content of BUFFER as a string.
Strips the final newline if there is one."
  (with-current-buffer buffer
    (buffer-substring-no-properties
     (point-min)
     (progn (goto-char (point-max))
            (if (eq (char-before) ?\n)
                (- (point) 1)
              (point))))))

(defun xetla-get-process-output ()
  "Return the content of the last process buffer.
Strips the final newline if there is one."
  (xetla-buffer-content xetla-last-process-buffer))

(defun xetla-get-error-output ()
  "Return the content of the last error buffer.
Strips the final newline if there is one."
  (xetla-buffer-content xetla-last-error-buffer))

(defvar xetla-switched-buffer nil)
(defvar xetla-switched-from-buffer nil)

(defun xetla-switch-to-buffer (buffer)
  "Switch to BUFFER using the user's preferred method.
See `xetla-switch-to-buffer-mode' for possible settings."
  (setq xetla-switched-from-buffer (current-buffer))
  (cond ((eq xetla-switch-to-buffer-mode 'pop-to-buffer)
         (pop-to-buffer buffer))
        ((eq xetla-switch-to-buffer-mode 'single-window)
         (switch-to-buffer buffer))
        ((eq xetla-switch-to-buffer-mode 'show-in-other-window)
         (pop-to-buffer buffer)
         (setq xetla-switched-buffer (current-buffer))
         (pop-to-buffer xetla-switched-from-buffer))
        ;; TODO : dedicated frame.
        (t
         (error "Switch mode %s not implemented" xetla-switch-to-buffer-mode))))

(defun xetla-post-switch-to-buffer ()
  "Executed when showing a changeset.

If `xetla-switched-buffer' is non-nil, show this buffer, but keep
cursor position in previous buffer."
  (when xetla-switched-buffer
    (pop-to-buffer xetla-switched-buffer)
    (setq xetla-switched-buffer nil)
    (goto-char (point-min))
    (pop-to-buffer xetla-switched-from-buffer)))


(defun xetla-show-process-buffer ()
  "Show the process buffer of the last started xetla command."
  (interactive)
  (xetla-switch-to-buffer xetla-last-process-buffer)
  (unless (member xetla-last-process-buffer
                  (mapcar (lambda (p)
                            (process-buffer (car p)))
                          xetla-process-running))
    (xetla-process-buffer-mode)))

(defun xetla-show-last-process-buffer (&optional type mode path)
  "Switch to the last used process buffer in a new buffer of TYPE.
If MODE is specified, it is a function that will be run in the
new buffer.  Otherwise, the buffer will remain in fundamental mode, in
read-only.

If PATH is specified, it will be passed to `xetla-get-buffer-create'."
  (when (buffer-live-p xetla-last-process-buffer)
    (let ((content (with-current-buffer xetla-last-process-buffer
                     (buffer-string))))
      (xetla-switch-to-buffer (xetla-get-buffer-create
                             (or type 'generic) path))
      (let ((inhibit-read-only t))
        (erase-buffer)
        (insert content)))
    (if mode
        (funcall mode)
      (xetla-process-buffer-mode))))

(defun xetla-show-error-buffer (buffer &optional type mode)
  "Pops up the error buffer.
Works like `xetla-show-last-process-buffer', but displays BUFFER, of type
'errors if TYPE is not specified.
If MODE is specified, the buffer will use that mode."
  (when (buffer-live-p buffer)
    (let ((content (with-current-buffer buffer
                     (buffer-string))))
      (xetla-switch-to-buffer (xetla-get-buffer-create
                             (or type 'errors)))
      (let ((inhibit-read-only t))
        (erase-buffer)
        (insert content)))
    (if mode
        (funcall mode)
      (xetla-process-buffer-mode))))

;; --------------------------------------
;; Arch name manipulators
;; ======================
;;
;; Normally in XEtla, a name, a revision specifier is represented as a
;; list like:
;;
;;    ("archive" "category" "branch" "version" "revision")
;;
;; Nil is permitted as the element. However the list length must be 5
;; like:
;;
;;    (nil "category" "branch" nil nil)
;;
;; In other hand, in tla command, the name must be represented as a
;; string like:
;;
;;    "archive/category-branch-version-revision"
;;
;; So we have to convert a name in different representation in many
;; cases.
;;
;; * xetla-name-split-* is for converting from a string representation
;;   to a list representation. There are semi-qualified version and
;;   fully-qualified version.
;;
;;   - semi-qualified: "category-branch-version-revision".
;;     `xetla-name-split-semi-qualified' expects a name string without
;;     archive component. The archive field of returned list is filled
;;     with nil.
;;
;;   - fully-qualified: "archive/category-branch-version-revision".
;;     `xetla-name-split' expects a name string including archive.
;;
;; * xetla-name-construct-* is for converting from a list
;;   representation to a string representation. The functions accept
;;   arguments two ways.
;;
;;   - normal passing: (xetla-name-construct "archive" "category"...)
;;   - packed passing: (xetla-name-construct '("archive" "category"...))
;;
;;   There are semi-qualified version and fully-qualified version.
;;   - semi-qualified: `xetla-name-construct-semi-qualified' connects
;;     arguments with "-".
;;   - fully-qualified: `xetla-name-construct" connects the first argument
;;     and the rest with "/". About the rest,
;;     `xetla-name-construct-semi-qualified' is applied.
;;
;; * xetla-name-{archive|category|branch|version|revision} is for
;;   extracting a component from a name. The both representations are
;;   acceptable.
;;
;; * xetla-name-mask is for replace a component in the name list with nil.
;;
;; --------------------------------------

;;
;; String representation -> List representation
;;
(defun xetla-name-split-semi-qualified (name &optional archive)
  "Split \"--\" connected string NAME into 5 elements list.
The first element is always nil if ARCHIVE is not given.
If ARCHIVE is given, use it as the first.
Even if the elements in name are less than 5, the list is filled by nil
to make the length 5.

  ELISP> (xetla-name-split-semi-qualified \"branch--category--version--revision\"
                                        \"archive\")
  (\"archive\" \"branch\" \"category\" \"version\" \"revision\")

  ELISP> (xetla-name-split-semi-qualified
            \"branch--category--version--revision\")
  (nil \"branch\" \"category\" \"version\" \"revision\")

  ELISP> (xetla-name-split-semi-qualified \"branch--category--version\")
  (nil \"branch\" \"category\" \"version\" nil)

  ELISP> (xetla-name-split-semi-qualified
            \"branch--category--version\" \"archive\")
  (\"archive\" \"branch\" \"category\" \"version\" nil)

  ELISP> (xetla-name-split-semi-qualified \"branch--category\" \"archive\")
  (\"archive\" \"branch\" \"category\" nil nil)

  ELISP> (xetla-name-split-semi-qualified \"branch--category\"nil)
  (nil \"branch\" \"category\" nil nil)

  ELISP> (xetla-name-split-semi-qualified \"branch--category--\" nil)
  (nil \"branch\" \"category\" \"\" nil)"
  (let ((list (xetla-name-split-semi-qualified-internal name)))
    (while (> 4 (length list))
      (setq list (cons nil list)))
    (let ((result (cons archive (nreverse list))))
      (when (xetla-is-version-string (caddr result))
        (setq result (list (car result)
                           (cadr result)
                           ""
                           (caddr result)
                           (cadddr result))))
      result)))

(defun xetla-is-version-string (string)
  "Non-nil if STRING is a candidate for a version name.
That is, if it contains only digits and dots.
The regexp here is less strict than the one of xetla, but must verify
\(xetla-is-version-string string) => string can't be a branch name."
  (and string (string-match "^[0-9\.]+$" string)))

(defun xetla-name-split-semi-qualified-internal (name)
  "Helper function for `xetla-name-split-semi-qualified'.
Splits a semi-qualified NAME."
  (if (string-match "^\\(.+\\)--\\(\\([^-]\\|-[^-]\\)*\\)" name)
      (cons (match-string 2 name)
            (xetla-name-split-semi-qualified-internal
             (match-string 1 name)))
    (cons name nil)))

(defun xetla-name-split (name)
  "Parse a fully qualified revision NAME, but possibly incomplete.
email@address.com--arch/cat--branch--ver ->
  (\"email@address.com--arch\" \"cat\" \"branch\" \"ver\" nil)
email@address.com--arch/cat ->
  (\"email@address.com--arch\" \"cat\" nil nil nil)
email@address.com--arch ->
  (\"email@address.com-arch\" nil nil nil nil)"
  (if (string-match "\\(.*\\)/\\(.*\\)" name)
      (xetla-name-split-semi-qualified (match-string 2 name) (match-string 1 name))
    (if (string= name "")
        (list nil nil nil nil nil)
      (list name nil nil nil nil))))


;;
;; List representation -> string
;;
(defun xetla-name-construct-semi-qualified (&rest comp)
  "Concatenate COMP with \"-\".
This function can accept strings or a list which contains strings.

    ELISP> (xetla-name-construct-semi-qualified \"a\" \"b\" \"c\")
    \"a--b--c\"
    ELISP> (xetla-name-construct-semi-qualified (list \"a\" \"b\" \"c\"))
    \"a--b--c\""
  (if (consp (car comp)) (setq comp (car comp)))
  (if (string= (cadr comp) "")
      ;; Unnamed branch.
      (concat (car comp) "--"
              (mapconcat 'identity (remove nil (cddr comp)) "--"))
    (mapconcat 'identity (remove nil comp) "--")))

(defun xetla-name-construct (archive &optional
                                    category
                                    branch
                                    version
                                    revision)
  "Create the revision name ARCHIVE/CATEGORY-BRANCH-VERSION-REVISION.
The arguments may be nil. If ARCHIVE is a revision name list like
 (archive category branch version revision), the list element is mapped
to arguments before creating the fully qualified revision name.

If the branch name is the empty string and the version is defined,
then, we have an unnamed branch. The full name is
archive/category-version."
  (when (consp archive)
    (setq category (xetla-name-category archive)
          branch   (xetla-name-branch archive)
          version  (xetla-name-version archive)
          revision (xetla-name-revision archive)
          ;; archive must be last
          archive  (xetla-name-archive archive)))
  (let ((semi (xetla-name-construct-semi-qualified
               category branch version revision)))
    (concat
     (and archive (not (string= archive ""))
          (concat archive (when category "/")))
     semi)))

;;
;; Get a component from a list or string.
;;
(defun xetla-name-archive (target)
  "Get archive component from TARGET.
Both representation of TARGET, a string and a list is acceptable."
  (when (stringp target)
    (setq target (xetla-name-split target)))
  (car target))

(defun xetla-name-category (target)
  "Get category component from TARGET.
Both representation of TARGET, a string and a list is acceptable."
  (when (stringp target)
    (setq target (xetla-name-split target)))
  (cadr target))

(defun xetla-name-branch (target)
  "Get branch component from a TARGET.
Both representation of TARGET, a string and a list is acceptable."
  (when (stringp target)
    (setq target (xetla-name-split target)))
  (caddr target))

(defun xetla-name-version (target)
  "Get version component from TARGET.
Both representation of TARGET, a string and a list is acceptable."
  (when (stringp target)
    (setq target (xetla-name-split target)))
  (cadddr target))

(defun xetla-name-revision (target)
  "Get revision component from TARGET.
Both representation of TARGET, a string and a list is acceptable."
  (when (stringp target)
    (setq target (xetla-name-split target)))
  (cadddr (cdr target)))

;;
;; Utilities
;; Mask a specified component in the name.
;;
(defun xetla-name-mask (original do-construct-p
                                &optional
                                archive-mask
                                category-mask
                                branch-mask
                                version-mask
                                revision-mask)
  "Mask ORIGINAL, a xetla revision name by masks; and return the masked value.

If DO-CONSTRUCT-P is given, the result is converted to a string by
`xetla-name-construct'.

ARCHIVE-MASK, CATEGORY-MASK, BRANCH-MASK, VERSION-MASK and REVISION-MASK should
be either nil or t, and indicate whether that field should be masked.

If a mask value is nil, the associated element in ORIGINAL is set to nil.
Else If a mask value is a string, the associated element in ORIGINAL is set
to the string.
Else the associated element in ORIGINAL is not changed.

Examples:
 ELISP> (xetla-name-mask '(\"a\" \"c\" \"b\" \"v\" \"r\") nil t t t t nil)
 (\"a\" \"c\" \"b\" \"v\" nil)

 ELISP> (xetla-name-mask '(\"a\" \"c\" \"b\" \"v\" \"r\") nil t t t nil nil)
 (\"a\" \"c\" \"b\" nil nil)

 ELISP> (xetla-name-mask '(\"a\" \"c\" \"b\" \"v\" \"r\") t t t t nil nil)
 \"a/c-b\"
 ELISP> (xetla-name-mask '(\"a\" \"c\" \"b\" \"v\" \"r\") t nil nil nil nil t)
 \"r\"
 ELISP> (xetla-name-mask '(\"a\" \"c\" \"b\" \"v\" \"r\") t nil nil nil t t)
 \"v-r\"
 ELISP>"
  (when (consp original)
    (let ((masked (list
                   (if archive-mask
                       (if (stringp archive-mask)
                           archive-mask
                         (xetla-name-archive original)))
                   (if category-mask
                       (if (stringp category-mask)
                           category-mask
                         (xetla-name-category original)))
                   (if branch-mask
                       (if (stringp branch-mask)
                           branch-mask
                         (xetla-name-branch original)))
                   (if version-mask
                       (if (stringp version-mask)
                           version-mask
                         (xetla-name-version original)))
                   (if revision-mask
                       (if (stringp revision-mask)
                           revision-mask
                         (xetla-name-revision original))))))
      (if do-construct-p
          (xetla-name-construct masked)
        masked))))

(defun xetla-name-match (target mask)
"Compare the fully qualified revision list TARGET with a MASK.
Each parameter is a list.  The elements of the both lists are compared
via a regexp match.  When the mask part of a component is nil, this
comparision is skipped.
Here are some examples:
\(xetla-name-match
 '(\"xsteve@nit.at-public\" \"xetla\" \"main\" \"0.1\" \"patch-116\")
 '(nil \"xt.*\" \"main\" nil nil)) => t
\(xetla-name-match
 '(\"xsteve@nit.at-public\" \"xetla\" \"main\" \"0.1\" \"patch-116\")
 '(nil \"xt.*\" \"devel\" nil nil)) => nil"  ;"
  (let ((tl target)
        (ml mask)
        (t-part)
        (m-part)
        (matching t))
    (while tl
      (setq t-part (car tl))
      (setq m-part (car ml))
      (when m-part
        (setq matching (string-match m-part t-part)))
      (if matching
          (progn
            (setq tl (cdr tl))
            (setq ml (cdr ml)))
        (setq tl nil)))
    (if matching t nil)))


(defun xetla-name-match-from-list (target match-list)
  "Match TARGET against a list of possible matches.
Every entry of MATCH-LIST is a list that contains a
match element and a possible result.
The target is matched against the elements in the match-list.
If a match is found return the corresponding result,
otherwise return nil."
  (let ((ml match-list)
        (match)
        (data)
        (result))
    (while (and (not result) ml)
      (setq match (caar ml))
      (setq data (cadar ml))
      (message "match: %s, data: %s" match data)
      (setq result (when (xetla-name-match target match) data))
      (setq ml (cdr ml)))
    result))

;; TODO: Use xetla-archive-tree.
(defun xetla-version-head (archive category branch version)
  "Return the newest revision for ARCHIVE/CATEGORY-BRANCH-VERSION."
  (xetla-run-tla-sync (list "revisions"
                           (xetla-name-construct
                            archive
                            category
                            branch
                            version))
                     :finished (lambda (output error status arguments)
                                 (with-current-buffer output
                                   (goto-char (point-max))
                                   (re-search-backward "^.")
                                   (buffer-substring-no-properties
                                    (point) (point-at-eol))))))

;; --------------------------------------
;; Archive tree manipulators
;; --------------------------------------

(defvar xetla-archive-tree nil
  "Arch archive/category/branch/version/revision are stored in assoc list:

 ((\"xsteve@nit.at-public\" \"http://arch.xsteve.at/2004\")
 [...]
  (\"mbp@sourcefrog.net-2004\"
   \"http://sourcefrog.net/arch/mbp@sourcefrog.net-2004\"
   (\"xetla\")
   (\"tilly\")
 [...]
   (\"dupes\"
    (\"mainline\"
     (\"0.1\")))
 [...]
   (\"archzoom\"))
  (\"mark@dishevelled.net-2003-mst\"
   \"http://members.iinet.net.au/~mtriggs/arch/\")
  (\"lord@emf.net-2004\"
   \"http://regexps.srparish.net/{archives}/lord@emf.net-2004\")
 [...]
  (\"Matthieu.Moy@imag.fr-public\"
   \"http://www-verimag.imag.fr/webdav/moy/public\"
   (\"xetla\"
    (\"main\"
     (\"0.1\"
      (\"patch-228\"
       \"Merged from Robert (patch8-9), Milan (patch21-22), Stefan (patch5-8)\"
       \"Matthieu Moy <Matthieu.Moy@imag.fr>\"
       \"2004-06-03 20:13:11 GMT\")
      (\"patch-227\"
       \"Fix default-directory in xetla-run-tla-sync, fix in xetla-changes-ediff\"
       \"Matthieu Moy <Matthieu.Moy@imag.fr>\"
       \"2004-06-03 15:26:15 GMT\")
 [...]
      (\"patch-1\"
       \"typo\"
       \"Matthieu Moy <Matthieu.Moy@imag.fr>\"
       \"2004-04-07 22:57:00 GMT\")
      (\"base-0\"
       \"tag of xsteve@nit.at-public/xetla-main-0.1-patch-5\"
       \"Matthieu Moy <Matthieu.Moy@imag.fr>\" \"2004-04-07 22:52:39 GMT\")))))
 [...]
   )

This list is initially empty, and is built/rebuilt on demand.")

;; Utilities
(defun xetla-archive-tree-setcdr (parent value &optional rest)
  "In PARENT, update VALUE.
REST are the items that are already present."
  (let* ((current (cdr parent))
         (list-details (assoc value current)))
    (if (or (null current) (null list-details))
        ;; rest is '("summary" "creator" "date") when value is "patch-N"
        (setcdr parent (cons (cons value rest) current))
      (if (and list-details rest)
          ;; Field already there. update details.
          (setcdr list-details rest)))))

(defun xetla-archive-tree-setcddr (parent value)
  "In PARENT, update VALUE."
  (let ((current (cddr parent)))
    (if (or (null current) (null (assoc value current)))
        (setcdr (cdr parent) (cons (cons value nil) current)))))

;; Archive
(defun xetla-archive-tree-add-archive (archive location &optional old)
  "Add ARCHIVE  at LOCATION to the archive tree.
If OLD is provided, it is an old archive tree from which some
information can be found (this is useful to keep the category/branch/version
info for existing archives)."
  (if (xetla-archive-tree-get-archive archive)
      (let* ((a (xetla-archive-tree-get-archive archive))
             (val (cdr a))
             (oldlocation (car val))
             (category (cdr val)))
        (setcdr a (cons (or location oldlocation) category)))
    (let ((oldinfo (xetla-archive-tree-get-archive archive old))
          (newinfo (list archive location)))
      (when oldinfo
        (setcdr (cdr newinfo) (cddr oldinfo))) ;; list of versions.
      (setq xetla-archive-tree (cons newinfo
                                    xetla-archive-tree)))))

(defun xetla-archive-tree-get-archive (archive &optional archive-tree)
  "Get the value of ARCHIVE from ARCHIVE-TREE.
If ARCHIVE-TREE is not given, `xetla-archive-tree' is used."
  (assoc archive (or archive-tree xetla-archive-tree)))

;; Category
(defun xetla-archive-tree-add-category (archive category)
  "Add a new category to ARCHIVE named CATEGORY."
  (xetla-archive-tree-add-archive archive nil)
  (xetla-archive-tree-setcddr
   (xetla-archive-tree-get-archive archive)
   category))

(defun xetla-archive-tree-get-category (archive category)
  "From ARCHIVE, get CATEGORY."
  (assoc category (cdr (cdr (xetla-archive-tree-get-archive archive)))))

;; Branch
(defun xetla-archive-tree-add-branch (archive category branch)
  "Add a new branch to ARCHIVE's CATEGORY named BRANCH."
  (xetla-archive-tree-add-category archive category)
  (xetla-archive-tree-setcdr
   (xetla-archive-tree-get-category archive category)
   branch))

(defun xetla-archive-tree-get-branch (archive category branch)
  "Get a branch from ARCHIVE's CATEGORY named BRANCH."
  (assoc branch (cdr (xetla-archive-tree-get-category
                      archive category))))

;; Version
(defun xetla-archive-tree-add-version (archive category branch version)
  "Add a new version to ARCHIVE CATEGORY BRANCH named VERSION."
  (xetla-archive-tree-add-branch archive category branch)
  (xetla-archive-tree-setcdr
   (xetla-archive-tree-get-branch archive category branch )
   version))

(defun xetla-archive-tree-get-version (archive category branch version)
  "Get a version from ARCHIVE CATEGORY BRANCH named VERSION."
  (assoc version (cdr (xetla-archive-tree-get-branch
                       archive category branch))))

;; Revision
(defun xetla-archive-tree-add-revision (archive category branch version revision
                                               &optional summary creator date)
  "Add a new revision to ARCHIVE CATEGORY BRANCH VERSION named REVISION."
  (xetla-archive-tree-add-version archive category branch version)
  (xetla-archive-tree-setcdr
   (xetla-archive-tree-get-version archive category branch version)
   revision (list summary creator date)))

(defun xetla-archive-tree-get-revision (archive category branch version revision)
  "Get a revision from ARCHIVE CATEGORY BRANCH VERSION named REVISION."
  (assoc revision (cdr (xetla-archive-tree-get-version
                        archive category branch version))))

;; Archive tree builders
(defun xetla-archive-tree-build (basename &optional use-cache ignore-error)
  "Generic version of xetla-archive-tree-build-*.
BASENAME is used as a base for this tree.
If USE-CACHE is non-nil, load details from the cache where possible.
If IGNORE-ERROR is non-nil, don't throw errors."
  (when (stringp basename)
    (setq basename (xetla-name-split basename)))
  (let ((archive (xetla-name-archive basename))
        (category (xetla-name-category basename))
        (branch (xetla-name-branch basename))
        (version (xetla-name-version basename)))
  (cond
   (version
    (xetla-archive-tree-build-revisions archive
                                       category
                                       branch
                                       version
                                       use-cache
                                       ignore-error))
   (branch
    (xetla-archive-tree-build-versions archive
                                      category
                                      branch
                                      use-cache
                                      ignore-error))
   (category
    (xetla-archive-tree-build-branches archive
                                      category
                                      use-cache
                                      ignore-error))
   (archive
    (xetla-archive-tree-build-categories archive
                                        use-cache
                                        ignore-error))
   (t
    (xetla-archive-tree-build-archives use-cache
                                      ignore-error)))))

(defun xetla-archive-tree-build-archives (&optional use-cache ignore-error)
  "Builds the list of archives.
If USE-CACHE is non-nil, load details from the cache where possible.
If IGNORE-ERROR is non-nil, don't throw errors."
  (when (or (not use-cache)
            (not xetla-archive-tree))
    (xetla-run-tla-sync '("archives")
                       :finished 'xetla-null-handler
                       :error
                       (if ignore-error
                           'xetla-null-handler
                         'xetla-default-error-function))
    (let ((old-archive-tree xetla-archive-tree))
      (setq xetla-archive-tree nil)
      (save-excursion
        (let ((archive-name)
              (archive-location))
          (set-buffer xetla-last-process-buffer)
          (goto-char (point-min))
          (while (> (point-at-eol) (point-at-bol))
            (setq archive-name (buffer-substring-no-properties
                                (point-at-bol)
                                (point-at-eol)))
            (beginning-of-line-text 2)
            (setq archive-location (buffer-substring-no-properties
                                    (point) (point-at-eol)))
            (forward-line 1)
            (xetla-archive-tree-add-archive archive-name
                                           archive-location
                                           old-archive-tree)))))))

(defun xetla-archive-tree-build-categories (archive &optional
                                                   use-cache
                                                   ignore-error)
  "Build the list of categories for ARCHIVE in `xetla-archive-tree'.
If USE-CACHE is non-nil, load details from the cache where possible.
If IGNORE-ERROR is non-nil, don't throw errors."
  (when (or (not use-cache)
            (not (cddr (xetla-archive-tree-get-archive archive))))
    (let ((basename archive))
      (message "building categories for `%s'..." basename)
      (xetla-run-tla-sync (list "categories" "-A" basename)
                         :finished 'xetla-null-handler
                         :error
                         (if ignore-error
                             'xetla-null-handler
                           'xetla-default-error-function))
      (message "building categories for `%s'...done" basename)
      (sit-for 0)
      (message nil))
    (with-current-buffer xetla-last-process-buffer
      (let (category)
        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq category (buffer-substring-no-properties
                          (point-at-bol)
                          (point-at-eol)))
          (forward-line 1)
          (xetla-archive-tree-add-category archive category)
          )))))

(defun xetla-archive-tree-build-branches (archive category
                                                 &optional
                                                 use-cache
                                                 ignore-error)
  "Build the list of branches for ARCHIVE/CATEGORY in `xetla-archive-tree'.
If USE-CACHE is non-nil, load details from the cache where possible.
If IGNORE-ERROR is non-nil, don't throw errors."
  (when (or (not use-cache)
            (not (cdr (xetla-archive-tree-get-category archive category))))
    (let ((basename (xetla-name-construct archive category)))
      (message "building branches for `%s'..." basename)
      (xetla-run-tla-sync (list "branches" basename)
                         :finished 'xetla-null-handler
                         :error
                         (if ignore-error
                             'xetla-null-handler
                           'xetla-default-error-function))
      (message "building branches for `%s'...done" basename)
      (sit-for 0)
      (message nil))
    (with-current-buffer xetla-last-process-buffer
      (let (branch)
        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq branch (buffer-substring-no-properties
                        (point-at-bol)
                        (point-at-eol)))
          (xetla-archive-tree-add-branch
           archive
           category
           (if (looking-at ".*-")
               (xetla-name-branch (xetla-name-split-semi-qualified
                                  branch))
             ;; unnamed branch
             ""))
          (forward-line 1))))))

(defun xetla-archive-tree-build-versions (archive category branch
                                                 &optional
                                                 use-cache
                                                 ignore-error)
  "Build the version list in ARCHIVE/CATEGORY-BRANCH in `xetla-archive-tree'.
If USE-CACHE is non-nil, load details from the cache where possible.
If IGNORE-ERROR is non-nil, don't throw errors."
  (when (or (not use-cache)
            (not (cdr (xetla-archive-tree-get-branch archive category
                                                    branch))))
    (let ((basename (xetla-name-construct archive category branch)))
      (message "building versions for `%s'..." basename)
      (xetla-run-tla-sync (list "versions" basename)
                       :finished 'xetla-null-handler
                       :error
                       (if ignore-error
                           'xetla-null-handler
                         'xetla-default-error-function))
      (message "building versions for `%s'...done" basename)
      (sit-for 0)
      (message nil))
    (with-current-buffer xetla-last-process-buffer
      (let (version)
        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq version (buffer-substring-no-properties
                         (point-at-bol)
                         (point-at-eol)))
          (forward-line 1)
          (xetla-archive-tree-add-version
           archive
           category
           branch
           (xetla-name-version (xetla-name-split-semi-qualified version))))))))

(defun xetla-archive-tree-build-revisions (archive category branch version
                                                  &optional
                                                  use-cache
                                                  ignore-error)

  "Build the revision list in ARCHIVE/CATEGORY-BRANCH-VERSION.
Updates `xetla-archive-tree'.
If USE-CACHE is non-nil, load details from the cache where possible.
If IGNORE-ERROR is non-nil, don't throw errors."
  (when (or (not use-cache)
            (not (cdr (xetla-archive-tree-get-version archive category branch
                                                     version))))
    (let ((details (or xetla-revisions-shows-summary
                       xetla-revisions-shows-date
                       xetla-revisions-shows-creator))
          (basename (xetla-name-construct
                     archive category branch version)))
      (message "building revisions for `%s'..." basename)
      (if details
          (progn
            (xetla-run-tla-sync (list "revisions"
                                     "--summary" "--date" "--creator"
                                     basename)
                               :finished 'xetla-null-handler
                               :error (if ignore-error
                                          'xetla-null-handler
                                        'xetla-default-error-function)))
        (progn
          (xetla-run-tla-sync (list "revisions" basename)
                             :finished 'xetla-null-handler
                             :error (if ignore-error
                                        'xetla-null-handler
                                      'xetla-default-error-function))))
      (message "building revisions for `%s'...done" basename)
      (sit-for 0)
      (message nil)
      (with-current-buffer xetla-last-process-buffer
        (let (revision date creator summary)
          (goto-char (point-min))
          (while (> (point-at-eol) (point-at-bol))
            (setq revision (buffer-substring-no-properties
                            (point-at-bol)
                            (point-at-eol)))
            (forward-line 1)
            (when details
              (skip-chars-forward " ")
              (setq date (buffer-substring-no-properties (point)
                                                         (point-at-eol)))
              (forward-line 1)
              (skip-chars-forward " ")
              (setq creator (buffer-substring-no-properties (point)
                                                            (point-at-eol)))
              (forward-line 1)
              (skip-chars-forward " ")
              (setq summary (buffer-substring-no-properties
                             (point)
                             (progn (re-search-forward "^\\([^ \t]\\|$\\)")
                                    (previous-line 1)
                                    (end-of-line)
                                    (point))))
              (forward-line 1))
            (xetla-archive-tree-add-revision
             archive
             category
             branch
             version
             revision
             summary
             creator
             date)))))))


(defun xetla-revisions-tree-contains-details
  (archive category branch version)
  "Whether VERSION has already been listed full details.
Details include summary lines, dates, and creator in the archive tree."
  (let ((vtree (xetla-archive-tree-get-version archive category branch
                                              version)))
    (and (cdr vtree) ;; revision list is here
         (cadr (cadr vtree))))) ;; summary line also

;; --------------------------------------
;; Revlib tree manipulators
;; --------------------------------------
(defvar xetla-revlib-tree nil)
(defun xetla-revlib-tree-get-archive (archive &optional archive-tree)
  "Get ARCHIVE from ARCHIVE-TREE.
If ARCHIVE-TREE is not given, `xetla-revlib-tree' is used instead."
  (assoc archive (or archive-tree xetla-revlib-tree)))

(defun xetla-revlib-tree-build-archives (&optional use-cache ignore-error)
  "Build the list of archives in `xetla-revlib-tree'.
If USE-CACHE is non-nil, load from the cache where possible.
If IGNORE-ERROR is non-nil, error is not reported.
Return non-nil if the tree entry for archives are updated."
  (when (or (not use-cache)
            (not xetla-revlib-tree))
    (xetla-run-tla-sync '("library-archives")
                       :finished 'xetla-null-handler
                       :error
                       (if ignore-error
                           'xetla-null-handler
                         'xetla-default-error-function))
    (let ((old-revlib-tree xetla-revlib-tree) )
      (setq xetla-revlib-tree nil)
      (save-excursion
        (let ((archive-name)
              (tmp xetla-archive-tree)
              (xetla-archive-tree xetla-revlib-tree)
              result)
          (set-buffer xetla-last-process-buffer)
          (goto-char (point-min))
          (while (> (point-at-eol) (point-at-bol))
            (setq result t)
            (setq archive-name (buffer-substring-no-properties
                                (point-at-bol)
                                (point-at-eol)))
            (forward-line 1)
            (xetla-archive-tree-add-archive archive-name
                                           nil
                                           old-revlib-tree))
          (setq xetla-revlib-tree xetla-archive-tree
                xetla-archive-tree tmp)
          result)))))

(defun xetla-revlib-tree-get-category (archive category)
  "Get a category from ARCHIVE named CATEGORY."
  (assoc category (cdr (cdr (xetla-revlib-tree-get-archive archive)))))

(defun xetla-revlib-tree-build-categories (archive &optional
                                                  use-cache
                                                  ignore-error)
  "Builds the list of categories for an ARCHIVE in `xetla-revlib-tree'.
If USE-CACHE is non-nil, load from the cache where possible.
If IGNORE-ERROR is non-nil, error is not reported.
Return non-nil if the tree entry for categories are updated."
  (when (or (not use-cache)
            (not (cddr (xetla-revlib-tree-get-archive archive))))
    (xetla-run-tla-sync (list "library-categories" "-A" archive)
                       :finished 'xetla-null-handler
                       :error
                       (if ignore-error
                           'xetla-null-handler
                         'xetla-default-error-function))
    (with-current-buffer xetla-last-process-buffer
      (let (category
            (tmp xetla-archive-tree)
            (xetla-archive-tree xetla-revlib-tree)
            result)
        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq result t)
          (setq category (buffer-substring-no-properties
                          (point-at-bol)
                          (point-at-eol)))
          (forward-line 1)
          (xetla-archive-tree-add-category archive category))
        (setq xetla-revlib-tree xetla-archive-tree
              xetla-archive-tree tmp)
        result))))

(defun xetla-revlib-tree-get-branch (archive category branch)
  "From ARCHIVE/CATEGORY, get BRANCH."
  (assoc branch (cdr (xetla-revlib-tree-get-category
                      archive category))))

(defun xetla-revlib-tree-build-branches (archive category
                                                &optional
                                                use-cache
                                                ignore-error)
  "Build the list of branches for ARCHIVE/CATEGORY in `xetla-revlib-tree'.
If USE-CACHE is non-nil, load from the cache where possible.
If IGNORE-ERROR is non-nil, error is not reported.
Return non-nil if the tree entry for branches are updated."
  (when (or (not use-cache)
            (not (cdr (xetla-revlib-tree-get-category archive category))))
    (xetla-run-tla-sync (list "library-branches" "-A" archive category)
                       :finished 'xetla-null-handler
                       :error
                       (if ignore-error
                           'xetla-null-handler
                         'xetla-default-error-function))
    (with-current-buffer xetla-last-process-buffer
      (let (branch
            (tmp xetla-archive-tree)
            (xetla-archive-tree xetla-revlib-tree)
            result)
        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq result t)
          (setq branch (buffer-substring-no-properties
                        (point-at-bol)
                        (point-at-eol)))
          (forward-line 1)
          (xetla-archive-tree-add-branch
           archive
           category
           (xetla-name-branch (xetla-name-split-semi-qualified branch))))
        (setq xetla-revlib-tree xetla-archive-tree
              xetla-archive-tree tmp)
        result))))

(defun xetla-revlib-tree-get-version (archive category branch version)
  "Get ARCHIVE/CATEGORY-BRANCH-VERSION from the revlib tree."
  (assoc version (cdr (xetla-revlib-tree-get-branch
                       archive category branch))))

(defun xetla-revlib-tree-build-versions (archive category branch
                                                &optional
                                                use-cache
                                                ignore-error)
  "Build the versions list in ARCHIVE/CATEGORY/BRANCH in `xetla-archive-tree'.
If USE-CACHE is non-nil, load from the cache where possible.
If IGNORE-ERROR is non-nil, error is not reported.
Return non-nil if the tree entry for versions are updated."
  (when (or (not use-cache)
            (not (cdr (xetla-revlib-tree-get-branch archive category
                                                   branch))))
    (xetla-run-tla-sync (list "library-versions"
                             (xetla-name-construct
                              archive category branch))
                       :finished 'xetla-null-handler
                       :error
                       (if ignore-error
                           'xetla-null-handler
                         'xetla-default-error-function))
    (with-current-buffer xetla-last-process-buffer
      (let (version
            (tmp xetla-archive-tree)
            (xetla-archive-tree xetla-revlib-tree)
            result)
        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq result t)
          (setq version (buffer-substring-no-properties
                         (point-at-bol)
                         (point-at-eol)))
          (forward-line 1)
          (xetla-archive-tree-add-version
           archive
           category
           branch
           (xetla-name-version (xetla-name-split-semi-qualified version))))
        (setq xetla-revlib-tree xetla-archive-tree
              xetla-archive-tree tmp)
        result))))

(defun xetla-revlib-tree-get-revision (archive category branch version revision)
  "Get ARCHIVE/CATEGORY-BRANCH-VERSION-REVISION from the revlib tree."
  (assoc revision (cdr (xetla-revlib-tree-get-version
                        archive category branch version))))

(defun xetla-revlib-tree-build-revisions (archive category branch version
                                                 &optional
                                                 use-cache
                                                 ignore-error)

  "Build the revision list of ARCHIVE/CATEGORY-BRANCH-VERSION.
Updates `xetla-revlib-tree'.
If IGNORE-ERROR is non-nil, error is not reported.
Return non-nil if the tree entry for revisions are updated."
  (when (or (not use-cache)
            (not (cdr (xetla-revlib-tree-get-version archive category branch
                                                    version))))
    (xetla-run-tla-sync (list "library-revisions"
                             "--summary" "--date" "--creator"
                             (xetla-name-construct
                              archive category branch version))
                       :finished 'xetla-null-handler
                       :error (if ignore-error
                                  'xetla-null-handler
                                'xetla-default-error-function))
    (with-current-buffer xetla-last-process-buffer
      (let (revision
            date
            creator
            summary
            (tmp xetla-archive-tree)
            (xetla-archive-tree xetla-revlib-tree)
            result)

        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq result t)
          (setq revision (buffer-substring-no-properties
                          (point-at-bol)
                          (point-at-eol)))
          (forward-line 1)
          (skip-chars-forward " ")
          (setq date (buffer-substring-no-properties (point)
                                                     (point-at-eol)))
          (forward-line 1)
          (skip-chars-forward " ")
          (setq creator (buffer-substring-no-properties (point)
                                                        (point-at-eol)))
          (forward-line 1)
          (skip-chars-forward " ")
          (setq summary (buffer-substring-no-properties
                         (point)
                         (progn (re-search-forward "^\\([^ \t]\\|$\\)")
                                (previous-line 1)
                                (end-of-line)
                                (point))))
          (forward-line 1)
          (xetla-archive-tree-add-revision
           archive
           category
           branch
           version
           revision
           summary
           creator
           date))
        (setq xetla-revlib-tree xetla-archive-tree
              xetla-archive-tree tmp)
        result
        ))))

;; --------------------------------------
;; Name reading engine
;; --------------------------------------
;;Currently only able to read a full revision starting from nothing.
(defun xetla-name-read-refresh-cache ()
  "Function to be called from the minibuffer while reading a name."
  (interactive)
  (xetla-archive-tree-build
   (xetla-name-construct
    (butlast (delete nil (xetla-name-split (buffer-substring))))))
  (setq xetla-archive-tree nil))

(defvar xetla-name-read-arguments "This value should not be refereed."
  "Used to suppress warnings from the byte code compiler.
This variable is a just placeholder introduced to suppress the
warnings from byte code compiler.  Variable `xetla-name-read-arguments'
should be bound in `let'.  Variable `xetla-name-read-arguments' is used
for passing information from `xetla-name-read' to functions called internally
from `xetla-name-read'.  Use function `xetla-name-read-arguments' to get the
information")

(defun xetla-name-read-arguments (key)
  "Get `xetla-name-read' context information associated to KEY.
`xetla-name-read' calls some functions to read a xetla name.
In the functions, the arguments passed to `xetla-name-read'(context information)
are needed to know.  However, `xetla-name-read' cannot pass the context
information directly to the functions because the functions are something to do
with Emacs's completion mechanism; and the mechanism specifies the number
of arguments of the functions.  So the context information is passed via
a local variable, `xetla-name-read-arguments', defined in let.

Symbol `archive', `category', `branch', `version', or `revision' are
acceptable as KEY."
  (cdr (assoc key xetla-name-read-arguments)))


(defun xetla-name-read-complete (string predicate what)
  "Completion function for name reading.

Displays STRING and prompts for something satisfying PREDICATE.

This function uses the free variables archive, category, branch,
version, and revision.  If one of these variables is non-nil, it means
the corresponding value must be read from keyboard.

REMINDER: this function may be called several times, with different
values for WHAT:

 - nil : The function must return the longest prefix
 - t : The function must return the list of completions
 - 'lambda : The function must return t if the completion correspond
   to an exact match, nil otherwise.  (so that Emacs can distinguish
   between \"sole completion\" and \"complete, but not unique\"."
  (if (and (eq what 'lambda)
           (string-match "/\\(.*--\\)?$" string))
      ;; The caller just want to know whether this is a full
      ;; completion. This can not be the case with such suffix.
      nil
    (let* ((empty-branch nil)
           (use-cache (not current-prefix-arg))
           (splited (xetla-name-split string))
           (archive-loc  (xetla-name-archive  splited))
           (category-loc (xetla-name-category splited))
           (branch-loc   (xetla-name-branch   splited))
           (version-loc  (xetla-name-version  splited))
           (revision-loc (xetla-name-revision splited))
           (suffix (cond
                    ((and (xetla-name-read-arguments 'category)
                          (not category-loc) "/"))
                    ((and (xetla-name-read-arguments 'branch)
                          (not branch-loc)   "--"))
                    ((and (xetla-name-read-arguments 'version)
                          (not version-loc)  "--"))
                    ((and (xetla-name-read-arguments 'revision)
                          (not revision-loc) "--"))
                    (t nil)))
           (maybep (cond
                    ((eq 'maybe (xetla-name-read-arguments 'category))
                     t)
                    ((and (eq 'maybe (xetla-name-read-arguments 'branch))
                          archive-loc category-loc)
                     t)
                    ((and (eq 'maybe (xetla-name-read-arguments 'version))
                          archive-loc category-loc branch-loc)
                     t)
                    ((and (eq 'maybe (xetla-name-read-arguments 'revision))
                          archive-loc category-loc branch-loc version-loc)
                     t)
                    (t nil)))
           (completions
            (cond
             ;; If the user started to write a revision ...
             (revision-loc
              ;; ... and if the user is supposed to be prompted a
              ;; revision
              (when (xetla-name-read-arguments 'revision)
                (let ((xetla-revisions-shows-summary nil)
                      (xetla-revisions-shows-date nil)
                      (xetla-revisions-shows-creator nil))
                  (xetla-archive-tree-build-revisions
                   archive-loc category-loc branch-loc version-loc use-cache t))
                (cdr (xetla-archive-tree-get-version
                      archive-loc category-loc branch-loc version-loc))))
             (version-loc
              (when (xetla-name-read-arguments 'version)
                (xetla-archive-tree-build-versions
                 archive-loc category-loc branch-loc use-cache t)
                (cdr (xetla-archive-tree-get-branch
                      archive-loc category-loc branch-loc))))
             ;; If the user started a branch ...
             (branch-loc
              ;; And a branch is needed
              (when (xetla-name-read-arguments 'branch)
                (xetla-archive-tree-build-branches
                 archive-loc category-loc use-cache t)
                (let ((result (cdr (xetla-archive-tree-get-category
                                    archive-loc category-loc))))
                  (when (and (string= branch-loc "")
                             (xetla-name-read-arguments 'version)
                             (let ((empty-br-exists nil))
                               (dolist (branch
                                        (cdr (xetla-archive-tree-get-category
                                              archive-loc category-loc)))
                                 (when (string= (car branch) "")
                                   (setq empty-br-exists t)))
                               empty-br-exists))
                    (xetla-archive-tree-build-versions
                     archive-loc category-loc "")
                    (setq empty-branch (xetla-archive-tree-get-branch
                                        archive-loc category-loc ""))
                    (when empty-branch
                      ;; Remove the "" branch to avoid the --
                      ;; completion.
                      (let ((tmp result))
                        (setq result nil)
                        (while tmp
                          (when (not (string= (caar tmp) ""))
                            (setq result (cons (car tmp) result)))
                          (setq tmp (cdr tmp))))))
                  result)))
             (category-loc
              (when (xetla-name-read-arguments 'category)
                (xetla-archive-tree-build-categories archive-loc use-cache t)
                (cddr (xetla-archive-tree-get-archive archive-loc))))
             (t
              (when (xetla-name-read-arguments 'archive)
                (xetla-archive-tree-build-archives use-cache t)
                xetla-archive-tree)))))
      (let* ((base (mapcar (lambda (x)
                             (xetla-name-construct
                              (delete
                               nil
                               (list
                                (when category-loc archive-loc)
                                (when branch-loc category-loc)
                                (when version-loc branch-loc)
                                (when revision-loc version-loc)
                                (car x)))))
                           completions))
             (sans-suffix
              (and maybep suffix))
             (empty-branch-versions
              (and empty-branch
                   (mapcar (lambda (x)
                             (xetla-name-construct
                              archive-loc category-loc "" (car x)))
                           (cdr empty-branch))))
             (completions (funcall 'all-completions
                                   string
                                   (nconc (mapcar
                                           (lambda (x)
                                             (list (concat x suffix)))
                                           base)
                                          (when sans-suffix
                                            (mapcar
                                             (lambda (x) (list x))
                                             base))
                                          (when empty-branch
                                            (mapcar
                                             (lambda (x) (list x))
                                             empty-branch-versions)))
                                   predicate)))
        (let ((result
               (cond ((eq what t)
                      ;; We just want the list of completions
                      completions)
                     ((eq (length completions) 1)
                      ;; There's only one completion
                      (if (eq what 'lambda)
                          (string= (car completions) string)
                        (cond ((string= (car completions) string) t)
                              (t (car completions)))))
                     ;; there are several possible completions
                     (t (if (eq what 'lambda)
                            ;; complete, but not unique ?
                            (member string completions)
                          (try-completion string (mapcar 'list
                                                         completions)))))))
;;          (xetla-trace "string=%s predicate=%S what=%s ==> result=%S\ncompletions=%S"
;;                      string predicate what result completions)
          result)))))

;; Test cases
;; (xetla-name-read "enter category: " "Matthieu.Moy@imag.fr--public" 'prompt)
;; (xetla-name-read "branch: " "lord@emf.net--2004" 'prompt 'prompt)
;; (xetla-name-read "revision: " 'prompt 'prompt 'prompt 'prompt 'prompt)
;; (xetla-name-read "revision or version: " 'prompt 'prompt 'prompt 'prompt 'maybe)
;; (xetla-name-read "revision or version: " "jet@gyve.org--xetla" "xetla" "jet" 'prompt 'maybe)
;;
(defvar xetla-name-read-history nil)     ; TODO: multiple history list?
(defvar xetla-name-read-debug nil
  "If non-nil, `condition-case' in `xetla-name-read' is made disabled.")
(defun xetla-name-read (&optional prompt archive category
                                 branch version revision)
  "Read a name.
To get help on the user interface of `xetla-name-read', please type
M-x xetla-name-read-help RET.

Function reading an archive location from keyboard.
Read name is expressed in a list built by `xetla-name-split'.

First argument PROMPT is the prompt the user will get. Next arguments
ARCHIVE CATEGORY BRANCH VERSION and REVISION are either the default
value, or a request for a value. They can take four values:

 - A string means the default value, and will be used as an initial
   input.

 - The symbol 'prompt means the value will be prompted from the user.
   The user will HAVE to give this value.

 - The symbol 'maybe means the value will be prompted, but is optional
   for the user.

 - nil means the value won't be prompted.

They should appear in the same order as above.

Example:
- Read a category in archive \"Matthieu.Moy@imag.fr--public\":
 (xetla-name-read \"enter category: \" \"Matthieu.Moy@imag.fr--public\" 'prompt)
- Read a revision, anywhere:
 (xetla-name-read \"revision: \" 'prompt 'prompt 'prompt 'prompt 'prompt)
- Read either a revision or a version:
 (xetla-name-read \"revision: \" 'prompt 'prompt 'prompt 'prompt 'maybe)

While prompting, a menu \"Xetla\" is added to the menubar. The
following commands are available:

\\{xetla-name-read-minibuf-map}"
  (let ((xetla-name-read-arguments `((archive  . ,archive)
                                    (category . ,category)
                                    (branch   . ,branch)
                                    (version  . ,version)
                                    (revision . ,revision))))
    (if xetla-name-read-debug
        (xetla-name-read-internal prompt archive category branch version revision)
      (condition-case reason
          (xetla-name-read-internal prompt archive category branch version revision)
        ((quit error)
         (run-hooks 'xetla-name-read-error-hook)
         (signal (car reason) (cdr reason)))))))

(defun xetla-name-read-internal (prompt archive category branch version revision)
  "See `xetla-name-read'."
  (run-hooks 'xetla-name-read-init-hook)
  (let* ((minibuffer-local-completion-map xetla-name-read-minibuf-map)
         (result (xetla-name-construct
                  (delete
                   'maybe
                   (delete 'prompt (list archive category
                                         branch version)))))
         (first-try t)
         not-finished too-long last-empty)
    ;; Without in some case 'maybe is ignored by xetla-prompt-not-finished
    ;; and never the control flow enters the while loop.
    ;; We need C language's do-while loop.
    (while (or first-try
               not-finished
               too-long
               last-empty)
      (unless first-try
        (unless (eq this-command 'choose-completion)
          (ding)
          (message (cond (not-finished "%s%s [incomplete input: %s]")
                         (too-long "%s%s [too long input for: %s]")
                         (last-empty (concat "%s%s [empty " last-empty
                                             " name]"))
                         (t (error
                             (concat "case not managed."
                                     " Please submit a bug report"))))
                   prompt result
                   (xetla-name-read-required-input archive
                                                  category
                                                  branch
                                                  version
                                                  revision))
          (sit-for 2)
          (message nil)))

      (setq result (completing-read
                    (or prompt "Location: ")
                    'xetla-name-read-complete
                    nil nil result
                    'xetla-name-read-history)
            first-try nil)
      (setq not-finished (xetla-prompt-not-finished
                          result archive category branch
                          version revision))
      (setq too-long (xetla-prompt-too-long
                      result archive category branch
                      version revision))
      (setq last-empty (xetla-prompt-last-empty result)))

    (when result
      (setq result (xetla-name-split result)))
    (run-hook-with-args 'xetla-name-read-final-hook result)
    result))

(defun xetla-prompt-not-finished (result archive category branch
                                        version revision)
  "Check whether user input is complete.
True if RESULT (a string) is not sufficient when the user is
prompted for ARCHIVE CATEGORY BRANCH VERSION REVISION."
  (let ((res-split (xetla-name-split result)))
    (or (and (eq archive 'prompt) ;; archive required
             (not (xetla-name-archive res-split))) ;; but not provided
        (and (eq category 'prompt)
             (not (xetla-name-category res-split)))
        (and (eq branch 'prompt)
             (not (xetla-name-branch res-split)))
        (and (eq version 'prompt)
             (not (xetla-name-version res-split)))
        (and (eq revision 'prompt)
             (not (xetla-name-revision res-split))))))

(defun xetla-prompt-too-long (result archive category branch
                                    version revision)
  "Check whether the user has entered too many elements.
True if RESULT (a string) contains too many elements when the user
is prompted for ARCHIVE CATEGORY BRANCH VERSION REVISION.

For example, will return true if the user entered
foo@bar-2004/xetla-main while prompted only for a category."
  (let ((res-split (xetla-name-split result)))
    (or (and (not revision) ;; revision not needed
             (xetla-name-revision res-split)) ;; but provided
        (and (not version)
             (xetla-name-version res-split))
        (and (not branch)
             (xetla-name-branch res-split))
        (and (not category)
             (xetla-name-category res-split))
        (and (not archive)
             (xetla-name-archive res-split)))))

(defun xetla-prompt-last-empty (result)
  "Check whether the last field is empty.
Non-nil if RESULT (a string) is terminated by \"--\" or \"/\". This
means the user entered a delimiter but not the element after.

When non-nil, the returned value is a string giving the name of the
item that is currently empty. (eg: archive, category, ...)"
  (let ((res-split (xetla-name-split result)))
    (cond ((equal (xetla-name-archive  res-split) "") "archive" )
          ((equal (xetla-name-category res-split) "") "category")
          ((and (equal (xetla-name-branch res-split) "")
                (not (xetla-name-version res-split))) "branch"  )
          ((equal (xetla-name-version  res-split) "") "version" )
          ((equal (xetla-name-revision res-split) "") "revision")
          (t nil))))


(defun xetla-name-read-required-input (archive
                                      category
                                      branch
                                      version
                                      revision)
  "Return string which represents the elements to be readin `xetla-name-read'.
If ARCHIVE, CATEGORY, BRANCH, VERSION or REVISION are equal to 'maybe, the
corresponding element will be optionally read.
If any of these are non-nil (but not 'maybe), the corresponding element will be
required.
If any of these are nil, the correpsonding element is not required."
  (concat
   (cond ((eq archive 'maybe) "[A]")
         (archive "A")
         (t ""))
   (cond ((eq category 'maybe) "[/C]")
         (category "/C")
         (t ""))
   (cond ((eq branch 'maybe) "[--B]")
         (branch "--B")
         (t ""))
   (cond ((eq version 'maybe) "[--V]")
         (version "--V")
         (t ""))
   (cond ((eq revision 'maybe) "[--R]")
         (revision "--R")
         (t ""))))



(defun xetla-location-type (location)
  "Return the type of LOCATION."
  (cond
   ((string-match "^ftp://" location) 'ftp)
   ((string-match "^sftp://" location) 'sftp)
   ((string-match "^http://" location) 'http)
   (t 'local)))

(defun xetla-archive-type (archive)
  "Return the type of ARCHIVE."
  (cond
   ((string-match "SOURCE$" archive) 'source)
   ;; archive-MIRROR, archive-MIRROR-2 should be treated as mirror
   ((string-match ".+-MIRROR" archive) 'mirror)
   (t 'normal)))

;; (xetla-archive-name-source "a")
;; (xetla-archive-name-source "a-SOURCE")
;; (xetla-archive-name-source "a-MIRROR")
(defun xetla-archive-name-source (archive &optional existence-check)
  "Make source archive name from ARCHIVE.
If EXISTENCE-CHECK is non-nil, check whether the made source archive name
already exists or not; return nil if it doesn't exists.
Example:
ELISP> (xetla-archive-name-source \"jet@gyve.org-xetla\")
\"jet@gyve.org-xetla-SOURCE\"
ELISP> (xetla-archive-name-source \"jet@gyve.org-xetla-MIRROR\")
\"jet@gyve.org-xetla\"
ELISP> (xetla-archive-name-source \"jet@gyve.org-xetla-SOURCE\")
nil"
  (let* ((type (xetla-archive-type archive))
         (source (cond
                 ((eq 'normal type)
                  (concat archive "-SOURCE"))
                 ((eq 'mirror type)
                  (string-match "\\(.*\\)-MIRROR$" archive)
                  (match-string 1 archive))
                 (t nil))))
    (if existence-check
        (progn
          (xetla-archive-tree-build-archives t)
          (when (and source (xetla-archive-tree-get-archive source))
            source))
      source)))

;; (xetla-archive-name-mirror "a")
;; (xetla-archive-name-mirror "a-SOURCE")
;; (xetla-archive-name-mirror "a-MIRROR")
(defun xetla-archive-name-mirror (archive &optional existence-check)
  "Make mirror archive name from ARCHIVE.
If EXISTENCE-CHECK is non-nil, check whether the made mirror archive name
already exists or not; return nil if it doesn't exists.
Example:
ELISP> (xetla-archive-name-mirror \"jet@gyve.org--xetla\")
\"jet@gyve.org--xetla-MIRROR\"
ELISP> (xetla-archive-name-mirror \"jet@gyve.org--xetla-SOURCE\")
\"jet@gyve.org--xetla\"
ELISP> (xetla-archive-name-mirror \"jet@gyve.org--xetla-MIRROR\")
nil"
  (let* ((type (xetla-archive-type archive))
         (mirror (cond
                  ((eq 'normal type)
                   (concat archive "-MIRROR"))
                  ((eq 'source type)
                   (string-match "\\(.*\\)-SOURCE" archive)
                   (match-string 1 archive))
                  (t nil))))
    (if existence-check
        (progn
          (xetla-archive-tree-build-archives t)
          (when (and mirror (xetla-archive-tree-get-archive mirror))
            mirror))
      mirror)))

(defun xetla-compute-direct-ancestor (&optional revision)
  "Compute the direct ancestor of REVISION.
REVISION must be provided as a list, and a list is returned.
If revision is nil, return the ancestor of the last revision
of the local tree."
  (interactive
   (list (xetla-name-read "Compute direct ancestor of: "
                         'prompt 'prompt 'prompt 'prompt 'prompt)))
  (let ((ancestor
         (xetla-run-tla-sync (list "ancestry-graph" "--immediate"
                                  (and revision
                                       (xetla-name-construct revision)))
                            :finished (lambda (output error status arguments)
                                        (xetla-name-split
                                         (xetla-buffer-content
                                          output))))))
    (when (interactive-p)
      (message "Ancestor of: %s\n         is: %s"
               (xetla-name-construct ancestor)
               (xetla-name-construct revision)))
    ancestor))

;; Copied from ediff-mouse-event-p. I prefer keeping this duplication
;; to avoid one more dependancy on ediff.el (whose interface may
;; change one day ...)
(defsubst xetla-mouse-event-p (event)
  "Return true if EVENT is a mouse-related event."
  (if (featurep 'xemacs)
      (xetla-do-in-xemacs (button-event-p event))
    (xetla-do-in-gnu-emacs
      (string-match "mouse" (format "%S" (event-basic-type event))))))

;; --------------------------------------
;; Face manipulators
;; --------------------------------------
(defun xetla-face-add (str face &optional keymap menu help)
  "Add to string STR the face FACE.
Optionally, also add the text properties KEYMAP, MENU and HELP.

If KEYMAP is a symbol, (symbol-value KEYMAP) is used
as a keymap; and `substitute-command-keys' result
against (format \"\\{%s}\" (symbol-name keymap)) is appended to HELP.

If HELP is nil and if MENU is non nil, the MENU title is used as HELP."
  (if xetla-highlight
      (let* ((strcpy (copy-sequence str))
             (key-help (when (symbolp keymap)
                         (substitute-command-keys (format "\\{%s}" (symbol-name keymap)))))
             (prefix-help (if help help (when (and menu (stringp (cadr menu))) (cadr menu))))
             (long-help (if key-help
                            (if prefix-help (concat prefix-help "\n"
                                             ;; Sigh. Font used on tooltips in GNU Emacs with Gtk+
                                             ;; is a proportional.
                                             ;; (make-string (length help) ?=) "\n"
                                             "================" "\n"
                                             key-help) key-help)
                          help))
             (keymap (if (symbolp keymap) (symbol-value keymap) keymap)))
        (add-text-properties 0 (length strcpy)
                             `(face ,face
;;; Even if we define a face in a buffer, it seems that
;;; font-lock mode just ignore it or remove the face property.
;;; I don't know the detail but in xetla-inventory buffer,
;;; I cannot make both font-lock keywords and faces put by tl-face-add
;;; highlight at once. When font-lock-face is defined, I can do.
;;; See "Special Properties" subsection in the emacs lisp reference manual.
;;; `font-lock-face' property is new in Emacs 21.4. However, I guess there is
;;; no wrong side effect if I define font-lock-face property here.
                                    font-lock-face ,face
                                    ,@(when keymap
                                        `(mouse-face highlight
                                                     keymap ,keymap
                                                     help-echo ,long-help))
                                    ,@(when menu
                                        `(menu ,menu))
                                    )
                             strcpy)
        strcpy)
    str))

;; --------------------------------------
;; Debugging facilities
;; --------------------------------------
(defvar xetla-debug t)

(defun xetla-trace (&rest msg)
  "Display the trace message MSG.
Same as `message' if `xetla-debug' is non-nil.
Does nothing otherwise.  Please use it for your debug messages."
  (when xetla-debug
    (apply 'message (concat "xetla: " (car msg)) (cdr msg))))

(defun xetla-reload (directory)
  "Reloads xetla \(usually for debugging purpose\).

With prefix arg, prompts for the DIRECTORY in which xetla should be
loaded.  Useful to switch from one branch to the other.

If a Makefile is present in the directory where xetla is to be loaded,
run \"make\"."
  (interactive
   (list (when current-prefix-arg
           (let* ((other (read-directory-name
                         "Load XEtla from: "))
                  (lispdir (concat (file-name-as-directory other)
                                   "lisp")))
             (if (file-directory-p lispdir)
                 lispdir
               other)))))
  (when directory
    (let ((current-path (file-name-directory (locate-library
                                              "xetla"))))
      (setq load-path
            (cons directory (remove current-path load-path)))))
  (let ((default-directory (file-name-directory (locate-library "xetla"))))
    (when (file-exists-p
           "Makefile")
      (shell-command "make")))
  (when (featurep 'xetla-tips)      (unload-feature 'xetla-tips      t))
  (when (featurep 'xetla-browse)    (unload-feature 'xetla-browse    t))
  (when (featurep 'xetla)           (unload-feature 'xetla           t))
  (when (featurep 'xetla-core)      (unload-feature 'xetla-core      t))
  (when (featurep 'xetla-defs)      (unload-feature 'xetla-defs      t))
  (when (featurep 'xetla-autoloads) (unload-feature 'xetla-autoloads t))
  (ignore-errors (require 'xetla-autoloads))
  (require 'xetla))

;; --------------------------------------
;; Supports spaces in filenames
;; --------------------------------------
(defvar xetla-supports-spaces-in-filenames nil
  "Wether xetla supports spaces in filenames.

Possible values are nil (don't know), 'yes, or 'no.  Don't use this
variable directly.  Use `xetla-supports-spaces-in-filenames' instead.")

(defun xetla-supports-spaces-in-filenames ()
  "Wether xetla supports spaces in filenames.

Returns 't or nil.

If `xetla-supports-spaces' is non-nil, use its value.  Otherwise, test
if \"escape\" is listed by \"xetla help\", and memorize the result in
`xetla-supports-spaces-in-filenames'"
  (interactive)
  (let ((answer
         (cond ((eq xetla-supports-spaces-in-filenames 'yes) t)
               ((eq xetla-supports-spaces-in-filenames 'no) nil)
               (t (xetla-run-tla-sync
                   '("help")
                   :finished (lambda (output error status arguments)
                               (with-current-buffer output
                                 (goto-char (point-min))
                                 (search-forward "escape :"
                                                 nil t))))))))
    (when (interactive-p)
      (message (if answer "Yes" "No")))
    (setq xetla-supports-spaces-in-filenames
          (if answer 'yes 'no))
    answer))

(defun xetla-escape (string &optional unescape message)
  "Return the pika escaped value of STRING.
If pika escaping is not supported by xetla, return STRING.
If UNESCAPE is non-nil, returns the unescaped version of string.
If MESSAGE is non-nil or if run interactively, also display the value
as a message."
  (interactive "sString to escape: ")
  (let ((res (if (and (string-match (if unescape "\\\\"
                                      "[^a-zA-Z._+,{}-]") string)
                      ;; We need to do the (un)escaping
                      (xetla-supports-spaces-in-filenames))
                 (xetla-run-tla-sync
                  (list "escape" (when unescape "--unescaped") string)
                  :finished (lambda (output error status arguments)
                              (xetla-buffer-content output)))
               string)))
    (when (or (interactive-p) message)
      (message res))
    res))

(defun xetla-unescape (string)
  "Run \"tla escape -unescaped\" on STRING.

Return STRING if \"tla escape\" is not available."
  (interactive "sString to unescape: ")
  (xetla-escape string t (interactive-p)))

(defun xetla-regexp-quote (string)
  "Return a regexp string which matches exactly STRING and nothing else.
Special characters are escaped to leave STRING in a suitable form for
Arch."
  (let ((quoted (regexp-quote string)))
    (replace-regexp-in-string
     "\\([{}()|]\\)"
     (concat "\\\\"                     ; leading slash
             "\\1")                     ; quoted character
     quoted)))

;; --------------------------------------
;; Saving and loading state variables
;; --------------------------------------
(defun xetla-pp-to-string (sexp)
  "Return sexp pretty printed by `pp-to-string'."
  (let ((print-readably t)
        print-level print-length)
    (pp-to-string sexp)))

(defun xetla-save-state (&optional vars state-file pp)
  "Save variables from VARS list to file STATE-FILE.
The default for VARS is `xetla-state-variables-list'
The default for STATE-FILE is `xetla-state-file-name'.
If PP is non-nil use `xetla-pp-to-string' to format object.

The file will contain a setq setting the vars during loading by
`xetla-load-state'."
  (let ((state-file (or state-file
                        (expand-file-name xetla-state-file-name
                                          xetla-config-directory)))
        (vars (or vars xetla-state-variables-list))
        v)
    (if (not (file-exists-p (file-name-directory state-file)))
        (make-directory (file-name-directory state-file) t))
    (save-excursion
      (set-buffer (get-buffer-create " *xetla-state*"))
      (erase-buffer)
      (insert ";; Generated file. Do not edit!!!\n(setq\n")
      (if pp
          (while vars
            (setq v (car vars) vars (cdr vars))
            (insert (format "%s\n'%s"
                            (symbol-name v)
                            (xetla-pp-to-string (symbol-value v)))))
        (while vars
          (setq v (car vars) vars (cdr vars))
          (insert (format "      %s '%S\n"
                          (symbol-name v)
                          (symbol-value v)))))
      (insert "      )")
      (write-region (point-min) (point-max) state-file))))

(defun xetla-load-state (&optional state-file)
  "Load `xetla-state-file-name`, i.e. evaluate its content."
  (let ((state-file (or state-file
                        (expand-file-name xetla-state-file-name
                                          xetla-config-directory))))
    (if (file-exists-p state-file)
        (load state-file nil t t))))

;; (setq xetla-archive-tree nil)
;; (setq xetla-revlib-tree nil)

(provide 'xetla-core)
;;; xetla-core.el ends here
