view lisp/filecache.el @ 94414:d86cb59eea9f

2008-04-27 Carsten Dominik <dominik@science.uva.nl> * org/org.el (org-html-level-start): Always have id's in HTML (org-export-as-html): Use `org-link-protocols' to retrieve the export form of the link. (org-add-link-type): Final parameter renamed from PUBLISH. Better documentation of how it is to be used. Avoid double entries for the same link type. (org-add-link-props): New function. (org-modules-loaded): New variable. (org-load-modules-maybe, org-set-modules): New function. (org-modules): New option. (org-mode, org-cycle, orgstruct-mode, org-run-like-in-org-mode) (orgtbl-mode, org-store-link, org-insert-link-global) (org-open-at-point): Call `org-load-modules-maybe'. (org-search-view): Add more text properties. (org-agenda-schedule, org-agenda-deadline): Allow also in search-type agendas. (org-search-view): Order of arguments has been changed. Interpret prefix-arg as TODO-ONLY. (org-agenda, org-run-agenda-series, org-agenda-manipulate-query): Take new argument order of `org-search-view' into account. (org-todo-only): New variable. (org-search-syntax-table): New variable and function. (org-search-view): Do the search with the special syntax table. (define-obsolete-function-alias): Make work with XEmacs. (org-add-planning-info): Use old date as default when modifying an existing deadline or scheduled item. (org-agenda-compute-time-span): Make argument N optional. (org-agenda-format-date-aligned): Require `cal-iso'. (org-agenda-list): Include week into into agenda heading, don't list it at each date (only on Mondays). (org-read-date-analyze): Define local variable `iso-date'. (org-agenda-format-date-aligned): Remove dependency on `calendar-time-from-absolute'. (org-remember-apply-template, org-go-to-remember-target): Interpret filenames relative to `org-directory'. (org-complete): Silently fail when trying to complete keywords that don't have a default value. (org-get-current-options): Added a #+DATE: option. (org-additional-option-like-keywords): Removed "DATE:" from the list of additional keywords. (org-export-as-html): Removed (current-time) as unnecessary second argument of `format-time-string'. (org-clock-find-position): Handle special case at end of buffer. (org-agenda-day-view): New argument DAY-OF-YEAR, pass it on to `org-agenda-change-time-span'. (org-agenda-week-view): New argument ISO-WEEK, pass it on to `org-agenda-change-time-span'. (org-agenda-month-view): New argument MONTH, pass it on to `org-agenda-change-time-span'. (org-agenda-year-view): New argument YEAR, pass it on to `org-agenda-change-time-span'. (org-agenda-change-time-span): New optional argument N, pass it on to `org-agenda-compute-time-span'. (org-agenda-compute-time-span): New argument N, interpret it by changing the starting day. (org-small-year-to-year): New function. (org-scheduled-past-days): Respect `org-scheduled-past-days'. (org-auto-repeat-maybe): Make sure that repeating dates are pushed into the future, and that the shift is at least one interval, never 0. (org-update-checkbox-count): Fix bug with checkbox counting. (org-add-note): New command. (org-add-log-setup): Renamed from `org-add-log-maybe'. (org-log-note-headings): New entry for plain notes (i.e. notes not related to state changes or clocking). (org-get-org-file): Check for availability of `remember-data-file'. (org-cached-entry-get): Allow a regexp value for `org-use-property-inheritance'. (org-use-property-inheritance): Allow regexp value. Fix bug in customization type. (org-use-tag-inheritance): Allow a list and a regexp value for this variable. (org-scan-tags, org-get-tags-at): Implement selective tag inheritance. (org-entry-get): Respect value `selective' for the INHERIT argument. (org-tag-inherit-p, org-property-inherit-p): New functions. (org-agenda-format-date-aligned): Allow 10 characters for weekday, to acomodate German locale. (org-add-archive-files): New function. (org-agenda-files): New argument `ext', to get archive files as well. (org-tbl-menu): Protect the use of variables that are only available when org-table.el gets loaded. (org-read-agenda-file-list): Error if `org-agenda-files' is a single directory. (org-open-file): Allow a batch process to trigger waiting after executing a system command. (org-store-link): Link to headline when there is not target and no region in an org-mode buffer when creating a link. (org-link-types-re): New variable. (org-make-link-regexps): Compute `org-link-types-re'. (org-make-link-description-function): New option. (org-agenda-date, org-agenda-date-weekend): New faces. (org-archive-sibling-heading): New option. (org-archive-to-archive-sibling): New function. (org-iswitchb): New command. (org-buffer-list): New function. (org-agenda-columns): Also try the #+COLUMNS line in the buffer associated with the entry at point (or with the first entry in the agenda view). (org-modules): Add entry for org-bibtex.el. (org-completion-fallback-command): Moved into `org-completion' group. (org-clock-heading-function): Moved to `org-progress' group. (org-auto-repeat-maybe): Make sure that a note can be enforces if `org-log-repeat' is `note'. (org-modules): Allow additional symbols for external packages. (org-ctrl-c-ctrl-c): Allow for `org-clock-overlays' to be undefined. (org-clock-goto): Hide drawers after showing an entry with `org-clock-goto.' (org-shiftup, org-shiftdown, org-shiftright, org-shiftleft): Try also a clocktable block shift. (org-clocktable-try-shift): New function. (org-columns-hscoll-title): New function. (org-columns-previous-hscroll): New variable. (org-columns-full-header-line-format): New variable. (org-columns-display-here-title, org-columns-remove-overlays): Install `org-columns-hscoll-title' in post-command-hook. * org/org.el: Split into many small files. * org/org-agenda.el: New file, split off from org.el. * org/org-archive.el: New file, split off from org.el. * org/org-bbdb.el: New file. * org/org-bibtex.el: New file, split off from org.el. * org/org-clock.el: New file, split off from org.el. * org/org-colview.el: New file, split off from org.el. * org/org-compat.el: New file, split off from org.el. * org/org-exp.el: New file, split off from org.el. * org/org-faces.el: New file, split off from org.el. * org/org-gnus.el: New file, split off from org.el. * org/org-info.el: New file, split off from org.el. * org/org-infojs.el: New file. * org/org-irc.el: New file. * org/org-macs.el: New file, split off from org.el. * org/org-mew.el: New file. * org/org-mhe.el: New file, split off from org.el. * org/org-publish.el: New file, split off from org.el. * org/org-remember.el: New file, split off from org.el. * org/org-rmail.el: New file, split off from org.el. * org/org-table.el: New file, split off from org.el. * org/org-vm.el: New file, split off from org.el. * org/org-wl.el: New file, split off from org.el. 2008-04-27 Jason Riedy <jason@acm.org> * lisp/org-table.el (orgtbl-to-generic): Add a :remove-nil-lines parameter that supresses lines that evaluate to NIL. (orgtbl-get-fmt): New inline function for picking apart formats that may be lists. (orgtbl-apply-fmt): New inline function for applying formats that may be functions. (orgtbl-eval-str): New inline function for strings that may be functions. (orgtbl-format-line, orgtbl-to-generic): Use and document. (orgtbl-to-latex, orgtbl-to-texinfo): Document. (*orgtbl-llfmt*, *orgtbl-llstart*) (*orgtbl-llend*): Dynamic variables for last-line formatting. (orgtbl-format-section): Shift formatting to support detecting the last line and formatting it specially. (orgtbl-to-generic): Document :ll* formats. Set to the non-ll formats unless overridden. (orgtbl-to-latex): Suggest using :llend to suppress the final \\. (*orgtbl-table*, *orgtbl-rtn*): Dynamically bound variables to hold the input collection of lines and output formatted text. (*orgtbl-hline*, *orgtbl-sep*, *orgtbl-fmt*, *orgtbl-efmt*, (*orgtbl-lfmt*, *orgtbl-lstart*, *orgtbl-lend*): Dynamically bound format parameters. (orgtbl-format-line): New function encapsulating formatting for a single line. (orgtbl-format-section): Similar for each section. Rebinding the dynamic vars customizes the formatting for each section. (orgtbl-to-generic): Use orgtbl-format-line and orgtbl-format-section. (org-get-param): Now unused, so delete. (orgtbl-gather-send-defs): New function to gather all the SEND definitions before a table. (orgtbl-send-replace-tbl): New function to find the RECEIVE corresponding to the current name. (orgtbl-send-table): Use the previous two functions and implement multiple destinations for each table. * doc/org.texi (A LaTeX example): Note that fmt may be a one-argument function, and efmt may be a two-argument function. (Radio tables): Document multiple destinations. 2008-04-27 Carsten Dominik <dominik@science.uva.nl> * org/org-agenda.el (org-add-to-diary-list): New function. (org-prefix-has-effort): New variable. (org-sort-agenda-noeffort-is-high): New option. (org-agenda-columns-show-summaries) (org-agenda-columns-compute-summary-properties): New options. (org-format-agenda-item): Compute the duration of the item. (org-agenda-weekend-days): New variable. (org-agenda-list, org-timeline): Use the proper faces for dates in the agenda and timeline buffers. (org-agenda-archive-to-archive-sibling): New command. (org-agenda-start-with-clockreport-mode): New option. (org-agenda-clockreport-parameter-plist): New option. (org-agenda-clocktable-mode): New variable. (org-agenda-deadline-leaders): Allow a function value for the deadline leader. (org-agenda-get-deadlines): Deal with new function value. * lisp/org-clock.el (org-clock): New customization group. (org-clock-into-drawer, org-clock-out-when-done) (org-clock-in-switch-to-state, org-clock-heading-function): Moved into the new group. (org-clock-out-remove-zero-time-clocks): New option. (org-clock-out): Use `org-clock-out-remove-zero-time-clocks'. (org-dblock-write:clocktable): Allow a Lisp form for the scope parameter. (org-dblock-write:clocktable): Fixed bug with total time calculation. (org-dblock-write:clocktable): Request the unrestricted list of files. (org-get-clocktable): New function. (org-dblock-write:clocktable): Make sure :tstart and :tend can not only be strings but also integers (an absolute day number) and lists (m d y). * org/org-colview.el (org-columns-next-allowed-value) (org-columns-edit-value): Limit the effort for updatig in the agenda to recomputing a single file. (org-columns-compute): Only write property value if it has changed. This avoids raising the buffer-change-flag unnecessarily. (org-agenda-colview-summarize) (org-agenda-colview-compute): New functions. (org-agenda-columns): Call `org-agenda-colview-summarize'. * org/org-exp.el (org-export-run-in-background): New option. (org-export-icalendar): Allow a batch process to trigger waiting after executing a system command. (org-export-preprocess-string): Renamed-from `org-cleaned-string-for-export'. (org-export-html-style): Made target class look like normal text. (org-export-as-html): Make use of the better proprocessing in `org-cleaned-string-for-export'. (org-cleaned-string-for-export): Better treatment of heuristic targets, many more internal links will now work in HTML export. (org-get-current-options): Incorporate LINK_UP, LINK_HOME, and INFOJS. (org-export-inbuffer-options-extra): New variable. (org-export-options-filters): New hook. (org-infile-export-plist): Find also the settings keywords in `org-export-inbuffer-options-extra'. (org-infile-export-plist): Allow multiple #+OPTIONS lines and multiple #+INFOJS_OPT lines. (org-export-html-handle-js-options): New function. (org-export-html-infojs-setup): New option. (org-export-as-html): Call `org-export-html-handle-js-options'. Add autoload to all entry points. (org-skip-comments): Function removed. * org/org-table.el (org-table-make-reference): Extra parenthesis around single fields, to make sure that algebraic formulas get correctly interpreted by calc. (org-table-current-column): No longer interactive. * org/org-export-latex.el (org-export-latex-preprocess): Renamed from `org-export-latex-cleaned-string'. 2008-04-27 Bastien Guerry <bzg@altern.org> * org/org-publish.el (org-publish-get-base-files-1): New function. (org-publish-get-base-files): Use it. (org-publish-temp-files): New variable. Don't require 'dired-aux anymore. (org-publish-initial-buffer): New variable. (org-publish-org-to, org-publish): Use it. (org-publish-get-base-files-1): Bug fix: get the proper list of files when recursing thru a directory. (org-publish-get-base-files): Use the :exclude property to skip both files and directories.
author Carsten Dominik <dominik@science.uva.nl>
date Sun, 27 Apr 2008 18:33:39 +0000
parents d23d9685c214
children ee5932bf781d
line wrap: on
line source

;;; filecache.el --- find files using a pre-loaded cache
;;
;; Author:  Peter Breton <pbreton@cs.umb.edu>
;; Created: Sun Nov 10 1996
;; Keywords: convenience
;;
;; Copyright (C) 1996, 2000, 2001, 2002, 2003, 2004,
;;   2005, 2006, 2007, 2008 Free Software Foundation, Inc.

;; This file is part of GNU Emacs.

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

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

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.

;;; Commentary:
;;
;; The file-cache package is an attempt to make it easy to locate files
;; by name, without having to remember exactly where they are located.
;; This is very handy when working with source trees. You can also add
;; frequently used files to the cache to create a hotlist effect.
;; The cache can be used with any interactive command which takes a
;; filename as an argument.
;;
;; It is worth noting that this package works best when most of the files
;; in the cache have unique names, or (if they have the same name) exist in
;; only a few directories. The worst case is many files all with
;; the same name and in different directories, for example a big source tree
;; with a Makefile in each directory. In such a case, you should probably
;; use an alternate strategy to find the files.
;;
;; ADDING FILES TO THE CACHE:
;;
;; Use the following functions to add items to the file cache:
;;
;;   * `file-cache-add-file': Adds a single file to the cache
;;
;;   * `file-cache-add-file-list': Adds a list of files to the cache
;;
;; The following functions use the regular expressions in
;; `file-cache-delete-regexps' to eliminate unwanted files:
;;
;;   * `file-cache-add-directory': Adds the files in a directory to the
;;     cache. You can also specify a regular expression to match the files
;;     which should be added.
;;
;;   * `file-cache-add-directory-list': Same as above, but acts on a list
;;     of directories. You can use `load-path', `exec-path' and the like.
;;
;;   * `file-cache-add-directory-using-find': Uses the `find' command to
;;     add a directory tree to the cache.
;;
;;   * `file-cache-add-directory-using-locate': Uses the `locate' command to
;;     add files matching a pattern to the cache.
;;
;;   * `file-cache-add-directory-recursively': Uses the find-lisp package to
;;     add all files matching a pattern to the cache.
;;
;; Use the function `file-cache-clear-cache' to remove all items from the
;; cache. There are a number of `file-cache-delete' functions provided
;; as well, but in general it is probably better to not worry too much
;; about extra files in the cache.
;;
;; The most convenient way to initialize the cache is with an
;; `eval-after-load' function, as noted in the ADDING FILES
;; AUTOMATICALLY section.
;;
;; FINDING FILES USING THE CACHE:
;;
;; You can use the file-cache with any function that expects a filename as
;; an argument. For example:
;;
;; 1) Invoke a function which expects a filename as an argument:
;;    M-x find-file
;;
;; 2) Begin typing a file name.
;;
;; 3) Invoke `file-cache-minibuffer-complete' (bound by default to
;; C-TAB) to complete on the filename using the cache.
;;
;; 4) When you have found a unique completion, the minibuffer contents
;; will change to the full name of that file.
;;
;; If there are a number of directories which contain the completion,
;; invoking `file-cache-minibuffer-complete' repeatedly will cycle through
;; them.
;;
;; 5) You can then edit the minibuffer contents, or press RETURN.
;;
;; It is much easier to simply try it than trying to explain it :)
;;
;;; ADDING FILES AUTOMATICALLY
;;
;; For maximum utility, you should probably define an `eval-after-load'
;; form which loads your favorite files:
;;
;;      (eval-after-load
;;       "filecache"
;;       '(progn
;; 	    (message "Loading file cache...")
;; 	    (file-cache-add-directory-using-find "~/projects")
;;	    (file-cache-add-directory-list load-path)
;;	    (file-cache-add-directory "~/")
;;	    (file-cache-add-file-list (list "~/foo/bar" "~/baz/bar"))
;; 	   ))
;;
;; If you clear and reload the cache frequently, it is probably easiest
;; to put your initializations in a function:
;;
;;   (eval-after-load
;;     "filecache"
;;      '(my-file-cache-initialize))
;;
;;   (defun my-file-cache-initialize ()
;;      (interactive)
;; 	(message "Loading file cache...")
;; 	(file-cache-add-directory-using-find "~/projects")
;;	(file-cache-add-directory-list load-path)
;;	(file-cache-add-directory "~/")
;;	(file-cache-add-file-list (list "~/foo/bar" "~/baz/bar"))
;;   ))
;;
;; Of course, you can still add files to the cache afterwards, via
;; Lisp functions.
;;
;; RELATED WORK:
;;
;; This package is a distant relative of Noah Friedman's fff utilities.
;; Our goal is pretty similar, but the implementation strategies are
;; different.

;;; Code:

(eval-when-compile
  (require 'find-lisp))

(defgroup file-cache nil
  "Find files using a pre-loaded cache."
  :group 'files
  :group 'convenience
  :prefix "file-cache-")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Customization Variables
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; User-modifiable variables
(defcustom file-cache-filter-regexps
  (list "~$" "\\.o$" "\\.exe$" "\\.a$" "\\.elc$" ",v$" "\\.output$"
	"\\.$" "#$" "\\.class$")
  "*List of regular expressions used as filters by the file cache.
File names which match these expressions will not be added to the cache.
Note that the functions `file-cache-add-file' and `file-cache-add-file-list'
do not use this variable."
  :type '(repeat regexp)
  :group 'file-cache)

(defcustom file-cache-find-command "find"
  "*External program used by `file-cache-add-directory-using-find'."
  :type 'string
  :group 'file-cache)

(defcustom file-cache-find-command-posix-flag 'not-defined
  "*Set to t, if `file-cache-find-command' handles wildcards POSIX style.
This variable is automatically set to nil or non-nil
if it has the initial value `not-defined' whenever you first
call the `file-cache-add-directory-using-find'.

Under Windows operating system where Cygwin is available, this value
should be t."
  :type  '(choice (const :tag "Yes" t)
		  (const :tag "No" nil)
		  (const :tag "Unknown" not-defined))
  :group 'file-cache)

(defcustom file-cache-locate-command "locate"
  "*External program used by `file-cache-add-directory-using-locate'."
  :type 'string
  :group 'file-cache)

;; Minibuffer messages
(defcustom file-cache-no-match-message " [File Cache: No match]"
  "Message to display when there is no completion."
  :type 'string
  :group 'file-cache)

(defcustom file-cache-sole-match-message " [File Cache: sole completion]"
  "Message to display when there is only one completion."
  :type 'string
  :group 'file-cache)

(defcustom file-cache-non-unique-message
  " [File Cache: complete but not unique]"
  "Message to display when there is a non-unique completion."
  :type 'string
  :group 'file-cache)

(defcustom file-cache-completion-ignore-case
   (if (memq system-type (list 'ms-dos 'windows-nt 'cygwin))
      t
     completion-ignore-case)
  "If non-nil, file-cache completion should ignore case.
Defaults to the value of `completion-ignore-case'."
  :type 'sexp
  :group 'file-cache
  )

(defcustom file-cache-case-fold-search
  (if (memq system-type (list 'ms-dos 'windows-nt 'cygwin))
      t
    case-fold-search)
  "If non-nil, file-cache completion should ignore case.
Defaults to the value of `case-fold-search'."
  :type 'sexp
  :group 'file-cache
  )

(defcustom file-cache-ignore-case
  (memq system-type (list 'ms-dos 'windows-nt 'cygwin))
  "Non-nil means ignore case when checking completions in the file cache.
Defaults to nil on DOS and Windows, and t on other systems."
  :type 'sexp
  :group 'file-cache
  )

(defvar file-cache-multiple-directory-message nil)

;; Internal variables
;; This should be named *Completions* because that's what the function
;; switch-to-completions in simple.el expects
(defcustom file-cache-completions-buffer "*Completions*"
  "Buffer to display completions when using the file cache."
  :type 'string
  :group 'file-cache)

(defcustom file-cache-buffer "*File Cache*"
  "Buffer to hold the cache of file names."
  :type 'string
  :group 'file-cache)

(defcustom file-cache-buffer-default-regexp "^.+$"
  "Regexp to match files in `file-cache-buffer'."
  :type 'regexp
  :group 'file-cache)

(defvar file-cache-last-completion nil)

(defvar file-cache-alist nil
  "Internal data structure to hold cache of file names.")

(defvar file-cache-completions-keymap
  (let ((map (make-sparse-keymap)))
    (set-keymap-parent map completion-list-mode-map)
    (define-key map [mouse-2] 'file-cache-mouse-choose-completion)
    (define-key map "\C-m" 'file-cache-choose-completion)
    map)
  "Keymap for file cache completions buffer.")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Functions to add files to the cache
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;###autoload
(defun file-cache-add-directory (directory &optional regexp)
  "Add DIRECTORY to the file cache.
If the optional REGEXP argument is non-nil, only files which match it will
be added to the cache."
  (interactive "DAdd files from directory: ")
  ;; Not an error, because otherwise we can't use load-paths that
  ;; contain non-existent directories.
  (if (not (file-accessible-directory-p directory))
      (message "Directory %s does not exist" directory)
    (let* ((dir       (expand-file-name directory))
	   (dir-files (directory-files dir t regexp))
	   )
      ;; Filter out files we don't want to see
      (mapc
       '(lambda (file)
          (if (file-directory-p file)
              (setq dir-files (delq file dir-files))
	    (mapc
	     '(lambda (regexp)
		(if (string-match regexp file)
		    (setq dir-files (delq file dir-files))))
	     file-cache-filter-regexps)))
       dir-files)
      (file-cache-add-file-list dir-files))))

;;;###autoload
(defun file-cache-add-directory-list (directory-list &optional regexp)
  "Add DIRECTORY-LIST (a list of directory names) to the file cache.
If the optional REGEXP argument is non-nil, only files which match it
will be added to the cache. Note that the REGEXP is applied to the files
in each directory, not to the directory list itself."
  (interactive "XAdd files from directory list: ")
  (mapcar
   '(lambda (dir) (file-cache-add-directory dir regexp))
   directory-list))

(defun file-cache-add-file-list  (file-list)
  "Add FILE-LIST (a list of files names) to the file cache."
  (interactive "XFile List: ")
  (mapcar 'file-cache-add-file file-list))

;; Workhorse function

;;;###autoload
(defun file-cache-add-file (file)
  "Add FILE to the file cache."
  (interactive "fAdd File: ")
  (if (not (file-exists-p file))
      (message "Filecache: file %s does not exist" file)
    (let* ((file-name (file-name-nondirectory file))
	   (dir-name  (file-name-directory    file))
	   (the-entry (assoc-string
		       file-name file-cache-alist
		       file-cache-ignore-case))
	   )
      ;; Does the entry exist already?
      (if the-entry
	  (if (or (and (stringp (cdr the-entry))
		       (string= dir-name (cdr the-entry)))
		  (and (listp (cdr the-entry))
		       (member dir-name (cdr the-entry))))
	      nil
	    (setcdr the-entry (append (list dir-name) (cdr the-entry)))
	    )
	;; If not, add it to the cache
	(setq file-cache-alist
	      (cons (cons file-name (list dir-name))
		    file-cache-alist)))
      )))

;;;###autoload
(defun file-cache-add-directory-using-find (directory)
  "Use the `find' command to add files to the file cache.
Find is run in DIRECTORY."
  (interactive "DAdd files under directory: ")
  (let ((dir (expand-file-name directory)))
    (when (memq system-type '(windows-nt cygwin))
      (if (eq file-cache-find-command-posix-flag 'not-defined)
	  (setq file-cache-find-command-posix-flag
		(executable-command-find-posix-p file-cache-find-command))))
    (set-buffer (get-buffer-create file-cache-buffer))
    (erase-buffer)
    (call-process file-cache-find-command nil
		  (get-buffer file-cache-buffer) nil
		  dir "-name"
		  (if (memq system-type '(windows-nt cygwin))
		      (if file-cache-find-command-posix-flag
			  "\\*"
			"'*'")
		    "*")
		  "-print")
    (file-cache-add-from-file-cache-buffer)))

;;;###autoload
(defun file-cache-add-directory-using-locate (string)
  "Use the `locate' command to add files to the file cache.
STRING is passed as an argument to the locate command."
  (interactive "sAdd files using locate string: ")
  (set-buffer (get-buffer-create file-cache-buffer))
  (erase-buffer)
  (call-process file-cache-locate-command nil
		(get-buffer file-cache-buffer) nil
		string)
  (file-cache-add-from-file-cache-buffer))

;;;###autoload
(defun file-cache-add-directory-recursively  (dir &optional regexp)
  "Adds DIR and any subdirectories to the file-cache.
This function does not use any external programs
If the optional REGEXP argument is non-nil, only files which match it
will be added to the cache. Note that the REGEXP is applied to the files
in each directory, not to the directory list itself."
  (interactive "DAdd directory: ")
  (require 'find-lisp)
  (mapcar
   (function
    (lambda(file)
      (or (file-directory-p file)
	  (let (filtered)
	    (mapc
	     (function
	      (lambda(regexp)
		(and (string-match regexp file)
		     (setq filtered t))
		))
	     file-cache-filter-regexps)
	    filtered)
	  (file-cache-add-file file))))
   (find-lisp-find-files dir (if regexp regexp "^"))))

(defun file-cache-add-from-file-cache-buffer (&optional regexp)
  "Add any entries found in the file cache buffer.
Each entry matches the regular expression `file-cache-buffer-default-regexp'
or the optional REGEXP argument."
  (set-buffer file-cache-buffer)
  (mapc
   (function (lambda (elt)
	       (goto-char (point-min))
	       (delete-matching-lines elt)))
   file-cache-filter-regexps)
  (goto-char (point-min))
  (let ((full-filename))
    (while (re-search-forward
	    (or regexp file-cache-buffer-default-regexp)
	    (point-max) t)
      (setq full-filename (buffer-substring-no-properties
		      (match-beginning 0) (match-end 0)))
      (file-cache-add-file full-filename))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Functions to delete from the cache
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defun file-cache-clear-cache ()
  "Clear the file cache."
  (interactive)
  (setq file-cache-alist nil))

;; This clears *all* files with the given name
(defun file-cache-delete-file (file)
  "Delete FILE from the file cache."
  (interactive
   (list (completing-read "Delete file from cache: " file-cache-alist)))
  (setq file-cache-alist
	(delq (assoc-string file file-cache-alist file-cache-ignore-case)
	      file-cache-alist)))

(defun file-cache-delete-file-list (file-list)
  "Delete FILE-LIST (a list of files) from the file cache."
  (interactive "XFile List: ")
  (mapcar 'file-cache-delete-file file-list))

(defun file-cache-delete-file-regexp (regexp)
  "Delete files matching REGEXP from the file cache."
  (interactive "sRegexp: ")
  (let ((delete-list))
    (mapc '(lambda (elt)
	     (and (string-match regexp (car elt))
		  (setq delete-list (cons (car elt) delete-list))))
	  file-cache-alist)
    (file-cache-delete-file-list delete-list)
    (message "Filecache: deleted %d files from file cache"
             (length delete-list))))

(defun file-cache-delete-directory (directory)
  "Delete DIRECTORY from the file cache."
  (interactive "DDelete directory from file cache: ")
  (let ((dir (expand-file-name directory))
	(result 0))
    (mapc
     '(lambda (entry)
	(if (file-cache-do-delete-directory dir entry)
	    (setq result (1+ result))))
     file-cache-alist)
    (if (zerop result)
	(error "Filecache: no entries containing %s found in cache" directory)
      (message "Filecache: deleted %d entries" result))))

(defun file-cache-do-delete-directory (dir entry)
  (let ((directory-list (cdr entry))
	(directory (file-cache-canonical-directory dir))
	)
    (and (member directory directory-list)
	 (if (equal 1 (length directory-list))
	     (setq file-cache-alist
		   (delq entry file-cache-alist))
	   (setcdr entry (delete directory directory-list)))
	 )
    ))

(defun file-cache-delete-directory-list (directory-list)
  "Delete DIRECTORY-LIST (a list of directories) from the file cache."
  (interactive "XDirectory List: ")
  (mapcar 'file-cache-delete-directory directory-list))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Utility functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Returns the name of a directory for a file in the cache
(defun file-cache-directory-name  (file)
  (let* ((directory-list (cdr (assoc-string
			       file file-cache-alist
			       file-cache-ignore-case)))
	 (len            (length directory-list))
	 (directory)
	 (num)
	 )
    (if (not (listp directory-list))
	(error "Filecache: unknown type in file-cache-alist for key %s" file))
    (cond
     ;; Single element
     ((eq 1 len)
      (setq directory (elt directory-list 0)))
     ;; No elements
     ((eq 0 len)
      (error "Filecache: no directory found for key %s" file))
     ;; Multiple elements
     (t
      (let* ((minibuffer-dir (file-name-directory (minibuffer-contents)))
	     (dir-list       (member minibuffer-dir directory-list))
	     )
	(setq directory
	      ;; If the directory is in the list, return the next element
	      ;; Otherwise, return the first element
	      (if dir-list
		  (or (elt directory-list
			   (setq num (1+ (- len (length dir-list)))))
		      (elt directory-list (setq num 0)))
		(elt directory-list (setq num 0))))
	)
      )
     )
    ;; If there were multiple directories, set up a minibuffer message
    (setq file-cache-multiple-directory-message
	  (and num (format " [%d of %d]" (1+ num) len)))
    directory))

;; Returns the name of a file in the cache
(defun file-cache-file-name  (file)
  (let ((directory (file-cache-directory-name file)))
    (concat directory file)))

;; Return a canonical directory for comparison purposes.
;; Such a directory ends with a forward slash.
(defun file-cache-canonical-directory (dir)
  (let ((directory dir))
    (if (not (char-equal ?/ (string-to-char (substring directory -1))))
	(concat directory "/")
      directory)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Minibuffer functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; The prefix argument works around a bug in the minibuffer completion.
;; The completion function doesn't distinguish between the states:
;;
;;   "Multiple completions of name" (eg, Makefile, Makefile.in)
;;   "Name available in multiple directories" (/tmp/Makefile, ~me/Makefile)
;;
;; The default is to do the former; a prefix arg forces the latter.

;;;###autoload
(defun file-cache-minibuffer-complete (arg)
  "Complete a filename in the minibuffer using a preloaded cache.
Filecache does two kinds of substitution: it completes on names in
the cache, and, once it has found a unique name, it cycles through
the directories that the name is available in.  With a prefix argument,
the name is considered already unique; only the second substitution
\(directories) is done."
  (interactive "P")
  (let*
      (
       (completion-ignore-case file-cache-completion-ignore-case)
       (case-fold-search       file-cache-case-fold-search)
       (string                 (file-name-nondirectory (minibuffer-contents)))
       (completion-string      (try-completion string file-cache-alist))
       (completion-list)
       (len)
       (file-cache-string)
       )
    (cond
     ;; If it's the only match, replace the original contents
     ((or arg (eq completion-string t))
      (setq file-cache-string (file-cache-file-name string))
      (if (string= file-cache-string (minibuffer-contents))
	  (file-cache-temp-minibuffer-message file-cache-sole-match-message)
	(delete-minibuffer-contents)
	(insert file-cache-string)
	(if file-cache-multiple-directory-message
	    (file-cache-temp-minibuffer-message
	     file-cache-multiple-directory-message))
      ))

     ;; If it's the longest match, insert it
     ((stringp completion-string)
      ;; If we've already inserted a unique string, see if the user
      ;; wants to use that one
      (if (and (string= string completion-string)
	       (assoc-string string file-cache-alist
			     file-cache-ignore-case))
	  (if (and (eq last-command this-command)
		   (string= file-cache-last-completion completion-string))
	      (progn
		(delete-minibuffer-contents)
		(insert (file-cache-file-name completion-string))
		(setq file-cache-last-completion nil)
		)
	    (file-cache-temp-minibuffer-message file-cache-non-unique-message)
	    (setq file-cache-last-completion string)
	    )
	(setq file-cache-last-completion string)
	(setq completion-list (all-completions string file-cache-alist)
	      len             (length completion-list))
	(if (> len 1)
	    (progn
	      (goto-char (point-max))
	      (insert
	       (substring completion-string (length string)))
	      ;; Add our own setup function to the Completions Buffer
	      (let ((completion-setup-hook
                     (append completion-setup-hook
                             (list 'file-cache-completion-setup-function))))
		(with-output-to-temp-buffer file-cache-completions-buffer
		  (display-completion-list completion-list string))))
	  (setq file-cache-string (file-cache-file-name completion-string))
	  (if (string= file-cache-string (minibuffer-contents))
	      (file-cache-temp-minibuffer-message
	       file-cache-sole-match-message)
	    (delete-minibuffer-contents)
	    (insert file-cache-string)
	    (if file-cache-multiple-directory-message
		(file-cache-temp-minibuffer-message
		 file-cache-multiple-directory-message)))
	  )))

     ;; No match
     ((eq completion-string nil)
      (file-cache-temp-minibuffer-message file-cache-no-match-message))
     )
))

;; Lifted from "complete.el"
(defun file-cache-temp-minibuffer-message (msg)
  "A Lisp version of `temp_minibuffer_message' from minibuf.c."
  (let ((savemax (point-max)))
    (save-excursion
      (goto-char (point-max))
      (insert msg))
    (let ((inhibit-quit t))
      (sit-for 2)
      (delete-region savemax (point-max))
      (if quit-flag
	  (setq quit-flag nil
		unread-command-events (list 7))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Completion functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defun file-cache-completion-setup-function  ()
  (with-current-buffer standard-output ;; i.e. file-cache-completions-buffer
    (use-local-map file-cache-completions-keymap)))

(defun file-cache-choose-completion  ()
  "Choose a completion in the `*Completions*' buffer."
  (interactive)
  (let ((completion-no-auto-exit t))
    (choose-completion)
    (select-window (active-minibuffer-window))
    (file-cache-minibuffer-complete nil)
    )
  )

(defun file-cache-mouse-choose-completion  (event)
  "Choose a completion with the mouse."
  (interactive "e")
  (let ((completion-no-auto-exit t))
    (mouse-choose-completion event)
    (select-window (active-minibuffer-window))
    (file-cache-minibuffer-complete nil)
    )
  )

(defun file-cache-complete  ()
  "Complete the word at point, using the filecache."
  (interactive)
  (let (start pattern completion all)
    (save-excursion
      (skip-syntax-backward "^\"")
      (setq start (point)))
    (setq pattern    (buffer-substring-no-properties start (point)))
    (setq completion (try-completion  pattern file-cache-alist))
    (setq all        (all-completions pattern file-cache-alist nil))
    (cond ((eq completion t))
	  ((null completion)
	   (message "Can't find completion for \"%s\"" pattern)
	   (ding))
	  ((not (string= pattern completion))
	   (delete-region start (point))
	   (insert completion)
	   )
	  (t
	   (with-output-to-temp-buffer "*Completions*"
	     (display-completion-list all pattern))
	   ))
    ))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Show parts of the cache
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defun file-cache-files-matching-internal (regexp)
  "Output a list of files whose names (not including directories)
match REGEXP."
  (let ((results))
    (mapc
     (function
      (lambda(cache-element)
	(and (string-match regexp
			   (elt cache-element 0))
	     (if results
		 (nconc results (list (elt cache-element 0)))
	       (setq results (list (elt cache-element 0)))))))
     file-cache-alist)
    results))

(defun file-cache-files-matching (regexp)
  "Output a list of files whose names (not including directories)
match REGEXP."
  (interactive "sFind files matching regexp: ")
  (let ((results
	 (file-cache-files-matching-internal regexp))
	buf)
    (set-buffer
     (setq buf (get-buffer-create
		"*File Cache Files Matching*")))
    (erase-buffer)
    (insert
     (mapconcat
      'identity
      results
      "\n"))
    (goto-char (point-min))
    (display-buffer buf)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Debugging functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defun file-cache-debug-read-from-minibuffer (file)
  "Debugging function."
  (interactive
   (list (completing-read "File Cache: " file-cache-alist)))
  (message "%s" (assoc-string file file-cache-alist
			      file-cache-ignore-case))
  )

(defun file-cache-display  ()
  "Display the file cache."
  (interactive)
  (let ((buf "*File Cache Contents*"))
    (with-current-buffer
	(get-buffer-create buf)
      (erase-buffer)
      (mapc
       (function
	(lambda(item)
	 (insert (nth 1 item) (nth 0 item) "\n")))
       file-cache-alist)
      (pop-to-buffer buf)
    )))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Keybindings
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(provide 'filecache)

;; arch-tag: 433d3ca4-4af2-47ce-b2cf-1f727460f538
;;; filecache.el ends here