*** empty log message ***
[emacs.git] / lisp / complete.el
blob1cdff0d9acd609e530c2754a4f072c246f824527
1 ;;; complete.el --- partial completion mechanism plus other goodies
3 ;; Copyright (C) 1990, 1991, 1992, 1993, 1999, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
6 ;; Author: Dave Gillespie <daveg@synaptics.com>
7 ;; Keywords: abbrev convenience
8 ;; Special thanks to Hallvard Furuseth for his many ideas and contributions.
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
27 ;;; Commentary:
29 ;; Extended completion for the Emacs minibuffer.
31 ;; The basic idea is that the command name or other completable text is
32 ;; divided into words and each word is completed separately, so that
33 ;; "M-x p-b" expands to "M-x print-buffer". If the entry is ambiguous
34 ;; each word is completed as much as possible and then the cursor is
35 ;; left at the first position where typing another letter will resolve
36 ;; the ambiguity.
38 ;; Word separators for this purpose are hyphen, space, and period.
39 ;; These would most likely occur in command names, Info menu items,
40 ;; and file names, respectively. But all word separators are treated
41 ;; alike at all times.
43 ;; This completion package replaces the old-style completer's key
44 ;; bindings for TAB, SPC, RET, and `?'. The old completer is still
45 ;; available on the Meta versions of those keys. If you set
46 ;; PC-meta-flag to nil, the old completion keys will be left alone
47 ;; and the partial completer will use the Meta versions of the keys.
50 ;; Usage: M-x partial-completion-mode. During completable minibuffer entry,
52 ;; TAB means to do a partial completion;
53 ;; SPC means to do a partial complete-word;
54 ;; RET means to do a partial complete-and-exit;
55 ;; ? means to do a partial completion-help.
57 ;; If you set PC-meta-flag to nil, then TAB, SPC, RET, and ? perform
58 ;; original Emacs completions, and M-TAB etc. do partial completion.
59 ;; To do this, put the command,
61 ;; (setq PC-meta-flag nil)
63 ;; in your .emacs file. To load partial completion automatically, put
65 ;; (partial-completion-mode t)
67 ;; in your .emacs file, too. Things will be faster if you byte-compile
68 ;; this file when you install it.
70 ;; As an extra feature, in cases where RET would not normally
71 ;; complete (such as `C-x b'), the M-RET key will always do a partial
72 ;; complete-and-exit. Thus `C-x b f.c RET' will select or create a
73 ;; buffer called "f.c", but `C-x b f.c M-RET' will select the existing
74 ;; buffer whose name matches that pattern (perhaps "filing.c").
75 ;; (PC-meta-flag does not affect this behavior; M-RET used to be
76 ;; undefined in this situation.)
78 ;; The regular M-TAB (lisp-complete-symbol) command also supports
79 ;; partial completion in this package.
81 ;; In addition, this package includes a feature for accessing include
82 ;; files. For example, `C-x C-f <sys/time.h> RET' reads the file
83 ;; /usr/include/sys/time.h. The variable PC-include-file-path is a
84 ;; list of directories in which to search for include files. Completion
85 ;; is supported in include file names.
88 ;;; Code:
90 (defgroup partial-completion nil
91 "Partial Completion of items."
92 :prefix "pc-"
93 :group 'minibuffer
94 :group 'convenience)
96 (defcustom PC-first-char 'find-file
97 "Control how the first character of a string is to be interpreted.
98 If nil, the first character of a string is not taken literally if it is a word
99 delimiter, so that \".e\" matches \"*.e*\".
100 If t, the first character of a string is always taken literally even if it is a
101 word delimiter, so that \".e\" matches \".e*\".
102 If non-nil and non-t, the first character is taken literally only for file name
103 completion."
104 :type '(choice (const :tag "delimiter" nil)
105 (const :tag "literal" t)
106 (other :tag "find-file" find-file))
107 :group 'partial-completion)
109 (defcustom PC-meta-flag t
110 "If non-nil, TAB means PC completion and M-TAB means normal completion.
111 Otherwise, TAB means normal completion and M-TAB means Partial Completion."
112 :type 'boolean
113 :group 'partial-completion)
115 (defcustom PC-word-delimiters "-_. "
116 "A string of characters treated as word delimiters for completion.
117 Some arcane rules:
118 If `]' is in this string, it must come first.
119 If `^' is in this string, it must not come first.
120 If `-' is in this string, it must come first or right after `]'.
121 In other words, if S is this string, then `[S]' must be a valid Emacs regular
122 expression (not containing character ranges like `a-z')."
123 :type 'string
124 :group 'partial-completion)
126 (defcustom PC-include-file-path '("/usr/include" "/usr/local/include")
127 "A list of directories in which to look for include files.
128 If nil, means use the colon-separated path in the variable $INCPATH instead."
129 :type '(repeat directory)
130 :group 'partial-completion)
132 (defcustom PC-disable-includes nil
133 "If non-nil, include-file support in \\[find-file] is disabled."
134 :type 'boolean
135 :group 'partial-completion)
137 (defvar PC-default-bindings t
138 "If non-nil, default partial completion key bindings are suppressed.")
140 (defvar PC-env-vars-alist nil
141 "A list of the environment variable names and values.")
144 (defun PC-bindings (bind)
145 (let ((completion-map minibuffer-local-completion-map)
146 (must-match-map minibuffer-local-must-match-map))
147 (cond ((not bind)
148 ;; These bindings are the default bindings. It would be better to
149 ;; restore the previous bindings.
150 (define-key read-expression-map "\e\t" 'lisp-complete-symbol)
152 (define-key completion-map "\t" 'minibuffer-complete)
153 (define-key completion-map " " 'minibuffer-complete-word)
154 (define-key completion-map "?" 'minibuffer-completion-help)
156 (define-key must-match-map "\t" 'minibuffer-complete)
157 (define-key must-match-map " " 'minibuffer-complete-word)
158 (define-key must-match-map "\r" 'minibuffer-complete-and-exit)
159 (define-key must-match-map "\n" 'minibuffer-complete-and-exit)
160 (define-key must-match-map "?" 'minibuffer-completion-help)
162 (define-key global-map [remap lisp-complete-symbol] nil))
163 (PC-default-bindings
164 (define-key read-expression-map "\e\t" 'PC-lisp-complete-symbol)
166 (define-key completion-map "\t" 'PC-complete)
167 (define-key completion-map " " 'PC-complete-word)
168 (define-key completion-map "?" 'PC-completion-help)
170 (define-key completion-map "\e\t" 'PC-complete)
171 (define-key completion-map "\e " 'PC-complete-word)
172 (define-key completion-map "\e\r" 'PC-force-complete-and-exit)
173 (define-key completion-map "\e\n" 'PC-force-complete-and-exit)
174 (define-key completion-map "\e?" 'PC-completion-help)
176 (define-key must-match-map "\t" 'PC-complete)
177 (define-key must-match-map " " 'PC-complete-word)
178 (define-key must-match-map "\r" 'PC-complete-and-exit)
179 (define-key must-match-map "\n" 'PC-complete-and-exit)
180 (define-key must-match-map "?" 'PC-completion-help)
182 (define-key must-match-map "\e\t" 'PC-complete)
183 (define-key must-match-map "\e " 'PC-complete-word)
184 (define-key must-match-map "\e\r" 'PC-complete-and-exit)
185 (define-key must-match-map "\e\n" 'PC-complete-and-exit)
186 (define-key must-match-map "\e?" 'PC-completion-help)
188 (define-key global-map [remap lisp-complete-symbol] 'PC-lisp-complete-symbol)))))
190 (defvar PC-do-completion-end nil
191 "Internal variable used by `PC-do-completion'.")
193 ;;;###autoload
194 (define-minor-mode partial-completion-mode
195 "Toggle Partial Completion mode.
196 With prefix ARG, turn Partial Completion mode on if ARG is positive.
198 When Partial Completion mode is enabled, TAB (or M-TAB if `PC-meta-flag' is
199 nil) is enhanced so that if some string is divided into words and each word is
200 delimited by a character in `PC-word-delimiters', partial words are completed
201 as much as possible and `*' characters are treated likewise in file names.
203 For example, M-x p-c-m expands to M-x partial-completion-mode since no other
204 command begins with that sequence of characters, and
205 \\[find-file] f_b.c TAB might complete to foo_bar.c if that file existed and no
206 other file in that directory begins with that sequence of characters.
208 Unless `PC-disable-includes' is non-nil, the `<...>' sequence is interpreted
209 specially in \\[find-file]. For example,
210 \\[find-file] <sys/time.h> RET finds the file `/usr/include/sys/time.h'.
211 See also the variable `PC-include-file-path'.
213 Partial Completion mode extends the meaning of `completion-auto-help' (which
214 see), so that if it is neither nil nor t, Emacs shows the `*Completions*'
215 buffer only on the second attempt to complete. That is, if TAB finds nothing
216 to complete, the first TAB just says \"Next char not unique\" and the
217 second TAB brings up the `*Completions*' buffer."
218 :global t :group 'partial-completion
219 ;; Deal with key bindings...
220 (PC-bindings partial-completion-mode)
221 ;; Deal with include file feature...
222 (cond ((not partial-completion-mode)
223 (remove-hook 'find-file-not-found-functions 'PC-look-for-include-file))
224 ((not PC-disable-includes)
225 (add-hook 'find-file-not-found-functions 'PC-look-for-include-file)))
226 ;; ... with some underhand redefining.
227 (cond ((not partial-completion-mode)
228 (ad-disable-advice 'read-file-name-internal 'around 'PC-include-file)
229 (ad-activate 'read-file-name-internal))
230 ((not PC-disable-includes)
231 (ad-enable-advice 'read-file-name-internal 'around 'PC-include-file)
232 (ad-activate 'read-file-name-internal)))
233 ;; Adjust the completion selection in *Completion* buffers to the way
234 ;; we work. The default minibuffer completion code only completes the
235 ;; text before point and leaves the text after point alone (new in
236 ;; Emacs-22). In contrast we use the whole text and we even sometimes
237 ;; move point to a place before EOB, to indicate the first position where
238 ;; there's a difference, so when the user uses choose-completion, we have
239 ;; to trick choose-completion into replacing the whole minibuffer text
240 ;; rather than only the text before point. --Stef
241 (funcall
242 (if partial-completion-mode 'add-hook 'remove-hook)
243 'choose-completion-string-functions
244 (lambda (choice buffer mini-p base-size)
245 (if mini-p (goto-char (point-max))
246 ;; Need a similar hack for the non-minibuffer-case -- gm.
247 (when PC-do-completion-end
248 (goto-char PC-do-completion-end)
249 (setq PC-do-completion-end nil)))
250 nil))
251 ;; Build the env-completion and mapping table.
252 (when (and partial-completion-mode (null PC-env-vars-alist))
253 (setq PC-env-vars-alist
254 (mapcar (lambda (string)
255 (let ((d (string-match "=" string)))
256 (cons (concat "$" (substring string 0 d))
257 (and d (substring string (1+ d))))))
258 process-environment))))
261 (defun PC-complete ()
262 "Like minibuffer-complete, but allows \"b--di\"-style abbreviations.
263 For example, \"M-x b--di\" would match `byte-recompile-directory', or any
264 name which consists of three or more words, the first beginning with \"b\"
265 and the third beginning with \"di\".
267 The pattern \"b--d\" is ambiguous for `byte-recompile-directory' and
268 `beginning-of-defun', so this would produce a list of completions
269 just like when normal Emacs completions are ambiguous.
271 Word-delimiters for the purposes of Partial Completion are \"-\", \"_\",
272 \".\", and SPC."
273 (interactive)
274 (if (PC-was-meta-key)
275 (minibuffer-complete)
276 ;; If the previous command was not this one,
277 ;; never scroll, always retry completion.
278 (or (eq last-command this-command)
279 (setq minibuffer-scroll-window nil))
280 (let ((window minibuffer-scroll-window))
281 ;; If there's a fresh completion window with a live buffer,
282 ;; and this command is repeated, scroll that window.
283 (if (and window (window-buffer window)
284 (buffer-name (window-buffer window)))
285 (with-current-buffer (window-buffer window)
286 (if (pos-visible-in-window-p (point-max) window)
287 (set-window-start window (point-min) nil)
288 (scroll-other-window)))
289 (PC-do-completion nil)))))
292 (defun PC-complete-word ()
293 "Like `minibuffer-complete-word', but allows \"b--di\"-style abbreviations.
294 See `PC-complete' for details.
295 This can be bound to other keys, like `-' and `.', if you wish."
296 (interactive)
297 (if (eq (PC-was-meta-key) PC-meta-flag)
298 (if (eq last-command-char ? )
299 (minibuffer-complete-word)
300 (self-insert-command 1))
301 (self-insert-command 1)
302 (if (eobp)
303 (PC-do-completion 'word))))
306 (defun PC-complete-space ()
307 "Like `minibuffer-complete-word', but allows \"b--di\"-style abbreviations.
308 See `PC-complete' for details.
309 This is suitable for binding to other keys which should act just like SPC."
310 (interactive)
311 (if (eq (PC-was-meta-key) PC-meta-flag)
312 (minibuffer-complete-word)
313 (insert " ")
314 (if (eobp)
315 (PC-do-completion 'word))))
318 (defun PC-complete-and-exit ()
319 "Like `minibuffer-complete-and-exit', but allows \"b--di\"-style abbreviations.
320 See `PC-complete' for details."
321 (interactive)
322 (if (eq (PC-was-meta-key) PC-meta-flag)
323 (minibuffer-complete-and-exit)
324 (PC-do-complete-and-exit)))
326 (defun PC-force-complete-and-exit ()
327 "Like `minibuffer-complete-and-exit', but allows \"b--di\"-style abbreviations.
328 See `PC-complete' for details."
329 (interactive)
330 (let ((minibuffer-completion-confirm nil))
331 (PC-do-complete-and-exit)))
333 (defun PC-do-complete-and-exit ()
334 (if (= (point-max) (minibuffer-prompt-end)) ; Duplicate the "bug" that Info-menu relies on...
335 (exit-minibuffer)
336 (let ((flag (PC-do-completion 'exit)))
337 (and flag
338 (if (or (eq flag 'complete)
339 (not minibuffer-completion-confirm))
340 (exit-minibuffer)
341 (PC-temp-minibuffer-message " [Confirm]"))))))
344 (defun PC-completion-help ()
345 "Like `minibuffer-completion-help', but allows \"b--di\"-style abbreviations.
346 See `PC-complete' for details."
347 (interactive)
348 (if (eq (PC-was-meta-key) PC-meta-flag)
349 (minibuffer-completion-help)
350 (PC-do-completion 'help)))
352 (defun PC-was-meta-key ()
353 (or (/= (length (this-command-keys)) 1)
354 (let ((key (aref (this-command-keys) 0)))
355 (if (integerp key)
356 (>= key 128)
357 (not (null (memq 'meta (event-modifiers key))))))))
360 (defvar PC-ignored-extensions 'empty-cache)
361 (defvar PC-delims 'empty-cache)
362 (defvar PC-ignored-regexp nil)
363 (defvar PC-word-failed-flag nil)
364 (defvar PC-delim-regex nil)
365 (defvar PC-ndelims-regex nil)
366 (defvar PC-delims-list nil)
368 (defvar PC-completion-as-file-name-predicate
369 (lambda () minibuffer-completing-file-name)
370 "A function testing whether a minibuffer completion now will work filename-style.
371 The function takes no arguments, and typically looks at the value
372 of `minibuffer-completion-table' and the minibuffer contents.")
374 ;; Returns the sequence of non-delimiter characters that follow regexp in string.
375 (defun PC-chunk-after (string regexp)
376 (if (not (string-match regexp string))
377 (let ((message (format "String %s didn't match regexp %s" string regexp)))
378 (message message)
379 (error message)))
380 (let ((result (substring string (match-end 0))))
381 ;; result may contain multiple chunks
382 (if (string-match PC-delim-regex result)
383 (setq result (substring result 0 (match-beginning 0))))
384 result))
386 (defun test-completion-ignore-case (str table pred)
387 "Like `test-completion', but ignores case when possible."
388 ;; Binding completion-ignore-case to nil ensures, for compatibility with
389 ;; standard completion, that the return value is exactly one of the
390 ;; possibilities. Do this binding only if pred is nil, out of paranoia;
391 ;; perhaps it is safe even if pred is non-nil.
392 (if pred
393 (test-completion str table pred)
394 (let ((completion-ignore-case nil))
395 (test-completion str table pred))))
397 ;; The following function is an attempt to work around two problems:
399 ;; (1) When complete.el was written, (try-completion "" '(("") (""))) used to
400 ;; return the value "". With a change from 2002-07-07 it returns t which caused
401 ;; `PC-lisp-complete-symbol' to fail with a "Wrong type argument: sequencep, t"
402 ;; error. `PC-try-completion' returns STRING in this case.
404 ;; (2) (try-completion "" '((""))) returned t before the above-mentioned change.
405 ;; Since `PC-chop-word' operates on the return value of `try-completion' this
406 ;; case might have provoked a similar error as in (1). `PC-try-completion'
407 ;; returns "" instead. I don't know whether this is a real problem though.
409 ;; Since `PC-try-completion' is not a guaranteed to fix these bugs reliably, you
410 ;; should try to look at the following discussions when you encounter problems:
411 ;; - emacs-pretest-bug ("Partial Completion" starting 2007-02-23),
412 ;; - emacs-devel ("[address-of-OP: Partial completion]" starting 2007-02-24),
413 ;; - emacs-devel ("[address-of-OP: EVAL and mouse selection in *Completions*]"
414 ;; starting 2007-03-05).
415 (defun PC-try-completion (string alist &optional predicate)
416 "Like `try-completion' but return STRING instead of t."
417 (let ((result (try-completion string alist predicate)))
418 (if (eq result t) string result)))
420 (defun PC-do-completion (&optional mode beg end)
421 (or beg (setq beg (minibuffer-prompt-end)))
422 (or end (setq end (point-max)))
423 (let* ((table minibuffer-completion-table)
424 (pred minibuffer-completion-predicate)
425 (filename (funcall PC-completion-as-file-name-predicate))
426 (dirname nil) ; non-nil only if a filename is being completed
427 ;; The following used to be "(dirlength 0)" which caused the erasure of
428 ;; the entire buffer text before `point' when inserting a completion
429 ;; into a buffer.
430 dirlength
431 (str (buffer-substring beg end))
432 (incname (and filename (string-match "<\\([^\"<>]*\\)>?$" str)))
433 (ambig nil)
434 basestr origstr
435 env-on
436 regex
437 p offset
438 (poss nil)
439 helpposs
440 (case-fold-search completion-ignore-case))
442 ;; Check if buffer contents can already be considered complete
443 (if (and (eq mode 'exit)
444 (test-completion str table pred))
445 (progn
446 ;; If completion-ignore-case is non-nil, insert the
447 ;; completion string since that may have a different case.
448 (when completion-ignore-case
449 (setq str (PC-try-completion str table pred))
450 (delete-region beg end)
451 (insert str))
452 'complete)
454 ;; Do substitutions in directory names
455 (and filename
456 (setq basestr (or (file-name-directory str) ""))
457 (setq dirlength (length basestr))
458 ;; Do substitutions in directory names
459 (setq p (substitute-in-file-name basestr))
460 (not (string-equal basestr p))
461 (setq str (concat p (file-name-nondirectory str)))
462 (progn
463 (delete-region beg end)
464 (insert str)
465 (setq end (+ beg (length str)))))
467 ;; Prepare various delimiter strings
468 (or (equal PC-word-delimiters PC-delims)
469 (setq PC-delims PC-word-delimiters
470 PC-delim-regex (concat "[" PC-delims "]")
471 PC-ndelims-regex (concat "[^" PC-delims "]*")
472 PC-delims-list (append PC-delims nil)))
474 ;; Add wildcards if necessary
475 (and filename
476 (let ((dir (file-name-directory str))
477 (file (file-name-nondirectory str))
478 ;; The base dir for file-completion is passed in `predicate'.
479 (default-directory (expand-file-name pred)))
480 (while (and (stringp dir) (not (file-directory-p dir)))
481 (setq dir (directory-file-name dir))
482 (setq file (concat (replace-regexp-in-string
483 PC-delim-regex "*\\&"
484 (file-name-nondirectory dir))
485 "*/" file))
486 (setq dir (file-name-directory dir)))
487 (setq origstr str str (concat dir file))))
489 ;; Look for wildcard expansions in directory name
490 (and filename
491 (string-match "\\*.*/" str)
492 (let ((pat str)
493 ;; The base dir for file-completion is passed in `predicate'.
494 (default-directory (expand-file-name pred))
495 files)
496 (setq p (1+ (string-match "/[^/]*\\'" pat)))
497 (while (setq p (string-match PC-delim-regex pat p))
498 (setq pat (concat (substring pat 0 p)
500 (substring pat p))
501 p (+ p 2)))
502 (setq files (PC-expand-many-files (concat pat "*")))
503 (if files
504 (let ((dir (file-name-directory (car files)))
505 (p files))
506 (while (and (setq p (cdr p))
507 (equal dir (file-name-directory (car p)))))
508 (if p
509 (setq filename nil table nil pred nil
510 ambig t)
511 (delete-region beg end)
512 (setq str (concat dir (file-name-nondirectory str)))
513 (insert str)
514 (setq end (+ beg (length str)))))
515 (if origstr
516 ;; If the wildcards were introduced by us, it's possible
517 ;; that read-file-name-internal (especially our
518 ;; PC-include-file advice) can still find matches for the
519 ;; original string even if we couldn't, so remove the
520 ;; added wildcards.
521 (setq str origstr)
522 (setq filename nil table nil pred nil)))))
524 ;; Strip directory name if appropriate
525 (if filename
526 (if incname
527 (setq basestr (substring str incname)
528 dirname (substring str 0 incname))
529 (setq basestr (file-name-nondirectory str)
530 dirname (file-name-directory str))
531 ;; Make sure str is consistent with its directory and basename
532 ;; parts. This is important on DOZe'NT systems when str only
533 ;; includes a drive letter, like in "d:".
534 (setq str (concat dirname basestr)))
535 (setq basestr str))
537 ;; Convert search pattern to a standard regular expression
538 (setq regex (regexp-quote basestr)
539 offset (if (and (> (length regex) 0)
540 (not (eq (aref basestr 0) ?\*))
541 (or (eq PC-first-char t)
542 (and PC-first-char filename))) 1 0)
543 p offset)
544 (while (setq p (string-match PC-delim-regex regex p))
545 (if (eq (aref regex p) ? )
546 (setq regex (concat (substring regex 0 p)
547 PC-ndelims-regex
548 PC-delim-regex
549 (substring regex (1+ p)))
550 p (+ p (length PC-ndelims-regex) (length PC-delim-regex)))
551 (let ((bump (if (memq (aref regex p)
552 '(?$ ?^ ?\. ?* ?+ ?? ?[ ?] ?\\))
553 -1 0)))
554 (setq regex (concat (substring regex 0 (+ p bump))
555 PC-ndelims-regex
556 (substring regex (+ p bump)))
557 p (+ p (length PC-ndelims-regex) 1)))))
558 (setq p 0)
559 (if filename
560 (while (setq p (string-match "\\\\\\*" regex p))
561 (setq regex (concat (substring regex 0 p)
562 "[^/]*"
563 (substring regex (+ p 2))))))
564 ;;(setq the-regex regex)
565 (setq regex (concat "\\`" regex))
567 (and (> (length basestr) 0)
568 (= (aref basestr 0) ?$)
569 (setq env-on t
570 table PC-env-vars-alist
571 pred nil))
573 ;; Find an initial list of possible completions
574 (if (not (setq p (string-match (concat PC-delim-regex
575 (if filename "\\|\\*" ""))
577 (+ (length dirname) offset))))
579 ;; Minibuffer contains no hyphens -- simple case!
580 (setq poss (all-completions (if env-on
581 basestr str)
582 table
583 pred))
585 ;; Use all-completions to do an initial cull. This is a big win,
586 ;; since all-completions is written in C!
587 (let ((compl (all-completions (if env-on
588 (file-name-nondirectory (substring str 0 p))
589 (substring str 0 p))
590 table
591 pred)))
592 (setq p compl)
593 (while p
594 (and (string-match regex (car p))
595 (progn
596 (set-text-properties 0 (length (car p)) '() (car p))
597 (setq poss (cons (car p) poss))))
598 (setq p (cdr p)))))
600 ;; If table had duplicates, they can be here.
601 (delete-dups poss)
603 ;; Handle completion-ignored-extensions
604 (and filename
605 (not (eq mode 'help))
606 (let ((p2 poss))
608 ;; Build a regular expression representing the extensions list
609 (or (equal completion-ignored-extensions PC-ignored-extensions)
610 (setq PC-ignored-regexp
611 (concat "\\("
612 (mapconcat
613 'regexp-quote
614 (setq PC-ignored-extensions
615 completion-ignored-extensions)
616 "\\|")
617 "\\)\\'")))
619 ;; Check if there are any without an ignored extension.
620 ;; Also ignore `.' and `..'.
621 (setq p nil)
622 (while p2
623 (or (string-match PC-ignored-regexp (car p2))
624 (string-match "\\(\\`\\|/\\)[.][.]?/?\\'" (car p2))
625 (setq p (cons (car p2) p)))
626 (setq p2 (cdr p2)))
628 ;; If there are "good" names, use them
629 (and p (setq poss p))))
631 ;; Now we have a list of possible completions
632 (cond
634 ;; No valid completions found
635 ((null poss)
636 (if (and (eq mode 'word)
637 (not PC-word-failed-flag))
638 (let ((PC-word-failed-flag t))
639 (delete-backward-char 1)
640 (PC-do-completion 'word))
641 (beep)
642 (PC-temp-minibuffer-message (if ambig
643 " [Ambiguous dir name]"
644 (if (eq mode 'help)
645 " [No completions]"
646 " [No match]")))
647 nil))
649 ;; More than one valid completion found
650 ((or (cdr (setq helpposs poss))
651 (memq mode '(help word)))
653 ;; Is the actual string one of the possible completions?
654 (setq p (and (not (eq mode 'help)) poss))
655 (while (and p
656 (not (string-equal (car p) basestr)))
657 (setq p (cdr p)))
658 (and p (null mode)
659 (PC-temp-minibuffer-message " [Complete, but not unique]"))
660 (if (and p
661 (not (and (null mode)
662 (eq this-command last-command))))
665 ;; If ambiguous, try for a partial completion
666 (let ((improved nil)
667 prefix
668 (pt nil)
669 (skip "\\`"))
671 ;; Check if next few letters are the same in all cases
672 (if (and (not (eq mode 'help))
673 (setq prefix (PC-try-completion
674 (PC-chunk-after basestr skip) poss)))
675 (let ((first t) i)
676 ;; Retain capitalization of user input even if
677 ;; completion-ignore-case is set.
678 (if (eq mode 'word)
679 (setq prefix (PC-chop-word prefix basestr)))
680 (goto-char (+ beg (length dirname)))
681 (while (and (progn
682 (setq i 0) ; index into prefix string
683 (while (< i (length prefix))
684 (if (and (< (point) end)
685 (eq (downcase (aref prefix i))
686 (downcase (following-char))))
687 ;; same char (modulo case); no action
688 (forward-char 1)
689 (if (and (< (point) end)
690 (and (looking-at " ")
691 (memq (aref prefix i)
692 PC-delims-list)))
693 ;; replace " " by the actual delimiter
694 (progn
695 (delete-char 1)
696 (insert (substring prefix i (1+ i))))
697 ;; insert a new character
698 (progn
699 (and filename (looking-at "\\*")
700 (progn
701 (delete-char 1)
702 (setq end (1- end))))
703 (setq improved t)
704 (insert (substring prefix i (1+ i)))
705 (setq end (1+ end)))))
706 (setq i (1+ i)))
707 (or pt (setq pt (point)))
708 (looking-at PC-delim-regex))
709 (setq skip (concat skip
710 (regexp-quote prefix)
711 PC-ndelims-regex)
712 prefix (PC-try-completion
713 (PC-chunk-after
714 ;; not basestr, because that does
715 ;; not reflect insertions
716 (buffer-substring
717 (+ beg (length dirname)) end)
718 skip)
719 (mapcar
720 (lambda (x)
721 (when (string-match skip x)
722 (substring x (match-end 0))))
723 poss)))
724 (or (> i 0) (> (length prefix) 0))
725 (or (not (eq mode 'word))
726 (and first (> (length prefix) 0)
727 (setq first nil
728 prefix (substring prefix 0 1))))))
729 (goto-char (if (eq mode 'word) end
730 (or pt beg)))))
732 (if (and (eq mode 'word)
733 (not PC-word-failed-flag))
735 (if improved
737 ;; We changed it... would it be complete without the space?
738 (if (test-completion (buffer-substring 1 (1- end))
739 table pred)
740 (delete-region (1- end) end)))
742 (if improved
744 ;; We changed it... enough to be complete?
745 (and (eq mode 'exit)
746 (test-completion-ignore-case (field-string) table pred))
748 ;; If totally ambiguous, display a list of completions
749 (if (or (eq completion-auto-help t)
750 (and completion-auto-help
751 (eq last-command this-command))
752 (eq mode 'help))
753 (let ((prompt-end (minibuffer-prompt-end)))
754 (with-output-to-temp-buffer "*Completions*"
755 (display-completion-list (sort helpposs 'string-lessp))
756 (with-current-buffer standard-output
757 ;; Record which part of the buffer we are completing
758 ;; so that choosing a completion from the list
759 ;; knows how much old text to replace.
760 ;; This was briefly nil in the non-dirname case.
761 ;; However, if one calls PC-lisp-complete-symbol
762 ;; on "(ne-f" with point on the hyphen, PC offers
763 ;; all completions starting with "(ne", some of
764 ;; which do not match the "-f" part (maybe it
765 ;; should not, but it does). In such cases,
766 ;; completion gets confused trying to figure out
767 ;; how much to replace, so we tell it explicitly
768 ;; (ie, the number of chars in the buffer before beg).
770 ;; Note that choose-completion-string-functions
771 ;; plays around with point.
772 (setq completion-base-size (if dirname
773 dirlength
774 (- beg prompt-end))
775 PC-do-completion-end end))))
776 (PC-temp-minibuffer-message " [Next char not unique]"))
777 nil)))))
779 ;; Only one possible completion
781 (if (and (equal basestr (car poss))
782 (not (and env-on filename)))
783 (if (null mode)
784 (PC-temp-minibuffer-message " [Sole completion]"))
785 (delete-region beg end)
786 (insert (format "%s"
787 (if filename
788 (substitute-in-file-name (concat dirname (car poss)))
789 (car poss)))))
790 t)))))
792 (defun PC-chop-word (new old)
793 (let ((i -1)
794 (j -1))
795 (while (and (setq i (string-match PC-delim-regex old (1+ i)))
796 (setq j (string-match PC-delim-regex new (1+ j)))))
797 (if (and j
798 (or (not PC-word-failed-flag)
799 (setq j (string-match PC-delim-regex new (1+ j)))))
800 (substring new 0 (1+ j))
801 new)))
803 (defvar PC-not-minibuffer nil)
805 (defun PC-temp-minibuffer-message (message)
806 "A Lisp version of `temp_minibuffer_message' from minibuf.c."
807 (cond (PC-not-minibuffer
808 (message message)
809 (sit-for 2)
810 (message ""))
811 ((fboundp 'temp-minibuffer-message)
812 (temp-minibuffer-message message))
814 (let ((point-max (point-max)))
815 (save-excursion
816 (goto-char point-max)
817 (insert message))
818 (let ((inhibit-quit t))
819 (sit-for 2)
820 (delete-region point-max (point-max))
821 (when quit-flag
822 (setq quit-flag nil
823 unread-command-events '(7))))))))
825 ;; Does not need to be buffer-local (?) because only used when one
826 ;; PC-l-c-s immediately follows another.
827 (defvar PC-lisp-complete-end nil
828 "Internal variable used by `PC-lisp-complete-symbol'.")
830 (defun PC-lisp-complete-symbol ()
831 "Perform completion on Lisp symbol preceding point.
832 That symbol is compared against the symbols that exist
833 and any additional characters determined by what is there
834 are inserted.
835 If the symbol starts just after an open-parenthesis,
836 only symbols with function definitions are considered.
837 Otherwise, all symbols with function definitions, values
838 or properties are considered."
839 (interactive)
840 (let* ((end (point))
841 ;; To complete the word under point, rather than just the portion
842 ;; before point, use this:
843 ;;; (save-excursion
844 ;;; (with-syntax-table lisp-mode-syntax-table
845 ;;; (forward-sexp 1)
846 ;;; (point))))
847 (beg (save-excursion
848 (with-syntax-table lisp-mode-syntax-table
849 (backward-sexp 1)
850 (while (= (char-syntax (following-char)) ?\')
851 (forward-char 1))
852 (point))))
853 (minibuffer-completion-table obarray)
854 (minibuffer-completion-predicate
855 (if (eq (char-after (1- beg)) ?\()
856 'fboundp
857 (function (lambda (sym)
858 (or (boundp sym) (fboundp sym)
859 (symbol-plist sym))))))
860 (PC-not-minibuffer t))
861 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-03/msg01211.html
863 ;; This deals with cases like running PC-l-c-s on "M-: (n-f".
864 ;; The first call to PC-l-c-s expands this to "(ne-f", and moves
865 ;; point to the hyphen [1]. If one calls PC-l-c-s immediately after,
866 ;; then without the last-command check, one is offered all
867 ;; completions of "(ne", which is presumably not what one wants.
869 ;; This is arguably (at least, it seems to be the existing intended
870 ;; behaviour) what one _does_ want if point has been explicitly
871 ;; positioned on the hyphen. Note that if PC-do-completion (qv) binds
872 ;; completion-base-size to nil, then completion does not replace the
873 ;; correct amount of text in such cases.
875 ;; Neither of these problems occur when using PC for filenames in the
876 ;; minibuffer, because in that case PC-do-completion is called without
877 ;; an explicit value for END, and so uses (point-max). This is fine for
878 ;; a filename, because the end of the filename must be at the end of
879 ;; the minibuffer. The same is not true for lisp symbols.
881 ;; [1] An alternate fix would be to not move point to the hyphen
882 ;; in such cases, but that would make the behaviour different from
883 ;; that for filenames. It seems PC moves point to the site of the
884 ;; first difference between the possible completions.
886 ;; Alternatively alternatively, maybe end should be computed in
887 ;; the same way as beg. That would change the behaviour though.
888 (if (equal last-command 'PC-lisp-complete-symbol)
889 (PC-do-completion nil beg PC-lisp-complete-end)
890 (if PC-lisp-complete-end
891 (move-marker PC-lisp-complete-end end)
892 (setq PC-lisp-complete-end (copy-marker end t)))
893 (PC-do-completion nil beg end))))
895 (defun PC-complete-as-file-name ()
896 "Perform completion on file names preceding point.
897 Environment vars are converted to their values."
898 (interactive)
899 (let* ((end (point))
900 (beg (if (re-search-backward "[^\\][ \t\n\"\`\'][^ \t\n\"\`\']"
901 (point-min) t)
902 (+ (point) 2)
903 (point-min)))
904 (minibuffer-completion-table 'read-file-name-internal)
905 (minibuffer-completion-predicate "")
906 (PC-not-minibuffer t))
907 (goto-char end)
908 (PC-do-completion nil beg end)))
910 ;; Use the shell to do globbing.
911 ;; This could now use file-expand-wildcards instead.
913 (defun PC-expand-many-files (name)
914 (with-current-buffer (generate-new-buffer " *Glob Output*")
915 (erase-buffer)
916 (when (and (file-name-absolute-p name)
917 (not (file-directory-p default-directory)))
918 ;; If the current working directory doesn't exist `shell-command'
919 ;; signals an error. So if the file names we're looking for don't
920 ;; depend on the working directory, switch to a valid directory first.
921 (setq default-directory "/"))
922 (shell-command (concat "echo " name) t)
923 (goto-char (point-min))
924 ;; CSH-style shells were known to output "No match", whereas
925 ;; SH-style shells tend to simply output `name' when no match is found.
926 (if (looking-at (concat ".*No match\\|\\(^\\| \\)\\("
927 (regexp-quote name)
928 "\\|"
929 (regexp-quote (expand-file-name name))
930 "\\)\\( \\|$\\)"))
932 (insert "(\"")
933 (while (search-forward " " nil t)
934 (delete-backward-char 1)
935 (insert "\" \""))
936 (goto-char (point-max))
937 (delete-backward-char 1)
938 (insert "\")")
939 (goto-char (point-min))
940 (let ((files (read (current-buffer))) (p nil))
941 (kill-buffer (current-buffer))
942 (or (equal completion-ignored-extensions PC-ignored-extensions)
943 (setq PC-ignored-regexp
944 (concat "\\("
945 (mapconcat
946 'regexp-quote
947 (setq PC-ignored-extensions
948 completion-ignored-extensions)
949 "\\|")
950 "\\)\\'")))
951 (setq p nil)
952 (while files
953 ;; This whole process of going through to shell, to echo, and
954 ;; finally parsing the output is a hack. It breaks as soon as
955 ;; there are spaces in the file names or when the no-match
956 ;; message changes. To make up for it, we check that what we read
957 ;; indeed exists, so we may miss some files, but we at least won't
958 ;; list non-existent ones.
959 (or (not (file-exists-p (car files)))
960 (string-match PC-ignored-regexp (car files))
961 (setq p (cons (car files) p)))
962 (setq files (cdr files)))
963 p))))
965 ;; Facilities for loading C header files. This is independent from the
966 ;; main completion code. See also the variable `PC-include-file-path'
967 ;; at top of this file.
969 (defun PC-look-for-include-file ()
970 (if (string-match "[\"<]\\([^\"<>]*\\)[\">]?$" (buffer-file-name))
971 (let ((name (substring (buffer-file-name)
972 (match-beginning 1) (match-end 1)))
973 (punc (aref (buffer-file-name) (match-beginning 0)))
974 (path nil)
975 new-buf)
976 (kill-buffer (current-buffer))
977 (if (equal name "")
978 (with-current-buffer (car (buffer-list))
979 (save-excursion
980 (beginning-of-line)
981 (if (looking-at
982 "[ \t]*#[ \t]*include[ \t]+[<\"]\\(.+\\)[>\"][ \t]*[\n/]")
983 (setq name (buffer-substring (match-beginning 1)
984 (match-end 1))
985 punc (char-after (1- (match-beginning 1))))
986 ;; Suggested by Frank Siebenlist:
987 (if (or (looking-at
988 "[ \t]*([ \t]*load[ \t]+\"\\([^\"]+\\)\"")
989 (looking-at
990 "[ \t]*([ \t]*load-library[ \t]+\"\\([^\"]+\\)\"")
991 (looking-at
992 "[ \t]*([ \t]*require[ \t]+'\\([^\t )]+\\)[\t )]"))
993 (progn
994 (setq name (buffer-substring (match-beginning 1)
995 (match-end 1))
996 punc ?\<
997 path load-path)
998 (if (string-match "\\.elc$" name)
999 (setq name (substring name 0 -1))
1000 (or (string-match "\\.el$" name)
1001 (setq name (concat name ".el")))))
1002 (error "Not on an #include line"))))))
1003 (or (string-match "\\.[[:alnum:]]+$" name)
1004 (setq name (concat name ".h")))
1005 (if (eq punc ?\<)
1006 (let ((path (or path (PC-include-file-path))))
1007 (while (and path
1008 (not (file-exists-p
1009 (concat (file-name-as-directory (car path))
1010 name))))
1011 (setq path (cdr path)))
1012 (if path
1013 (setq name (concat (file-name-as-directory (car path)) name))
1014 (error "No such include file: <%s>" name)))
1015 (let ((dir (with-current-buffer (car (buffer-list))
1016 default-directory)))
1017 (if (file-exists-p (concat dir name))
1018 (setq name (concat dir name))
1019 (error "No such include file: `%s'" name))))
1020 (setq new-buf (get-file-buffer name))
1021 (if new-buf
1022 ;; no need to verify last-modified time for this!
1023 (set-buffer new-buf)
1024 (set-buffer (create-file-buffer name))
1025 (erase-buffer)
1026 (insert-file-contents name t))
1027 ;; Returning non-nil with the new buffer current
1028 ;; is sufficient to tell find-file to use it.
1030 nil))
1032 (defun PC-include-file-path ()
1033 (or PC-include-file-path
1034 (let ((env (getenv "INCPATH"))
1035 (path nil)
1036 pos)
1037 (or env (error "No include file path specified"))
1038 (while (setq pos (string-match ":[^:]+$" env))
1039 (setq path (cons (substring env (1+ pos)) path)
1040 env (substring env 0 pos)))
1041 path)))
1043 ;; This is adapted from lib-complete.el, by Mike Williams.
1044 (defun PC-include-file-all-completions (file search-path &optional full)
1045 "Return all completions for FILE in any directory on SEARCH-PATH.
1046 If optional third argument FULL is non-nil, returned pathnames should be
1047 absolute rather than relative to some directory on the SEARCH-PATH."
1048 (setq search-path
1049 (mapcar (lambda (dir)
1050 (if dir (file-name-as-directory dir) default-directory))
1051 search-path))
1052 (if (file-name-absolute-p file)
1053 ;; It's an absolute file name, so don't need search-path
1054 (progn
1055 (setq file (expand-file-name file))
1056 (file-name-all-completions
1057 (file-name-nondirectory file) (file-name-directory file)))
1058 (let ((subdir (file-name-directory file))
1059 (ndfile (file-name-nondirectory file))
1060 file-lists)
1061 ;; Append subdirectory part to each element of search-path
1062 (if subdir
1063 (setq search-path
1064 (mapcar (lambda (dir) (concat dir subdir))
1065 search-path)
1066 file ))
1067 ;; Make list of completions in each directory on search-path
1068 (while search-path
1069 (let* ((dir (car search-path))
1070 (subdir (if full dir subdir)))
1071 (if (file-directory-p dir)
1072 (progn
1073 (setq file-lists
1074 (cons
1075 (mapcar (lambda (file) (concat subdir file))
1076 (file-name-all-completions ndfile
1077 (car search-path)))
1078 file-lists))))
1079 (setq search-path (cdr search-path))))
1080 ;; Compress out duplicates while building complete list (slloooow!)
1081 (let ((sorted (sort (apply 'nconc file-lists)
1082 (lambda (x y) (not (string-lessp x y)))))
1083 compressed)
1084 (while sorted
1085 (if (equal (car sorted) (car compressed)) nil
1086 (setq compressed (cons (car sorted) compressed)))
1087 (setq sorted (cdr sorted)))
1088 compressed))))
1090 (defadvice read-file-name-internal (around PC-include-file disable)
1091 (if (string-match "<\\([^\"<>]*\\)>?\\'" (ad-get-arg 0))
1092 (let* ((string (ad-get-arg 0))
1093 (action (ad-get-arg 2))
1094 (name (match-string 1 string))
1095 (str2 (substring string (match-beginning 0)))
1096 (completion-table
1097 (mapcar (lambda (x)
1098 (format (if (string-match "/\\'" x) "<%s" "<%s>") x))
1099 (PC-include-file-all-completions
1100 name (PC-include-file-path)))))
1101 (setq ad-return-value
1102 (cond
1103 ((not completion-table) nil)
1104 ((eq action 'lambda) (test-completion str2 completion-table nil))
1105 ((eq action nil) (PC-try-completion str2 completion-table nil))
1106 ((eq action t) (all-completions str2 completion-table nil)))))
1107 ad-do-it))
1110 (provide 'complete)
1112 ;; arch-tag: fc7e2768-ff44-4e22-b579-4d825b968458
1113 ;;; complete.el ends here