(readchar): Extend BLOCK_INPUT block to ferror/clearerr.
[emacs.git] / lisp / complete.el
blobe0ed2e490103fb5570b4227879b36dfae75d7582
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 (if PC-do-completion-end (goto-char PC-do-completion-end)))
248 nil))
249 ;; Build the env-completion and mapping table.
250 (when (and partial-completion-mode (null PC-env-vars-alist))
251 (setq PC-env-vars-alist
252 (mapcar (lambda (string)
253 (let ((d (string-match "=" string)))
254 (cons (concat "$" (substring string 0 d))
255 (and d (substring string (1+ d))))))
256 process-environment))))
259 (defun PC-complete ()
260 "Like minibuffer-complete, but allows \"b--di\"-style abbreviations.
261 For example, \"M-x b--di\" would match `byte-recompile-directory', or any
262 name which consists of three or more words, the first beginning with \"b\"
263 and the third beginning with \"di\".
265 The pattern \"b--d\" is ambiguous for `byte-recompile-directory' and
266 `beginning-of-defun', so this would produce a list of completions
267 just like when normal Emacs completions are ambiguous.
269 Word-delimiters for the purposes of Partial Completion are \"-\", \"_\",
270 \".\", and SPC."
271 (interactive)
272 (if (PC-was-meta-key)
273 (minibuffer-complete)
274 ;; If the previous command was not this one,
275 ;; never scroll, always retry completion.
276 (or (eq last-command this-command)
277 (setq minibuffer-scroll-window nil))
278 (let ((window minibuffer-scroll-window))
279 ;; If there's a fresh completion window with a live buffer,
280 ;; and this command is repeated, scroll that window.
281 (if (and window (window-buffer window)
282 (buffer-name (window-buffer window)))
283 (with-current-buffer (window-buffer window)
284 (if (pos-visible-in-window-p (point-max) window)
285 (set-window-start window (point-min) nil)
286 (scroll-other-window)))
287 (PC-do-completion nil)))))
290 (defun PC-complete-word ()
291 "Like `minibuffer-complete-word', but allows \"b--di\"-style abbreviations.
292 See `PC-complete' for details.
293 This can be bound to other keys, like `-' and `.', if you wish."
294 (interactive)
295 (if (eq (PC-was-meta-key) PC-meta-flag)
296 (if (eq last-command-char ? )
297 (minibuffer-complete-word)
298 (self-insert-command 1))
299 (self-insert-command 1)
300 (if (eobp)
301 (PC-do-completion 'word))))
304 (defun PC-complete-space ()
305 "Like `minibuffer-complete-word', but allows \"b--di\"-style abbreviations.
306 See `PC-complete' for details.
307 This is suitable for binding to other keys which should act just like SPC."
308 (interactive)
309 (if (eq (PC-was-meta-key) PC-meta-flag)
310 (minibuffer-complete-word)
311 (insert " ")
312 (if (eobp)
313 (PC-do-completion 'word))))
316 (defun PC-complete-and-exit ()
317 "Like `minibuffer-complete-and-exit', but allows \"b--di\"-style abbreviations.
318 See `PC-complete' for details."
319 (interactive)
320 (if (eq (PC-was-meta-key) PC-meta-flag)
321 (minibuffer-complete-and-exit)
322 (PC-do-complete-and-exit)))
324 (defun PC-force-complete-and-exit ()
325 "Like `minibuffer-complete-and-exit', but allows \"b--di\"-style abbreviations.
326 See `PC-complete' for details."
327 (interactive)
328 (let ((minibuffer-completion-confirm nil))
329 (PC-do-complete-and-exit)))
331 (defun PC-do-complete-and-exit ()
332 (if (= (point-max) (minibuffer-prompt-end)) ; Duplicate the "bug" that Info-menu relies on...
333 (exit-minibuffer)
334 (let ((flag (PC-do-completion 'exit)))
335 (and flag
336 (if (or (eq flag 'complete)
337 (not minibuffer-completion-confirm))
338 (exit-minibuffer)
339 (PC-temp-minibuffer-message " [Confirm]"))))))
342 (defun PC-completion-help ()
343 "Like `minibuffer-completion-help', but allows \"b--di\"-style abbreviations.
344 See `PC-complete' for details."
345 (interactive)
346 (if (eq (PC-was-meta-key) PC-meta-flag)
347 (minibuffer-completion-help)
348 (PC-do-completion 'help)))
350 (defun PC-was-meta-key ()
351 (or (/= (length (this-command-keys)) 1)
352 (let ((key (aref (this-command-keys) 0)))
353 (if (integerp key)
354 (>= key 128)
355 (not (null (memq 'meta (event-modifiers key))))))))
358 (defvar PC-ignored-extensions 'empty-cache)
359 (defvar PC-delims 'empty-cache)
360 (defvar PC-ignored-regexp nil)
361 (defvar PC-word-failed-flag nil)
362 (defvar PC-delim-regex nil)
363 (defvar PC-ndelims-regex nil)
364 (defvar PC-delims-list nil)
366 (defvar PC-completion-as-file-name-predicate
367 (lambda () minibuffer-completing-file-name)
368 "A function testing whether a minibuffer completion now will work filename-style.
369 The function takes no arguments, and typically looks at the value
370 of `minibuffer-completion-table' and the minibuffer contents.")
372 ;; Returns the sequence of non-delimiter characters that follow regexp in string.
373 (defun PC-chunk-after (string regexp)
374 (if (not (string-match regexp string))
375 (let ((message (format "String %s didn't match regexp %s" string regexp)))
376 (message message)
377 (error message)))
378 (let ((result (substring string (match-end 0))))
379 ;; result may contain multiple chunks
380 (if (string-match PC-delim-regex result)
381 (setq result (substring result 0 (match-beginning 0))))
382 result))
384 (defun test-completion-ignore-case (str table pred)
385 "Like `test-completion', but ignores case when possible."
386 ;; Binding completion-ignore-case to nil ensures, for compatibility with
387 ;; standard completion, that the return value is exactly one of the
388 ;; possibilities. Do this binding only if pred is nil, out of paranoia;
389 ;; perhaps it is safe even if pred is non-nil.
390 (if pred
391 (test-completion str table pred)
392 (let ((completion-ignore-case nil))
393 (test-completion str table pred))))
395 ;; The following function is an attempt to work around two problems:
397 ;; (1) When complete.el was written, (try-completion "" '(("") (""))) used to
398 ;; return the value "". With a change from 2002-07-07 it returns t which caused
399 ;; `PC-lisp-complete-symbol' to fail with a "Wrong type argument: sequencep, t"
400 ;; error. `PC-try-completion' returns STRING in this case.
402 ;; (2) (try-completion "" '((""))) returned t before the above-mentioned change.
403 ;; Since `PC-chop-word' operates on the return value of `try-completion' this
404 ;; case might have provoked a similar error as in (1). `PC-try-completion'
405 ;; returns "" instead. I don't know whether this is a real problem though.
407 ;; Since `PC-try-completion' is not a guaranteed to fix these bugs reliably, you
408 ;; should try to look at the following discussions when you encounter problems:
409 ;; - emacs-pretest-bug ("Partial Completion" starting 2007-02-23),
410 ;; - emacs-devel ("[address-of-OP: Partial completion]" starting 2007-02-24),
411 ;; - emacs-devel ("[address-of-OP: EVAL and mouse selection in *Completions*]"
412 ;; starting 2007-03-05).
413 (defun PC-try-completion (string alist &optional predicate)
414 "Like `try-completion' but return STRING instead of t."
415 (let ((result (try-completion string alist predicate)))
416 (if (eq result t) string result)))
418 (defun PC-do-completion (&optional mode beg end)
419 (or beg (setq beg (minibuffer-prompt-end)))
420 (or end (setq end (point-max)))
421 (let* ((table minibuffer-completion-table)
422 (pred minibuffer-completion-predicate)
423 (filename (funcall PC-completion-as-file-name-predicate))
424 (dirname nil) ; non-nil only if a filename is being completed
425 ;; The following used to be "(dirlength 0)" which caused the erasure of
426 ;; the entire buffer text before `point' when inserting a completion
427 ;; into a buffer.
428 dirlength
429 (str (buffer-substring beg end))
430 (incname (and filename (string-match "<\\([^\"<>]*\\)>?$" str)))
431 (ambig nil)
432 basestr origstr
433 env-on
434 regex
435 p offset
436 (poss nil)
437 helpposs
438 (case-fold-search completion-ignore-case))
440 ;; Check if buffer contents can already be considered complete
441 (if (and (eq mode 'exit)
442 (test-completion str table pred))
443 (progn
444 ;; If completion-ignore-case is non-nil, insert the
445 ;; completion string since that may have a different case.
446 (when completion-ignore-case
447 (setq str (PC-try-completion str table pred))
448 (delete-region beg end)
449 (insert str))
450 'complete)
452 ;; Do substitutions in directory names
453 (and filename
454 (setq basestr (or (file-name-directory str) ""))
455 (setq dirlength (length basestr))
456 ;; Do substitutions in directory names
457 (setq p (substitute-in-file-name basestr))
458 (not (string-equal basestr p))
459 (setq str (concat p (file-name-nondirectory str)))
460 (progn
461 (delete-region beg end)
462 (insert str)
463 (setq end (+ beg (length str)))))
465 ;; Prepare various delimiter strings
466 (or (equal PC-word-delimiters PC-delims)
467 (setq PC-delims PC-word-delimiters
468 PC-delim-regex (concat "[" PC-delims "]")
469 PC-ndelims-regex (concat "[^" PC-delims "]*")
470 PC-delims-list (append PC-delims nil)))
472 ;; Add wildcards if necessary
473 (and filename
474 (let ((dir (file-name-directory str))
475 (file (file-name-nondirectory str))
476 ;; The base dir for file-completion is passed in `predicate'.
477 (default-directory (expand-file-name pred)))
478 (while (and (stringp dir) (not (file-directory-p dir)))
479 (setq dir (directory-file-name dir))
480 (setq file (concat (replace-regexp-in-string
481 PC-delim-regex "*\\&"
482 (file-name-nondirectory dir))
483 "*/" file))
484 (setq dir (file-name-directory dir)))
485 (setq origstr str str (concat dir file))))
487 ;; Look for wildcard expansions in directory name
488 (and filename
489 (string-match "\\*.*/" str)
490 (let ((pat str)
491 ;; The base dir for file-completion is passed in `predicate'.
492 (default-directory (expand-file-name pred))
493 files)
494 (setq p (1+ (string-match "/[^/]*\\'" pat)))
495 (while (setq p (string-match PC-delim-regex pat p))
496 (setq pat (concat (substring pat 0 p)
498 (substring pat p))
499 p (+ p 2)))
500 (setq files (PC-expand-many-files (concat pat "*")))
501 (if files
502 (let ((dir (file-name-directory (car files)))
503 (p files))
504 (while (and (setq p (cdr p))
505 (equal dir (file-name-directory (car p)))))
506 (if p
507 (setq filename nil table nil pred nil
508 ambig t)
509 (delete-region beg end)
510 (setq str (concat dir (file-name-nondirectory str)))
511 (insert str)
512 (setq end (+ beg (length str)))))
513 (if origstr
514 ;; If the wildcards were introduced by us, it's possible
515 ;; that read-file-name-internal (especially our
516 ;; PC-include-file advice) can still find matches for the
517 ;; original string even if we couldn't, so remove the
518 ;; added wildcards.
519 (setq str origstr)
520 (setq filename nil table nil pred nil)))))
522 ;; Strip directory name if appropriate
523 (if filename
524 (if incname
525 (setq basestr (substring str incname)
526 dirname (substring str 0 incname))
527 (setq basestr (file-name-nondirectory str)
528 dirname (file-name-directory str))
529 ;; Make sure str is consistent with its directory and basename
530 ;; parts. This is important on DOZe'NT systems when str only
531 ;; includes a drive letter, like in "d:".
532 (setq str (concat dirname basestr)))
533 (setq basestr str))
535 ;; Convert search pattern to a standard regular expression
536 (setq regex (regexp-quote basestr)
537 offset (if (and (> (length regex) 0)
538 (not (eq (aref basestr 0) ?\*))
539 (or (eq PC-first-char t)
540 (and PC-first-char filename))) 1 0)
541 p offset)
542 (while (setq p (string-match PC-delim-regex regex p))
543 (if (eq (aref regex p) ? )
544 (setq regex (concat (substring regex 0 p)
545 PC-ndelims-regex
546 PC-delim-regex
547 (substring regex (1+ p)))
548 p (+ p (length PC-ndelims-regex) (length PC-delim-regex)))
549 (let ((bump (if (memq (aref regex p)
550 '(?$ ?^ ?\. ?* ?+ ?? ?[ ?] ?\\))
551 -1 0)))
552 (setq regex (concat (substring regex 0 (+ p bump))
553 PC-ndelims-regex
554 (substring regex (+ p bump)))
555 p (+ p (length PC-ndelims-regex) 1)))))
556 (setq p 0)
557 (if filename
558 (while (setq p (string-match "\\\\\\*" regex p))
559 (setq regex (concat (substring regex 0 p)
560 "[^/]*"
561 (substring regex (+ p 2))))))
562 ;;(setq the-regex regex)
563 (setq regex (concat "\\`" regex))
565 (and (> (length basestr) 0)
566 (= (aref basestr 0) ?$)
567 (setq env-on t
568 table PC-env-vars-alist
569 pred nil))
571 ;; Find an initial list of possible completions
572 (if (not (setq p (string-match (concat PC-delim-regex
573 (if filename "\\|\\*" ""))
575 (+ (length dirname) offset))))
577 ;; Minibuffer contains no hyphens -- simple case!
578 (setq poss (all-completions (if env-on
579 basestr str)
580 table
581 pred))
583 ;; Use all-completions to do an initial cull. This is a big win,
584 ;; since all-completions is written in C!
585 (let ((compl (all-completions (if env-on
586 (file-name-nondirectory (substring str 0 p))
587 (substring str 0 p))
588 table
589 pred)))
590 (setq p compl)
591 (while p
592 (and (string-match regex (car p))
593 (progn
594 (set-text-properties 0 (length (car p)) '() (car p))
595 (setq poss (cons (car p) poss))))
596 (setq p (cdr p)))))
598 ;; If table had duplicates, they can be here.
599 (delete-dups poss)
601 ;; Handle completion-ignored-extensions
602 (and filename
603 (not (eq mode 'help))
604 (let ((p2 poss))
606 ;; Build a regular expression representing the extensions list
607 (or (equal completion-ignored-extensions PC-ignored-extensions)
608 (setq PC-ignored-regexp
609 (concat "\\("
610 (mapconcat
611 'regexp-quote
612 (setq PC-ignored-extensions
613 completion-ignored-extensions)
614 "\\|")
615 "\\)\\'")))
617 ;; Check if there are any without an ignored extension.
618 ;; Also ignore `.' and `..'.
619 (setq p nil)
620 (while p2
621 (or (string-match PC-ignored-regexp (car p2))
622 (string-match "\\(\\`\\|/\\)[.][.]?/?\\'" (car p2))
623 (setq p (cons (car p2) p)))
624 (setq p2 (cdr p2)))
626 ;; If there are "good" names, use them
627 (and p (setq poss p))))
629 ;; Now we have a list of possible completions
630 (cond
632 ;; No valid completions found
633 ((null poss)
634 (if (and (eq mode 'word)
635 (not PC-word-failed-flag))
636 (let ((PC-word-failed-flag t))
637 (delete-backward-char 1)
638 (PC-do-completion 'word))
639 (beep)
640 (PC-temp-minibuffer-message (if ambig
641 " [Ambiguous dir name]"
642 (if (eq mode 'help)
643 " [No completions]"
644 " [No match]")))
645 nil))
647 ;; More than one valid completion found
648 ((or (cdr (setq helpposs poss))
649 (memq mode '(help word)))
651 ;; Is the actual string one of the possible completions?
652 (setq p (and (not (eq mode 'help)) poss))
653 (while (and p
654 (not (string-equal (car p) basestr)))
655 (setq p (cdr p)))
656 (and p (null mode)
657 (PC-temp-minibuffer-message " [Complete, but not unique]"))
658 (if (and p
659 (not (and (null mode)
660 (eq this-command last-command))))
663 ;; If ambiguous, try for a partial completion
664 (let ((improved nil)
665 prefix
666 (pt nil)
667 (skip "\\`"))
669 ;; Check if next few letters are the same in all cases
670 (if (and (not (eq mode 'help))
671 (setq prefix (PC-try-completion
672 (PC-chunk-after basestr skip) poss)))
673 (let ((first t) i)
674 ;; Retain capitalization of user input even if
675 ;; completion-ignore-case is set.
676 (if (eq mode 'word)
677 (setq prefix (PC-chop-word prefix basestr)))
678 (goto-char (+ beg (length dirname)))
679 (while (and (progn
680 (setq i 0) ; index into prefix string
681 (while (< i (length prefix))
682 (if (and (< (point) end)
683 (eq (downcase (aref prefix i))
684 (downcase (following-char))))
685 ;; same char (modulo case); no action
686 (forward-char 1)
687 (if (and (< (point) end)
688 (and (looking-at " ")
689 (memq (aref prefix i)
690 PC-delims-list)))
691 ;; replace " " by the actual delimiter
692 (progn
693 (delete-char 1)
694 (insert (substring prefix i (1+ i))))
695 ;; insert a new character
696 (progn
697 (and filename (looking-at "\\*")
698 (progn
699 (delete-char 1)
700 (setq end (1- end))))
701 (setq improved t)
702 (insert (substring prefix i (1+ i)))
703 (setq end (1+ end)))))
704 (setq i (1+ i)))
705 (or pt (setq pt (point)))
706 (looking-at PC-delim-regex))
707 (setq skip (concat skip
708 (regexp-quote prefix)
709 PC-ndelims-regex)
710 prefix (PC-try-completion
711 (PC-chunk-after
712 ;; not basestr, because that does
713 ;; not reflect insertions
714 (buffer-substring
715 (+ beg (length dirname)) end)
716 skip)
717 (mapcar
718 (lambda (x)
719 (when (string-match skip x)
720 (substring x (match-end 0))))
721 poss)))
722 (or (> i 0) (> (length prefix) 0))
723 (or (not (eq mode 'word))
724 (and first (> (length prefix) 0)
725 (setq first nil
726 prefix (substring prefix 0 1))))))
727 (goto-char (if (eq mode 'word) end
728 (or pt beg)))))
730 (if (and (eq mode 'word)
731 (not PC-word-failed-flag))
733 (if improved
735 ;; We changed it... would it be complete without the space?
736 (if (test-completion (buffer-substring 1 (1- end))
737 table pred)
738 (delete-region (1- end) end)))
740 (if improved
742 ;; We changed it... enough to be complete?
743 (and (eq mode 'exit)
744 (test-completion-ignore-case (field-string) table pred))
746 ;; If totally ambiguous, display a list of completions
747 (if (or (eq completion-auto-help t)
748 (and completion-auto-help
749 (eq last-command this-command))
750 (eq mode 'help))
751 (let ((prompt-end (minibuffer-prompt-end)))
752 (with-output-to-temp-buffer "*Completions*"
753 (display-completion-list (sort helpposs 'string-lessp))
754 (with-current-buffer standard-output
755 ;; Record which part of the buffer we are completing
756 ;; so that choosing a completion from the list
757 ;; knows how much old text to replace.
758 ;; This was briefly nil in the non-dirname case.
759 ;; However, if one calls PC-lisp-complete-symbol
760 ;; on "(ne-f" with point on the hyphen, PC offers
761 ;; all completions starting with "(ne", some of
762 ;; which do not match the "-f" part (maybe it
763 ;; should not, but it does). In such cases,
764 ;; completion gets confused trying to figure out
765 ;; how much to replace, so we tell it explicitly
766 ;; (ie, the number of chars in the buffer before beg).
768 ;; Note that choose-completion-string-functions
769 ;; plays around with point.
770 (setq completion-base-size (if dirname
771 dirlength
772 (- beg prompt-end))
773 PC-do-completion-end end))))
774 (PC-temp-minibuffer-message " [Next char not unique]"))
775 nil)))))
777 ;; Only one possible completion
779 (if (and (equal basestr (car poss))
780 (not (and env-on filename)))
781 (if (null mode)
782 (PC-temp-minibuffer-message " [Sole completion]"))
783 (delete-region beg end)
784 (insert (format "%s"
785 (if filename
786 (substitute-in-file-name (concat dirname (car poss)))
787 (car poss)))))
788 t)))))
790 (defun PC-chop-word (new old)
791 (let ((i -1)
792 (j -1))
793 (while (and (setq i (string-match PC-delim-regex old (1+ i)))
794 (setq j (string-match PC-delim-regex new (1+ j)))))
795 (if (and j
796 (or (not PC-word-failed-flag)
797 (setq j (string-match PC-delim-regex new (1+ j)))))
798 (substring new 0 (1+ j))
799 new)))
801 (defvar PC-not-minibuffer nil)
803 (defun PC-temp-minibuffer-message (message)
804 "A Lisp version of `temp_minibuffer_message' from minibuf.c."
805 (cond (PC-not-minibuffer
806 (message message)
807 (sit-for 2)
808 (message ""))
809 ((fboundp 'temp-minibuffer-message)
810 (temp-minibuffer-message message))
812 (let ((point-max (point-max)))
813 (save-excursion
814 (goto-char point-max)
815 (insert message))
816 (let ((inhibit-quit t))
817 (sit-for 2)
818 (delete-region point-max (point-max))
819 (when quit-flag
820 (setq quit-flag nil
821 unread-command-events '(7))))))))
823 (defvar PC-lisp-complete-end nil
824 "Internal variable used by `PC-lisp-complete-symbol'.")
826 (defun PC-lisp-complete-symbol ()
827 "Perform completion on Lisp symbol preceding point.
828 That symbol is compared against the symbols that exist
829 and any additional characters determined by what is there
830 are inserted.
831 If the symbol starts just after an open-parenthesis,
832 only symbols with function definitions are considered.
833 Otherwise, all symbols with function definitions, values
834 or properties are considered."
835 (interactive)
836 (let* ((end (point))
837 (beg (save-excursion
838 (with-syntax-table lisp-mode-syntax-table
839 (backward-sexp 1)
840 (while (= (char-syntax (following-char)) ?\')
841 (forward-char 1))
842 (point))))
843 (minibuffer-completion-table obarray)
844 (minibuffer-completion-predicate
845 (if (eq (char-after (1- beg)) ?\()
846 'fboundp
847 (function (lambda (sym)
848 (or (boundp sym) (fboundp sym)
849 (symbol-plist sym))))))
850 (PC-not-minibuffer t))
851 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-03/msg01211.html
853 ;; This deals with cases like running PC-l-c-s on "M-: (n-f".
854 ;; The first call to PC-l-c-s expands this to "(ne-f", and moves
855 ;; point to the hyphen [1]. If one calls PC-l-c-s immediately after,
856 ;; then without the last-command check, one is offered all
857 ;; completions of "(ne", which is presumably not what one wants.
859 ;; This is arguably (at least, it seems to be the existing intended
860 ;; behaviour) what one _does_ want if point has been explicitly
861 ;; positioned on the hyphen. Note that if PC-do-completion (qv) binds
862 ;; completion-base-size to nil, then completion does not replace the
863 ;; correct amount of text in such cases.
865 ;; Neither of these problems occur when using PC for filenames in the
866 ;; minibuffer, because in that case PC-do-completion is called without
867 ;; an explicit value for END, and so uses (point-max). This is fine for
868 ;; a filename, because the end of the filename must be at the end of
869 ;; the minibuffer. The same is not true for lisp symbols.
871 ;; [1] An alternate fix would be to not move point to the hyphen
872 ;; in such cases, but that would make the behaviour different from
873 ;; that for filenames. It seems PC moves point to the site of the
874 ;; first difference between the possible completions.
876 ;; Alternatively alternatively, maybe end should be computed in
877 ;; the same way as beg. That would change the behaviour though.
878 (if (equal last-command 'PC-lisp-complete-symbol)
879 (PC-do-completion nil beg PC-lisp-complete-end)
880 (setq PC-lisp-complete-end (point-marker))
881 (set-marker-insertion-type PC-lisp-complete-end t)
882 (PC-do-completion nil beg end))))
884 (defun PC-complete-as-file-name ()
885 "Perform completion on file names preceding point.
886 Environment vars are converted to their values."
887 (interactive)
888 (let* ((end (point))
889 (beg (if (re-search-backward "[^\\][ \t\n\"\`\'][^ \t\n\"\`\']"
890 (point-min) t)
891 (+ (point) 2)
892 (point-min)))
893 (minibuffer-completion-table 'read-file-name-internal)
894 (minibuffer-completion-predicate "")
895 (PC-not-minibuffer t))
896 (goto-char end)
897 (PC-do-completion nil beg end)))
899 ;; Use the shell to do globbing.
900 ;; This could now use file-expand-wildcards instead.
902 (defun PC-expand-many-files (name)
903 (with-current-buffer (generate-new-buffer " *Glob Output*")
904 (erase-buffer)
905 (when (and (file-name-absolute-p name)
906 (not (file-directory-p default-directory)))
907 ;; If the current working directory doesn't exist `shell-command'
908 ;; signals an error. So if the file names we're looking for don't
909 ;; depend on the working directory, switch to a valid directory first.
910 (setq default-directory "/"))
911 (shell-command (concat "echo " name) t)
912 (goto-char (point-min))
913 ;; CSH-style shells were known to output "No match", whereas
914 ;; SH-style shells tend to simply output `name' when no match is found.
915 (if (looking-at (concat ".*No match\\|\\(^\\| \\)\\("
916 (regexp-quote name)
917 "\\|"
918 (regexp-quote (expand-file-name name))
919 "\\)\\( \\|$\\)"))
921 (insert "(\"")
922 (while (search-forward " " nil t)
923 (delete-backward-char 1)
924 (insert "\" \""))
925 (goto-char (point-max))
926 (delete-backward-char 1)
927 (insert "\")")
928 (goto-char (point-min))
929 (let ((files (read (current-buffer))) (p nil))
930 (kill-buffer (current-buffer))
931 (or (equal completion-ignored-extensions PC-ignored-extensions)
932 (setq PC-ignored-regexp
933 (concat "\\("
934 (mapconcat
935 'regexp-quote
936 (setq PC-ignored-extensions
937 completion-ignored-extensions)
938 "\\|")
939 "\\)\\'")))
940 (setq p nil)
941 (while files
942 ;; This whole process of going through to shell, to echo, and
943 ;; finally parsing the output is a hack. It breaks as soon as
944 ;; there are spaces in the file names or when the no-match
945 ;; message changes. To make up for it, we check that what we read
946 ;; indeed exists, so we may miss some files, but we at least won't
947 ;; list non-existent ones.
948 (or (not (file-exists-p (car files)))
949 (string-match PC-ignored-regexp (car files))
950 (setq p (cons (car files) p)))
951 (setq files (cdr files)))
952 p))))
954 ;; Facilities for loading C header files. This is independent from the
955 ;; main completion code. See also the variable `PC-include-file-path'
956 ;; at top of this file.
958 (defun PC-look-for-include-file ()
959 (if (string-match "[\"<]\\([^\"<>]*\\)[\">]?$" (buffer-file-name))
960 (let ((name (substring (buffer-file-name)
961 (match-beginning 1) (match-end 1)))
962 (punc (aref (buffer-file-name) (match-beginning 0)))
963 (path nil)
964 new-buf)
965 (kill-buffer (current-buffer))
966 (if (equal name "")
967 (with-current-buffer (car (buffer-list))
968 (save-excursion
969 (beginning-of-line)
970 (if (looking-at
971 "[ \t]*#[ \t]*include[ \t]+[<\"]\\(.+\\)[>\"][ \t]*[\n/]")
972 (setq name (buffer-substring (match-beginning 1)
973 (match-end 1))
974 punc (char-after (1- (match-beginning 1))))
975 ;; Suggested by Frank Siebenlist:
976 (if (or (looking-at
977 "[ \t]*([ \t]*load[ \t]+\"\\([^\"]+\\)\"")
978 (looking-at
979 "[ \t]*([ \t]*load-library[ \t]+\"\\([^\"]+\\)\"")
980 (looking-at
981 "[ \t]*([ \t]*require[ \t]+'\\([^\t )]+\\)[\t )]"))
982 (progn
983 (setq name (buffer-substring (match-beginning 1)
984 (match-end 1))
985 punc ?\<
986 path load-path)
987 (if (string-match "\\.elc$" name)
988 (setq name (substring name 0 -1))
989 (or (string-match "\\.el$" name)
990 (setq name (concat name ".el")))))
991 (error "Not on an #include line"))))))
992 (or (string-match "\\.[[:alnum:]]+$" name)
993 (setq name (concat name ".h")))
994 (if (eq punc ?\<)
995 (let ((path (or path (PC-include-file-path))))
996 (while (and path
997 (not (file-exists-p
998 (concat (file-name-as-directory (car path))
999 name))))
1000 (setq path (cdr path)))
1001 (if path
1002 (setq name (concat (file-name-as-directory (car path)) name))
1003 (error "No such include file: <%s>" name)))
1004 (let ((dir (with-current-buffer (car (buffer-list))
1005 default-directory)))
1006 (if (file-exists-p (concat dir name))
1007 (setq name (concat dir name))
1008 (error "No such include file: `%s'" name))))
1009 (setq new-buf (get-file-buffer name))
1010 (if new-buf
1011 ;; no need to verify last-modified time for this!
1012 (set-buffer new-buf)
1013 (set-buffer (create-file-buffer name))
1014 (erase-buffer)
1015 (insert-file-contents name t))
1016 ;; Returning non-nil with the new buffer current
1017 ;; is sufficient to tell find-file to use it.
1019 nil))
1021 (defun PC-include-file-path ()
1022 (or PC-include-file-path
1023 (let ((env (getenv "INCPATH"))
1024 (path nil)
1025 pos)
1026 (or env (error "No include file path specified"))
1027 (while (setq pos (string-match ":[^:]+$" env))
1028 (setq path (cons (substring env (1+ pos)) path)
1029 env (substring env 0 pos)))
1030 path)))
1032 ;; This is adapted from lib-complete.el, by Mike Williams.
1033 (defun PC-include-file-all-completions (file search-path &optional full)
1034 "Return all completions for FILE in any directory on SEARCH-PATH.
1035 If optional third argument FULL is non-nil, returned pathnames should be
1036 absolute rather than relative to some directory on the SEARCH-PATH."
1037 (setq search-path
1038 (mapcar (lambda (dir)
1039 (if dir (file-name-as-directory dir) default-directory))
1040 search-path))
1041 (if (file-name-absolute-p file)
1042 ;; It's an absolute file name, so don't need search-path
1043 (progn
1044 (setq file (expand-file-name file))
1045 (file-name-all-completions
1046 (file-name-nondirectory file) (file-name-directory file)))
1047 (let ((subdir (file-name-directory file))
1048 (ndfile (file-name-nondirectory file))
1049 file-lists)
1050 ;; Append subdirectory part to each element of search-path
1051 (if subdir
1052 (setq search-path
1053 (mapcar (lambda (dir) (concat dir subdir))
1054 search-path)
1055 file ))
1056 ;; Make list of completions in each directory on search-path
1057 (while search-path
1058 (let* ((dir (car search-path))
1059 (subdir (if full dir subdir)))
1060 (if (file-directory-p dir)
1061 (progn
1062 (setq file-lists
1063 (cons
1064 (mapcar (lambda (file) (concat subdir file))
1065 (file-name-all-completions ndfile
1066 (car search-path)))
1067 file-lists))))
1068 (setq search-path (cdr search-path))))
1069 ;; Compress out duplicates while building complete list (slloooow!)
1070 (let ((sorted (sort (apply 'nconc file-lists)
1071 (lambda (x y) (not (string-lessp x y)))))
1072 compressed)
1073 (while sorted
1074 (if (equal (car sorted) (car compressed)) nil
1075 (setq compressed (cons (car sorted) compressed)))
1076 (setq sorted (cdr sorted)))
1077 compressed))))
1079 (defadvice read-file-name-internal (around PC-include-file disable)
1080 (if (string-match "<\\([^\"<>]*\\)>?\\'" (ad-get-arg 0))
1081 (let* ((string (ad-get-arg 0))
1082 (action (ad-get-arg 2))
1083 (name (match-string 1 string))
1084 (str2 (substring string (match-beginning 0)))
1085 (completion-table
1086 (mapcar (lambda (x)
1087 (format (if (string-match "/\\'" x) "<%s" "<%s>") x))
1088 (PC-include-file-all-completions
1089 name (PC-include-file-path)))))
1090 (setq ad-return-value
1091 (cond
1092 ((not completion-table) nil)
1093 ((eq action 'lambda) (test-completion str2 completion-table nil))
1094 ((eq action nil) (PC-try-completion str2 completion-table nil))
1095 ((eq action t) (all-completions str2 completion-table nil)))))
1096 ad-do-it))
1099 (provide 'complete)
1101 ;; arch-tag: fc7e2768-ff44-4e22-b579-4d825b968458
1102 ;;; complete.el ends here