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