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