pcomplete.el 52.5 KB
Newer Older
1
;;; pcomplete.el --- programmable completion
Gerd Moellmann's avatar
Gerd Moellmann committed
2

3
;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004
Glenn Morris's avatar
Glenn Morris committed
4
;;   2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
Gerd Moellmann's avatar
Gerd Moellmann committed
5 6

;; Author: John Wiegley <johnw@gnu.org>
7
;; Keywords: processes abbrev
Gerd Moellmann's avatar
Gerd Moellmann committed
8 9 10

;; This file is part of GNU Emacs.

11
;; GNU Emacs is free software: you can redistribute it and/or modify
Gerd Moellmann's avatar
Gerd Moellmann committed
12
;; it under the terms of the GNU General Public License as published by
13 14
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Gerd Moellmann's avatar
Gerd Moellmann committed
15 16 17 18 19 20 21

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

;; You should have received a copy of the GNU General Public License
22
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Gerd Moellmann's avatar
Gerd Moellmann committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

;;; Commentary:

;; This module provides a programmable completion facility using
;; "completion functions".  Each completion function is responsible
;; for producing a list of possible completions relevant to the current
;; argument position.
;;
;; To use pcomplete with shell-mode, for example, you will need the
;; following in your .emacs file:
;;
;;   (add-hook 'shell-mode-hook 'pcomplete-shell-setup)
;;
;; Most of the code below simply provides support mechanisms for
;; writing completion functions.  Completion functions themselves are
;; very easy to write.  They have few requirements beyond those of
;; regular Lisp functions.
;;
;; Consider the following example, which will complete against
;; filenames for the first two arguments, and directories for all
;; remaining arguments:
;;
;;   (defun pcomplete/my-command ()
;;     (pcomplete-here (pcomplete-entries))
;;     (pcomplete-here (pcomplete-entries))
;;     (while (pcomplete-here (pcomplete-dirs))))
;;
;; Here are the requirements for completion functions:
;;
;; @ They must be called "pcomplete/MAJOR-MODE/NAME", or
;;   "pcomplete/NAME".  This is how they are looked up, using the NAME
;;   specified in the command argument (the argument in first
;;   position).
;;
;; @ They must be callable with no arguments.
;;
;; @ Their return value is ignored.  If they actually return normally,
;;   it means no completions were available.
;;
;; @ In order to provide completions, they must throw the tag
63 64 65
;;   `pcomplete-completions'.  The value must be a completion table
;;   (i.e. a table that can be passed to try-completion and friends)
;;   for the final argument.
Gerd Moellmann's avatar
Gerd Moellmann committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
;;
;; @ To simplify completion function logic, the tag `pcompleted' may
;;   be thrown with a value of nil in order to abort the function.  It
;;   means that there were no completions available.
;;
;; When a completion function is called, the variable `pcomplete-args'
;; is in scope, and contains all of the arguments specified on the
;; command line.  The variable `pcomplete-last' is the index of the
;; last argument in that list.
;;
;; The variable `pcomplete-index' is used by the completion code to
;; know which argument the completion function is currently examining.
;; It always begins at 1, meaning the first argument after the command
;; name.
;;
;; To facilitate writing completion logic, a special macro,
;; `pcomplete-here', has been provided which does several things:
;;
;;  1. It will throw `pcompleted' (with a value of nil) whenever
;;     `pcomplete-index' exceeds `pcomplete-last'.
;;
;;  2. It will increment `pcomplete-index' if the final argument has
;;     not been reached yet.
;;
;;  3. It will evaluate the form passed to it, and throw the result
;;     using the `pcomplete-completions' tag, if it is called when
;;     `pcomplete-index' is pointing to the final argument.
;;
;; Sometimes a completion function will want to vary the possible
;; completions for an argument based on the previous one.  To
;; facilitate tests like this, the function `pcomplete-test' and
;; `pcomplete-match' are provided.  Called with one argument, they
;; test the value of the previous command argument.  Otherwise, a
;; relative index may be given as an optional second argument, where 0
;; refers to the current argument, 1 the previous, 2 the one before
;; that, etc.  The symbols `first' and `last' specify absolute
;; offsets.
;;
;; Here is an example which will only complete against directories for
;; the second argument if the first argument is also a directory:
;;
;;   (defun pcomplete/example ()
;;      (pcomplete-here (pcomplete-entries))
;;      (if (pcomplete-test 'file-directory-p)
;;          (pcomplete-here (pcomplete-dirs))
;;        (pcomplete-here (pcomplete-entries))))
;;
;; For generating completion lists based on directory contents, see
;; the functions `pcomplete-entries', `pcomplete-dirs',
;; `pcomplete-executables' and `pcomplete-all-entries'.
;;
;; Consult the documentation for `pcomplete-here' for information
;; about its other arguments.

;;; Code:

122
(eval-when-compile (require 'cl))
Gerd Moellmann's avatar
Gerd Moellmann committed
123 124 125

(defgroup pcomplete nil
  "Programmable completion."
126
  :version "21.1"
Gerd Moellmann's avatar
Gerd Moellmann committed
127 128 129 130 131
  :group 'processes)

;;; User Variables:

(defcustom pcomplete-file-ignore nil
Lute Kamstra's avatar
Lute Kamstra committed
132
  "A regexp of filenames to be disregarded during file completion."
John Wiegley's avatar
John Wiegley committed
133
  :type '(choice regexp (const :tag "None" nil))
Gerd Moellmann's avatar
Gerd Moellmann committed
134 135 136
  :group 'pcomplete)

(defcustom pcomplete-dir-ignore nil
Lute Kamstra's avatar
Lute Kamstra committed
137
  "A regexp of names to be disregarded during directory completion."
John Wiegley's avatar
John Wiegley committed
138
  :type '(choice regexp (const :tag "None" nil))
Gerd Moellmann's avatar
Gerd Moellmann committed
139 140
  :group 'pcomplete)

Juanma Barranquero's avatar
Juanma Barranquero committed
141
(defcustom pcomplete-ignore-case (memq system-type '(ms-dos windows-nt cygwin))
142 143
  ;; FIXME: the doc mentions file-name completion, but the code
  ;; seems to apply it to all completions.
Lute Kamstra's avatar
Lute Kamstra committed
144
  "If non-nil, ignore case when doing filename completion."
Gerd Moellmann's avatar
Gerd Moellmann committed
145 146 147 148
  :type 'boolean
  :group 'pcomplete)

(defcustom pcomplete-autolist nil
Lute Kamstra's avatar
Lute Kamstra committed
149
  "If non-nil, automatically list possibilities on partial completion.
Gerd Moellmann's avatar
Gerd Moellmann committed
150 151 152 153
This mirrors the optional behavior of tcsh."
  :type 'boolean
  :group 'pcomplete)

154
(defcustom pcomplete-suffix-list (list ?/ ?:)
Lute Kamstra's avatar
Lute Kamstra committed
155
  "A list of characters which constitute a proper suffix."
Gerd Moellmann's avatar
Gerd Moellmann committed
156 157 158 159
  :type '(repeat character)
  :group 'pcomplete)

(defcustom pcomplete-recexact nil
Lute Kamstra's avatar
Lute Kamstra committed
160
  "If non-nil, use shortest completion if characters cannot be added.
Gerd Moellmann's avatar
Gerd Moellmann committed
161 162 163 164 165 166 167
This mirrors the optional behavior of tcsh.

A non-nil value is useful if `pcomplete-autolist' is non-nil too."
  :type 'boolean
  :group 'pcomplete)

(defcustom pcomplete-arg-quote-list nil
Lute Kamstra's avatar
Lute Kamstra committed
168
  "List of characters to quote when completing an argument."
Gerd Moellmann's avatar
Gerd Moellmann committed
169 170 171 172 173
  :type '(choice (repeat character)
		 (const :tag "Don't quote" nil))
  :group 'pcomplete)

(defcustom pcomplete-quote-arg-hook nil
Lute Kamstra's avatar
Lute Kamstra committed
174
  "A hook which is run to quote a character within a filename.
Gerd Moellmann's avatar
Gerd Moellmann committed
175 176 177 178 179 180 181 182 183 184
Each function is passed both the filename to be quoted, and the index
to be considered.  If the function wishes to provide an alternate
quoted form, it need only return the replacement string.  If no
function provides a replacement, quoting shall proceed as normal,
using a backslash to quote any character which is a member of
`pcomplete-arg-quote-list'."
  :type 'hook
  :group 'pcomplete)

(defcustom pcomplete-man-function 'man
Lute Kamstra's avatar
Lute Kamstra committed
185
  "A function to that will be called to display a manual page.
Gerd Moellmann's avatar
Gerd Moellmann committed
186 187 188 189 190
It will be passed the name of the command to document."
  :type 'function
  :group 'pcomplete)

(defcustom pcomplete-compare-entry-function 'string-lessp
Lute Kamstra's avatar
Lute Kamstra committed
191
  "This function is used to order file entries for completion.
Gerd Moellmann's avatar
Gerd Moellmann committed
192 193 194 195 196 197 198
The behavior of most all shells is to sort alphabetically."
  :type '(radio (function-item string-lessp)
		(function-item file-newer-than-file-p)
		(function :tag "Other"))
  :group 'pcomplete)

(defcustom pcomplete-help nil
Lute Kamstra's avatar
Lute Kamstra committed
199
  "A string or function (or nil) used for context-sensitive help.
Gerd Moellmann's avatar
Gerd Moellmann committed
200 201 202 203 204 205 206 207 208
If a string, it should name an Info node that will be jumped to.
If non-nil, it must a sexp that will be evaluated, and whose
result will be shown in the minibuffer.
If nil, the function `pcomplete-man-function' will be called with the
current command argument."
  :type '(choice string sexp (const :tag "Use man page" nil))
  :group 'pcomplete)

(defcustom pcomplete-expand-before-complete nil
Lute Kamstra's avatar
Lute Kamstra committed
209
  "If non-nil, expand the current argument before completing it.
Gerd Moellmann's avatar
Gerd Moellmann committed
210 211 212 213 214 215 216 217 218 219 220
This means that typing something such as '$HOME/bi' followed by
\\[pcomplete-argument] will cause the variable reference to be
resolved first, and the resultant value that will be completed against
to be inserted in the buffer.  Note that exactly what gets expanded
and how is entirely up to the behavior of the
`pcomplete-parse-arguments-function'."
  :type 'boolean
  :group 'pcomplete)

(defcustom pcomplete-parse-arguments-function
  'pcomplete-parse-buffer-arguments
Lute Kamstra's avatar
Lute Kamstra committed
221
  "A function to call to parse the current line's arguments.
Gerd Moellmann's avatar
Gerd Moellmann committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
It should be called with no parameters, and with point at the position
of the argument that is to be completed.

It must either return nil, or a cons cell of the form:

  ((ARG...) (BEG-POS...))

The two lists must be identical in length.  The first gives the final
value of each command line argument (which need not match the textual
representation of that argument), and BEG-POS gives the beginning
position of each argument, as it is seen by the user.  The establishes
a relationship between the fully resolved value of the argument, and
the textual representation of the argument."
  :type 'function
  :group 'pcomplete)

(defcustom pcomplete-cycle-completions t
Lute Kamstra's avatar
Lute Kamstra committed
239
  "If non-nil, hitting the TAB key cycles through the completion list.
Gerd Moellmann's avatar
Gerd Moellmann committed
240 241 242 243 244 245 246 247 248 249 250
Typical Emacs behavior is to complete as much as possible, then pause
waiting for further input.  Then if TAB is hit again, show a list of
possible completions.  When `pcomplete-cycle-completions' is non-nil,
it acts more like zsh or 4nt, showing the first maximal match first,
followed by any further matches on each subsequent pressing of the TAB
key.  \\[pcomplete-list] is the key to press if the user wants to see
the list of possible completions."
  :type 'boolean
  :group 'pcomplete)

(defcustom pcomplete-cycle-cutoff-length 5
Lute Kamstra's avatar
Lute Kamstra committed
251
  "If the number of completions is greater than this, don't cycle.
Gerd Moellmann's avatar
Gerd Moellmann committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
This variable is a compromise between the traditional Emacs style of
completion, and the \"cycling\" style.  Basically, if there are more
than this number of completions possible, don't automatically pick the
first one and then expect the user to press TAB to cycle through them.
Typically, when there are a large number of completion possibilities,
the user wants to see them in a list buffer so that they can know what
options are available.  But if the list is small, it means the user
has already entered enough input to disambiguate most of the
possibilities, and therefore they are probably most interested in
cycling through the candidates.  Set this value to nil if you want
cycling to always be enabled."
  :type '(choice integer (const :tag "Always cycle" nil))
  :group 'pcomplete)

(defcustom pcomplete-restore-window-delay 1
Lute Kamstra's avatar
Lute Kamstra committed
267
  "The number of seconds to wait before restoring completion windows.
Gerd Moellmann's avatar
Gerd Moellmann committed
268 269 270 271 272 273 274 275 276 277 278
Once the completion window has been displayed, if the user then goes
on to type something else, that completion window will be removed from
the display (actually, the original window configuration before it was
displayed will be restored), after this many seconds of idle time.  If
set to nil, completion windows will be left on second until the user
removes them manually.  If set to 0, they will disappear immediately
after the user enters a key other than TAB."
  :type '(choice integer (const :tag "Never restore" nil))
  :group 'pcomplete)

(defcustom pcomplete-try-first-hook nil
Lute Kamstra's avatar
Lute Kamstra committed
279
  "A list of functions which are called before completing an argument.
Gerd Moellmann's avatar
Gerd Moellmann committed
280 281 282 283 284
This can be used, for example, for completing things which might apply
to all arguments, such as variable names after a $."
  :type 'hook
  :group 'pcomplete)

285 286 287 288
(defsubst pcomplete-executables (&optional regexp)
  "Complete amongst a list of directories and executables."
  (pcomplete-entries regexp 'file-executable-p))

Gerd Moellmann's avatar
Gerd Moellmann committed
289 290 291 292
(defcustom pcomplete-command-completion-function
  (function
   (lambda ()
     (pcomplete-here (pcomplete-executables))))
Lute Kamstra's avatar
Lute Kamstra committed
293
  "Function called for completing the initial command argument."
Gerd Moellmann's avatar
Gerd Moellmann committed
294 295 296 297
  :type 'function
  :group 'pcomplete)

(defcustom pcomplete-command-name-function 'pcomplete-command-name
Lute Kamstra's avatar
Lute Kamstra committed
298
  "Function called for determining the current command name."
Gerd Moellmann's avatar
Gerd Moellmann committed
299 300 301 302 303 304 305
  :type 'function
  :group 'pcomplete)

(defcustom pcomplete-default-completion-function
  (function
   (lambda ()
     (while (pcomplete-here (pcomplete-entries)))))
Lute Kamstra's avatar
Lute Kamstra committed
306
  "Function called when no completion rule can be found.
Gerd Moellmann's avatar
Gerd Moellmann committed
307 308 309 310
This function is used to generate completions for every argument."
  :type 'function
  :group 'pcomplete)

John Wiegley's avatar
John Wiegley committed
311
(defcustom pcomplete-use-paring t
Lute Kamstra's avatar
Lute Kamstra committed
312
  "If t, pare alternatives that have already been used.
John Wiegley's avatar
John Wiegley committed
313 314 315 316 317 318
If nil, you will always see the completion set of possible options, no
matter which of those options have already been used in previous
command arguments."
  :type 'boolean
  :group 'pcomplete)

319
(defcustom pcomplete-termination-string " "
Lute Kamstra's avatar
Lute Kamstra committed
320
  "A string that is inserted after any completion or expansion.
321 322 323 324 325 326 327 328
This is usually a space character, useful when completing lists of
words separated by spaces.  However, if your list uses a different
separator character, or if the completion occurs in a word that is
already terminated by a character, this variable should be locally
modified to be an empty string, or the desired separation string."
  :type 'string
  :group 'pcomplete)

Gerd Moellmann's avatar
Gerd Moellmann committed
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
;;; Internal Variables:

;; for cycling completion support
(defvar pcomplete-current-completions nil)
(defvar pcomplete-last-completion-length)
(defvar pcomplete-last-completion-stub)
(defvar pcomplete-last-completion-raw)
(defvar pcomplete-last-window-config nil)
(defvar pcomplete-window-restore-timer nil)

(make-variable-buffer-local 'pcomplete-current-completions)
(make-variable-buffer-local 'pcomplete-last-completion-length)
(make-variable-buffer-local 'pcomplete-last-completion-stub)
(make-variable-buffer-local 'pcomplete-last-completion-raw)
(make-variable-buffer-local 'pcomplete-last-window-config)
(make-variable-buffer-local 'pcomplete-window-restore-timer)

;; used for altering pcomplete's behavior.  These global variables
;; should always be nil.
(defvar pcomplete-show-help nil)
(defvar pcomplete-show-list nil)
(defvar pcomplete-expand-only-p nil)

;;; User Functions:

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
;;; Alternative front-end using the standard completion facilities.

;; The way pcomplete-parse-arguments, pcomplete-stub, and
;; pcomplete-quote-argument work only works because of some deep
;; hypothesis about the way the completion work.  Basically, it makes
;; it pretty much impossible to have completion other than
;; prefix-completion.
;;
;; pcomplete--common-quoted-suffix and pcomplete--table-subvert try to
;; work around this difficulty with heuristics, but it's
;; really a hack.

(defvar pcomplete-unquote-argument-function nil)

(defun pcomplete-unquote-argument (s)
  (cond
   (pcomplete-unquote-argument-function
    (funcall pcomplete-unquote-argument-function s))
   ((null pcomplete-arg-quote-list) s)
   (t
    (replace-regexp-in-string "\\\\\\(.\\)" "\\1" s t))))
Gerd Moellmann's avatar
Gerd Moellmann committed
375

376
(defun pcomplete--common-suffix (s1 s2)
377
  (assert (not (or (string-match "\n" s1) (string-match "\n" s2))))
378 379 380 381
  ;; Since S2 is expected to be the "unquoted/expanded" version of S1,
  ;; there shouldn't be any case difference, even if the completion is
  ;; case-insensitive.
  (let ((case-fold-search nil)) ;; pcomplete-ignore-case
382 383 384
    (string-match ".*?\\(.*\\)\n.*\\1\\'" (concat s1 "\n" s2))
    (- (match-end 1) (match-beginning 1))))

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
(defun pcomplete--common-quoted-suffix (s1 s2)
  "Find the common suffix between S1 and S2 where S1 is the expanded S2.
S1 is expected to be the unquoted and expanded version of S1.
Returns (PS1 . PS2), i.e. the shortest prefixes of S1 and S2, such that
S1 = (concat PS1 SS1) and S2 = (concat PS2 SS2) and
SS1 = (unquote SS2)."
  (let* ((cs (pcomplete--common-suffix s1 s2))
         (ss1 (substring s1 (- (length s1) cs)))
         (qss1 (pcomplete-quote-argument ss1))
         qc)
    (if (and (not (equal ss1 qss1))
             (setq qc (pcomplete-quote-argument (substring ss1 0 1)))
             (eq t (compare-strings s2 (- (length s2) cs (length qc) -1)
                                    (- (length s2) cs -1)
                                    qc nil nil)))
        ;; The difference found is just that one char is quoted in S2
        ;; but not in S1, keep looking before this difference.
        (pcomplete--common-quoted-suffix
         (substring s1 0 (- (length s1) cs))
         (substring s2 0 (- (length s2) cs (length qc) -1)))
      (cons (substring s1 0 (- (length s1) cs))
            (substring s2 0 (- (length s2) cs))))))

(defun pcomplete--table-subvert (table s1 s2 string pred action)
409 410 411 412 413 414
  "Completion table that replaces the prefix S1 with S2 in STRING.
When TABLE, S1 and S2 are provided by `apply-partially', the result
is a completion table which completes strings of the form (concat S1 S)
in the same way as TABLE completes strings of the form (concat S2 S)."
  (let* ((str (if (eq t (compare-strings string 0 (length s1) s1 nil nil
                                         completion-ignore-case))
415 416
                  (concat s2 (pcomplete-unquote-argument
                              (substring string (length s1))))))
417 418 419 420 421 422 423
         (res (if str (complete-with-action action table str pred))))
    (when res
      (cond
       ((and (eq (car-safe action) 'boundaries))
        (let ((beg (or (and (eq (car-safe res) 'boundaries) (cadr res)) 0)))
          (list* 'boundaries
                 (max (length s1)
424
                      ;; FIXME: Adjust because of quoting/unquoting.
425 426 427 428 429
                      (+ beg (- (length s1) (length s2))))
                 (and (eq (car-safe res) 'boundaries) (cddr res)))))
       ((stringp res)
        (if (eq t (compare-strings res 0 (length s2) s2 nil nil
                                   completion-ignore-case))
430 431
            (concat s1 (pcomplete-quote-argument
                        (substring res (length s2))))))
432 433 434 435 436 437 438 439 440 441 442 443
       ((eq action t)
        (let ((bounds (completion-boundaries str table pred "")))
          (if (>= (car bounds) (length s2))
              res
            (let ((re (concat "\\`"
                              (regexp-quote (substring s2 (car bounds))))))
              (delq nil
                    (mapcar (lambda (c)
                              (if (string-match re c)
                                  (substring c (match-end 0))))
                            res))))))))))
        
444 445 446
;; I don't think such commands are usable before first setting up buffer-local
;; variables to parse args, so there's no point autoloading it.
;; ;;;###autoload
447 448 449 450
(defun pcomplete-std-complete ()
  "Provide standard completion using pcomplete's completion tables.
Same as `pcomplete' but using the standard completion UI."
  (interactive)
451 452
  ;; FIXME: it only completes the text before point, whereas the
  ;; standard UI may also consider text after point.
453 454 455 456 457 458 459 460 461 462 463 464
  (catch 'pcompleted
    (let* ((pcomplete-stub)
           pcomplete-seen pcomplete-norm-func
           pcomplete-args pcomplete-last pcomplete-index
           (pcomplete-autolist pcomplete-autolist)
           (pcomplete-suffix-list pcomplete-suffix-list)
           ;; Apparently the vars above are global vars modified by
           ;; side-effects, whereas pcomplete-completions is the core
           ;; function that finds the chunk of text to complete
           ;; (returned indirectly in pcomplete-stub) and the set of
           ;; possible completions.
           (completions (pcomplete-completions))
465 466 467 468 469 470 471 472 473 474
           ;; Usually there's some close connection between pcomplete-stub
           ;; and the text before point.  But depending on what
           ;; pcomplete-parse-arguments-function does, that connection
           ;; might not be that close.  E.g. in eshell,
           ;; pcomplete-parse-arguments-function expands envvars.
           ;; 
           ;; Since we use minibuffer-complete, which doesn't know
           ;; pcomplete-stub and works from the buffer's text instead,
           ;; we need to trick minibuffer-complete, into using
           ;; pcomplete-stub without its knowledge.  To that end, we
475
           ;; use pcomplete--table-subvert to construct a completion
476 477 478 479
           ;; table which expects strings using a prefix from the
           ;; buffer's text but internally uses the corresponding
           ;; prefix from pcomplete-stub.
           (beg (max (- (point) (length pcomplete-stub))
480
                     (pcomplete-begin)))
481
           (buftext (buffer-substring beg (point)))
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
           (table
            (if (not (equal pcomplete-stub buftext))
                ;; This isn't always strictly right (e.g. if
                ;; FOO="toto/$FOO", then completion of /$FOO/bar may
                ;; result in something incorrect), but given the lack of
                ;; any other info, it's about as good as it gets, and in
                ;; practice it should work just fine (fingers crossed).
                (let ((prefixes (pcomplete--common-quoted-suffix
                                 pcomplete-stub buftext)))
                  (apply-partially
                   'pcomplete--table-subvert
                   completions
                   (cdr prefixes) (car prefixes)))
              (lexical-let ((completions completions))
                (lambda (string pred action)
                  (let ((res (complete-with-action
                              action completions string pred)))
                    (if (stringp res)
                        (pcomplete-quote-argument res)
501 502 503 504 505 506 507 508 509 510 511 512 513 514
                      res))))))
           (pred
            ;; pare it down, if applicable
            (when (and pcomplete-use-paring pcomplete-seen)
              (setq pcomplete-seen
                    (mapcar (lambda (f)
                              (funcall pcomplete-norm-func
                                       (directory-file-name f)))
                            pcomplete-seen))
              (lambda (f)
                (not (member
                      (funcall pcomplete-norm-func
                               (directory-file-name f))
                      pcomplete-seen))))))
515

516 517 518 519 520 521 522 523 524 525 526 527
      (completion-in-region
       beg (point)
       ;; Add a space at the end of completion.  Use a terminator-regexp
       ;; that never matches since the terminator cannot appear
       ;; within the completion field anyway.
       (if (zerop (length pcomplete-termination-string))
           table
         (apply-partially 'completion-table-with-terminator
                          (cons pcomplete-termination-string
                                "\\`a\\`")
                          table))
       pred))))
528

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
;;; Pcomplete's native UI.

;;;###autoload
(defun pcomplete (&optional interactively)
  "Support extensible programmable completion.
To use this function, just bind the TAB key to it, or add it to your
completion functions list (it should occur fairly early in the list)."
  (interactive "p")
  (if (and interactively
	   pcomplete-cycle-completions
	   pcomplete-current-completions
	   (memq last-command '(pcomplete
				pcomplete-expand-and-complete
				pcomplete-reverse)))
      (progn
	(delete-backward-char pcomplete-last-completion-length)
	(if (eq this-command 'pcomplete-reverse)
	    (progn
547 548
              (push (car (last pcomplete-current-completions))
                    pcomplete-current-completions)
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
	      (setcdr (last pcomplete-current-completions 2) nil))
	  (nconc pcomplete-current-completions
		 (list (car pcomplete-current-completions)))
	  (setq pcomplete-current-completions
		(cdr pcomplete-current-completions)))
	(pcomplete-insert-entry pcomplete-last-completion-stub
                                (car pcomplete-current-completions)
				nil pcomplete-last-completion-raw))
    (setq pcomplete-current-completions nil
	  pcomplete-last-completion-raw nil)
    (catch 'pcompleted
      (let* ((pcomplete-stub)
	     pcomplete-seen pcomplete-norm-func
	     pcomplete-args pcomplete-last pcomplete-index
	     (pcomplete-autolist pcomplete-autolist)
	     (pcomplete-suffix-list pcomplete-suffix-list)
	     (completions (pcomplete-completions))
	     (result (pcomplete-do-complete pcomplete-stub completions)))
	(and result
	     (not (eq (car result) 'listed))
	     (cdr result)
	     (pcomplete-insert-entry pcomplete-stub (cdr result)
				     (memq (car result)
					   '(sole shortest))
				     pcomplete-last-completion-raw))))))

Gerd Moellmann's avatar
Gerd Moellmann committed
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
;;;###autoload
(defun pcomplete-reverse ()
  "If cycling completion is in use, cycle backwards."
  (interactive)
  (call-interactively 'pcomplete))

;;;###autoload
(defun pcomplete-expand-and-complete ()
  "Expand the textual value of the current argument.
This will modify the current buffer."
  (interactive)
  (let ((pcomplete-expand-before-complete t))
    (pcomplete)))

;;;###autoload
(defun pcomplete-continue ()
  "Complete without reference to any cycling completions."
  (interactive)
  (setq pcomplete-current-completions nil
	pcomplete-last-completion-raw nil)
  (call-interactively 'pcomplete))

;;;###autoload
(defun pcomplete-expand ()
  "Expand the textual value of the current argument.
This will modify the current buffer."
  (interactive)
  (let ((pcomplete-expand-before-complete t)
	(pcomplete-expand-only-p t))
    (pcomplete)
    (when (and pcomplete-current-completions
606
	       (> (length pcomplete-current-completions) 0)) ;??
Gerd Moellmann's avatar
Gerd Moellmann committed
607 608 609 610
      (delete-backward-char pcomplete-last-completion-length)
      (while pcomplete-current-completions
	(unless (pcomplete-insert-entry
		 "" (car pcomplete-current-completions) t
611
                 pcomplete-last-completion-raw)
612
	  (insert-and-inherit pcomplete-termination-string))
Gerd Moellmann's avatar
Gerd Moellmann committed
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
	(setq pcomplete-current-completions
	      (cdr pcomplete-current-completions))))))

;;;###autoload
(defun pcomplete-help ()
  "Display any help information relative to the current argument."
  (interactive)
  (let ((pcomplete-show-help t))
    (pcomplete)))

;;;###autoload
(defun pcomplete-list ()
  "Show the list of possible completions for the current argument."
  (interactive)
  (when (and pcomplete-cycle-completions
	     pcomplete-current-completions
	     (eq last-command 'pcomplete-argument))
    (delete-backward-char pcomplete-last-completion-length)
    (setq pcomplete-current-completions nil
	  pcomplete-last-completion-raw nil))
  (let ((pcomplete-show-list t))
    (pcomplete)))

;;; Internal Functions:

;; argument handling

;; for the sake of the bye-compiler, when compiling other files that
;; contain completion functions
(defvar pcomplete-args nil)
(defvar pcomplete-begins nil)
(defvar pcomplete-last nil)
(defvar pcomplete-index nil)
(defvar pcomplete-stub nil)
(defvar pcomplete-seen nil)
(defvar pcomplete-norm-func nil)

(defun pcomplete-arg (&optional index offset)
  "Return the textual content of the INDEXth argument.
INDEX is based from the current processing position.  If INDEX is
positive, values returned are closer to the command argument; if
negative, they are closer to the last argument.  If the INDEX is
outside of the argument list, nil is returned.  The default value for
INDEX is 0, meaning the current argument being examined.

The special indices `first' and `last' may be used to access those
parts of the list.

The OFFSET argument is added to/taken away from the index that will be
used.  This is really only useful with `first' and `last', for
accessing absolute argument positions."
  (setq index
	(if (eq index 'first)
	    0
	  (if (eq index 'last)
	      pcomplete-last
	    (- pcomplete-index (or index 0)))))
  (if offset
      (setq index (+ index offset)))
  (nth index pcomplete-args))

(defun pcomplete-begin (&optional index offset)
  "Return the beginning position of the INDEXth argument.
See the documentation for `pcomplete-arg'."
  (setq index
	(if (eq index 'first)
	    0
	  (if (eq index 'last)
	      pcomplete-last
	    (- pcomplete-index (or index 0)))))
  (if offset
      (setq index (+ index offset)))
  (nth index pcomplete-begins))

(defsubst pcomplete-actual-arg (&optional index offset)
  "Return the actual text representation of the last argument.
689
This is different from `pcomplete-arg', which returns the textual value
Gerd Moellmann's avatar
Gerd Moellmann committed
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
that the last argument evaluated to.  This function returns what the
user actually typed in."
  (buffer-substring (pcomplete-begin index offset) (point)))

(defsubst pcomplete-next-arg ()
  "Move the various pointers to the next argument."
  (setq pcomplete-index (1+ pcomplete-index)
	pcomplete-stub (pcomplete-arg))
  (if (> pcomplete-index pcomplete-last)
      (progn
	(message "No completions")
	(throw 'pcompleted nil))))

(defun pcomplete-command-name ()
  "Return the command name of the first argument."
  (file-name-nondirectory (pcomplete-arg 'first)))

(defun pcomplete-match (regexp &optional index offset start)
  "Like `string-match', but on the current completion argument."
  (let ((arg (pcomplete-arg (or index 1) offset)))
    (if arg
	(string-match regexp arg start)
      (throw 'pcompleted nil))))

(defun pcomplete-match-string (which &optional index offset)
715
  "Like `match-string', but on the current completion argument."
Gerd Moellmann's avatar
Gerd Moellmann committed
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
  (let ((arg (pcomplete-arg (or index 1) offset)))
    (if arg
	(match-string which arg)
      (throw 'pcompleted nil))))

(defalias 'pcomplete-match-beginning 'match-beginning)
(defalias 'pcomplete-match-end 'match-end)

(defsubst pcomplete--test (pred arg)
  "Perform a programmable completion predicate match."
  (and pred
       (cond ((eq pred t) t)
	     ((functionp pred)
	      (funcall pred arg))
	     ((stringp pred)
	      (string-match (concat "^" pred "$") arg)))
       pred))

(defun pcomplete-test (predicates &optional index offset)
  "Predicates to test the current programmable argument with."
  (let ((arg (pcomplete-arg (or index 1) offset)))
    (unless (null predicates)
      (if (not (listp predicates))
	  (pcomplete--test predicates arg)
	(let ((pred predicates)
	      found)
	  (while (and pred (not found))
	    (setq found (pcomplete--test (car pred) arg)
		  pred (cdr pred)))
	  found)))))

(defun pcomplete-parse-buffer-arguments ()
  "Parse whitespace separated arguments in the current region."
  (let ((begin (point-min))
	(end (point-max))
	begins args)
    (save-excursion
      (goto-char begin)
      (while (< (point) end)
	(skip-chars-forward " \t\n")
756
	(push (point) begins)
Gerd Moellmann's avatar
Gerd Moellmann committed
757
	(skip-chars-forward "^ \t\n")
758 759 760 761
	(push (buffer-substring-no-properties
               (car begins) (point))
              args))
      (cons (nreverse args) (nreverse begins)))))
Gerd Moellmann's avatar
Gerd Moellmann committed
762 763 764 765 766

;;;###autoload
(defun pcomplete-comint-setup (completef-sym)
  "Setup a comint buffer to use pcomplete.
COMPLETEF-SYM should be the symbol where the
767 768
dynamic-complete-functions are kept.  For comint mode itself,
this is `comint-dynamic-complete-functions'."
Gerd Moellmann's avatar
Gerd Moellmann committed
769 770
  (set (make-local-variable 'pcomplete-parse-arguments-function)
       'pcomplete-parse-comint-arguments)
771 772
  (set (make-local-variable completef-sym)
       (copy-sequence (symbol-value completef-sym)))
773
  (let* ((funs (symbol-value completef-sym))
774 775
	 (elem (or (memq 'shell-dynamic-complete-filename funs)
		   (memq 'comint-dynamic-complete-filename funs))))
Gerd Moellmann's avatar
Gerd Moellmann committed
776 777
    (if elem
	(setcar elem 'pcomplete)
778
      (add-to-list completef-sym 'pcomplete))))
Gerd Moellmann's avatar
Gerd Moellmann committed
779 780 781

;;;###autoload
(defun pcomplete-shell-setup ()
782
  "Setup `shell-mode' to use pcomplete."
783
  ;; FIXME: insufficient
784
  (pcomplete-comint-setup 'comint-dynamic-complete-functions))
Gerd Moellmann's avatar
Gerd Moellmann committed
785

786 787
(declare-function comint-bol "comint" (&optional arg))

Gerd Moellmann's avatar
Gerd Moellmann committed
788 789 790 791 792 793 794 795 796
(defun pcomplete-parse-comint-arguments ()
  "Parse whitespace separated arguments in the current region."
  (let ((begin (save-excursion (comint-bol nil) (point)))
	(end (point))
	begins args)
    (save-excursion
      (goto-char begin)
      (while (< (point) end)
	(skip-chars-forward " \t\n")
797
	(push (point) begins)
Gerd Moellmann's avatar
Gerd Moellmann committed
798 799 800 801 802 803
	(let ((skip t))
	  (while skip
	    (skip-chars-forward "^ \t\n")
	    (if (eq (char-before) ?\\)
		(skip-chars-forward " \t\n")
	      (setq skip nil))))
804 805 806
	(push (buffer-substring-no-properties (car begins) (point))
              args))
      (cons (nreverse args) (nreverse begins)))))
Gerd Moellmann's avatar
Gerd Moellmann committed
807 808 809 810 811 812 813 814 815 816 817 818

(defun pcomplete-parse-arguments (&optional expand-p)
  "Parse the command line arguments.  Most completions need this info."
  (let ((results (funcall pcomplete-parse-arguments-function)))
    (when results
      (setq pcomplete-args (or (car results) (list ""))
	    pcomplete-begins (or (cdr results) (list (point)))
	    pcomplete-last (1- (length pcomplete-args))
	    pcomplete-index 0
	    pcomplete-stub (pcomplete-arg 'last))
      (let ((begin (pcomplete-begin 'last)))
	(if (and pcomplete-cycle-completions
819
		 (listp pcomplete-stub) ;??
Gerd Moellmann's avatar
Gerd Moellmann committed
820
		 (not pcomplete-expand-only-p))
821
	    (let* ((completions pcomplete-stub) ;??
Gerd Moellmann's avatar
Gerd Moellmann committed
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
		   (common-stub (car completions))
		   (c completions)
		   (len (length common-stub)))
	      (while (and c (> len 0))
		(while (and (> len 0)
			    (not (string=
				  (substring common-stub 0 len)
				  (substring (car c) 0
					     (min (length (car c))
						  len)))))
		  (setq len (1- len)))
		(setq c (cdr c)))
	      (setq pcomplete-stub (substring common-stub 0 len)
		    pcomplete-autolist t)
	      (when (and begin (not pcomplete-show-list))
		(delete-region begin (point))
		(pcomplete-insert-entry "" pcomplete-stub))
	      (throw 'pcomplete-completions completions))
	  (when expand-p
	    (if (stringp pcomplete-stub)
		(when begin
		  (delete-region begin (point))
		  (insert-and-inherit pcomplete-stub))
	      (if (and (listp pcomplete-stub)
		       pcomplete-expand-only-p)
		  ;; this is for the benefit of `pcomplete-expand'
		  (setq pcomplete-last-completion-length (- (point) begin)
			pcomplete-current-completions pcomplete-stub)
		(error "Cannot expand argument"))))
	  (if pcomplete-expand-only-p
	      (throw 'pcompleted t)
	    pcomplete-args))))))

(defun pcomplete-quote-argument (filename)
  "Return FILENAME with magic characters quoted.
Magic characters are those in `pcomplete-arg-quote-list'."
  (if (null pcomplete-arg-quote-list)
      filename
860 861 862 863 864 865 866 867 868 869 870
    (let ((index 0))
      (mapconcat (lambda (c)
                   (prog1
                       (or (run-hook-with-args-until-success
                            'pcomplete-quote-arg-hook filename index)
                           (when (memq c pcomplete-arg-quote-list)
                             (string "\\" c))
                           (char-to-string c))
                     (setq index (1+ index))))
                 filename
                 ""))))
Gerd Moellmann's avatar
Gerd Moellmann committed
871 872 873 874 875

;; file-system completion lists

(defsubst pcomplete-dirs-or-entries (&optional regexp predicate)
  "Return either directories, or qualified entries."
876 877 878 879 880 881 882 883 884
  ;; FIXME: pcomplete-entries doesn't return a list any more.
  (pcomplete-entries
   nil
   (lexical-let ((re regexp)
                 (pred predicate))
     (lambda (f)
       (or (file-directory-p f)
           (and (if (not re) t (string-match re f))
                (if (not pred) t (funcall pred f))))))))
Gerd Moellmann's avatar
Gerd Moellmann committed
885 886 887 888 889 890 891

(defun pcomplete-entries (&optional regexp predicate)
  "Complete against a list of directory candidates.
If REGEXP is non-nil, it is a regular expression used to refine the
match (files not matching the REGEXP will be excluded).
If PREDICATE is non-nil, it will also be used to refine the match
\(files for which the PREDICATE returns nil will be excluded).
892
If no directory information can be extracted from the completed
893
component, `default-directory' is used as the basis for completion."
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
  ;; FIXME: obey pcomplete-file-ignore and pcomplete-dir-ignore.
  ;; FIXME: obey pcomplete-compare-entry-function (tho only if there
  ;; are less than pcomplete-cycle-cutoff-length completions).
  ;; FIXME: expand envvars?  shouldn't this be done globally instead?
  (let* ((reg-pred (when regexp
                     (lexical-let ((re regexp))
                       (lambda (f)
                         ;; (let ((name (file-name-nondirectory f)))
                         ;;   (if (zerop (length name))
                         ;;       (setq name (file-name-as-directory
                         ;;                   (file-name-nondirectory
                         ;;                    (directory-file-name f)))))
                         ;;   (string-match re name))
                         (string-match re f)))))
         (pred (cond
                ((null predicate) reg-pred)
                ((null reg-pred) predicate)
                (t (lexical-let ((predicate predicate)
                                 (reg-pred reg-pred))
                     (lambda (f)
                       (and (funcall predicate f)
                            (funcall reg-pred f)))))))
         (fun
          (lexical-let ((pred pred)
                        (dir default-directory))
            (lambda (s p a)
              ;; Remember the default-directory that was active when we built
              ;; the completion table.
              (let ((default-directory dir)
                    ;; The old code used only file-name-all-completions
                    ;; which ignores completion-ignored-extensions.
                    (completion-ignored-extensions nil))
                (completion-table-with-predicate
                 'completion-file-name-table pred 'strict s p a)))))
         ;; Indirect through a symbol rather than returning a lambda
         ;; expression, so as to help catch bugs where the caller
         ;; might treat the lambda expression as a list of completions.
         (sym (make-symbol "pcomplete-read-file-name-internal")))
    (fset sym fun)
    sym))
Gerd Moellmann's avatar
Gerd Moellmann committed
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970

(defsubst pcomplete-all-entries (&optional regexp predicate)
  "Like `pcomplete-entries', but doesn't ignore any entries."
  (let (pcomplete-file-ignore
	pcomplete-dir-ignore)
    (pcomplete-entries regexp predicate)))

(defsubst pcomplete-dirs (&optional regexp)
  "Complete amongst a list of directories."
  (pcomplete-entries regexp 'file-directory-p))

;; generation of completion lists

(defun pcomplete-find-completion-function (command)
  "Find the completion function to call for the given COMMAND."
  (let ((sym (intern-soft
	      (concat "pcomplete/" (symbol-name major-mode) "/" command))))
    (unless sym
      (setq sym (intern-soft (concat "pcomplete/" command))))
    (and sym (fboundp sym) sym)))

(defun pcomplete-completions ()
  "Return a list of completions for the current argument position."
  (catch 'pcomplete-completions
    (when (pcomplete-parse-arguments pcomplete-expand-before-complete)
      (if (= pcomplete-index pcomplete-last)
	  (funcall pcomplete-command-completion-function)
	(let ((sym (or (pcomplete-find-completion-function
			(funcall pcomplete-command-name-function))
		       pcomplete-default-completion-function)))
	  (ignore
	   (pcomplete-next-arg)
	   (funcall sym)))))))

(defun pcomplete-opt (options &optional prefix no-ganging args-follow)
  "Complete a set of OPTIONS, each beginning with PREFIX (?- by default).
PREFIX may be t, in which case no PREFIX character is necessary.
971 972 973 974
If NO-GANGING is non-nil, each option is separate (-xy is not allowed).
If ARGS-FOLLOW is non-nil, then options which take arguments may have
the argument appear after a ganged set of options.  This is how tar
behaves, for example."
Gerd Moellmann's avatar
Gerd Moellmann committed
975 976 977 978 979 980 981 982 983 984 985
  (if (and (= pcomplete-index pcomplete-last)
	   (string= (pcomplete-arg) "-"))
      (let ((len (length options))
	    (index 0)
	    char choices)
	(while (< index len)
	  (setq char (aref options index))
	  (if (eq char ?\()
	      (let ((result (read-from-string options index)))
		(setq index (cdr result)))
	    (unless (memq char '(?/ ?* ?? ?.))
986
	      (push (char-to-string char) choices))
Gerd Moellmann's avatar
Gerd Moellmann committed
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
	    (setq index (1+ index))))
	(throw 'pcomplete-completions
	       (mapcar
		(function
		 (lambda (opt)
		   (concat "-" opt)))
		(pcomplete-uniqify-list choices))))
    (let ((arg (pcomplete-arg)))
      (when (and (> (length arg) 1)
		 (stringp arg)
		 (eq (aref arg 0) (or prefix ?-)))
	(pcomplete-next-arg)
	(let ((char (aref arg 1))
	      (len (length options))
	      (index 0)
	      opt-char arg-char result)
	  (while (< (1+ index) len)
	    (setq opt-char (aref options index)
		  arg-char (aref options (1+ index)))
	    (if (eq arg-char ?\()
		(setq result
		      (read-from-string options (1+ index))
		      index (cdr result)
		      result (car result))
	      (setq result nil))
	    (when (and (eq char opt-char)
		       (memq arg-char '(?\( ?/ ?* ?? ?.)))
	      (if (< pcomplete-index pcomplete-last)
		  (pcomplete-next-arg)
		(throw 'pcomplete-completions
		       (cond ((eq arg-char ?/) (pcomplete-dirs))
			     ((eq arg-char ?*) (pcomplete-executables))
			     ((eq arg-char ??) nil)
			     ((eq arg-char ?.) (pcomplete-entries))
			     ((eq arg-char ?\() (eval result))))))
	    (setq index (1+ index))))))))

(defun pcomplete--here (&optional form stub paring form-only)
1025
  "Complete against the current argument, if at the end.
Gerd Moellmann's avatar
Gerd Moellmann committed
1026 1027 1028 1029 1030 1031 1032
See the documentation for `pcomplete-here'."
  (if (< pcomplete-index pcomplete-last)
      (progn
	(if (eq paring 0)
	    (setq pcomplete-seen nil)
	  (unless (eq paring t)
	    (let ((arg (pcomplete-arg)))
1033
	      (when (stringp arg)
1034 1035 1036 1037
                (push (if paring
                          (funcall paring arg)
                        (file-truename arg))
                      pcomplete-seen)))))
Gerd Moellmann's avatar
Gerd Moellmann committed
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
	(pcomplete-next-arg)
	t)
    (when pcomplete-show-help
      (pcomplete--help)
      (throw 'pcompleted t))
    (if stub
	(setq pcomplete-stub stub))
    (if (or (eq paring t) (eq paring 0))
	(setq pcomplete-seen nil)
      (setq pcomplete-norm-func (or paring 'file-truename)))
    (unless form-only
      (run-hooks 'pcomplete-try-first-hook))
1050 1051 1052 1053 1054 1055
    (throw 'pcomplete-completions
           (if (functionp form)
               (funcall form)
             ;; Old calling convention, might still be used by files
             ;; byte-compiled with the older code.
             (eval form)))))
Gerd Moellmann's avatar
Gerd Moellmann committed
1056 1057

(defmacro pcomplete-here (&optional form stub paring form-only)
1058
  "Complete against the current argument, if at the end.
1059 1060
If completion is to be done here, evaluate FORM to generate the completion
table which will be used for completion purposes.  If STUB is a
Gerd Moellmann's avatar
Gerd Moellmann committed
1061 1062 1063 1064 1065 1066 1067
string, use it as the completion stub instead of the default (which is
the entire text of the current argument).

For an example of when you might want to use STUB: if the current
argument text is 'long-path-name/', you don't want the completions
list display to be cluttered by 'long-path-name/' appearing at the
beginning of every alternative.  Not only does this make things less
1068
intelligible, but it is also inefficient.  Yet, if the completion list
Gerd Moellmann's avatar
Gerd Moellmann committed
1069 1070 1071 1072 1073 1074 1075 1076 1077
does not begin with this string for every entry, the current argument
won't complete correctly.

The solution is to specify a relative stub.  It allows you to
substitute a different argument from the current argument, almost
always for the sake of efficiency.

If PARING is nil, this argument will be pared against previous
arguments using the function `file-truename' to normalize them.
1078 1079 1080 1081 1082
PARING may be a function, in which case that function is used for
normalization.  If PARING is t, the argument dealt with by this
call will not participate in argument paring.  If it is the
integer 0, all previous arguments that have been seen will be
cleared.
Gerd Moellmann's avatar
Gerd Moellmann committed
1083 1084 1085 1086

If FORM-ONLY is non-nil, only the result of FORM will be used to
generate the completions list.  This means that the hook
`pcomplete-try-first-hook' will not be run."
1087 1088 1089
  (declare (debug t))
  `(pcomplete--here (lambda () ,form) ,stub ,paring ,form-only))

Gerd Moellmann's avatar
Gerd Moellmann committed
1090 1091 1092

(defmacro pcomplete-here* (&optional form stub form-only)
  "An alternate form which does not participate in argument paring."
1093 1094
  (declare (debug t))
  `(pcomplete-here (lambda () ,form) ,stub t ,form-only))
Gerd Moellmann's avatar
Gerd Moellmann committed
1095 1096 1097 1098 1099 1100 1101 1102

;; display support

(defun pcomplete-restore-windows ()
  "If the only window change was due to Completions, restore things."
  (if pcomplete-last-window-config
      (let* ((cbuf (get-buffer "*Completions*"))
	     (cwin (and cbuf (get-buffer-window cbuf))))
1103
	(when (window-live-p cwin)
Gerd Moellmann's avatar
Gerd Moellmann committed
1104 1105 1106 1107 1108 1109 1110 1111
	  (bury-buffer cbuf)
	  (set-window-configuration pcomplete-last-window-config))))
  (setq pcomplete-last-window-config nil
	pcomplete-window-restore-timer nil))

;; Abstractions so that the code below will work for both Emacs 20 and
;; XEmacs 21

1112 1113 1114 1115
(defalias 'pcomplete-event-matches-key-specifier-p
  (if (featurep 'xemacs)
      'event-matches-key-specifier-p
  'eq))
Gerd Moellmann's avatar
Gerd Moellmann committed
1116

1117 1118 1119
(defun pcomplete-read-event (&optional prompt)
  (if (fboundp 'read-event)
      (read-event prompt)
Gerd Moellmann's avatar
Gerd Moellmann committed
1120 1121 1122 1123 1124
    (aref (read-key-sequence prompt) 0)))

(defun pcomplete-show-completions (completions)
  "List in help buffer sorted COMPLETIONS.
Typing SPC flushes the help buffer."
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
  (when pcomplete-window-restore-timer
    (cancel-timer pcomplete-window-restore-timer)
    (setq pcomplete-window-restore-timer nil))
  (unless pcomplete-last-window-config
    (setq pcomplete-last-window-config (current-window-configuration)))
  (with-output-to-temp-buffer "*Completions*"
    (display-completion-list completions))
  (message "Hit space to flush")
  (let (event)
    (prog1
        (catch 'done
          (while (with-current-buffer (get-buffer "*Completions*")
                   (setq event (pcomplete-read-event)))
            (cond
             ((pcomplete-event-matches-key-specifier-p event ?\s)
              (set-window-configuration pcomplete-last-window-config)
              (setq pcomplete-last-window-config nil)
              (throw 'done nil))
             ((or (pcomplete-event-matches-key-specifier-p event 'tab)
                  ;; Needed on a terminal
                  (pcomplete-event-matches-key-specifier-p event 9))
              (let ((win (or (get-buffer-window "*Completions*" 0)
                             (display-buffer "*Completions*"
                                             'not-this-window))))
                (with-selected-window win
                  (if (pos-visible-in-window-p (point-max))
                      (goto-char (point-min))
                    (scroll-up))))
              (message ""))
             (t
              (setq unread-command-events (list event))
              (throw 'done nil)))))
      (if (and pcomplete-last-window-config
               pcomplete-restore-window-delay)
          (setq pcomplete-window-restore-timer
                (run-with-timer pcomplete-restore-window-delay nil
                                'pcomplete-restore-windows))))))
Gerd Moellmann's avatar
Gerd Moellmann committed
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175

;; insert completion at point

(defun pcomplete-insert-entry (stub entry &optional addsuffix raw-p)
  "Insert a completion entry at point.
Returns non-nil if a space was appended at the end."
  (let ((here (point)))
    (if (not pcomplete-ignore-case)
	(insert-and-inherit (if raw-p
				(substring entry (length stub))
			      (pcomplete-quote-argument
			       (substring entry (length stub)))))
      ;; the stub is not quoted at this time, so to determine the
      ;; length of what should be in the buffer, we must quote it
1176 1177 1178
      ;; FIXME: Here we presume that quoting `stub' gives us the exact
      ;; text in the buffer before point, which is not guaranteed;
      ;; e.g. it is not the case in eshell when completing ${FOO}tm[TAB].
Gerd Moellmann's avatar
Gerd Moellmann committed
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
      (delete-backward-char (length (pcomplete-quote-argument stub)))
      ;; if there is already a backslash present to handle the first
      ;; character, don't bother quoting it
      (when (eq (char-before) ?\\)
	(insert-and-inherit (substring entry 0 1))
	(setq entry (substring entry 1)))
      (insert-and-inherit (if raw-p
			      entry
			    (pcomplete-quote-argument entry))))
    (let (space-added)
      (when (and (not (memq (char-before) pcomplete-suffix-list))
		 addsuffix)
1191
	(insert-and-inherit pcomplete-termination-string)
Gerd Moellmann's avatar
Gerd Moellmann committed
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
	(setq space-added t))
      (setq pcomplete-last-completion-length (- (point) here)
	    pcomplete-last-completion-stub stub)
      space-added)))

;; selection of completions

(defun pcomplete-do-complete (stub completions)
  "Dynamically complete at point using STUB and COMPLETIONS.
This is basically just a wrapper for `pcomplete-stub' which does some
extra checking, and munging of the COMPLETIONS list."
  (unless (stringp stub)
    (message "Cannot complete argument")
    (throw 'pcompleted nil))
  (if (null completions)
      (ignore
       (if (and stub (> (length stub) 0))
	   (message "No completions of %s" stub)
	 (message "No completions")))
    ;; pare it down, if applicable
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    (when (and pcomplete-use-paring pcomplete-seen)
      (setq pcomplete-seen
            (mapcar 'directory-file-name pcomplete-seen))
      (dolist (p pcomplete-seen)
        (add-to-list 'pcomplete-seen
                     (funcall pcomplete-norm-func p)))
      (setq completions
            (apply-partially 'completion-table-with-predicate
                             completions
                             (lambda (f)
                               (not (member
                                     (funcall pcomplete-norm-func
                                              (directory-file-name f))
                                     pcomplete-seen)))
                             'strict)))
Gerd Moellmann's avatar
Gerd Moellmann committed
1227 1228
    ;; OK, we've got a list of completions.
    (if pcomplete-show-list
1229 1230
        ;; FIXME: pay attention to boundaries.
	(pcomplete-show-completions (all-completions stub completions))
Gerd Moellmann's avatar
Gerd Moellmann committed
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
      (pcomplete-stub stub completions))))

(defun pcomplete-stub (stub candidates &optional cycle-p)
  "Dynamically complete STUB from CANDIDATES list.
This function inserts completion characters at point by completing
STUB from the strings in CANDIDATES.  A completions listing may be
shown in a help buffer if completion is ambiguous.

Returns nil if no completion was inserted.
Returns `sole' if completed with the only completion match.
Returns `shortest' if completed with the shortest of the matches.
Returns `partial' if completed as far as possible with the matches.
Returns `listed' if a completion listing was shown.

See also `pcomplete-filename'."
  (let* ((completion-ignore-case pcomplete-ignore-case)
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
	 (completions (all-completions stub candidates))
         (entry (try-completion stub candidates))
         result)
    (cond
     ((null entry)
      (if (and stub (> (length stub) 0))
          (message "No completions of %s" stub)
        (message "No completions")))
     ((eq entry t)
      (setq entry stub)
      (message "Sole completion")
      (setq result 'sole))
     ((= 1 (length completions))
      (setq result 'sole))
     ((and pcomplete-cycle-completions
           (or cycle-p
               (not pcomplete-cycle-cutoff-length)
               (<= (length completions)
                   pcomplete-cycle-cutoff-length)))
      (let ((bound (car (completion-boundaries stub candidates nil ""))))
        (unless (zerop bound)
          (setq completions (mapcar (lambda (c) (concat (substring stub 0 bound) c))
                                    completions)))
        (setq entry (car completions)
              pcomplete-current-completions completions)))
     ((and pcomplete-recexact
           (string-equal stub entry)
           (member entry completions))
      ;; It's not unique, but user wants shortest match.
      (message "Completed shortest")
      (setq result 'shortest))
     ((or pcomplete-autolist
          (string-equal stub entry))
      ;; It's not unique, list possible completions.
      ;; FIXME: pay attention to boundaries.
      (pcomplete-show-completions completions)
      (setq result 'listed))
     (t
      (message "Partially completed")
      (setq result 'partial)))
    (cons result entry)))
Gerd Moellmann's avatar
Gerd Moellmann committed
1288 1289 1290 1291 1292

;; context sensitive help

(defun pcomplete--help ()
  "Produce context-sensitive help for the current argument.
1293
If specific documentation can't be given, be generic."
Gerd Moellmann's avatar
Gerd Moellmann committed
1294 1295 1296 1297 1298
  (if (and pcomplete-help
	   (or (and (stringp pcomplete-help)
		    (fboundp 'Info-goto-node))
	       (listp pcomplete-help)))
      (if (listp pcomplete-help)
Deepak Goel's avatar
Deepak Goel committed
1299
	  (message "%s" (eval pcomplete-help))
Gerd Moellmann's avatar
Gerd Moellmann committed
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
	(save-window-excursion (info))
	(switch-to-buffer-other-window "*info*")
	(funcall (symbol-function 'Info-goto-node) pcomplete-help))
    (if pcomplete-man-function
	(let ((cmd (funcall pcomplete-command-name-function)))
	  (if (and cmd (> (length cmd) 0))
	      (funcall pcomplete-man-function cmd)))
      (message "No context-sensitive help available"))))

;; general utilities

(defun pcomplete-pare-list (l r &optional pred)
  "Destructively remove from list L all elements matching any in list R.
Test is done using `equal'.
If PRED is non-nil, it is a function used for further removal.
Returns the resultant list."
  (while (and l (or (and r (member (car l) r))
		    (and pred
			 (funcall pred (car l)))))
    (setq l (cdr l)))
  (let ((m l))
    (while m
      (while (and (cdr m)
		  (or (and r (member (cadr m) r))
		      (and pred
			   (funcall pred (cadr m)))))
	(setcdr m (cddr m)))
      (setq m (cdr m))))
  l)

(defun pcomplete-uniqify-list (l)
  "Sort and remove multiples in L."
  (setq l (sort l 'string-lessp))
  (let ((m l))
    (while m
      (while (and (cdr m)
		  (string= (car m)
			   (cadr m)))
	(setcdr m (cddr m)))
      (setq m (cdr m))))
  l)

(defun pcomplete-process-result (cmd &rest args)
  "Call CMD using `call-process' and return the simplest result."
  (with-temp-buffer
    (apply 'call-process cmd nil t nil args)
    (skip-chars-backward "\n")
    (buffer-substring (point-min) (point))))

;; create a set of aliases which allow completion functions to be not
;; quite so verbose

1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
;;; jww (1999-10-20): are these a good idea?
;; (defalias 'pc-here 'pcomplete-here)
;; (defalias 'pc-test 'pcomplete-test)
;; (defalias 'pc-opt 'pcomplete-opt)
;; (defalias 'pc-match 'pcomplete-match)
;; (defalias 'pc-match-string 'pcomplete-match-string)
;; (defalias 'pc-match-beginning 'pcomplete-match-beginning)
;; (defalias 'pc-match-end 'pcomplete-match-end)

(provide 'pcomplete)
Gerd Moellmann's avatar
Gerd Moellmann committed
1362

1363
;; arch-tag: ae32ef2d-dbed-4244-8b0f-cf5a2a3b07a4
Gerd Moellmann's avatar
Gerd Moellmann committed
1364
;;; pcomplete.el ends here