home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / lucid / lemacs-19.6 / lisp / ilisp / completer.el < prev    next >
Encoding:
Text File  |  1992-12-10  |  33.9 KB  |  990 lines

  1. ;;; -*-Emacs-Lisp-*-
  2. ;;;%Header
  3. ;;; Partial completion mechanism for GNU Emacs.  Version 3.03
  4. ;;; Copyright (C) 1990, 1991, 1992 Chris McConnell, ccm@cs.cmu.edu.
  5. ;;; Thanks to Bjorn Victor for suggestions, testing, and patches for
  6. ;;; file completion. 
  7. ;;; hacked for Lucid GNU Emacs
  8.  
  9. ;;; This file is part of GNU Emacs.
  10.  
  11. ;;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;;; but WITHOUT ANY WARRANTY.  No author or distributor
  13. ;;; accepts responsibility to anyone for the consequences of using it
  14. ;;; or for whether it serves any particular purpose or works at all,
  15. ;;; unless he says so in writing.  Refer to the GNU Emacs General Public
  16. ;;; License for full details.
  17. ;;; Everyone is granted permission to copy, modify and redistribute
  18. ;;; GNU Emacs, but only under the conditions described in the
  19. ;;; GNU Emacs General Public License.   A copy of this license is
  20. ;;; supposed to have been given to you along with GNU Emacs so you
  21. ;;; can know your rights and responsibilities.  It should be in a
  22. ;;; file named COPYING.  Among other things, the copyright notice
  23. ;;; and this notice must be preserved on all copies.
  24.  
  25. ;;; When loaded, this file extends the standard completion mechanisms
  26. ;;; so that they perform pattern matching completions.  There is also
  27. ;;; an interface that allows it to be used by other programs.  The
  28. ;;; completion rules are:
  29. ;;;
  30. ;;; 1) If what has been typed matches any possibility, do normal
  31. ;;; completion. 
  32. ;;;
  33. ;;; 2) Otherwise, generate a regular expression such that
  34. ;;; completer-words delimit words and generate all possible matches.
  35. ;;; The variable completer-any-delimiter can be set to a character
  36. ;;; that matches any delimiter.  If it were " ", then "by  d" would be 
  37. ;;; byte-recompile-directory.  If completer-use-words is T, a match is
  38. ;;; unique if it is the only one with the same number of words.  If
  39. ;;; completer-use-words is NIL, a match is unique if it is the only
  40. ;;; possibility.  If you ask the completer to use its best guess, it
  41. ;;; will be the shortest match of the possibilities unless
  42. ;;; completer-exact is T.
  43. ;;;
  44. ;;; 3) For filenames, if completer-complete-filenames is T, each
  45. ;;; pathname component will be individually completed, otherwise only
  46. ;;; the final component will be completed.  If you are using a
  47. ;;; distributed file system like afs, you may want to set up a
  48. ;;; symbolic link in your home directory or add pathname components to
  49. ;;; completer-file-skip so that the pathname components that go across
  50. ;;; machines do not get expanded.
  51. ;;;
  52. ;;; SPACE, TAB, LFD, RET, and ? do normal completion if possible
  53. ;;; otherwise they do partial completion.  In addition, C-DEL will
  54. ;;; undo the last partial expansion or contraction.  M-RET will always
  55. ;;; complete to the current match before returning.  This is useful
  56. ;;; when any string is possible, but you want to complete to a string
  57. ;;; as when calling find-file.  The bindings can be changed by using
  58. ;;; completer-load-hook.
  59. ;;;
  60. ;;; Modes that use comint-dynamic-complete (like cmushell and ilisp)
  61. ;;; will also do partial completion as will M-tab in Emacs LISP.
  62. ;;;
  63. ;;; Examples:
  64. ;;; a-f     auto-fill-mode
  65. ;;; b--d    *beginning-of-defun or byte-recompile-directory
  66. ;;; by  d   *byte-recompile-directory if completer-any-delimiter is " "
  67. ;;; ~/i.e   *~/ilisp.el or ~/il-el.el or ~/ilisp.elc
  68. ;;; /u/mi/  /usr/misc/
  69. ;;;
  70.  
  71. ;;;%Globals
  72. ;;;%%Switches
  73. (defvar completer-load-hook nil
  74.   "Hook called when minibuffer partial completion is loaded.")
  75.  
  76. (defvar completer-disable nil
  77.   "*If T, turn off partial completion.  Use the command
  78. \\[completer-toggle] to set this.")
  79.  
  80. (defvar completer-complete-filenames t
  81.   "*If T, then each component of a filename will be completed,
  82. otherwise just the final component will be completed.")
  83.  
  84. (defvar completer-use-words t
  85.   "*If T, then prefer completions with the same number of words as the
  86. pattern.")
  87.  
  88. (defvar completer-words "---. <" 
  89.   "*Delimiters used in partial completions.  It should be a set of
  90. characters suitable for inclusion in a [] regular expression.")
  91.  
  92. (defvar completer-any-delimiter nil
  93.   "*If a character, then a delimiter in the pattern that matches the
  94. character will match any delimiter in completer-words.")
  95.  
  96. (defvar completer-file-skip "^cs/$\\|@sys\\|.edu/$\\|.gov/$\\|.com/$\\|:/$"
  97.   "*Regular expression for pathname components to not complete.")
  98.  
  99. (defvar completer-exact nil
  100.   "*If T, then you must have an exact match.  Otherwise, the shortest
  101. string that matches the pattern will be used.")
  102.  
  103. (defvar completer-cache-size 100
  104.   "*Size of cache to use for partially completed pathnames.")
  105.  
  106. (defvar completer-use-cache t
  107.   "*Set to nil to disable the partially completed pathname cache.")
  108.  
  109. ;;;%%Internal
  110. (defvar completer-last-pattern ""
  111.   "The last pattern expanded.")
  112.  
  113. (defvar completer-message nil
  114.   "T if temporary message was just displayed.")
  115.  
  116. (defvar completer-path-cache nil
  117.   "Cache of (path . choices) for completer.")
  118.  
  119. (defvar completer-string nil "Last completer string.")
  120. (defvar completer-table nil "Last completer table.")
  121. (defvar completer-pred nil "Last completer pred.")
  122. (defvar completer-mode nil "Last completer mode.")
  123. (defvar completer-result nil "Last completer result.")
  124.  
  125. ;;;%Utilities
  126. (defun completer-message (message &optional point)
  127.   "Display MESSAGE at optional POINT for two seconds."
  128.   (setq point (or point (point-max))
  129.     completer-message t)
  130.   (let ((end
  131.      (save-excursion
  132.        (goto-char point)
  133.        (insert message)
  134.        (point)))
  135.     (inhibit-quit t))
  136.     (sit-for 2)
  137.     (delete-region point end)
  138.     (or (string-match emacs-version "Lucid")
  139.     (if quit-flag
  140.         (setq quit-flag nil
  141.           unread-command-char 7)))))
  142.  
  143. ;;;
  144. (defun completer-deleter (regexp choices &optional keep)
  145.   "Destructively remove strings that match REGEXP in CHOICES and
  146. return the modified list.  If optional KEEP, then keep entries that
  147. match regexp."
  148.   (let* ((choiceb choices)
  149.      choicep)
  150.     (if keep
  151.     (progn
  152.       (while (and choiceb (not (string-match regexp (car choiceb))))
  153.         (setq choiceb (cdr choiceb)))
  154.       (setq choicep choiceb)
  155.       (while (cdr choicep)
  156.         (if (string-match regexp (car (cdr choicep)))
  157.         (setq choicep (cdr choicep))
  158.         (rplacd choicep (cdr (cdr choicep))))))
  159.     (while (and choiceb (string-match regexp (car choiceb)))
  160.       (setq choiceb (cdr choiceb)))
  161.     (setq choicep choiceb)
  162.     (while (cdr choicep)
  163.       (if (string-match regexp (car (cdr choicep)))
  164.           (rplacd choicep (cdr (cdr choicep)))
  165.           (setq choicep (cdr choicep)))))
  166.     choiceb))
  167.  
  168. ;;;%%Regexp
  169. (defun completer-regexp (string delimiters any)
  170.   "Convert STRING into a regexp with words delimited by characters in
  171. DELIMITERS.  Any delimiter in STRING that is the same as ANY will
  172. match any delimiter."
  173.   (let* ((delimiter-reg (concat "[" delimiters "]"))
  174.      (limit (length string))
  175.      (pos 0)
  176.      (regexp "^"))
  177.     (while (and (< pos limit) (string-match delimiter-reg string pos))
  178.       (let* ((begin (match-beginning 0))
  179.          (end (match-end 0))
  180.          (delimiter (substring string begin end))
  181.          (anyp (eq (elt string begin) any)))
  182.     (setq regexp 
  183.           (format "%s%s[^%s]*%s" 
  184.               regexp
  185.               (regexp-quote (substring string pos begin))
  186.               (if anyp delimiters delimiter)
  187.               (if anyp delimiter-reg delimiter))
  188.           pos end)))
  189.     (if (<= pos limit)
  190.     (setq regexp (concat regexp 
  191.                  (regexp-quote (substring string pos limit)))))))
  192.  
  193. ;;;
  194. (defun completer-words (regexp string &optional limit)
  195.   "Return the number of words matching REGEXP in STRING up to LIMIT."
  196.   (setq limit (or limit 1000))
  197.   (let ((count 1)
  198.     (pos 0))
  199.     (while (and (string-match regexp string pos) (<= count limit))
  200.       (setq count (1+ count)
  201.         pos (match-end 0)))
  202.     count))
  203.  
  204. ;;;%Matcher
  205. (defun completer-matches (string choices delimiters any)
  206.     "Return STRING's matches in CHOICES using DELIMITERS and wildcard
  207. ANY to segment the strings."
  208.     (let* ((regexp (concat "[" delimiters "]"))
  209.        (from nil)
  210.        (to 0)
  211.        (pattern nil)
  212.        (len (length string))
  213.        (matches nil)
  214.        sub sublen choice word wordlen pat)
  215.       ;; Segment pattern
  216.       (while (< (or from 0) len)
  217.     (setq to (or (string-match regexp string (if from (1+ from))) len))
  218.     (if (eq (elt string (or from 0)) completer-any-delimiter)
  219.         (setq sub (substring string (if from (1+ from) 0) to)
  220.           sublen (- (length sub)))
  221.         (setq sub (substring string (or from 0) to)
  222.           sublen (length sub)))
  223.     (setq pattern (cons (cons sub sublen) pattern)
  224.           from to))
  225.       (setq pattern (reverse pattern))
  226.       ;; Find choices that match patterns
  227.       (setq regexp (concat "[" delimiters "]"))
  228.       (while choices
  229.     (setq choice (car choices)
  230.           word pattern 
  231.           from 0)
  232.     (while (and word from
  233.             (let* (begin end)
  234.               (if (< (setq wordlen (cdr (setq pat (car word)))) 0)
  235.               (setq begin (1+ from)
  236.                 end (+ begin (- wordlen)))
  237.               (setq begin from
  238.                 end (+ begin wordlen)))
  239.               (and (<= end (length choice))
  240.                (or (zerop wordlen)
  241.                    (string-equal 
  242.                 (car pat)
  243.                 (substring choice begin end))))))
  244.       (setq from (string-match regexp choice 
  245.                    (if (and (zerop from) (zerop wordlen))
  246.                        from
  247.                        (1+ from)))
  248.         word (cdr word)))
  249.     (if (not word) (setq matches (cons choice matches)))
  250.     (setq choices (cdr choices)))
  251.       matches))
  252.  
  253. ;;;
  254. (defun completer-choice (string choices delimiters use-words)
  255.   "Return the best match of STRING in CHOICES with DELIMITERS between
  256. words and T if it is unique.  A match is unique if it is the only
  257. possibility or when USE-WORDS the only possibility with the same
  258. number of words.  The shortest string of multiple possiblities will be
  259. the best match."
  260.   (or (if (null (cdr choices)) (cons (car choices) t))
  261.       (let* ((regexp (concat "[^" delimiters "]*[" delimiters "]"))
  262.          (words (if use-words (completer-words regexp string)))
  263.          (choice choices)
  264.          (unique-p nil)
  265.          (match nil)
  266.          (match-count nil)
  267.          (match-len 1000))
  268.     (while choice
  269.       (let* ((current (car choice))
  270.          (length (length current)))
  271.         (if match-count
  272.         (if (= (completer-words regexp current words) words)
  273.             (progn
  274.               (setq unique-p nil)
  275.               (if (< length match-len)
  276.               (setq match current
  277.                 match-len length))))
  278.         (if (and use-words 
  279.              (= (completer-words regexp current words) words))
  280.             (setq match current
  281.               match-len length
  282.               match-count t
  283.               unique-p t)
  284.             (if (< length match-len)
  285.             (setq match current
  286.                   match-len length)))))
  287.       (setq choice (cdr choice)))
  288.     (cons match unique-p))))
  289.  
  290. ;;;%Completer
  291. ;;;%%Utilities
  292. (defun completer-region (delimiters)
  293.   "Return the completion region bounded by characters in DELIMITERS
  294. for the current buffer assuming that point is in it."
  295.   (cons (save-excursion (skip-chars-backward delimiters) (point))
  296.     (save-excursion (skip-chars-forward delimiters) (point))))
  297.      
  298. ;;;
  299. (defun completer-last-component (string)
  300.   "Return the start of the last filename component in STRING."
  301.   (let ((last (1- (length string)) )
  302.     (match 0)
  303.     (end 0))
  304.     (while (and (setq match (string-match "/" string end)) (< match last))
  305.       (setq end (1+ match)))
  306.     end))
  307.  
  308. ;;;
  309. (defun completer-match-record (string matches delimiters any dir mode)
  310.   "Return (match lcs choices unique) for STRING in MATCHES with
  311. DELIMITERS or ANY wildcards and DIR if a filename when in MODE."
  312.   (let ((pattern (if dir
  313.              (substring string (completer-last-component string))
  314.              string)))
  315.     (setq matches (completer-matches pattern matches delimiters any))
  316.     (if (cdr matches)
  317.     (let ((match
  318.            (if (not completer-exact)
  319.            (completer-choice
  320.             pattern matches delimiters completer-use-words)))
  321.           (lcs (concat dir (try-completion "" (mapcar 'list matches)))))
  322.       (list (if match (concat dir (car match)))
  323.         lcs
  324.         matches (cdr match)))
  325.       (if matches 
  326.       (let ((match (concat dir (car matches))))
  327.         (list match match matches t))
  328.     (list nil nil nil nil)))))
  329.  
  330. ;;;%%Complete file
  331. (defun completer-extension-regexp (extensions)
  332.   "Return a regexp that matches any of EXTENSIONS."
  333.   (let ((regexp "\\("))
  334.     (while extensions
  335.       (setq regexp (concat regexp (car extensions)
  336.                (if (cdr extensions) "\\|"))
  337.         extensions (cdr extensions)))
  338.     (concat regexp "\\)$")))
  339.  
  340. ;;;
  341. (defun completer-flush ()
  342.   "Flush completer's pathname cache."
  343.   (interactive)
  344.   (setq completer-path-cache nil))
  345.  
  346. ;;;
  347. (defun completer-cache (path pred words any mode)
  348.   "Check to see if PATH is in path cache with PRED, WORDS, ANY and
  349. MODE."
  350.   (let* ((last nil)
  351.      (ptr completer-path-cache)
  352.      (size 0) 
  353.      (result nil))
  354.     (if completer-use-cache
  355.     (while ptr
  356.       (let ((current (car (car ptr))))
  357.         (if (string-equal current path)
  358.         (progn
  359.           (if last
  360.               (progn
  361.             (rplacd last (cdr ptr))
  362.             (rplacd ptr completer-path-cache)
  363.             (setq completer-path-cache ptr)))
  364.           (setq result (cdr (car ptr))
  365.             ptr nil))
  366.           (if (cdr ptr) (setq last ptr))
  367.           (setq size (1+ size)
  368.             ptr (cdr ptr))))))
  369.     (or result
  370.     (let* ((choices 
  371.         (completer path 'read-file-name-internal pred words any
  372.                mode t)))
  373.       (if (and (or (car (cdr (cdr (cdr choices))))
  374.                (string= path (car choices)))
  375.            (eq (elt (car choices) (1- (length (car choices)))) ?/))
  376.           (progn 
  377.         (if (>= size completer-cache-size) (rplacd last nil))
  378.         (setq completer-path-cache 
  379.               (cons (cons path choices) completer-path-cache))))
  380.       choices))))
  381.  
  382. ;;;
  383. (defun completer-file (string pred words any mode)
  384.   "Return (match common-substring matches unique-p) for STRING using
  385. read-file-name-internal for choices that pass PRED using WORDS to
  386. delimit words.  Optional ANY is a delimiter that matches any of the
  387. delimiters in WORD.  If optional MODE is nil or 'help then possible
  388. matches will always be returned."
  389.   (let* ((case-fold-search completion-ignore-case)
  390.      (last (and (eq mode 'exit-ok) (completer-last-component string)))
  391.      (position
  392.       ;; Special hack for CMU RFS filenames
  393.       (if (string-match "^/\\.\\./[^/]*/" string)
  394.           (match-end 0)
  395.           (string-match "[^~/]" string)))
  396.      (new (substring string 0 position))
  397.      (user (if (string= new "~")
  398.            (setq new (file-name-directory (expand-file-name new)))))
  399.      (words (concat words "/"))
  400.      (len (length string))
  401.      (choices nil)
  402.      end
  403.      (old-choices (list nil nil nil nil)))
  404.     (while position
  405.       (let* ((begin (string-match "/" string position))
  406.          (exact-p nil))
  407.     (setq end (if begin (match-end 0))
  408.           choices
  409.           ;; Ends with a /, so check files in directory
  410.           (if (and (memq mode '(nil help)) (= position len))
  411.           (completer-match-record 
  412.            ""
  413.            ;; This assumes that .. and . come at the end
  414.            (let* ((choices
  415.                (all-completions new 'read-file-name-internal))
  416.               (choicep choices))
  417.              (if (string= (car choicep) "../")
  418.              (cdr (cdr choicep))
  419.              (while (cdr choicep)
  420.                (if (string= (car (cdr choicep)) "../")
  421.                    (rplacd choicep nil))
  422.                (setq choicep (cdr choicep)))
  423.              choices))
  424.            words any new mode)
  425.           (if (eq position last)
  426.               (let ((new (concat new (substring string position))))
  427.             (list new new nil t))
  428.               (let ((component (substring string position end)))
  429.             (if (and end
  430.                  (string-match completer-file-skip component))
  431.                 ;; Assume component is complete
  432.                 (list (concat new component) 
  433.                   (concat new component)
  434.                   nil t)
  435.                 (completer-cache
  436.                  (concat new component)
  437.                  pred words any mode))))))
  438.     ;; Keep going if unique or we match exactly
  439.     (if (or (car (cdr (cdr (cdr choices))))
  440.         (setq exact-p
  441.               (string= (concat new (substring string position end))
  442.                    (car choices))))
  443.         (setq old-choices
  444.           (let* ((lcs (car (cdr choices)))
  445.              (matches (car (cdr (cdr choices))))
  446.              (slash (and lcs (string-match "/$" lcs))))
  447.             (list nil
  448.               (if slash (substring lcs 0 slash) lcs)
  449.               (if (and (cdr matches) 
  450.                    (or (eq mode 'help) (not exact-p)))
  451.                   matches)
  452.               nil))
  453.           new (car choices)
  454.           position end)
  455.         ;; Its ok to not match user names because they may be in
  456.         ;; different root directories
  457.         (if (and (= position 1) (= (elt string 0) ?~))
  458.         (setq new (substring string 0 end)
  459.               choices (list new new (list new) t)
  460.               user nil
  461.               position end)
  462.         (setq position nil)))))
  463.     (if (not (car choices))
  464.     (setq choices old-choices))
  465.     (if (and (car choices)
  466.          (not (eq mode 'help))
  467.          (not (car (cdr (cdr (cdr choices))))))
  468.     ;; Try removing completion ignored extensions
  469.     (let* ((extensions
  470.         (completer-extension-regexp completion-ignored-extensions))
  471.            (choiceb (car (cdr (cdr choices))))
  472.            (choicep choiceb)
  473.            (isext nil)
  474.            (noext nil))
  475.       (while choicep
  476.         (if (string-match extensions (car choicep))
  477.         (setq isext t)
  478.         (setq noext t))
  479.         (if (and isext noext)
  480.         ;; There are matches besides extensions
  481.         (setq choiceb (completer-deleter extensions choiceb)
  482.               choicep nil)
  483.         (setq choicep (cdr choicep))))
  484.       (if (and isext noext)
  485.           (setq choices
  486.             (completer-match-record 
  487.              (if end (substring string end) "")
  488.              choiceb words any
  489.              (file-name-directory (car (cdr choices)))
  490.              mode)))))
  491.     (if user
  492.     (let ((match (car choices))
  493.           (lcs (car (cdr choices)))
  494.           (len (length user)))
  495.       (setq choices
  496.         (cons (if match (concat "~" (substring match len)))
  497.               (cons (if lcs (concat "~" (substring lcs len)))
  498.                 (cdr (cdr choices)))))))
  499.     choices))
  500.  
  501. ;;;%Exported program interface
  502. ;;;%%Completer
  503. (defun completer (string table pred words
  504.              &optional any mode file-p)
  505.   "Return (match common-substring matches unique-p) for STRING in
  506. TABLE for choices that pass PRED using WORDS to delimit words.  If the
  507. flag completer-complete-filenames is T and the table is
  508. read-file-name-internal, then filename components will be individually
  509. expanded.  Optional ANY is a delimiter that can match any delimiter in
  510. WORDS.  Optional MODE is nil for complete, 'help for help and 'exit
  511. for exit."
  512.   (if (and (stringp completer-string) 
  513.        (string= string completer-string)
  514.        (eq table completer-table)
  515.        (eq pred completer-pred)
  516.        (not file-p)
  517.        (or (eq mode completer-mode)
  518.            (memq table '(read-file-name-internal
  519.                  read-directory-name-internal))))
  520.       completer-result
  521.       (setq 
  522.        completer-string ""
  523.        completer-table table
  524.        completer-pred pred
  525.        completer-mode mode
  526.        completer-result
  527.        (if (and completer-complete-filenames
  528.         (not file-p) (eq table 'read-file-name-internal))
  529.        (completer-file string pred words any mode)
  530.        (let* ((file-p (or file-p (eq table 'read-file-name-internal)))
  531.           (case-fold-search completion-ignore-case)
  532.           (pattern (concat "[" words "]"))
  533.           (component (if file-p (completer-last-component string)))
  534.           (dir (if component (substring string 0 component)))
  535.           (string (if dir (substring string component) string))
  536.           (has-words (or (string-match pattern string)
  537.                  (length string))))
  538.          (if (and file-p (string-match "^\\$" string))
  539.          ;; Handle environment variables
  540.          (let ((match
  541.             (getenv (substring string 1 
  542.                        (string-match "/" string)))))
  543.            (if match (setq match (concat match "/")))
  544.            (list match match (list match) match))
  545.          (let* ((choices
  546.              (all-completions 
  547.               (concat dir (substring string 0 has-words))
  548.               table pred))
  549.             (regexp (completer-regexp string words any)))
  550.            (if choices
  551.                (completer-match-record 
  552.             string 
  553.             (completer-deleter regexp choices t) 
  554.             words any dir mode)
  555.                (list nil nil nil nil))))))
  556.        completer-string string)
  557.       completer-result))
  558.  
  559. ;;;%%Display choices
  560. (defun completer-display-choices (choices &optional match message end
  561.                       display)
  562.   "Display the list of possible CHOICES with optional MATCH, MESSAGE,
  563. END and DISPLAY.  If MATCH is non-nil, it will be flagged as the best
  564. guess.  If there are no choices, display MESSAGE.  END is where to put
  565. temporary messages.  If DISPLAY is present then it will be called on
  566. each possible completion and should return a string."
  567.   (if choices
  568.       (with-output-to-temp-buffer " *Completions*"
  569.     (if (cdr choices) 
  570.         (display-completion-list
  571.          (if display
  572.          (let ((new))
  573.            (while choices
  574.              (setq new (cons (funcall display (car choices)) new)
  575.                choices (cdr choices)))
  576.            (setq choices new))
  577.          choices)))
  578.     (if match
  579.         (save-excursion
  580.           (set-buffer " *Completions*")
  581.           (goto-char (point-min))
  582.           (insert "Guess = " match (if (cdr choices) ", " "")))))
  583.       (beep)
  584.       (completer-message (or message " (No completions)") end)))
  585.  
  586. ;;;%%Goto
  587. (defun completer-goto (match lcs choices unique delimiters words 
  588.                  &optional mode display)
  589.   "MATCH is the best match, LCS is the longest common substring of all
  590. of the matches.  CHOICES is a list of the possibilities, UNIQUE
  591. indicates if MATCH is unique.  DELIMITERS are possible bounding
  592. characters for the completion region.  WORDS are the characters that
  593. delimit the words for partial matches.  Replace the region bounded by
  594. delimiters with the match if unique and the lcs otherwise unless
  595. optional MODE is 'help.  Then go to the part of the string that
  596. disambiguates choices using WORDS to separate words and display the
  597. possibilities if the string was not extended.  If optional DISPLAY is
  598. present then it will be called on each possible completion and should
  599. return a string."
  600.   (setq completer-message nil)
  601.   (let* ((region (completer-region delimiters))
  602.      (start (car region))
  603.      (end (cdr region))
  604.      (string (buffer-substring start end))
  605.      (file-p (string-match "[^ ]*\\(~\\|/\\|$\\)" string))
  606.      (no-insert (eq mode 'help))
  607.      (message t)
  608.      (new (not (string= (buffer-substring start (point)) lcs))))
  609.     (if unique
  610.     (if no-insert
  611.         (progn
  612.           (goto-char end)
  613.           (completer-display-choices choices match nil end display))
  614.         (if (string= string match)
  615.         (if (not file-p) 
  616.             (progn (goto-char end)
  617.                (completer-message " (Sole completion)" end)))
  618.         (completer-insert match delimiters)))
  619.     ;;Not unique
  620.     (if lcs
  621.         (let* ((regexp 
  622.             (concat "[" words (if file-p "/") "]"))
  623.            (words (completer-words regexp lcs))
  624.            point)
  625.           ;; Go to where its ambiguous
  626.           (goto-char start)
  627.           (if (not no-insert)
  628.           (progn 
  629.             (insert lcs)
  630.             (setq completer-last-pattern 
  631.               (list string delimiters (current-buffer) start)
  632.               start (point)
  633.               end (+ end (length lcs)))))
  634.           ;; Skip to the first delimiter in the original string
  635.           ;; beyond the ambiguous point and keep from there on
  636.           (if (re-search-forward regexp end 'move words)
  637.           (progn
  638.             (if (and (not no-insert) match)
  639.             (let ((delimiter
  640.                    (progn
  641.                  (string-match lcs match)
  642.                  (substring match (match-end 0)
  643.                         (1+ (match-end 0))))))
  644.               (if (string-match regexp delimiter)
  645.                   (insert delimiter))))
  646.             (forward-char -1)))
  647.           (if (not no-insert) 
  648.           (progn
  649.             (setq end (- end (- (point) start)))
  650.             (delete-region start (point))))))
  651.     (if choices
  652.         (if (or no-insert (not new))
  653.         (completer-display-choices choices match nil end display))
  654.         (if file-p 
  655.         (progn 
  656.           (if (not (= (point) end)) (forward-char 1))
  657.           (if (not (save-excursion (re-search-forward "/" end t)))
  658.               (goto-char end))))
  659.         (if message
  660.         (progn
  661.           (beep)
  662.           (completer-message (if no-insert 
  663.                      " (No completions)"
  664.                      " (No match)")
  665.                      end)))))))        
  666.  
  667. ;;;%Exported buffer interface
  668. ;;;%%Complete and go
  669. (defun completer-complete-goto (delimiters words table pred 
  670.                        &optional no-insert display)
  671.   "Complete the string bound by DELIMITERS using WORDS to bound words
  672. for partial matches in TABLE with PRED and then insert the longest
  673. common substring unless optional NO-INSERT and go to the point of
  674. ambiguity.  If optional DISPLAY, it will be called on each match when
  675. possible completions are shown and should return a string."
  676.   (let* ((region (completer-region delimiters)))
  677.     (apply 'completer-goto 
  678.        (append (completer (buffer-substring (car region) (cdr region))
  679.                   table pred words completer-any-delimiter
  680.                   no-insert)
  681.           (list delimiters words no-insert display)))))
  682.  
  683. ;;;%%Undo
  684. (defun completer-insert (match delimiters &optional buffer undo)
  685.   "Replace the region bounded with characters in DELIMITERS by MATCH
  686. and save it so that it can be restored by completer-undo."
  687.   (let* ((region (completer-region delimiters))
  688.      (start (car region))
  689.      (end (cdr region)))
  690.     (if (and undo (or (not (= start undo)) 
  691.               (not (eq (current-buffer) buffer))))
  692.     (error "No previous pattern")
  693.     (setq completer-last-pattern (list (buffer-substring start end) 
  694.                        delimiters
  695.                        (current-buffer)
  696.                        start))
  697.     (delete-region start end)
  698.     (goto-char start)
  699.     (insert match))))
  700.  
  701. ;;;
  702. (defun completer-undo ()
  703.   "Swap the last expansion and the last match pattern."
  704.   (interactive)
  705.   (if completer-last-pattern
  706.       (apply 'completer-insert completer-last-pattern)
  707.       (error "No previous pattern")))
  708.  
  709. ;;;%Minibuffer specific code
  710. ;;;%%Utilities
  711. (defun completer-minibuf-string ()
  712.   "Remove dead filename specs from the minibuffer as delimited by //
  713. or ~ or $ and return the resulting string."
  714.   (save-excursion
  715.     (goto-char (point-max))
  716.     (if (and (eq minibuffer-completion-table 'read-file-name-internal)
  717.          (re-search-backward "//\\|/~\\|.\\$" nil t))
  718.     (delete-region (point-min) (1+ (point))))
  719.     (buffer-substring (point-min) (point-max))))
  720.  
  721. ;;;
  722. (defun completer-minibuf-exit ()
  723.   "Exit and clear pattern."
  724.   (interactive)
  725.   (setq completer-last-pattern nil)
  726.   (exit-minibuffer))
  727.  
  728. ;;;
  729. (defun completer-new-cmd (cmd)
  730.   "Return T if we can't execute the old minibuffer version of CMD."
  731.   (if (or completer-disable
  732.       (let ((string (completer-minibuf-string)))
  733.         (or
  734.          (not (string-match
  735.            (concat "[" completer-words "/~]")
  736.            string))
  737.           (condition-case ()
  738.           (let ((completion
  739.              (try-completion string
  740.                      minibuffer-completion-table
  741.                      minibuffer-completion-predicate)))
  742.             (if (eq minibuffer-completion-table
  743.                 'read-file-name-internal)
  744.             ;; Directories complete as themselves
  745.             (and completion
  746.                  (or (not (string= string completion))
  747.                  (file-exists-p completion)))
  748.             completion))
  749.         (error nil)))))
  750.       (progn
  751.     (funcall cmd)
  752.     nil)
  753.       t))
  754.  
  755. ;;;
  756. (defun completer-minibuf (&optional mode)
  757.   "Partial completion of minibuffer expressions.  Optional MODE is
  758. 'help for help and 'exit for exit.
  759.  
  760. If what has been typed so far matches any possibility normal
  761. completion will be done.  Otherwise, the string is considered to be a
  762. pattern with words delimited by the characters in
  763. completer-words.  If completer-exact is T, the best match will be
  764. the shortest one with the same number of words as the pattern if
  765. possible and otherwise the shortest matching expression.  If called
  766. with a prefix, caching will be temporarily disabled.
  767.  
  768. Examples:
  769. a-f     auto-fill-mode
  770. r-e     rmail-expunge
  771. b--d    *begining-of-defun or byte-recompile-directory
  772. by  d   *byte-recompile-directory if completer-any-delimiter is \" \"
  773. ~/i.e   *~/ilisp.el or ~/il-el.el or ~/ilisp.elc
  774. /u/mi/  /usr/misc/"
  775.   (interactive)
  776.   (append
  777.    (let ((completer-use-cache (not (or (not completer-use-cache)
  778.                        current-prefix-arg))))
  779.      (completer (completer-minibuf-string)
  780.         minibuffer-completion-table
  781.         minibuffer-completion-predicate
  782.         completer-words
  783.         completer-any-delimiter
  784.         mode))
  785.    (list "^" completer-words mode)))
  786.  
  787. ;;;%%Commands
  788. (defun completer-toggle ()
  789.   "Turn partial completion on or off."
  790.   (interactive)
  791.   (setq completer-disable (not completer-disable))
  792.   (message (if completer-disable 
  793.            "Partial completion OFF"
  794.            "Partial completion ON")))
  795.  
  796. ;;;
  797. (defvar completer-old-help
  798.   (lookup-key minibuffer-local-must-match-map "?")
  799.   "Old binding of ? in minibuffer completion map.")
  800. (defun completer-help ()
  801.   "Partial completion minibuffer-completion-help.  
  802. See completer-minibuf for more information."
  803.   (interactive)
  804.   (if (completer-new-cmd completer-old-help)
  805.       (apply 'completer-goto (completer-minibuf 'help))))
  806.  
  807. ;;;
  808. (defvar completer-old-completer
  809.   (lookup-key minibuffer-local-must-match-map "\t")
  810.   "Old binding of TAB in minibuffer completion map.")
  811. (defun completer-complete ()
  812.   "Partial completion minibuffer-complete.
  813. See completer-minibuf for more information."
  814.   (interactive)
  815.   (if (completer-new-cmd completer-old-completer)
  816.       (apply 'completer-goto (completer-minibuf))))
  817.  
  818. ;;;
  819. (defvar completer-old-word
  820.   (lookup-key minibuffer-local-must-match-map " ")
  821.   "Old binding of SPACE in minibuffer completion map.")
  822. (defun completer-word ()
  823.   "Partial completion minibuffer-complete.
  824. See completer-minibuf for more information."
  825.   (interactive)
  826.   (if (eq completer-any-delimiter ?\ )
  827.       (insert ?\ )
  828.       (if (completer-new-cmd completer-old-word)
  829.       (apply 'completer-goto (completer-minibuf)))))
  830.  
  831. ;;; 
  832. (defvar completer-old-exit
  833.   (lookup-key minibuffer-local-must-match-map "\n")
  834.   "Old binding of RET in minibuffer completion map.")
  835. (defun completer-exit ()
  836.   "Partial completion minibuffer-complete-and-exit.
  837. See completer-minibuf for more information."
  838.   (interactive)
  839.   (if (completer-new-cmd completer-old-exit)
  840.       (let* ((completions (completer-minibuf 'exit))
  841.          (match (car completions))
  842.          (unique-p (car (cdr (cdr (cdr completions))))))
  843.     (apply 'completer-goto completions)
  844.     (if unique-p
  845.         (completer-minibuf-exit)
  846.         (if match
  847.         (progn (completer-insert match "^")
  848.                (if minibuffer-completion-confirm
  849.                (completer-message " (Confirm)")
  850.                (completer-minibuf-exit)))
  851.         (if (not completer-message) (beep)))))))
  852.  
  853. ;;;
  854. (defun completer-match-exit ()
  855.   "Exit the minibuffer with the current best match."
  856.   (interactive)
  857.   (let* ((completions (completer-minibuf 'exit))
  858.      (guess (car completions)))
  859.     (if (not guess) 
  860.     ;; OK if last filename component doesn't match
  861.     (setq completions (completer-minibuf 'exit-ok)
  862.           guess (car completions)))
  863.     (if guess
  864.     (progn
  865.       (goto-char (point-min))
  866.       (insert guess)
  867.       (delete-region (point) (point-max))
  868.       (exit-minibuffer))
  869.     (apply 'completer-goto completions))))
  870.  
  871. ;;;%%Keymaps
  872. (define-key minibuffer-local-completion-map "\C-_"  'completer-undo)
  873. (define-key minibuffer-local-completion-map "\t"    'completer-complete)
  874. (define-key minibuffer-local-completion-map " "     'completer-word)
  875. (define-key minibuffer-local-completion-map "?"     'completer-help)
  876. (define-key minibuffer-local-completion-map "\n"    'completer-minibuf-exit)
  877. (define-key minibuffer-local-completion-map "\r"    'completer-minibuf-exit)
  878. (define-key minibuffer-local-completion-map "\M-\n" 'completer-match-exit)
  879. (define-key minibuffer-local-completion-map "\M-\r" 'completer-match-exit)
  880.  
  881. (define-key minibuffer-local-must-match-map "\C-_"  'completer-undo)
  882. (define-key minibuffer-local-must-match-map "\t"    'completer-complete)
  883. (define-key minibuffer-local-must-match-map " "     'completer-word)
  884. (define-key minibuffer-local-must-match-map "\n"    'completer-exit)
  885. (define-key minibuffer-local-must-match-map "\r"    'completer-exit)
  886. (define-key minibuffer-local-must-match-map "?"     'completer-help)
  887. (define-key minibuffer-local-must-match-map "\M-\n" 'completer-match-exit)
  888. (define-key minibuffer-local-must-match-map "\M-\r" 'completer-match-exit)
  889.  
  890. ;;;%comint 
  891. (defun completer-comint-dynamic-list-completions (prefix)
  892.   "Display the list of possible file name completions.  With a
  893. negative prefix, undo the last completion."
  894.   (interactive "P")
  895.   (completer-comint-dynamic-complete prefix 'help))
  896.  
  897. ;;;
  898. (defun completer-comint-dynamic-complete (&optional undo mode)
  899.   "Complete the previous filename or display possibilities if done
  900. twice in a row.  If called with a prefix, undo the last completion."
  901.   (interactive "P")
  902.   (if undo
  903.       (completer-undo)
  904.     ;; added by jwz: don't cache completions in shell buffer!
  905.     (setq completer-string nil)
  906.       (completer-complete-goto 
  907.        "^ \t\n\""
  908.        completer-words
  909.        'read-file-name-internal
  910.        default-directory
  911.        mode)))
  912. (fset 'comint-dynamic-complete 'completer-comint-dynamic-complete)
  913. (fset 'comint-dynamic-list-completions 
  914.       'completer-comint-dynamic-list-completions)
  915.  
  916. ;;; Set the functions again if comint is loaded
  917. (setq comint-load-hook 
  918.       (cons (function (lambda ()
  919.           (fset 'comint-dynamic-complete 
  920.             'completer-comint-dynamic-complete)
  921.           (fset 'comint-dynamic-list-completions 
  922.             'completer-comint-dynamic-list-completions)))
  923.         (if (and (boundp 'comint-load-hook) comint-load-hook)
  924.         (if (consp comint-load-hook) 
  925.             (if (eq (car comint-load-hook) 'lambda)
  926.             (list comint-load-hook)
  927.             comint-load-hook)
  928.             (list comint-load-hook)))))
  929.  
  930. ;;;%lisp-complete-symbol
  931. (defun lisp-complete-symbol (&optional mode)
  932.   "Perform partial completion on Lisp symbol preceding point.  That
  933. symbol is compared against the symbols that exist and any additional
  934. characters determined by what is there are inserted.  If the symbol
  935. starts just after an open-parenthesis, only symbols with function
  936. definitions are considered.  Otherwise, all symbols with function
  937. definitions, values or properties are considered.  If called with a
  938. negative prefix, the last completion will be undone."
  939.   (interactive "P")
  940.   (if (< (prefix-numeric-value mode) 0)
  941.       (completer-undo)
  942.       (let* ((end (save-excursion (skip-chars-forward "^ \t\n)]}\"") (point)))
  943.          (beg (save-excursion
  944.             (backward-sexp 1)
  945.             (while (= (char-syntax (following-char)) ?\')
  946.               (forward-char 1))
  947.             (point)))
  948.          (pattern (buffer-substring beg end))
  949.          (predicate
  950.           (if (eq (char-after (1- beg)) ?\()
  951.           'fboundp
  952.           (function (lambda (sym)
  953.             (or (boundp sym) (fboundp sym)
  954.             (symbol-plist sym))))))
  955.          (completion (try-completion pattern obarray predicate)))
  956.        (cond ((eq completion t))
  957.           ((null completion)
  958.            (completer-complete-goto
  959.         "^ \t\n\(\)[]{}'`" completer-words
  960.         obarray predicate 
  961.         nil
  962.         (if (not (eq predicate 'fboundp))
  963.             (function (lambda (choice)
  964.               (if (fboundp (intern choice))
  965.               (list choice " <f>")
  966.               choice))))))
  967.           ((not (string= pattern completion))
  968.            (delete-region beg end)
  969.            (insert completion))
  970.           (t
  971.            (message "Making completion list...")
  972.            (let ((list (all-completions pattern obarray predicate)))
  973.          (or (eq predicate 'fboundp)
  974.              (let (new)
  975.                (while list
  976.              (setq new (cons (if (fboundp (intern (car list)))
  977.                          (list (car list) " <f>")
  978.                          (car list))
  979.                      new))
  980.              (setq list (cdr list)))
  981.                (setq list (nreverse new))))
  982.          (with-output-to-temp-buffer "*Help*"
  983.            (display-completion-list list)))
  984.            (message "Making completion list...%s" "done"))))))
  985.  
  986. ;;;%Hooks
  987. (provide 'completer)
  988. (run-hooks 'completer-load-hook)
  989.  
  990.