Initial Commit
[packages] / xemacs-packages / pcomplete / pcomplete.el
1 ;;; pcomplete --- programmable completion
2
3 ;; Copyright (C) 1999, 2000 Free Sofware Foundation
4
5 ;; Author: John Wiegley <johnw@gnu.org>
6 ;; Keywords: processes
7 ;; X-URL: http://www.emacs.org/~johnw/emacs.html
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;; This module provides a programmable completion facility using
29 ;; "completion functions".  Each completion function is responsible
30 ;; for producing a list of possible completions relevant to the current
31 ;; argument position.
32 ;;
33 ;; To use pcomplete with shell-mode, for example, you will need the
34 ;; following in your .emacs file:
35 ;;
36 ;;   (load "pcmpl-auto")
37 ;;   (add-hook 'shell-mode-hook 'pcomplete-shell-setup)
38 ;;
39 ;; Most of the code below simply provides support mechanisms for
40 ;; writing completion functions.  Completion functions themselves are
41 ;; very easy to write.  They have few requirements beyond those of
42 ;; regular Lisp functions.
43 ;;
44 ;; Consider the following example, which will complete against
45 ;; filenames for the first two arguments, and directories for all
46 ;; remaining arguments:
47 ;;
48 ;;   (defun pcomplete/my-command ()
49 ;;     (pcomplete-here (pcomplete-entries))
50 ;;     (pcomplete-here (pcomplete-entries))
51 ;;     (while (pcomplete-here (pcomplete-dirs))))
52 ;;
53 ;; Here are the requirements for completion functions:
54 ;;
55 ;; @ They must be called "pcomplete/MAJOR-MODE/NAME", or
56 ;;   "pcomplete/NAME".  This is how they are looked up, using the NAME
57 ;;   specified in the command argument (the argument in first
58 ;;   position).
59 ;;
60 ;; @ They must be callable with no arguments.
61 ;;
62 ;; @ Their return value is ignored.  If they actually return normally,
63 ;;   it means no completions were available.
64 ;;
65 ;; @ In order to provide completions, they must throw the tag
66 ;;   `pcomplete-completions'.  The value must be the list of possible
67 ;;   completions for the final argument.
68 ;;
69 ;; @ To simplify completion function logic, the tag `pcompleted' may
70 ;;   be thrown with a value of nil in order to abort the function.  It
71 ;;   means that there were no completions available.
72 ;;
73 ;; When a completion function is called, the variable `pcomplete-args'
74 ;; is in scope, and contains all of the arguments specified on the
75 ;; command line.  The variable `pcomplete-last' is the index of the
76 ;; last argument in that list.
77 ;;
78 ;; The variable `pcomplete-index' is used by the completion code to
79 ;; know which argument the completion function is currently examining.
80 ;; It always begins at 1, meaning the first argument after the command
81 ;; name.
82 ;;
83 ;; To facilitate writing completion logic, a special macro,
84 ;; `pcomplete-here', has been provided which does several things:
85 ;;
86 ;;  1. It will throw `pcompleted' (with a value of nil) whenever
87 ;;     `pcomplete-index' exceeds `pcomplete-last'.
88 ;;
89 ;;  2. It will increment `pcomplete-index' if the final argument has
90 ;;     not been reached yet.
91 ;;
92 ;;  3. It will evaluate the form passed to it, and throw the result
93 ;;     using the `pcomplete-completions' tag, if it is called when
94 ;;     `pcomplete-index' is pointing to the final argument.
95 ;;
96 ;; Sometimes a completion function will want to vary the possible
97 ;; completions for an argument based on the previous one.  To
98 ;; facilitate tests like this, the function `pcomplete-test' and
99 ;; `pcomplete-match' are provided.  Called with one argument, they
100 ;; test the value of the previous command argument.  Otherwise, a
101 ;; relative index may be given as an optional second argument, where 0
102 ;; refers to the current argument, 1 the previous, 2 the one before
103 ;; that, etc.  The symbols `first' and `last' specify absolute
104 ;; offsets.
105 ;;
106 ;; Here is an example which will only complete against directories for
107 ;; the second argument if the first argument is also a directory:
108 ;;
109 ;;   (defun pcomplete/example ()
110 ;;      (pcomplete-here (pcomplete-entries))
111 ;;      (if (pcomplete-test 'file-directory-p)
112 ;;          (pcomplete-here (pcomplete-dirs))
113 ;;        (pcomplete-here (pcomplete-entries))))
114 ;;
115 ;; For generating completion lists based on directory contents, see
116 ;; the functions `pcomplete-entries', `pcomplete-dirs',
117 ;; `pcomplete-executables' and `pcomplete-all-entries'.
118 ;;
119 ;; Consult the documentation for `pcomplete-here' for information
120 ;; about its other arguments.
121
122 ;;; Code:
123
124 (provide 'pcomplete)
125
126 (defgroup pcomplete nil
127   "Programmable completion."
128   :group 'processes)
129
130 ;;; User Variables:
131
132 (defcustom pcomplete-file-ignore nil
133   "*A regexp of filenames to be disregarded during file completion."
134   :type 'regexp
135   :group 'pcomplete)
136
137 (defcustom pcomplete-dir-ignore nil
138   "*A regexp of names to be disregarded during directory completion."
139   :type 'regexp
140   :group 'pcomplete)
141
142 (defcustom pcomplete-ignore-case (memq system-type '(ms-dos windows-nt))
143   "*If non-nil, ignore case when doing filename completion."
144   :type 'boolean
145   :group 'pcomplete)
146
147 (defcustom pcomplete-autolist nil
148   "*If non-nil, automatically list possibilities on partial completion.
149 This mirrors the optional behavior of tcsh."
150   :type 'boolean
151   :group 'pcomplete)
152
153 (defcustom pcomplete-suffix-list (list directory-sep-char ?:)
154   "*A list of characters which constitute a proper suffix."
155   :type '(repeat character)
156   :group 'pcomplete)
157
158 (defcustom pcomplete-recexact nil
159   "*If non-nil, use shortest completion if characters cannot be added.
160 This mirrors the optional behavior of tcsh.
161
162 A non-nil value is useful if `pcomplete-autolist' is non-nil too."
163   :type 'boolean
164   :group 'pcomplete)
165
166 (defcustom pcomplete-arg-quote-list nil
167   "*List of characters to quote when completing an argument."
168   :type '(choice (repeat character)
169                  (const :tag "Don't quote" nil))
170   :group 'pcomplete)
171
172 (defcustom pcomplete-quote-arg-hook nil
173   "*A hook which is run to quote a character within a filename.
174 Each function is passed both the filename to be quoted, and the index
175 to be considered.  If the function wishes to provide an alternate
176 quoted form, it need only return the replacement string.  If no
177 function provides a replacement, quoting shall proceed as normal,
178 using a backslash to quote any character which is a member of
179 `pcomplete-arg-quote-list'."
180   :type 'hook
181   :group 'pcomplete)
182
183 (defcustom pcomplete-man-function (if (featurep 'xemacs)
184                                       #'manual-entry
185                                     'man)
186   "*A function to that will be called to display a manual page.
187 It will be passed the name of the command to document."
188   :type 'function
189   :group 'pcomplete)
190
191 (defcustom pcomplete-compare-entry-function 'string-lessp
192   "*This function is used to order file entries for completion.
193 The behavior of most all shells is to sort alphabetically."
194   :type '(radio (function-item string-lessp)
195                 (function-item file-newer-than-file-p)
196                 (function :tag "Other"))
197   :group 'pcomplete)
198
199 (defcustom pcomplete-help nil
200   "*A string or function (or nil) used for context-sensitive help.
201 If a string, it should name an Info node that will be jumped to.
202 If non-nil, it must a sexp that will be evaluated, and whose
203 result will be shown in the minibuffer.
204 If nil, the function `pcomplete-man-function' will be called with the
205 current command argument."
206   :type '(choice string sexp (const :tag "Use man page" nil))
207   :group 'pcomplete)
208
209 (defcustom pcomplete-expand-before-complete nil
210   "*If non-nil, expand the current argument before completing it.
211 This means that typing something such as '$HOME/bi' followed by
212 \\[pcomplete-argument] will cause the variable reference to be
213 resolved first, and the resultant value that will be completed against
214 to be inserted in the buffer.  Note that exactly what gets expanded
215 and how is entirely up to the behavior of the
216 `pcomplete-parse-arguments-function'."
217   :type 'boolean
218   :group 'pcomplete)
219
220 (defcustom pcomplete-parse-arguments-function
221   'pcomplete-parse-buffer-arguments
222   "*A function to call to parse the current line's arguments.
223 It should be called with no parameters, and with point at the position
224 of the argument that is to be completed.
225
226 It must either return nil, or a cons cell of the form:
227
228   ((ARG...) (BEG-POS...))
229
230 The two lists must be identical in length.  The first gives the final
231 value of each command line argument (which need not match the textual
232 representation of that argument), and BEG-POS gives the beginning
233 position of each argument, as it is seen by the user.  The establishes
234 a relationship between the fully resolved value of the argument, and
235 the textual representation of the argument."
236   :type 'function
237   :group 'pcomplete)
238
239 (defcustom pcomplete-cycle-completions t
240   "*If non-nil, hitting the TAB key cycles through the completion list.
241 Typical Emacs behavior is to complete as much as possible, then pause
242 waiting for further input.  Then if TAB is hit again, show a list of
243 possible completions.  When `pcomplete-cycle-completions' is non-nil,
244 it acts more like zsh or 4nt, showing the first maximal match first,
245 followed by any further matches on each subsequent pressing of the TAB
246 key.  \\[pcomplete-list] is the key to press if the user wants to see
247 the list of possible completions."
248   :type 'boolean
249   :group 'pcomplete)
250
251 (defcustom pcomplete-cycle-cutoff-length 5
252   "*If the number of completions is greater than this, don't cycle.
253 This variable is a compromise between the traditional Emacs style of
254 completion, and the \"cycling\" style.  Basically, if there are more
255 than this number of completions possible, don't automatically pick the
256 first one and then expect the user to press TAB to cycle through them.
257 Typically, when there are a large number of completion possibilities,
258 the user wants to see them in a list buffer so that they can know what
259 options are available.  But if the list is small, it means the user
260 has already entered enough input to disambiguate most of the
261 possibilities, and therefore they are probably most interested in
262 cycling through the candidates.  Set this value to nil if you want
263 cycling to always be enabled."
264   :type '(choice integer (const :tag "Always cycle" nil))
265   :group 'pcomplete)
266
267 (defcustom pcomplete-restore-window-delay 1
268   "*The number of seconds to wait before restoring completion windows.
269 Once the completion window has been displayed, if the user then goes
270 on to type something else, that completion window will be removed from
271 the display (actually, the original window configuration before it was
272 displayed will be restored), after this many seconds of idle time.  If
273 set to nil, completion windows will be left on second until the user
274 removes them manually.  If set to 0, they will disappear immediately
275 after the user enters a key other than TAB."
276   :type '(choice integer (const :tag "Never restore" nil))
277   :group 'pcomplete)
278
279 (defcustom pcomplete-try-first-hook nil
280   "*A list of functions which are called before completing an argument.
281 This can be used, for example, for completing things which might apply
282 to all arguments, such as variable names after a $."
283   :type 'hook
284   :group 'pcomplete)
285
286 (defcustom pcomplete-command-completion-function
287   (function
288    (lambda ()
289      (pcomplete-here (pcomplete-executables))))
290   "*Function called for completing the initial command argument."
291   :type 'function
292   :group 'pcomplete)
293
294 (defcustom pcomplete-command-name-function 'pcomplete-command-name
295   "*Function called for determining the current command name."
296   :type 'function
297   :group 'pcomplete)
298
299 (defcustom pcomplete-default-completion-function
300   (function
301    (lambda ()
302      (while (pcomplete-here (pcomplete-entries)))))
303   "*Function called when no completion rule can be found.
304 This function is used to generate completions for every argument."
305   :type 'function
306   :group 'pcomplete)
307
308 (defcustom pcomplete-use-paring t
309   "*If t, pare alternatives that have already been used.
310 If nil, you will always see the completion set of possible options, no
311 matter which of those options have already been used in previous
312 command arguments."
313   :type 'boolean
314   :group 'pcomplete)
315
316 ;;; Internal Variables:
317
318 ;; for cycling completion support
319 (defvar pcomplete-current-completions nil)
320 (defvar pcomplete-last-completion-length)
321 (defvar pcomplete-last-completion-stub)
322 (defvar pcomplete-last-completion-raw)
323 (defvar pcomplete-last-window-config nil)
324 (defvar pcomplete-window-restore-timer nil)
325
326 (make-variable-buffer-local 'pcomplete-current-completions)
327 (make-variable-buffer-local 'pcomplete-last-completion-length)
328 (make-variable-buffer-local 'pcomplete-last-completion-stub)
329 (make-variable-buffer-local 'pcomplete-last-completion-raw)
330 (make-variable-buffer-local 'pcomplete-last-window-config)
331 (make-variable-buffer-local 'pcomplete-window-restore-timer)
332
333 ;; used for altering pcomplete's behavior.  These global variables
334 ;; should always be nil.
335 (defvar pcomplete-show-help nil)
336 (defvar pcomplete-show-list nil)
337 (defvar pcomplete-expand-only-p nil)
338
339 ;;; User Functions:
340
341 ;;;###autoload
342 (defun pcomplete ()
343   "Support extensible programmable completion.
344 To use this function, just bind the TAB key to it, or add it to your
345 completion functions list (it should occur fairly early in the list)."
346   (interactive)
347   (if (and (interactive-p)
348            pcomplete-cycle-completions
349            pcomplete-current-completions
350            (memq last-command '(pcomplete
351                                 pcomplete-expand-and-complete
352                                 pcomplete-reverse)))
353       (progn
354         (delete-backward-char pcomplete-last-completion-length)
355         (if (eq this-command 'pcomplete-reverse)
356             (progn
357               (setq pcomplete-current-completions
358                     (cons (car (last pcomplete-current-completions))
359                           pcomplete-current-completions))
360               (setcdr (last pcomplete-current-completions 2) nil))
361           (nconc pcomplete-current-completions
362                  (list (car pcomplete-current-completions)))
363           (setq pcomplete-current-completions
364                 (cdr pcomplete-current-completions)))
365         (pcomplete-insert-entry pcomplete-last-completion-stub
366                                 (car pcomplete-current-completions)
367                                 nil pcomplete-last-completion-raw))
368     (setq pcomplete-current-completions nil
369           pcomplete-last-completion-raw nil)
370     (catch 'pcompleted
371       (let* ((pcomplete-stub)
372              pcomplete-seen pcomplete-norm-func
373              pcomplete-args pcomplete-last pcomplete-index
374              (pcomplete-autolist pcomplete-autolist)
375              (pcomplete-suffix-list pcomplete-suffix-list)
376              (completions (pcomplete-completions))
377              (result (pcomplete-do-complete pcomplete-stub completions)))
378         (and result
379              (not (eq (car result) 'listed))
380              (cdr result)
381              (pcomplete-insert-entry pcomplete-stub (cdr result)
382                                      (memq (car result)
383                                            '(sole shortest))
384                                      pcomplete-last-completion-raw))))))
385
386 ;;;###autoload
387 (defun pcomplete-reverse ()
388   "If cycling completion is in use, cycle backwards."
389   (interactive)
390   (call-interactively 'pcomplete))
391
392 ;;;###autoload
393 (defun pcomplete-expand-and-complete ()
394   "Expand the textual value of the current argument.
395 This will modify the current buffer."
396   (interactive)
397   (let ((pcomplete-expand-before-complete t))
398     (pcomplete)))
399
400 ;;;###autoload
401 (defun pcomplete-continue ()
402   "Complete without reference to any cycling completions."
403   (interactive)
404   (setq pcomplete-current-completions nil
405         pcomplete-last-completion-raw nil)
406   (call-interactively 'pcomplete))
407
408 ;;;###autoload
409 (defun pcomplete-expand ()
410   "Expand the textual value of the current argument.
411 This will modify the current buffer."
412   (interactive)
413   (let ((pcomplete-expand-before-complete t)
414         (pcomplete-expand-only-p t))
415     (pcomplete)
416     (when (and pcomplete-current-completions
417                (> (length pcomplete-current-completions) 0))
418       (delete-backward-char pcomplete-last-completion-length)
419       (while pcomplete-current-completions
420         (unless (pcomplete-insert-entry
421                  "" (car pcomplete-current-completions) t
422                  pcomplete-last-completion-raw)
423           (insert-and-inherit " "))
424         (setq pcomplete-current-completions
425               (cdr pcomplete-current-completions))))))
426
427 ;;;###autoload
428 (defun pcomplete-help ()
429   "Display any help information relative to the current argument."
430   (interactive)
431   (let ((pcomplete-show-help t))
432     (pcomplete)))
433
434 ;;;###autoload
435 (defun pcomplete-list ()
436   "Show the list of possible completions for the current argument."
437   (interactive)
438   (when (and pcomplete-cycle-completions
439              pcomplete-current-completions
440              (eq last-command 'pcomplete-argument))
441     (delete-backward-char pcomplete-last-completion-length)
442     (setq pcomplete-current-completions nil
443           pcomplete-last-completion-raw nil))
444   (let ((pcomplete-show-list t))
445     (pcomplete)))
446
447 ;;; Internal Functions:
448
449 ;; argument handling
450
451 ;; for the sake of the bye-compiler, when compiling other files that
452 ;; contain completion functions
453 (defvar pcomplete-args nil)
454 (defvar pcomplete-begins nil)
455 (defvar pcomplete-last nil)
456 (defvar pcomplete-index nil)
457 (defvar pcomplete-stub nil)
458 (defvar pcomplete-seen nil)
459 (defvar pcomplete-norm-func nil)
460
461 (defun pcomplete-arg (&optional index offset)
462   "Return the textual content of the INDEXth argument.
463 INDEX is based from the current processing position.  If INDEX is
464 positive, values returned are closer to the command argument; if
465 negative, they are closer to the last argument.  If the INDEX is
466 outside of the argument list, nil is returned.  The default value for
467 INDEX is 0, meaning the current argument being examined.
468
469 The special indices `first' and `last' may be used to access those
470 parts of the list.
471
472 The OFFSET argument is added to/taken away from the index that will be
473 used.  This is really only useful with `first' and `last', for
474 accessing absolute argument positions."
475   (setq index
476         (if (eq index 'first)
477             0
478           (if (eq index 'last)
479               pcomplete-last
480             (- pcomplete-index (or index 0)))))
481   (if offset
482       (setq index (+ index offset)))
483   (nth index pcomplete-args))
484
485 (defun pcomplete-begin (&optional index offset)
486   "Return the beginning position of the INDEXth argument.
487 See the documentation for `pcomplete-arg'."
488   (setq index
489         (if (eq index 'first)
490             0
491           (if (eq index 'last)
492               pcomplete-last
493             (- pcomplete-index (or index 0)))))
494   (if offset
495       (setq index (+ index offset)))
496   (nth index pcomplete-begins))
497
498 (defsubst pcomplete-actual-arg (&optional index offset)
499   "Return the actual text representation of the last argument.
500 This different from `pcomplete-arg', which returns the textual value
501 that the last argument evaluated to.  This function returns what the
502 user actually typed in."
503   (buffer-substring (pcomplete-begin index offset) (point)))
504
505 (defsubst pcomplete-next-arg ()
506   "Move the various pointers to the next argument."
507   (setq pcomplete-index (1+ pcomplete-index)
508         pcomplete-stub (pcomplete-arg))
509   (if (> pcomplete-index pcomplete-last)
510       (progn
511         (message "No completions")
512         (throw 'pcompleted nil))))
513
514 (defun pcomplete-command-name ()
515   "Return the command name of the first argument."
516   (file-name-nondirectory (pcomplete-arg 'first)))
517
518 (defun pcomplete-match (regexp &optional index offset start)
519   "Like `string-match', but on the current completion argument."
520   (let ((arg (pcomplete-arg (or index 1) offset)))
521     (if arg
522         (string-match regexp arg start)
523       (throw 'pcompleted nil))))
524
525 (defun pcomplete-match-string (which &optional index offset)
526   "Like `string-match', but on the current completion argument."
527   (let ((arg (pcomplete-arg (or index 1) offset)))
528     (if arg
529         (match-string which arg)
530       (throw 'pcompleted nil))))
531
532 (defalias 'pcomplete-match-beginning 'match-beginning)
533 (defalias 'pcomplete-match-end 'match-end)
534
535 (defsubst pcomplete--test (pred arg)
536   "Perform a programmable completion predicate match."
537   (and pred
538        (cond ((eq pred t) t)
539              ((functionp pred)
540               (funcall pred arg))
541              ((stringp pred)
542               (string-match (concat "^" pred "$") arg)))
543        pred))
544
545 (defun pcomplete-test (predicates &optional index offset)
546   "Predicates to test the current programmable argument with."
547   (let ((arg (pcomplete-arg (or index 1) offset)))
548     (unless (null predicates)
549       (if (not (listp predicates))
550           (pcomplete--test predicates arg)
551         (let ((pred predicates)
552               found)
553           (while (and pred (not found))
554             (setq found (pcomplete--test (car pred) arg)
555                   pred (cdr pred)))
556           found)))))
557
558 (defun pcomplete-parse-buffer-arguments ()
559   "Parse whitespace separated arguments in the current region."
560   (let ((begin (point-min))
561         (end (point-max))
562         begins args)
563     (save-excursion
564       (goto-char begin)
565       (while (< (point) end)
566         (skip-chars-forward " \t\n")
567         (setq begins (cons (point) begins))
568         (skip-chars-forward "^ \t\n")
569         (setq args (cons (buffer-substring-no-properties
570                           (car begins) (point))
571                          args)))
572       (cons (reverse args) (reverse begins)))))
573
574 ;;;###autoload
575 (defun pcomplete-comint-setup (completef-sym)
576   "Setup a comint buffer to use pcomplete.
577 COMPLETEF-SYM should be the symbol where the
578 dynamic-complete-functions are kept.  For comint mode itself, this is
579 `comint-dynamic-complete-functions'."
580   (set (make-local-variable 'pcomplete-parse-arguments-function)
581        'pcomplete-parse-comint-arguments)
582   (make-local-variable completef-sym)
583   (let ((elem (memq 'comint-dynamic-complete-filename
584                     (symbol-value completef-sym))))
585     (if elem
586         (setcar elem 'pcomplete)
587       (nconc (symbol-value completef-sym)
588              (list 'pcomplete)))))
589
590 ;;;###autoload
591 (defun pcomplete-shell-setup ()
592   "Setup shell-mode to use pcomplete."
593   (pcomplete-comint-setup 'shell-dynamic-complete-functions))
594
595 (defun pcomplete-parse-comint-arguments ()
596   "Parse whitespace separated arguments in the current region."
597   (let ((begin (save-excursion (comint-bol nil) (point)))
598         (end (point))
599         begins args)
600     (save-excursion
601       (goto-char begin)
602       (while (< (point) end)
603         (skip-chars-forward " \t\n")
604         (setq begins (cons (point) begins))
605         (let ((skip t))
606           (while skip
607             (skip-chars-forward "^ \t\n")
608             (if (eq (char-before) ?\\)
609                 (skip-chars-forward " \t\n")
610               (setq skip nil))))
611         (setq args (cons (buffer-substring-no-properties
612                           (car begins) (point))
613                          args)))
614       (cons (reverse args) (reverse begins)))))
615
616 (defun pcomplete-parse-arguments (&optional expand-p)
617   "Parse the command line arguments.  Most completions need this info."
618   (let ((results (funcall pcomplete-parse-arguments-function)))
619     (when results
620       (setq pcomplete-args (or (car results) (list ""))
621             pcomplete-begins (or (cdr results) (list (point)))
622             pcomplete-last (1- (length pcomplete-args))
623             pcomplete-index 0
624             pcomplete-stub (pcomplete-arg 'last))
625       (let ((begin (pcomplete-begin 'last)))
626         (if (and pcomplete-cycle-completions
627                  (listp pcomplete-stub)
628                  (not pcomplete-expand-only-p))
629             (let* ((completions pcomplete-stub)
630                    (common-stub (car completions))
631                    (c completions)
632                    (len (length common-stub)))
633               (while (and c (> len 0))
634                 (while (and (> len 0)
635                             (not (string=
636                                   (substring common-stub 0 len)
637                                   (substring (car c) 0
638                                              (min (length (car c))
639                                                   len)))))
640                   (setq len (1- len)))
641                 (setq c (cdr c)))
642               (setq pcomplete-stub (substring common-stub 0 len)
643                     pcomplete-autolist t)
644               (when (and begin (not pcomplete-show-list))
645                 (delete-region begin (point))
646                 (pcomplete-insert-entry "" pcomplete-stub))
647               (throw 'pcomplete-completions completions))
648           (when expand-p
649             (if (stringp pcomplete-stub)
650                 (when begin
651                   (delete-region begin (point))
652                   (insert-and-inherit pcomplete-stub))
653               (if (and (listp pcomplete-stub)
654                        pcomplete-expand-only-p)
655                   ;; this is for the benefit of `pcomplete-expand'
656                   (setq pcomplete-last-completion-length (- (point) begin)
657                         pcomplete-current-completions pcomplete-stub)
658                 (error "Cannot expand argument"))))
659           (if pcomplete-expand-only-p
660               (throw 'pcompleted t)
661             pcomplete-args))))))
662
663 (defun pcomplete-quote-argument (filename)
664   "Return FILENAME with magic characters quoted.
665 Magic characters are those in `pcomplete-arg-quote-list'."
666   (if (null pcomplete-arg-quote-list)
667       filename
668     (let ((len (length filename))
669           (index 0)
670           (result "")
671           replacement char)
672       (while (< index len)
673         (setq replacement (run-hook-with-args-until-success
674                            'pcomplete-quote-arg-hook filename index))
675         (cond
676          (replacement
677           (setq result (concat result replacement)))
678          ((and (setq char (aref filename index))
679                (memq char pcomplete-arg-quote-list))
680           (setq result (concat result "\\" (char-to-string char))))
681          (t
682           (setq result (concat result (char-to-string char)))))
683         (setq index (1+ index)))
684       result)))
685
686 ;; file-system completion lists
687
688 (defsubst pcomplete-dirs-or-entries (&optional regexp predicate)
689   "Return either directories, or qualified entries."
690   (append (let ((pcomplete-stub pcomplete-stub))
691             (pcomplete-entries regexp predicate))
692           (pcomplete-entries nil 'file-directory-p)))
693
694 (defun pcomplete-entries (&optional regexp predicate)
695   "Complete against a list of directory candidates.
696 This function always uses the last argument as the basis for
697 completion.
698 If REGEXP is non-nil, it is a regular expression used to refine the
699 match (files not matching the REGEXP will be excluded).
700 If PREDICATE is non-nil, it will also be used to refine the match
701 \(files for which the PREDICATE returns nil will be excluded).
702 If PATH is non-nil, it will be used for completion instead of
703 consulting the last argument."
704   (let* ((name pcomplete-stub)
705          (default-directory (expand-file-name
706                              (or (file-name-directory name)
707                                  default-directory)))
708          above-cutoff)
709     (setq name (file-name-nondirectory name)
710           pcomplete-stub name)
711     (let ((completions
712            (file-name-all-completions name default-directory)))
713       (if regexp
714           (setq completions
715                 (pcomplete-pare-list
716                  completions nil
717                  (function
718                   (lambda (file)
719                     (not (string-match regexp file)))))))
720       (if predicate
721           (setq completions
722                 (pcomplete-pare-list
723                  completions nil
724                  (function
725                   (lambda (file)
726                     (not (funcall predicate file)))))))
727       (if (or pcomplete-file-ignore pcomplete-dir-ignore)
728           (setq completions
729                 (pcomplete-pare-list
730                  completions nil
731                  (function
732                   (lambda (file)
733                     (if (eq (aref file (1- (length file)))
734                             directory-sep-char)
735                         (and pcomplete-dir-ignore
736                              (string-match pcomplete-dir-ignore file))
737                       (and pcomplete-file-ignore
738                            (string-match pcomplete-file-ignore file))))))))
739       (setq above-cutoff (> (length completions)
740                             pcomplete-cycle-cutoff-length))
741       (sort completions
742             (function
743              (lambda (l r)
744                ;; for the purposes of comparison, remove the
745                ;; trailing slash from directory names.
746                ;; Otherwise, "foo.old/" will come before "foo/",
747                ;; since . is earlier in the ASCII alphabet than
748                ;; /
749                (let ((left (if (eq (aref l (1- (length l)))
750                                    directory-sep-char)
751                                (substring l 0 (1- (length l)))
752                              l))
753                      (right (if (eq (aref r (1- (length r)))
754                                     directory-sep-char)
755                                 (substring r 0 (1- (length r)))
756                               r)))
757                  (if above-cutoff
758                      (string-lessp left right)
759                    (funcall pcomplete-compare-entry-function
760                             left right)))))))))
761
762 (defsubst pcomplete-all-entries (&optional regexp predicate)
763   "Like `pcomplete-entries', but doesn't ignore any entries."
764   (let (pcomplete-file-ignore
765         pcomplete-dir-ignore)
766     (pcomplete-entries regexp predicate)))
767
768 (defsubst pcomplete-dirs (&optional regexp)
769   "Complete amongst a list of directories."
770   (pcomplete-entries regexp 'file-directory-p))
771
772 (defsubst pcomplete-executables (&optional regexp)
773   "Complete amongst a list of directories and executables."
774   (pcomplete-entries regexp 'file-executable-p))
775
776 ;; generation of completion lists
777
778 (defun pcomplete-find-completion-function (command)
779   "Find the completion function to call for the given COMMAND."
780   (let ((sym (intern-soft
781               (concat "pcomplete/" (symbol-name major-mode) "/" command))))
782     (unless sym
783       (setq sym (intern-soft (concat "pcomplete/" command))))
784     (and sym (fboundp sym) sym)))
785
786 (defun pcomplete-completions ()
787   "Return a list of completions for the current argument position."
788   (catch 'pcomplete-completions
789     (when (pcomplete-parse-arguments pcomplete-expand-before-complete)
790       (if (= pcomplete-index pcomplete-last)
791           (funcall pcomplete-command-completion-function)
792         (let ((sym (or (pcomplete-find-completion-function
793                         (funcall pcomplete-command-name-function))
794                        pcomplete-default-completion-function)))
795           (ignore
796            (pcomplete-next-arg)
797            (funcall sym)))))))
798
799 (defun pcomplete-opt (options &optional prefix no-ganging args-follow)
800   "Complete a set of OPTIONS, each beginning with PREFIX (?- by default).
801 PREFIX may be t, in which case no PREFIX character is necessary.
802 If REQUIRED is non-nil, the options must be present.
803 If NO-GANGING is non-nil, each option is separate.  -xy is not allowed.
804 If ARGS-FOLLOW is non-nil, then options which arguments which take may
805 have the argument appear after a ganged set of options.  This is how
806 tar behaves, for example."
807   (if (and (= pcomplete-index pcomplete-last)
808            (string= (pcomplete-arg) "-"))
809       (let ((len (length options))
810             (index 0)
811             char choices)
812         (while (< index len)
813           (setq char (aref options index))
814           (if (eq char ?\()
815               (let ((result (read-from-string options index)))
816                 (setq index (cdr result)))
817             (unless (memq char '(?/ ?* ?? ?.))
818               (setq choices (cons (char-to-string char) choices)))
819             (setq index (1+ index))))
820         (throw 'pcomplete-completions
821                (mapcar
822                 (function
823                  (lambda (opt)
824                    (concat "-" opt)))
825                 (pcomplete-uniqify-list choices))))
826     (let ((arg (pcomplete-arg)))
827       (when (and (> (length arg) 1)
828                  (stringp arg)
829                  (eq (aref arg 0) (or prefix ?-)))
830         (pcomplete-next-arg)
831         (let ((char (aref arg 1))
832               (len (length options))
833               (index 0)
834               opt-char arg-char result)
835           (while (< (1+ index) len)
836             (setq opt-char (aref options index)
837                   arg-char (aref options (1+ index)))
838             (if (eq arg-char ?\()
839                 (setq result
840                       (read-from-string options (1+ index))
841                       index (cdr result)
842                       result (car result))
843               (setq result nil))
844             (when (and (eq char opt-char)
845                        (memq arg-char '(?\( ?/ ?* ?? ?.)))
846               (if (< pcomplete-index pcomplete-last)
847                   (pcomplete-next-arg)
848                 (throw 'pcomplete-completions
849                        (cond ((eq arg-char ?/) (pcomplete-dirs))
850                              ((eq arg-char ?*) (pcomplete-executables))
851                              ((eq arg-char ??) nil)
852                              ((eq arg-char ?.) (pcomplete-entries))
853                              ((eq arg-char ?\() (eval result))))))
854             (setq index (1+ index))))))))
855
856 (defun pcomplete--here (&optional form stub paring form-only)
857   "Complete aganst the current argument, if at the end.
858 See the documentation for `pcomplete-here'."
859   (if (< pcomplete-index pcomplete-last)
860       (progn
861         (if (eq paring 0)
862             (setq pcomplete-seen nil)
863           (unless (eq paring t)
864             (let ((arg (pcomplete-arg)))
865               (unless (not (stringp arg))
866                 (setq pcomplete-seen
867                       (cons (if paring
868                                 (funcall paring arg)
869                               (file-truename arg))
870                             pcomplete-seen))))))
871         (pcomplete-next-arg)
872         t)
873     (when pcomplete-show-help
874       (pcomplete--help)
875       (throw 'pcompleted t))
876     (if stub
877         (setq pcomplete-stub stub))
878     (if (or (eq paring t) (eq paring 0))
879         (setq pcomplete-seen nil)
880       (setq pcomplete-norm-func (or paring 'file-truename)))
881     (unless form-only
882       (run-hooks 'pcomplete-try-first-hook))
883     (throw 'pcomplete-completions (eval form))))
884
885 (defmacro pcomplete-here (&optional form stub paring form-only)
886   "Complete aganst the current argument, if at the end.
887 If completion is to be done here, evaluate FORM to generate the list
888 of strings which will be used for completion purposes.  If STUB is a
889 string, use it as the completion stub instead of the default (which is
890 the entire text of the current argument).
891
892 For an example of when you might want to use STUB: if the current
893 argument text is 'long-path-name/', you don't want the completions
894 list display to be cluttered by 'long-path-name/' appearing at the
895 beginning of every alternative.  Not only does this make things less
896 intelligle, but it is also inefficient.  Yet, if the completion list
897 does not begin with this string for every entry, the current argument
898 won't complete correctly.
899
900 The solution is to specify a relative stub.  It allows you to
901 substitute a different argument from the current argument, almost
902 always for the sake of efficiency.
903
904 If PARING is nil, this argument will be pared against previous
905 arguments using the function `file-truename' to normalize them.
906 PARING may be a function, in which case that function is for
907 normalization.  If PARING is the value t, the argument dealt with by
908 this call will not participate in argument paring.  If it the integer
909 0, all previous arguments that have been seen will be cleared.
910
911 If FORM-ONLY is non-nil, only the result of FORM will be used to
912 generate the completions list.  This means that the hook
913 `pcomplete-try-first-hook' will not be run."
914   `(pcomplete--here (quote ,form) ,stub ,paring ,form-only))
915
916 (defmacro pcomplete-here* (&optional form stub form-only)
917   "An alternate form which does not participate in argument paring."
918   `(pcomplete-here ,form ,stub t ,form-only))
919
920 ;; display support
921
922 (defun pcomplete-restore-windows ()
923   "If the only window change was due to Completions, restore things."
924   (if pcomplete-last-window-config
925       (let* ((cbuf (get-buffer "*Completions*"))
926              (cwin (and cbuf (get-buffer-window cbuf))))
927         (when (and cwin (window-live-p cwin))
928           (bury-buffer cbuf)
929           (set-window-configuration pcomplete-last-window-config))))
930   (setq pcomplete-last-window-config nil
931         pcomplete-window-restore-timer nil))
932
933 ;; Abstractions so that the code below will work for both Emacs 20 and
934 ;; XEmacs 21
935
936 (unless (fboundp 'event-matches-key-specifier-p)
937   (defalias 'event-matches-key-specifier-p 'eq))
938
939 (if (fboundp 'read-event)
940     (defsubst pcomplete-read-event (&optional prompt)
941       (read-event prompt))
942   (defsubst pcomplete-read-event (&optional prompt)
943     (aref (read-key-sequence prompt) 0)))
944
945 (unless (fboundp 'event-basic-type)
946   (defalias 'event-basic-type 'event-key))
947
948 (defun pcomplete-show-completions (completions)
949   "List in help buffer sorted COMPLETIONS.
950 Typing SPC flushes the help buffer."
951   (let* ((curbuf (current-buffer)))
952     (when pcomplete-window-restore-timer
953       (cancel-timer pcomplete-window-restore-timer)
954       (setq pcomplete-window-restore-timer nil))
955     (unless pcomplete-last-window-config
956       (setq pcomplete-last-window-config (current-window-configuration)))
957     (with-output-to-temp-buffer "*Completions*"
958       (display-completion-list completions))
959     (message "Hit space to flush")
960     (let (event)
961       (prog1
962           (catch 'done
963             (while (with-current-buffer (get-buffer "*Completions*")
964                      (setq event (pcomplete-read-event)))
965               (cond
966                ((event-matches-key-specifier-p event ? )
967                 (set-window-configuration pcomplete-last-window-config)
968                 (setq pcomplete-last-window-config nil)
969                 (throw 'done nil))
970                ((event-matches-key-specifier-p event 'tab)
971                 (save-selected-window
972                   (select-window (get-buffer-window "*Completions*"))
973                   (if (pos-visible-in-window-p (point-max))
974                       (goto-char (point-min))
975                     (scroll-up)))
976                 (message ""))
977                (t
978                 (setq unread-command-events (list event))
979                 (throw 'done nil)))))
980         (if (and pcomplete-last-window-config
981                  pcomplete-restore-window-delay)
982             (setq pcomplete-window-restore-timer
983                   (run-with-timer pcomplete-restore-window-delay nil
984                                   'pcomplete-restore-windows)))))))
985
986 ;; insert completion at point
987
988 (defun pcomplete-insert-entry (stub entry &optional addsuffix raw-p)
989   "Insert a completion entry at point.
990 Returns non-nil if a space was appended at the end."
991   (let ((here (point)))
992     (if (not pcomplete-ignore-case)
993         (insert-and-inherit (if raw-p
994                                 (substring entry (length stub))
995                               (pcomplete-quote-argument
996                                (substring entry (length stub)))))
997       ;; the stub is not quoted at this time, so to determine the
998       ;; length of what should be in the buffer, we must quote it
999       (delete-backward-char (length (pcomplete-quote-argument stub)))
1000       ;; if there is already a backslash present to handle the first
1001       ;; character, don't bother quoting it
1002       (when (eq (char-before) ?\\)
1003         (insert-and-inherit (substring entry 0 1))
1004         (setq entry (substring entry 1)))
1005       (insert-and-inherit (if raw-p
1006                               entry
1007                             (pcomplete-quote-argument entry))))
1008     (let (space-added)
1009       (when (and (not (memq (char-before) pcomplete-suffix-list))
1010                  addsuffix)
1011         (insert-and-inherit " ")
1012         (setq space-added t))
1013       (setq pcomplete-last-completion-length (- (point) here)
1014             pcomplete-last-completion-stub stub)
1015       space-added)))
1016
1017 ;; selection of completions
1018
1019 (defun pcomplete-do-complete (stub completions)
1020   "Dynamically complete at point using STUB and COMPLETIONS.
1021 This is basically just a wrapper for `pcomplete-stub' which does some
1022 extra checking, and munging of the COMPLETIONS list."
1023   (unless (stringp stub)
1024     (message "Cannot complete argument")
1025     (throw 'pcompleted nil))
1026   (if (null completions)
1027       (ignore
1028        (if (and stub (> (length stub) 0))
1029            (message "No completions of %s" stub)
1030          (message "No completions")))
1031     ;; pare it down, if applicable
1032     (if (and pcomplete-use-paring pcomplete-seen)
1033         (let* ((arg (pcomplete-arg))
1034                (prefix
1035                 (file-name-as-directory
1036                  (funcall pcomplete-norm-func
1037                           (substring arg 0 (- (length arg)
1038                                               (length pcomplete-stub)))))))
1039           (setq pcomplete-seen
1040                 (mapcar 'directory-file-name pcomplete-seen))
1041           (let ((p pcomplete-seen))
1042             (while p
1043               (add-to-list 'pcomplete-seen
1044                            (funcall pcomplete-norm-func (car p)))
1045               (setq p (cdr p))))
1046           (setq completions
1047                 (mapcar
1048                  (function
1049                   (lambda (elem)
1050                     (file-relative-name elem prefix)))
1051                  (pcomplete-pare-list
1052                   (mapcar
1053                    (function
1054                     (lambda (elem)
1055                       (expand-file-name elem prefix)))
1056                    completions)
1057                   pcomplete-seen
1058                   (function
1059                    (lambda (elem)
1060                      (member (directory-file-name
1061                               (funcall pcomplete-norm-func elem))
1062                              pcomplete-seen))))))))
1063     ;; OK, we've got a list of completions.
1064     (if pcomplete-show-list
1065         (pcomplete-show-completions completions)
1066       (pcomplete-stub stub completions))))
1067
1068 (defun pcomplete-stub (stub candidates &optional cycle-p)
1069   "Dynamically complete STUB from CANDIDATES list.
1070 This function inserts completion characters at point by completing
1071 STUB from the strings in CANDIDATES.  A completions listing may be
1072 shown in a help buffer if completion is ambiguous.
1073
1074 Returns nil if no completion was inserted.
1075 Returns `sole' if completed with the only completion match.
1076 Returns `shortest' if completed with the shortest of the matches.
1077 Returns `partial' if completed as far as possible with the matches.
1078 Returns `listed' if a completion listing was shown.
1079
1080 See also `pcomplete-filename'."
1081   (let* ((completion-ignore-case pcomplete-ignore-case)
1082          (candidates (mapcar 'list candidates))
1083          (completions (all-completions stub candidates)))
1084     (let (result entry)
1085       (cond
1086        ((null completions)
1087         (if (and stub (> (length stub) 0))
1088             (message "No completions of %s" stub)
1089           (message "No completions")))
1090        ((= 1 (length completions))
1091         (setq entry (car completions))
1092         (if (string-equal entry stub)
1093             (message "Sole completion"))
1094         (setq result 'sole))
1095        ((and pcomplete-cycle-completions
1096              (or cycle-p
1097                  (not pcomplete-cycle-cutoff-length)
1098                  (<= (length completions)
1099                      pcomplete-cycle-cutoff-length)))
1100         (setq entry (car completions)
1101               pcomplete-current-completions completions))
1102        (t ; There's no unique completion; use longest substring
1103         (setq entry (try-completion stub candidates))
1104         (cond ((and pcomplete-recexact
1105                     (string-equal stub entry)
1106                     (member entry completions))
1107                ;; It's not unique, but user wants shortest match.
1108                (message "Completed shortest")
1109                (setq result 'shortest))
1110               ((or pcomplete-autolist
1111                    (string-equal stub entry))
1112                ;; It's not unique, list possible completions.
1113                (pcomplete-show-completions completions)
1114                (setq result 'listed))
1115               (t
1116                (message "Partially completed")
1117                (setq result 'partial)))))
1118       (cons result entry))))
1119
1120 ;; context sensitive help
1121
1122 (defun pcomplete--help ()
1123   "Produce context-sensitive help for the current argument.
1124 If specific documentation can't be given, be generic.
1125 INFODOC specifies the Info node to goto.  DOCUMENTATION is a sexp
1126 which will produce documentation for the argument (it is responsible
1127 for displaying in its own buffer)."
1128   (if (and pcomplete-help
1129            (or (and (stringp pcomplete-help)
1130                     (fboundp 'Info-goto-node))
1131                (listp pcomplete-help)))
1132       (if (listp pcomplete-help)
1133           (message (eval pcomplete-help))
1134         (save-window-excursion (info))
1135         (switch-to-buffer-other-window "*info*")
1136         (funcall (symbol-function 'Info-goto-node) pcomplete-help))
1137     (if pcomplete-man-function
1138         (let ((cmd (funcall pcomplete-command-name-function)))
1139           (if (and cmd (> (length cmd) 0))
1140               (funcall pcomplete-man-function cmd)))
1141       (message "No context-sensitive help available"))))
1142
1143 ;; general utilities
1144
1145 (defsubst pcomplete-time-less-p (t1 t2)
1146   "Say whether time T1 is less than time T2."
1147   (or (< (car t1) (car t2))
1148       (and (= (car t1) (car t2))
1149            (< (nth 1 t1) (nth 1 t2)))))
1150
1151 (defun pcomplete-pare-list (l r &optional pred)
1152   "Destructively remove from list L all elements matching any in list R.
1153 Test is done using `equal'.
1154 If PRED is non-nil, it is a function used for further removal.
1155 Returns the resultant list."
1156   (while (and l (or (and r (member (car l) r))
1157                     (and pred
1158                          (funcall pred (car l)))))
1159     (setq l (cdr l)))
1160   (let ((m l))
1161     (while m
1162       (while (and (cdr m)
1163                   (or (and r (member (cadr m) r))
1164                       (and pred
1165                            (funcall pred (cadr m)))))
1166         (setcdr m (cddr m)))
1167       (setq m (cdr m))))
1168   l)
1169
1170 (defun pcomplete-uniqify-list (l)
1171   "Sort and remove multiples in L."
1172   (setq l (sort l 'string-lessp))
1173   (let ((m l))
1174     (while m
1175       (while (and (cdr m)
1176                   (string= (car m)
1177                            (cadr m)))
1178         (setcdr m (cddr m)))
1179       (setq m (cdr m))))
1180   l)
1181
1182 (defun pcomplete-process-result (cmd &rest args)
1183   "Call CMD using `call-process' and return the simplest result."
1184   (with-temp-buffer
1185     (apply 'call-process cmd nil t nil args)
1186     (skip-chars-backward "\n")
1187     (buffer-substring (point-min) (point))))
1188
1189 ;; create a set of aliases which allow completion functions to be not
1190 ;; quite so verbose
1191
1192 ;; jww (1999-10-20): are these a good idea?
1193 ; (defalias 'pc-here 'pcomplete-here)
1194 ; (defalias 'pc-test 'pcomplete-test)
1195 ; (defalias 'pc-opt 'pcomplete-opt)
1196 ; (defalias 'pc-match 'pcomplete-match)
1197 ; (defalias 'pc-match-string 'pcomplete-match-string)
1198 ; (defalias 'pc-match-beginning 'pcomplete-match-beginning)
1199 ; (defalias 'pc-match-end 'pcomplete-match-end)
1200
1201 ;;; pcomplete.el ends here