* lisp/minibuffer.el (completion-category-overrides): Fix type of styles
[bpt/emacs.git] / lisp / pcomplete.el
CommitLineData
1c6d8c76 1;;; pcomplete.el --- programmable completion -*- lexical-binding: t -*-
affbf647 2
73b0cd50 3;; Copyright (C) 1999-2011 Free Software Foundation, Inc.
affbf647
GM
4
5;; Author: John Wiegley <johnw@gnu.org>
5751b8f9 6;; Keywords: processes abbrev
affbf647
GM
7
8;; This file is part of GNU Emacs.
9
eb3fa2cf 10;; GNU Emacs is free software: you can redistribute it and/or modify
affbf647 11;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
affbf647
GM
14
15;; GNU Emacs is distributed in the hope that it will be useful,
16;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18;; GNU General Public License for more details.
19
20;; You should have received a copy of the GNU General Public License
eb3fa2cf 21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
affbf647
GM
22
23;;; Commentary:
24
25;; This module provides a programmable completion facility using
26;; "completion functions". Each completion function is responsible
27;; for producing a list of possible completions relevant to the current
28;; argument position.
29;;
30;; To use pcomplete with shell-mode, for example, you will need the
31;; following in your .emacs file:
32;;
affbf647
GM
33;; (add-hook 'shell-mode-hook 'pcomplete-shell-setup)
34;;
35;; Most of the code below simply provides support mechanisms for
36;; writing completion functions. Completion functions themselves are
37;; very easy to write. They have few requirements beyond those of
38;; regular Lisp functions.
39;;
40;; Consider the following example, which will complete against
41;; filenames for the first two arguments, and directories for all
42;; remaining arguments:
43;;
44;; (defun pcomplete/my-command ()
45;; (pcomplete-here (pcomplete-entries))
46;; (pcomplete-here (pcomplete-entries))
47;; (while (pcomplete-here (pcomplete-dirs))))
48;;
49;; Here are the requirements for completion functions:
50;;
51;; @ They must be called "pcomplete/MAJOR-MODE/NAME", or
52;; "pcomplete/NAME". This is how they are looked up, using the NAME
53;; specified in the command argument (the argument in first
54;; position).
55;;
56;; @ They must be callable with no arguments.
57;;
58;; @ Their return value is ignored. If they actually return normally,
59;; it means no completions were available.
60;;
61;; @ In order to provide completions, they must throw the tag
3b067af1
SM
62;; `pcomplete-completions'. The value must be a completion table
63;; (i.e. a table that can be passed to try-completion and friends)
64;; for the final argument.
affbf647
GM
65;;
66;; @ To simplify completion function logic, the tag `pcompleted' may
67;; be thrown with a value of nil in order to abort the function. It
68;; means that there were no completions available.
69;;
70;; When a completion function is called, the variable `pcomplete-args'
71;; is in scope, and contains all of the arguments specified on the
72;; command line. The variable `pcomplete-last' is the index of the
73;; last argument in that list.
74;;
75;; The variable `pcomplete-index' is used by the completion code to
76;; know which argument the completion function is currently examining.
77;; It always begins at 1, meaning the first argument after the command
78;; name.
79;;
80;; To facilitate writing completion logic, a special macro,
81;; `pcomplete-here', has been provided which does several things:
82;;
83;; 1. It will throw `pcompleted' (with a value of nil) whenever
84;; `pcomplete-index' exceeds `pcomplete-last'.
85;;
86;; 2. It will increment `pcomplete-index' if the final argument has
87;; not been reached yet.
88;;
89;; 3. It will evaluate the form passed to it, and throw the result
90;; using the `pcomplete-completions' tag, if it is called when
91;; `pcomplete-index' is pointing to the final argument.
92;;
93;; Sometimes a completion function will want to vary the possible
94;; completions for an argument based on the previous one. To
95;; facilitate tests like this, the function `pcomplete-test' and
96;; `pcomplete-match' are provided. Called with one argument, they
97;; test the value of the previous command argument. Otherwise, a
98;; relative index may be given as an optional second argument, where 0
99;; refers to the current argument, 1 the previous, 2 the one before
100;; that, etc. The symbols `first' and `last' specify absolute
101;; offsets.
102;;
103;; Here is an example which will only complete against directories for
104;; the second argument if the first argument is also a directory:
105;;
106;; (defun pcomplete/example ()
107;; (pcomplete-here (pcomplete-entries))
108;; (if (pcomplete-test 'file-directory-p)
109;; (pcomplete-here (pcomplete-dirs))
110;; (pcomplete-here (pcomplete-entries))))
111;;
112;; For generating completion lists based on directory contents, see
113;; the functions `pcomplete-entries', `pcomplete-dirs',
114;; `pcomplete-executables' and `pcomplete-all-entries'.
115;;
116;; Consult the documentation for `pcomplete-here' for information
117;; about its other arguments.
118
119;;; Code:
120
3b067af1 121(eval-when-compile (require 'cl))
32c1fffd 122(require 'comint)
affbf647
GM
123
124(defgroup pcomplete nil
125 "Programmable completion."
5751b8f9 126 :version "21.1"
affbf647
GM
127 :group 'processes)
128
129;;; User Variables:
130
131(defcustom pcomplete-file-ignore nil
9201cc28 132 "A regexp of filenames to be disregarded during file completion."
219227ea 133 :type '(choice regexp (const :tag "None" nil))
affbf647
GM
134 :group 'pcomplete)
135
136(defcustom pcomplete-dir-ignore nil
9201cc28 137 "A regexp of names to be disregarded during directory completion."
219227ea 138 :type '(choice regexp (const :tag "None" nil))
affbf647
GM
139 :group 'pcomplete)
140
c60ee5e7 141(defcustom pcomplete-ignore-case (memq system-type '(ms-dos windows-nt cygwin))
48feed59
SM
142 ;; FIXME: the doc mentions file-name completion, but the code
143 ;; seems to apply it to all completions.
9201cc28 144 "If non-nil, ignore case when doing filename completion."
affbf647
GM
145 :type 'boolean
146 :group 'pcomplete)
147
148(defcustom pcomplete-autolist nil
9201cc28 149 "If non-nil, automatically list possibilities on partial completion.
affbf647
GM
150This mirrors the optional behavior of tcsh."
151 :type 'boolean
152 :group 'pcomplete)
153
58cc447b 154(defcustom pcomplete-suffix-list (list ?/ ?:)
9201cc28 155 "A list of characters which constitute a proper suffix."
affbf647
GM
156 :type '(repeat character)
157 :group 'pcomplete)
1c6d8c76 158(make-obsolete-variable 'pcomplete-suffix-list nil "24.1")
affbf647
GM
159
160(defcustom pcomplete-recexact nil
9201cc28 161 "If non-nil, use shortest completion if characters cannot be added.
affbf647
GM
162This mirrors the optional behavior of tcsh.
163
164A non-nil value is useful if `pcomplete-autolist' is non-nil too."
165 :type 'boolean
166 :group 'pcomplete)
167
168(defcustom pcomplete-arg-quote-list nil
9201cc28 169 "List of characters to quote when completing an argument."
affbf647
GM
170 :type '(choice (repeat character)
171 (const :tag "Don't quote" nil))
172 :group 'pcomplete)
173
174(defcustom pcomplete-quote-arg-hook nil
9201cc28 175 "A hook which is run to quote a character within a filename.
affbf647
GM
176Each function is passed both the filename to be quoted, and the index
177to be considered. If the function wishes to provide an alternate
178quoted form, it need only return the replacement string. If no
179function provides a replacement, quoting shall proceed as normal,
180using a backslash to quote any character which is a member of
181`pcomplete-arg-quote-list'."
182 :type 'hook
183 :group 'pcomplete)
184
185(defcustom pcomplete-man-function 'man
9201cc28 186 "A function to that will be called to display a manual page.
affbf647
GM
187It 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
9201cc28 192 "This function is used to order file entries for completion.
affbf647
GM
193The 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
9201cc28 200 "A string or function (or nil) used for context-sensitive help.
affbf647
GM
201If a string, it should name an Info node that will be jumped to.
202If non-nil, it must a sexp that will be evaluated, and whose
203result will be shown in the minibuffer.
204If nil, the function `pcomplete-man-function' will be called with the
205current command argument."
206 :type '(choice string sexp (const :tag "Use man page" nil))
207 :group 'pcomplete)
208
209(defcustom pcomplete-expand-before-complete nil
9201cc28 210 "If non-nil, expand the current argument before completing it.
affbf647
GM
211This means that typing something such as '$HOME/bi' followed by
212\\[pcomplete-argument] will cause the variable reference to be
213resolved first, and the resultant value that will be completed against
214to be inserted in the buffer. Note that exactly what gets expanded
215and 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
9201cc28 222 "A function to call to parse the current line's arguments.
affbf647
GM
223It should be called with no parameters, and with point at the position
224of the argument that is to be completed.
225
226It must either return nil, or a cons cell of the form:
227
228 ((ARG...) (BEG-POS...))
229
230The two lists must be identical in length. The first gives the final
231value of each command line argument (which need not match the textual
232representation of that argument), and BEG-POS gives the beginning
233position of each argument, as it is seen by the user. The establishes
234a relationship between the fully resolved value of the argument, and
235the textual representation of the argument."
236 :type 'function
237 :group 'pcomplete)
238
239(defcustom pcomplete-cycle-completions t
9201cc28 240 "If non-nil, hitting the TAB key cycles through the completion list.
affbf647
GM
241Typical Emacs behavior is to complete as much as possible, then pause
242waiting for further input. Then if TAB is hit again, show a list of
243possible completions. When `pcomplete-cycle-completions' is non-nil,
244it acts more like zsh or 4nt, showing the first maximal match first,
245followed by any further matches on each subsequent pressing of the TAB
246key. \\[pcomplete-list] is the key to press if the user wants to see
247the list of possible completions."
248 :type 'boolean
249 :group 'pcomplete)
250
251(defcustom pcomplete-cycle-cutoff-length 5
9201cc28 252 "If the number of completions is greater than this, don't cycle.
affbf647
GM
253This variable is a compromise between the traditional Emacs style of
254completion, and the \"cycling\" style. Basically, if there are more
255than this number of completions possible, don't automatically pick the
256first one and then expect the user to press TAB to cycle through them.
257Typically, when there are a large number of completion possibilities,
258the user wants to see them in a list buffer so that they can know what
259options are available. But if the list is small, it means the user
260has already entered enough input to disambiguate most of the
261possibilities, and therefore they are probably most interested in
262cycling through the candidates. Set this value to nil if you want
263cycling to always be enabled."
264 :type '(choice integer (const :tag "Always cycle" nil))
265 :group 'pcomplete)
266
267(defcustom pcomplete-restore-window-delay 1
9201cc28 268 "The number of seconds to wait before restoring completion windows.
affbf647
GM
269Once the completion window has been displayed, if the user then goes
270on to type something else, that completion window will be removed from
271the display (actually, the original window configuration before it was
272displayed will be restored), after this many seconds of idle time. If
273set to nil, completion windows will be left on second until the user
274removes them manually. If set to 0, they will disappear immediately
275after 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
9201cc28 280 "A list of functions which are called before completing an argument.
affbf647
GM
281This can be used, for example, for completing things which might apply
282to all arguments, such as variable names after a $."
283 :type 'hook
284 :group 'pcomplete)
285
004a00f4
DN
286(defsubst pcomplete-executables (&optional regexp)
287 "Complete amongst a list of directories and executables."
288 (pcomplete-entries regexp 'file-executable-p))
289
affbf647
GM
290(defcustom pcomplete-command-completion-function
291 (function
292 (lambda ()
293 (pcomplete-here (pcomplete-executables))))
9201cc28 294 "Function called for completing the initial command argument."
affbf647
GM
295 :type 'function
296 :group 'pcomplete)
297
298(defcustom pcomplete-command-name-function 'pcomplete-command-name
9201cc28 299 "Function called for determining the current command name."
affbf647
GM
300 :type 'function
301 :group 'pcomplete)
302
303(defcustom pcomplete-default-completion-function
304 (function
305 (lambda ()
306 (while (pcomplete-here (pcomplete-entries)))))
9201cc28 307 "Function called when no completion rule can be found.
affbf647
GM
308This function is used to generate completions for every argument."
309 :type 'function
310 :group 'pcomplete)
311
ca7aae91 312(defcustom pcomplete-use-paring t
9201cc28 313 "If t, pare alternatives that have already been used.
ca7aae91
JW
314If nil, you will always see the completion set of possible options, no
315matter which of those options have already been used in previous
316command arguments."
317 :type 'boolean
318 :group 'pcomplete)
319
150158c4 320(defcustom pcomplete-termination-string " "
9201cc28 321 "A string that is inserted after any completion or expansion.
150158c4
JW
322This is usually a space character, useful when completing lists of
323words separated by spaces. However, if your list uses a different
324separator character, or if the completion occurs in a word that is
325already terminated by a character, this variable should be locally
326modified to be an empty string, or the desired separation string."
327 :type 'string
328 :group 'pcomplete)
329
affbf647
GM
330;;; Internal Variables:
331
332;; for cycling completion support
333(defvar pcomplete-current-completions nil)
334(defvar pcomplete-last-completion-length)
335(defvar pcomplete-last-completion-stub)
336(defvar pcomplete-last-completion-raw)
337(defvar pcomplete-last-window-config nil)
338(defvar pcomplete-window-restore-timer nil)
339
340(make-variable-buffer-local 'pcomplete-current-completions)
341(make-variable-buffer-local 'pcomplete-last-completion-length)
342(make-variable-buffer-local 'pcomplete-last-completion-stub)
343(make-variable-buffer-local 'pcomplete-last-completion-raw)
344(make-variable-buffer-local 'pcomplete-last-window-config)
345(make-variable-buffer-local 'pcomplete-window-restore-timer)
346
347;; used for altering pcomplete's behavior. These global variables
348;; should always be nil.
349(defvar pcomplete-show-help nil)
350(defvar pcomplete-show-list nil)
351(defvar pcomplete-expand-only-p nil)
352
06b60517
JB
353;; for the sake of the bye-compiler, when compiling other files that
354;; contain completion functions
355(defvar pcomplete-args nil)
356(defvar pcomplete-begins nil)
357(defvar pcomplete-last nil)
358(defvar pcomplete-index nil)
359(defvar pcomplete-stub nil)
360(defvar pcomplete-seen nil)
361(defvar pcomplete-norm-func nil)
362
affbf647
GM
363;;; User Functions:
364
2d085307
SM
365;;; Alternative front-end using the standard completion facilities.
366
367;; The way pcomplete-parse-arguments, pcomplete-stub, and
368;; pcomplete-quote-argument work only works because of some deep
369;; hypothesis about the way the completion work. Basically, it makes
370;; it pretty much impossible to have completion other than
371;; prefix-completion.
372;;
373;; pcomplete--common-quoted-suffix and pcomplete--table-subvert try to
374;; work around this difficulty with heuristics, but it's
375;; really a hack.
376
377(defvar pcomplete-unquote-argument-function nil)
378
379(defun pcomplete-unquote-argument (s)
380 (cond
381 (pcomplete-unquote-argument-function
382 (funcall pcomplete-unquote-argument-function s))
383 ((null pcomplete-arg-quote-list) s)
384 (t
385 (replace-regexp-in-string "\\\\\\(.\\)" "\\1" s t))))
affbf647 386
2d085307 387(defun pcomplete--common-quoted-suffix (s1 s2)
32c1fffd 388 ;; FIXME: Copied in comint.el.
2d085307
SM
389 "Find the common suffix between S1 and S2 where S1 is the expanded S2.
390S1 is expected to be the unquoted and expanded version of S1.
391Returns (PS1 . PS2), i.e. the shortest prefixes of S1 and S2, such that
392S1 = (concat PS1 SS1) and S2 = (concat PS2 SS2) and
393SS1 = (unquote SS2)."
32c1fffd 394 (let* ((cs (comint--common-suffix s1 s2))
2d085307
SM
395 (ss1 (substring s1 (- (length s1) cs)))
396 (qss1 (pcomplete-quote-argument ss1))
397 qc)
398 (if (and (not (equal ss1 qss1))
399 (setq qc (pcomplete-quote-argument (substring ss1 0 1)))
400 (eq t (compare-strings s2 (- (length s2) cs (length qc) -1)
401 (- (length s2) cs -1)
402 qc nil nil)))
403 ;; The difference found is just that one char is quoted in S2
404 ;; but not in S1, keep looking before this difference.
405 (pcomplete--common-quoted-suffix
406 (substring s1 0 (- (length s1) cs))
407 (substring s2 0 (- (length s2) cs (length qc) -1)))
408 (cons (substring s1 0 (- (length s1) cs))
409 (substring s2 0 (- (length s2) cs))))))
410
411(defun pcomplete--table-subvert (table s1 s2 string pred action)
32c1fffd 412 ;; FIXME: Copied in comint.el.
48feed59
SM
413 "Completion table that replaces the prefix S1 with S2 in STRING.
414When TABLE, S1 and S2 are provided by `apply-partially', the result
415is a completion table which completes strings of the form (concat S1 S)
416in the same way as TABLE completes strings of the form (concat S2 S)."
417 (let* ((str (if (eq t (compare-strings string 0 (length s1) s1 nil nil
418 completion-ignore-case))
2d085307
SM
419 (concat s2 (pcomplete-unquote-argument
420 (substring string (length s1))))))
48feed59
SM
421 (res (if str (complete-with-action action table str pred))))
422 (when res
423 (cond
424 ((and (eq (car-safe action) 'boundaries))
425 (let ((beg (or (and (eq (car-safe res) 'boundaries) (cadr res)) 0)))
426 (list* 'boundaries
427 (max (length s1)
2d085307 428 ;; FIXME: Adjust because of quoting/unquoting.
48feed59
SM
429 (+ beg (- (length s1) (length s2))))
430 (and (eq (car-safe res) 'boundaries) (cddr res)))))
431 ((stringp res)
432 (if (eq t (compare-strings res 0 (length s2) s2 nil nil
433 completion-ignore-case))
2d085307
SM
434 (concat s1 (pcomplete-quote-argument
435 (substring res (length s2))))))
48feed59
SM
436 ((eq action t)
437 (let ((bounds (completion-boundaries str table pred "")))
438 (if (>= (car bounds) (length s2))
439 res
440 (let ((re (concat "\\`"
441 (regexp-quote (substring s2 (car bounds))))))
442 (delq nil
443 (mapcar (lambda (c)
444 (if (string-match re c)
445 (substring c (match-end 0))))
32c1fffd
SM
446 res))))))
447 ;; E.g. action=nil and it's the only completion.
448 (res)))))
06b60517 449
2d085307
SM
450;; I don't think such commands are usable before first setting up buffer-local
451;; variables to parse args, so there's no point autoloading it.
452;; ;;;###autoload
c26ea4b2 453(defun pcomplete-completions-at-point ()
3b067af1
SM
454 "Provide standard completion using pcomplete's completion tables.
455Same as `pcomplete' but using the standard completion UI."
0667de21
SM
456 ;; FIXME: it only completes the text before point, whereas the
457 ;; standard UI may also consider text after point.
c26ea4b2
SM
458 ;; FIXME: the `pcomplete' UI may be used internally during
459 ;; pcomplete-completions and then throw to `pcompleted', thus
460 ;; imposing the pcomplete UI over the standard UI.
3b067af1
SM
461 (catch 'pcompleted
462 (let* ((pcomplete-stub)
463 pcomplete-seen pcomplete-norm-func
464 pcomplete-args pcomplete-last pcomplete-index
465 (pcomplete-autolist pcomplete-autolist)
466 (pcomplete-suffix-list pcomplete-suffix-list)
467 ;; Apparently the vars above are global vars modified by
468 ;; side-effects, whereas pcomplete-completions is the core
469 ;; function that finds the chunk of text to complete
470 ;; (returned indirectly in pcomplete-stub) and the set of
471 ;; possible completions.
472 (completions (pcomplete-completions))
48feed59
SM
473 ;; Usually there's some close connection between pcomplete-stub
474 ;; and the text before point. But depending on what
475 ;; pcomplete-parse-arguments-function does, that connection
476 ;; might not be that close. E.g. in eshell,
477 ;; pcomplete-parse-arguments-function expands envvars.
06b60517 478 ;;
48feed59
SM
479 ;; Since we use minibuffer-complete, which doesn't know
480 ;; pcomplete-stub and works from the buffer's text instead,
481 ;; we need to trick minibuffer-complete, into using
482 ;; pcomplete-stub without its knowledge. To that end, we
2d085307 483 ;; use pcomplete--table-subvert to construct a completion
48feed59
SM
484 ;; table which expects strings using a prefix from the
485 ;; buffer's text but internally uses the corresponding
486 ;; prefix from pcomplete-stub.
487 (beg (max (- (point) (length pcomplete-stub))
2d085307 488 (pcomplete-begin)))
08abfaad
SM
489 (buftext (buffer-substring beg (point))))
490 (when completions
491 (let ((table
492 (cond
493 ((not (equal pcomplete-stub buftext))
494 ;; This isn't always strictly right (e.g. if
495 ;; FOO="toto/$FOO", then completion of /$FOO/bar may
496 ;; result in something incorrect), but given the lack of
497 ;; any other info, it's about as good as it gets, and in
498 ;; practice it should work just fine (fingers crossed).
499 (let ((prefixes (pcomplete--common-quoted-suffix
500 pcomplete-stub buftext)))
1c6d8c76
SM
501 (apply-partially #'pcomplete--table-subvert
502 completions
503 (cdr prefixes) (car prefixes))))
08abfaad 504 (t
1c6d8c76
SM
505 (lambda (string pred action)
506 (let ((res (complete-with-action
507 action completions string pred)))
508 (if (stringp res)
509 (pcomplete-quote-argument res)
510 res))))))
08abfaad
SM
511 (pred
512 ;; Pare it down, if applicable.
513 (when (and pcomplete-use-paring pcomplete-seen)
1c6d8c76
SM
514 ;; Capture the dynbound values for later use.
515 (let ((norm-func pcomplete-norm-func)
78054a46
SM
516 (seen
517 (mapcar (lambda (f)
518 (funcall pcomplete-norm-func
519 (directory-file-name f)))
520 pcomplete-seen)))
1c6d8c76
SM
521 (lambda (f)
522 (not (member
523 (funcall norm-func (directory-file-name f))
524 seen)))))))
08abfaad
SM
525 (when pcomplete-ignore-case
526 (setq table
527 (apply-partially #'completion-table-case-fold table)))
a2a25d24
SM
528 (list beg (point) table
529 :predicate pred
530 :exit-function
531 (unless (zerop (length pcomplete-termination-string))
532 (lambda (_s finished)
533 (when (memq finished '(sole finished))
534 (if (looking-at
535 (regexp-quote pcomplete-termination-string))
536 (goto-char (match-end 0))
537 (insert pcomplete-termination-string)))))))))))
c26ea4b2
SM
538
539 ;; I don't think such commands are usable before first setting up buffer-local
540 ;; variables to parse args, so there's no point autoloading it.
541 ;; ;;;###autoload
542(defun pcomplete-std-complete ()
20e0e05f 543 (let ((data (pcomplete-completions-at-point)))
14a7fbd8
SM
544 (completion-in-region (nth 0 data) (nth 1 data) (nth 2 data)
545 (plist-get :predicate (nthcdr 3 data)))))
3b067af1 546
2d085307
SM
547;;; Pcomplete's native UI.
548
549;;;###autoload
550(defun pcomplete (&optional interactively)
551 "Support extensible programmable completion.
552To use this function, just bind the TAB key to it, or add it to your
553completion functions list (it should occur fairly early in the list)."
554 (interactive "p")
555 (if (and interactively
556 pcomplete-cycle-completions
557 pcomplete-current-completions
558 (memq last-command '(pcomplete
559 pcomplete-expand-and-complete
560 pcomplete-reverse)))
561 (progn
d355a0b7 562 (delete-char (- pcomplete-last-completion-length))
2d085307
SM
563 (if (eq this-command 'pcomplete-reverse)
564 (progn
0667de21
SM
565 (push (car (last pcomplete-current-completions))
566 pcomplete-current-completions)
2d085307
SM
567 (setcdr (last pcomplete-current-completions 2) nil))
568 (nconc pcomplete-current-completions
569 (list (car pcomplete-current-completions)))
570 (setq pcomplete-current-completions
571 (cdr pcomplete-current-completions)))
572 (pcomplete-insert-entry pcomplete-last-completion-stub
573 (car pcomplete-current-completions)
574 nil pcomplete-last-completion-raw))
575 (setq pcomplete-current-completions nil
576 pcomplete-last-completion-raw nil)
577 (catch 'pcompleted
578 (let* ((pcomplete-stub)
579 pcomplete-seen pcomplete-norm-func
580 pcomplete-args pcomplete-last pcomplete-index
581 (pcomplete-autolist pcomplete-autolist)
582 (pcomplete-suffix-list pcomplete-suffix-list)
583 (completions (pcomplete-completions))
584 (result (pcomplete-do-complete pcomplete-stub completions)))
585 (and result
586 (not (eq (car result) 'listed))
587 (cdr result)
588 (pcomplete-insert-entry pcomplete-stub (cdr result)
589 (memq (car result)
590 '(sole shortest))
591 pcomplete-last-completion-raw))))))
592
affbf647
GM
593;;;###autoload
594(defun pcomplete-reverse ()
595 "If cycling completion is in use, cycle backwards."
596 (interactive)
597 (call-interactively 'pcomplete))
598
599;;;###autoload
600(defun pcomplete-expand-and-complete ()
601 "Expand the textual value of the current argument.
602This will modify the current buffer."
603 (interactive)
604 (let ((pcomplete-expand-before-complete t))
605 (pcomplete)))
606
607;;;###autoload
608(defun pcomplete-continue ()
609 "Complete without reference to any cycling completions."
610 (interactive)
611 (setq pcomplete-current-completions nil
612 pcomplete-last-completion-raw nil)
613 (call-interactively 'pcomplete))
614
615;;;###autoload
616(defun pcomplete-expand ()
617 "Expand the textual value of the current argument.
618This will modify the current buffer."
619 (interactive)
620 (let ((pcomplete-expand-before-complete t)
621 (pcomplete-expand-only-p t))
622 (pcomplete)
623 (when (and pcomplete-current-completions
3b067af1 624 (> (length pcomplete-current-completions) 0)) ;??
d355a0b7 625 (delete-char (- pcomplete-last-completion-length))
affbf647
GM
626 (while pcomplete-current-completions
627 (unless (pcomplete-insert-entry
628 "" (car pcomplete-current-completions) t
3b067af1 629 pcomplete-last-completion-raw)
150158c4 630 (insert-and-inherit pcomplete-termination-string))
affbf647
GM
631 (setq pcomplete-current-completions
632 (cdr pcomplete-current-completions))))))
633
634;;;###autoload
635(defun pcomplete-help ()
636 "Display any help information relative to the current argument."
637 (interactive)
638 (let ((pcomplete-show-help t))
639 (pcomplete)))
640
641;;;###autoload
642(defun pcomplete-list ()
643 "Show the list of possible completions for the current argument."
644 (interactive)
645 (when (and pcomplete-cycle-completions
646 pcomplete-current-completions
647 (eq last-command 'pcomplete-argument))
d355a0b7 648 (delete-char (- pcomplete-last-completion-length))
affbf647
GM
649 (setq pcomplete-current-completions nil
650 pcomplete-last-completion-raw nil))
651 (let ((pcomplete-show-list t))
652 (pcomplete)))
653
654;;; Internal Functions:
655
656;; argument handling
affbf647
GM
657(defun pcomplete-arg (&optional index offset)
658 "Return the textual content of the INDEXth argument.
659INDEX is based from the current processing position. If INDEX is
660positive, values returned are closer to the command argument; if
661negative, they are closer to the last argument. If the INDEX is
662outside of the argument list, nil is returned. The default value for
663INDEX is 0, meaning the current argument being examined.
664
665The special indices `first' and `last' may be used to access those
666parts of the list.
667
668The OFFSET argument is added to/taken away from the index that will be
669used. This is really only useful with `first' and `last', for
670accessing absolute argument positions."
671 (setq index
672 (if (eq index 'first)
673 0
674 (if (eq index 'last)
675 pcomplete-last
676 (- pcomplete-index (or index 0)))))
677 (if offset
678 (setq index (+ index offset)))
679 (nth index pcomplete-args))
680
681(defun pcomplete-begin (&optional index offset)
682 "Return the beginning position of the INDEXth argument.
683See the documentation for `pcomplete-arg'."
684 (setq index
685 (if (eq index 'first)
686 0
687 (if (eq index 'last)
688 pcomplete-last
689 (- pcomplete-index (or index 0)))))
690 (if offset
691 (setq index (+ index offset)))
692 (nth index pcomplete-begins))
693
694(defsubst pcomplete-actual-arg (&optional index offset)
695 "Return the actual text representation of the last argument.
21a2e05d 696This is different from `pcomplete-arg', which returns the textual value
affbf647
GM
697that the last argument evaluated to. This function returns what the
698user actually typed in."
699 (buffer-substring (pcomplete-begin index offset) (point)))
700
701(defsubst pcomplete-next-arg ()
702 "Move the various pointers to the next argument."
703 (setq pcomplete-index (1+ pcomplete-index)
704 pcomplete-stub (pcomplete-arg))
705 (if (> pcomplete-index pcomplete-last)
706 (progn
707 (message "No completions")
708 (throw 'pcompleted nil))))
709
710(defun pcomplete-command-name ()
711 "Return the command name of the first argument."
712 (file-name-nondirectory (pcomplete-arg 'first)))
713
714(defun pcomplete-match (regexp &optional index offset start)
715 "Like `string-match', but on the current completion argument."
716 (let ((arg (pcomplete-arg (or index 1) offset)))
717 (if arg
718 (string-match regexp arg start)
719 (throw 'pcompleted nil))))
720
721(defun pcomplete-match-string (which &optional index offset)
21a2e05d 722 "Like `match-string', but on the current completion argument."
affbf647
GM
723 (let ((arg (pcomplete-arg (or index 1) offset)))
724 (if arg
725 (match-string which arg)
726 (throw 'pcompleted nil))))
727
728(defalias 'pcomplete-match-beginning 'match-beginning)
729(defalias 'pcomplete-match-end 'match-end)
730
731(defsubst pcomplete--test (pred arg)
732 "Perform a programmable completion predicate match."
733 (and pred
734 (cond ((eq pred t) t)
735 ((functionp pred)
736 (funcall pred arg))
737 ((stringp pred)
738 (string-match (concat "^" pred "$") arg)))
739 pred))
740
741(defun pcomplete-test (predicates &optional index offset)
742 "Predicates to test the current programmable argument with."
743 (let ((arg (pcomplete-arg (or index 1) offset)))
744 (unless (null predicates)
745 (if (not (listp predicates))
746 (pcomplete--test predicates arg)
747 (let ((pred predicates)
748 found)
749 (while (and pred (not found))
750 (setq found (pcomplete--test (car pred) arg)
751 pred (cdr pred)))
752 found)))))
753
754(defun pcomplete-parse-buffer-arguments ()
755 "Parse whitespace separated arguments in the current region."
756 (let ((begin (point-min))
757 (end (point-max))
758 begins args)
759 (save-excursion
760 (goto-char begin)
761 (while (< (point) end)
762 (skip-chars-forward " \t\n")
0667de21 763 (push (point) begins)
affbf647 764 (skip-chars-forward "^ \t\n")
0667de21
SM
765 (push (buffer-substring-no-properties
766 (car begins) (point))
767 args))
768 (cons (nreverse args) (nreverse begins)))))
affbf647
GM
769
770;;;###autoload
771(defun pcomplete-comint-setup (completef-sym)
772 "Setup a comint buffer to use pcomplete.
773COMPLETEF-SYM should be the symbol where the
21a2e05d
JB
774dynamic-complete-functions are kept. For comint mode itself,
775this is `comint-dynamic-complete-functions'."
affbf647
GM
776 (set (make-local-variable 'pcomplete-parse-arguments-function)
777 'pcomplete-parse-comint-arguments)
1c6d8c76
SM
778 (add-hook 'completion-at-point-functions
779 'pcomplete-completions-at-point nil 'local)
48feed59
SM
780 (set (make-local-variable completef-sym)
781 (copy-sequence (symbol-value completef-sym)))
208384c5 782 (let* ((funs (symbol-value completef-sym))
8fff8daa
SM
783 (elem (or (memq 'comint-filename-completion funs)
784 (memq 'shell-filename-completion funs)
785 (memq 'shell-dynamic-complete-filename funs)
70f44c65 786 (memq 'comint-dynamic-complete-filename funs))))
affbf647
GM
787 (if elem
788 (setcar elem 'pcomplete)
22eb1d41 789 (add-to-list completef-sym 'pcomplete))))
affbf647
GM
790
791;;;###autoload
792(defun pcomplete-shell-setup ()
3b067af1 793 "Setup `shell-mode' to use pcomplete."
2d085307 794 ;; FIXME: insufficient
48feed59 795 (pcomplete-comint-setup 'comint-dynamic-complete-functions))
affbf647 796
004a00f4
DN
797(declare-function comint-bol "comint" (&optional arg))
798
affbf647
GM
799(defun pcomplete-parse-comint-arguments ()
800 "Parse whitespace separated arguments in the current region."
801 (let ((begin (save-excursion (comint-bol nil) (point)))
802 (end (point))
803 begins args)
804 (save-excursion
805 (goto-char begin)
806 (while (< (point) end)
807 (skip-chars-forward " \t\n")
48feed59 808 (push (point) begins)
b3fd59bd
SM
809 (while
810 (progn
811 (skip-chars-forward "^ \t\n\\")
812 (when (eq (char-after) ?\\)
813 (forward-char 1)
814 (unless (eolp)
815 (forward-char 1)
816 t))))
48feed59
SM
817 (push (buffer-substring-no-properties (car begins) (point))
818 args))
819 (cons (nreverse args) (nreverse begins)))))
b3fd59bd
SM
820(make-obsolete 'pcomplete-parse-comint-arguments
821 'comint-parse-pcomplete-arguments "24.1")
affbf647
GM
822
823(defun pcomplete-parse-arguments (&optional expand-p)
824 "Parse the command line arguments. Most completions need this info."
825 (let ((results (funcall pcomplete-parse-arguments-function)))
826 (when results
827 (setq pcomplete-args (or (car results) (list ""))
828 pcomplete-begins (or (cdr results) (list (point)))
829 pcomplete-last (1- (length pcomplete-args))
830 pcomplete-index 0
831 pcomplete-stub (pcomplete-arg 'last))
832 (let ((begin (pcomplete-begin 'last)))
833 (if (and pcomplete-cycle-completions
48feed59 834 (listp pcomplete-stub) ;??
affbf647 835 (not pcomplete-expand-only-p))
48feed59 836 (let* ((completions pcomplete-stub) ;??
affbf647
GM
837 (common-stub (car completions))
838 (c completions)
839 (len (length common-stub)))
840 (while (and c (> len 0))
841 (while (and (> len 0)
842 (not (string=
843 (substring common-stub 0 len)
844 (substring (car c) 0
845 (min (length (car c))
846 len)))))
847 (setq len (1- len)))
848 (setq c (cdr c)))
849 (setq pcomplete-stub (substring common-stub 0 len)
850 pcomplete-autolist t)
851 (when (and begin (not pcomplete-show-list))
852 (delete-region begin (point))
853 (pcomplete-insert-entry "" pcomplete-stub))
854 (throw 'pcomplete-completions completions))
855 (when expand-p
856 (if (stringp pcomplete-stub)
857 (when begin
858 (delete-region begin (point))
859 (insert-and-inherit pcomplete-stub))
860 (if (and (listp pcomplete-stub)
861 pcomplete-expand-only-p)
862 ;; this is for the benefit of `pcomplete-expand'
863 (setq pcomplete-last-completion-length (- (point) begin)
864 pcomplete-current-completions pcomplete-stub)
865 (error "Cannot expand argument"))))
866 (if pcomplete-expand-only-p
867 (throw 'pcompleted t)
868 pcomplete-args))))))
869
870(defun pcomplete-quote-argument (filename)
871 "Return FILENAME with magic characters quoted.
872Magic characters are those in `pcomplete-arg-quote-list'."
873 (if (null pcomplete-arg-quote-list)
874 filename
2d085307
SM
875 (let ((index 0))
876 (mapconcat (lambda (c)
877 (prog1
878 (or (run-hook-with-args-until-success
879 'pcomplete-quote-arg-hook filename index)
880 (when (memq c pcomplete-arg-quote-list)
1802e444 881 (string ?\\ c))
2d085307
SM
882 (char-to-string c))
883 (setq index (1+ index))))
884 filename
885 ""))))
affbf647
GM
886
887;; file-system completion lists
888
889(defsubst pcomplete-dirs-or-entries (&optional regexp predicate)
890 "Return either directories, or qualified entries."
3b067af1
SM
891 (pcomplete-entries
892 nil
1c6d8c76
SM
893 (lambda (f)
894 (or (file-directory-p f)
895 (and (or (null regexp) (string-match regexp f))
896 (or (null predicate) (funcall predicate f)))))))
897
898(defun pcomplete--entries (&optional regexp predicate)
899 "Like `pcomplete-entries' but without env-var handling."
900 (let* ((ign-pred
901 (when (or pcomplete-file-ignore pcomplete-dir-ignore)
902 ;; Capture the dynbound value for later use.
903 (let ((file-ignore pcomplete-file-ignore)
904 (dir-ignore pcomplete-dir-ignore))
905 (lambda (file)
906 (not
907 (if (eq (aref file (1- (length file))) ?/)
908 (and dir-ignore (string-match dir-ignore file))
909 (and file-ignore (string-match file-ignore file))))))))
910 (reg-pred (if regexp (lambda (file) (string-match regexp file))))
911 (pred (cond
912 ((null (or ign-pred reg-pred)) predicate)
913 ((null (or ign-pred predicate)) reg-pred)
914 ((null (or reg-pred predicate)) ign-pred)
915 (t (lambda (f)
916 (and (or (null reg-pred) (funcall reg-pred f))
917 (or (null ign-pred) (funcall ign-pred f))
918 (or (null predicate) (funcall predicate f))))))))
919 (lambda (s p a)
920 (if (and (eq a 'metadata) pcomplete-compare-entry-function)
921 `(metadata (cycle-sort-function
922 . ,(lambda (comps)
923 (sort comps pcomplete-compare-entry-function)))
924 ,@(cdr (completion-file-name-table s p a)))
925 (let ((completion-ignored-extensions nil))
926 (completion-table-with-predicate
32c1fffd 927 #'comint-completion-file-name-table pred 'strict s p a))))))
1c6d8c76
SM
928
929(defconst pcomplete--env-regexp
930 "\\(?:\\`\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\(\\$\\(?:{\\([^}]+\\)}\\|\\(?2:[[:alnum:]_]+\\)\\)\\)")
affbf647
GM
931
932(defun pcomplete-entries (&optional regexp predicate)
933 "Complete against a list of directory candidates.
affbf647
GM
934If REGEXP is non-nil, it is a regular expression used to refine the
935match (files not matching the REGEXP will be excluded).
936If PREDICATE is non-nil, it will also be used to refine the match
937\(files for which the PREDICATE returns nil will be excluded).
430190ba 938If no directory information can be extracted from the completed
21a2e05d 939component, `default-directory' is used as the basis for completion."
1c6d8c76
SM
940 ;; FIXME: The old code did env-var expansion here, so we reproduce this
941 ;; behavior for now, but really env-var handling should be performed globally
942 ;; rather than here since it also applies to non-file arguments.
943 (let ((table (pcomplete--entries regexp predicate)))
944 (lambda (string pred action)
945 (let ((strings nil)
946 (orig-length (length string)))
947 ;; Perform env-var expansion.
948 (while (string-match pcomplete--env-regexp string)
949 (push (substring string 0 (match-beginning 1)) strings)
950 (push (getenv (match-string 2 string)) strings)
951 (setq string (substring string (match-end 1))))
952 (if (not (and strings
953 (or (eq action t)
954 (eq (car-safe action) 'boundaries))))
955 (let ((newstring
956 (mapconcat 'identity (nreverse (cons string strings)) "")))
957 ;; FIXME: We could also try to return unexpanded envvars.
958 (complete-with-action action table newstring pred))
959 (let* ((envpos (apply #'+ (mapcar #' length strings)))
960 (newstring
961 (mapconcat 'identity (nreverse (cons string strings)) ""))
962 (bounds (completion-boundaries newstring table pred
963 (or (cdr-safe action) ""))))
964 (if (>= (car bounds) envpos)
965 ;; The env-var is "out of bounds".
966 (if (eq action t)
967 (complete-with-action action table newstring pred)
968 (list* 'boundaries
969 (+ (car bounds) (- orig-length (length newstring)))
970 (cdr bounds)))
971 ;; The env-var is in the file bounds.
972 (if (eq action t)
973 (let ((comps (complete-with-action
974 action table newstring pred))
975 (len (- envpos (car bounds))))
976 ;; Strip the part of each completion that's actually
977 ;; coming from the env-var.
978 (mapcar (lambda (s) (substring s len)) comps))
979 (list* 'boundaries
980 (+ envpos (- orig-length (length newstring)))
981 (cdr bounds))))))))))
affbf647
GM
982
983(defsubst pcomplete-all-entries (&optional regexp predicate)
984 "Like `pcomplete-entries', but doesn't ignore any entries."
985 (let (pcomplete-file-ignore
986 pcomplete-dir-ignore)
987 (pcomplete-entries regexp predicate)))
988
989(defsubst pcomplete-dirs (&optional regexp)
990 "Complete amongst a list of directories."
991 (pcomplete-entries regexp 'file-directory-p))
992
affbf647
GM
993;; generation of completion lists
994
995(defun pcomplete-find-completion-function (command)
996 "Find the completion function to call for the given COMMAND."
997 (let ((sym (intern-soft
998 (concat "pcomplete/" (symbol-name major-mode) "/" command))))
999 (unless sym
1000 (setq sym (intern-soft (concat "pcomplete/" command))))
1001 (and sym (fboundp sym) sym)))
1002
1003(defun pcomplete-completions ()
1004 "Return a list of completions for the current argument position."
1005 (catch 'pcomplete-completions
1006 (when (pcomplete-parse-arguments pcomplete-expand-before-complete)
1007 (if (= pcomplete-index pcomplete-last)
1008 (funcall pcomplete-command-completion-function)
1009 (let ((sym (or (pcomplete-find-completion-function
1010 (funcall pcomplete-command-name-function))
1011 pcomplete-default-completion-function)))
1012 (ignore
1013 (pcomplete-next-arg)
1014 (funcall sym)))))))
1015
06b60517 1016(defun pcomplete-opt (options &optional prefix _no-ganging _args-follow)
affbf647
GM
1017 "Complete a set of OPTIONS, each beginning with PREFIX (?- by default).
1018PREFIX may be t, in which case no PREFIX character is necessary.
21a2e05d
JB
1019If NO-GANGING is non-nil, each option is separate (-xy is not allowed).
1020If ARGS-FOLLOW is non-nil, then options which take arguments may have
1021the argument appear after a ganged set of options. This is how tar
06b60517
JB
1022behaves, for example.
1023Arguments NO-GANGING and ARGS-FOLLOW are currently ignored."
affbf647
GM
1024 (if (and (= pcomplete-index pcomplete-last)
1025 (string= (pcomplete-arg) "-"))
1026 (let ((len (length options))
1027 (index 0)
1028 char choices)
1029 (while (< index len)
1030 (setq char (aref options index))
1031 (if (eq char ?\()
1032 (let ((result (read-from-string options index)))
1033 (setq index (cdr result)))
1034 (unless (memq char '(?/ ?* ?? ?.))
0667de21 1035 (push (char-to-string char) choices))
affbf647
GM
1036 (setq index (1+ index))))
1037 (throw 'pcomplete-completions
1038 (mapcar
1039 (function
1040 (lambda (opt)
1041 (concat "-" opt)))
1042 (pcomplete-uniqify-list choices))))
1043 (let ((arg (pcomplete-arg)))
1044 (when (and (> (length arg) 1)
1045 (stringp arg)
1046 (eq (aref arg 0) (or prefix ?-)))
1047 (pcomplete-next-arg)
1048 (let ((char (aref arg 1))
1049 (len (length options))
1050 (index 0)
1051 opt-char arg-char result)
1052 (while (< (1+ index) len)
1053 (setq opt-char (aref options index)
1054 arg-char (aref options (1+ index)))
1055 (if (eq arg-char ?\()
1056 (setq result
1057 (read-from-string options (1+ index))
1058 index (cdr result)
1059 result (car result))
1060 (setq result nil))
1061 (when (and (eq char opt-char)
1062 (memq arg-char '(?\( ?/ ?* ?? ?.)))
1063 (if (< pcomplete-index pcomplete-last)
1064 (pcomplete-next-arg)
1065 (throw 'pcomplete-completions
1066 (cond ((eq arg-char ?/) (pcomplete-dirs))
1067 ((eq arg-char ?*) (pcomplete-executables))
1068 ((eq arg-char ??) nil)
1069 ((eq arg-char ?.) (pcomplete-entries))
1070 ((eq arg-char ?\() (eval result))))))
1071 (setq index (1+ index))))))))
1072
1073(defun pcomplete--here (&optional form stub paring form-only)
21a2e05d 1074 "Complete against the current argument, if at the end.
affbf647
GM
1075See the documentation for `pcomplete-here'."
1076 (if (< pcomplete-index pcomplete-last)
1077 (progn
1078 (if (eq paring 0)
1079 (setq pcomplete-seen nil)
1080 (unless (eq paring t)
1081 (let ((arg (pcomplete-arg)))
3b067af1 1082 (when (stringp arg)
0667de21
SM
1083 (push (if paring
1084 (funcall paring arg)
1085 (file-truename arg))
1086 pcomplete-seen)))))
affbf647
GM
1087 (pcomplete-next-arg)
1088 t)
1089 (when pcomplete-show-help
1090 (pcomplete--help)
1091 (throw 'pcompleted t))
1092 (if stub
1093 (setq pcomplete-stub stub))
1094 (if (or (eq paring t) (eq paring 0))
1095 (setq pcomplete-seen nil)
1096 (setq pcomplete-norm-func (or paring 'file-truename)))
1097 (unless form-only
1098 (run-hooks 'pcomplete-try-first-hook))
3b067af1
SM
1099 (throw 'pcomplete-completions
1100 (if (functionp form)
1101 (funcall form)
1102 ;; Old calling convention, might still be used by files
1103 ;; byte-compiled with the older code.
1104 (eval form)))))
affbf647
GM
1105
1106(defmacro pcomplete-here (&optional form stub paring form-only)
21a2e05d 1107 "Complete against the current argument, if at the end.
3b067af1
SM
1108If completion is to be done here, evaluate FORM to generate the completion
1109table which will be used for completion purposes. If STUB is a
affbf647
GM
1110string, use it as the completion stub instead of the default (which is
1111the entire text of the current argument).
1112
1113For an example of when you might want to use STUB: if the current
1114argument text is 'long-path-name/', you don't want the completions
1115list display to be cluttered by 'long-path-name/' appearing at the
1116beginning of every alternative. Not only does this make things less
3b067af1 1117intelligible, but it is also inefficient. Yet, if the completion list
affbf647
GM
1118does not begin with this string for every entry, the current argument
1119won't complete correctly.
1120
1121The solution is to specify a relative stub. It allows you to
1122substitute a different argument from the current argument, almost
1123always for the sake of efficiency.
1124
1125If PARING is nil, this argument will be pared against previous
1126arguments using the function `file-truename' to normalize them.
21a2e05d
JB
1127PARING may be a function, in which case that function is used for
1128normalization. If PARING is t, the argument dealt with by this
1129call will not participate in argument paring. If it is the
1130integer 0, all previous arguments that have been seen will be
1131cleared.
affbf647
GM
1132
1133If FORM-ONLY is non-nil, only the result of FORM will be used to
1134generate the completions list. This means that the hook
1135`pcomplete-try-first-hook' will not be run."
3b067af1
SM
1136 (declare (debug t))
1137 `(pcomplete--here (lambda () ,form) ,stub ,paring ,form-only))
1138
affbf647
GM
1139
1140(defmacro pcomplete-here* (&optional form stub form-only)
1141 "An alternate form which does not participate in argument paring."
3b067af1 1142 (declare (debug t))
5b31b787 1143 `(pcomplete-here ,form ,stub t ,form-only))
affbf647
GM
1144
1145;; display support
1146
1147(defun pcomplete-restore-windows ()
1148 "If the only window change was due to Completions, restore things."
1149 (if pcomplete-last-window-config
1150 (let* ((cbuf (get-buffer "*Completions*"))
1151 (cwin (and cbuf (get-buffer-window cbuf))))
ccb13f4d 1152 (when (window-live-p cwin)
affbf647
GM
1153 (bury-buffer cbuf)
1154 (set-window-configuration pcomplete-last-window-config))))
1155 (setq pcomplete-last-window-config nil
1156 pcomplete-window-restore-timer nil))
1157
1158;; Abstractions so that the code below will work for both Emacs 20 and
1159;; XEmacs 21
1160
a3269bc4
DN
1161(defalias 'pcomplete-event-matches-key-specifier-p
1162 (if (featurep 'xemacs)
1163 'event-matches-key-specifier-p
1164 'eq))
affbf647 1165
2d8e5088
RS
1166(defun pcomplete-read-event (&optional prompt)
1167 (if (fboundp 'read-event)
1168 (read-event prompt)
affbf647
GM
1169 (aref (read-key-sequence prompt) 0)))
1170
affbf647
GM
1171(defun pcomplete-show-completions (completions)
1172 "List in help buffer sorted COMPLETIONS.
1173Typing SPC flushes the help buffer."
3b067af1
SM
1174 (when pcomplete-window-restore-timer
1175 (cancel-timer pcomplete-window-restore-timer)
1176 (setq pcomplete-window-restore-timer nil))
1177 (unless pcomplete-last-window-config
1178 (setq pcomplete-last-window-config (current-window-configuration)))
1179 (with-output-to-temp-buffer "*Completions*"
1180 (display-completion-list completions))
1181 (message "Hit space to flush")
1182 (let (event)
1183 (prog1
1184 (catch 'done
1185 (while (with-current-buffer (get-buffer "*Completions*")
1186 (setq event (pcomplete-read-event)))
1187 (cond
1188 ((pcomplete-event-matches-key-specifier-p event ?\s)
1189 (set-window-configuration pcomplete-last-window-config)
1190 (setq pcomplete-last-window-config nil)
1191 (throw 'done nil))
1192 ((or (pcomplete-event-matches-key-specifier-p event 'tab)
1193 ;; Needed on a terminal
1194 (pcomplete-event-matches-key-specifier-p event 9))
1195 (let ((win (or (get-buffer-window "*Completions*" 0)
1196 (display-buffer "*Completions*"
1197 'not-this-window))))
1198 (with-selected-window win
1199 (if (pos-visible-in-window-p (point-max))
1200 (goto-char (point-min))
1201 (scroll-up))))
1202 (message ""))
1203 (t
1204 (setq unread-command-events (list event))
1205 (throw 'done nil)))))
1206 (if (and pcomplete-last-window-config
1207 pcomplete-restore-window-delay)
1208 (setq pcomplete-window-restore-timer
1209 (run-with-timer pcomplete-restore-window-delay nil
1210 'pcomplete-restore-windows))))))
affbf647
GM
1211
1212;; insert completion at point
1213
1214(defun pcomplete-insert-entry (stub entry &optional addsuffix raw-p)
1215 "Insert a completion entry at point.
1216Returns non-nil if a space was appended at the end."
1217 (let ((here (point)))
1218 (if (not pcomplete-ignore-case)
1219 (insert-and-inherit (if raw-p
1220 (substring entry (length stub))
1221 (pcomplete-quote-argument
1222 (substring entry (length stub)))))
1223 ;; the stub is not quoted at this time, so to determine the
1224 ;; length of what should be in the buffer, we must quote it
48feed59
SM
1225 ;; FIXME: Here we presume that quoting `stub' gives us the exact
1226 ;; text in the buffer before point, which is not guaranteed;
1227 ;; e.g. it is not the case in eshell when completing ${FOO}tm[TAB].
d355a0b7 1228 (delete-char (- (length (pcomplete-quote-argument stub))))
affbf647
GM
1229 ;; if there is already a backslash present to handle the first
1230 ;; character, don't bother quoting it
1231 (when (eq (char-before) ?\\)
1232 (insert-and-inherit (substring entry 0 1))
1233 (setq entry (substring entry 1)))
1234 (insert-and-inherit (if raw-p
1235 entry
1236 (pcomplete-quote-argument entry))))
1237 (let (space-added)
1238 (when (and (not (memq (char-before) pcomplete-suffix-list))
1239 addsuffix)
150158c4 1240 (insert-and-inherit pcomplete-termination-string)
affbf647
GM
1241 (setq space-added t))
1242 (setq pcomplete-last-completion-length (- (point) here)
1243 pcomplete-last-completion-stub stub)
1244 space-added)))
1245
1246;; selection of completions
1247
1248(defun pcomplete-do-complete (stub completions)
1249 "Dynamically complete at point using STUB and COMPLETIONS.
1250This is basically just a wrapper for `pcomplete-stub' which does some
1251extra checking, and munging of the COMPLETIONS list."
1252 (unless (stringp stub)
1253 (message "Cannot complete argument")
1254 (throw 'pcompleted nil))
1255 (if (null completions)
1256 (ignore
1257 (if (and stub (> (length stub) 0))
1258 (message "No completions of %s" stub)
1259 (message "No completions")))
1260 ;; pare it down, if applicable
3b067af1
SM
1261 (when (and pcomplete-use-paring pcomplete-seen)
1262 (setq pcomplete-seen
1263 (mapcar 'directory-file-name pcomplete-seen))
1264 (dolist (p pcomplete-seen)
1265 (add-to-list 'pcomplete-seen
1266 (funcall pcomplete-norm-func p)))
1267 (setq completions
1268 (apply-partially 'completion-table-with-predicate
1269 completions
8fff8daa
SM
1270 (when pcomplete-seen
1271 (lambda (f)
1272 (not (member
1273 (funcall pcomplete-norm-func
1274 (directory-file-name f))
1275 pcomplete-seen))))
3b067af1 1276 'strict)))
affbf647
GM
1277 ;; OK, we've got a list of completions.
1278 (if pcomplete-show-list
3b067af1
SM
1279 ;; FIXME: pay attention to boundaries.
1280 (pcomplete-show-completions (all-completions stub completions))
affbf647
GM
1281 (pcomplete-stub stub completions))))
1282
1283(defun pcomplete-stub (stub candidates &optional cycle-p)
1284 "Dynamically complete STUB from CANDIDATES list.
1285This function inserts completion characters at point by completing
1286STUB from the strings in CANDIDATES. A completions listing may be
1287shown in a help buffer if completion is ambiguous.
1288
1289Returns nil if no completion was inserted.
1290Returns `sole' if completed with the only completion match.
1291Returns `shortest' if completed with the shortest of the matches.
1292Returns `partial' if completed as far as possible with the matches.
1293Returns `listed' if a completion listing was shown.
1294
1295See also `pcomplete-filename'."
1296 (let* ((completion-ignore-case pcomplete-ignore-case)
3b067af1
SM
1297 (completions (all-completions stub candidates))
1298 (entry (try-completion stub candidates))
1299 result)
1300 (cond
1301 ((null entry)
1302 (if (and stub (> (length stub) 0))
1303 (message "No completions of %s" stub)
1304 (message "No completions")))
1305 ((eq entry t)
1306 (setq entry stub)
1307 (message "Sole completion")
1308 (setq result 'sole))
1309 ((= 1 (length completions))
1310 (setq result 'sole))
1311 ((and pcomplete-cycle-completions
1312 (or cycle-p
1313 (not pcomplete-cycle-cutoff-length)
1314 (<= (length completions)
1315 pcomplete-cycle-cutoff-length)))
1316 (let ((bound (car (completion-boundaries stub candidates nil ""))))
1317 (unless (zerop bound)
1318 (setq completions (mapcar (lambda (c) (concat (substring stub 0 bound) c))
1319 completions)))
1320 (setq entry (car completions)
1321 pcomplete-current-completions completions)))
1322 ((and pcomplete-recexact
1323 (string-equal stub entry)
1324 (member entry completions))
1325 ;; It's not unique, but user wants shortest match.
1326 (message "Completed shortest")
1327 (setq result 'shortest))
1328 ((or pcomplete-autolist
1329 (string-equal stub entry))
1330 ;; It's not unique, list possible completions.
1331 ;; FIXME: pay attention to boundaries.
1332 (pcomplete-show-completions completions)
1333 (setq result 'listed))
1334 (t
1335 (message "Partially completed")
1336 (setq result 'partial)))
1337 (cons result entry)))
affbf647
GM
1338
1339;; context sensitive help
1340
1341(defun pcomplete--help ()
1342 "Produce context-sensitive help for the current argument.
21a2e05d 1343If specific documentation can't be given, be generic."
affbf647
GM
1344 (if (and pcomplete-help
1345 (or (and (stringp pcomplete-help)
1346 (fboundp 'Info-goto-node))
1347 (listp pcomplete-help)))
1348 (if (listp pcomplete-help)
8a26c165 1349 (message "%s" (eval pcomplete-help))
affbf647
GM
1350 (save-window-excursion (info))
1351 (switch-to-buffer-other-window "*info*")
1352 (funcall (symbol-function 'Info-goto-node) pcomplete-help))
1353 (if pcomplete-man-function
1354 (let ((cmd (funcall pcomplete-command-name-function)))
1355 (if (and cmd (> (length cmd) 0))
1356 (funcall pcomplete-man-function cmd)))
1357 (message "No context-sensitive help available"))))
1358
1359;; general utilities
1360
affbf647
GM
1361(defun pcomplete-uniqify-list (l)
1362 "Sort and remove multiples in L."
1363 (setq l (sort l 'string-lessp))
1364 (let ((m l))
1365 (while m
1366 (while (and (cdr m)
1367 (string= (car m)
1368 (cadr m)))
1369 (setcdr m (cddr m)))
1370 (setq m (cdr m))))
1371 l)
1372
1373(defun pcomplete-process-result (cmd &rest args)
1374 "Call CMD using `call-process' and return the simplest result."
1375 (with-temp-buffer
1376 (apply 'call-process cmd nil t nil args)
1377 (skip-chars-backward "\n")
1378 (buffer-substring (point-min) (point))))
1379
1380;; create a set of aliases which allow completion functions to be not
1381;; quite so verbose
1382
3b067af1
SM
1383;;; jww (1999-10-20): are these a good idea?
1384;; (defalias 'pc-here 'pcomplete-here)
1385;; (defalias 'pc-test 'pcomplete-test)
1386;; (defalias 'pc-opt 'pcomplete-opt)
1387;; (defalias 'pc-match 'pcomplete-match)
1388;; (defalias 'pc-match-string 'pcomplete-match-string)
1389;; (defalias 'pc-match-beginning 'pcomplete-match-beginning)
1390;; (defalias 'pc-match-end 'pcomplete-match-end)
1391
1392(provide 'pcomplete)
affbf647
GM
1393
1394;;; pcomplete.el ends here