* term/x-win.el: Change x-menu-bar-start to menu-bar-open.
[bpt/emacs.git] / lisp / complete.el
1 ;;; complete.el --- partial completion mechanism plus other goodies
2
3 ;; Copyright (C) 1990, 1991, 1992, 1993, 1999, 2000, 2002, 2003, 2004,
4 ;; 2005, 2006 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 2, 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 completion-map "\t" 'minibuffer-complete)
151 (define-key completion-map " " 'minibuffer-complete-word)
152 (define-key completion-map "?" 'minibuffer-completion-help)
153
154 (define-key must-match-map "\t" 'minibuffer-complete)
155 (define-key must-match-map " " 'minibuffer-complete-word)
156 (define-key must-match-map "\r" 'minibuffer-complete-and-exit)
157 (define-key must-match-map "\n" 'minibuffer-complete-and-exit)
158 (define-key must-match-map "?" 'minibuffer-completion-help)
159
160 (define-key global-map "\e\t" 'complete-symbol))
161 (PC-default-bindings
162 (define-key completion-map "\t" 'PC-complete)
163 (define-key completion-map " " 'PC-complete-word)
164 (define-key completion-map "?" 'PC-completion-help)
165
166 (define-key completion-map "\e\t" 'PC-complete)
167 (define-key completion-map "\e " 'PC-complete-word)
168 (define-key completion-map "\e\r" 'PC-force-complete-and-exit)
169 (define-key completion-map "\e\n" 'PC-force-complete-and-exit)
170 (define-key completion-map "\e?" 'PC-completion-help)
171
172 (define-key must-match-map "\t" 'PC-complete)
173 (define-key must-match-map " " 'PC-complete-word)
174 (define-key must-match-map "\r" 'PC-complete-and-exit)
175 (define-key must-match-map "\n" 'PC-complete-and-exit)
176 (define-key must-match-map "?" 'PC-completion-help)
177
178 (define-key must-match-map "\e\t" 'PC-complete)
179 (define-key must-match-map "\e " 'PC-complete-word)
180 (define-key must-match-map "\e\r" 'PC-complete-and-exit)
181 (define-key must-match-map "\e\n" 'PC-complete-and-exit)
182 (define-key must-match-map "\e?" 'PC-completion-help)
183
184 (define-key global-map "\e\t" 'PC-lisp-complete-symbol)))))
185
186 ;;;###autoload
187 (define-minor-mode partial-completion-mode
188 "Toggle Partial Completion mode.
189 With prefix ARG, turn Partial Completion mode on if ARG is positive.
190
191 When Partial Completion mode is enabled, TAB (or M-TAB if `PC-meta-flag' is
192 nil) is enhanced so that if some string is divided into words and each word is
193 delimited by a character in `PC-word-delimiters', partial words are completed
194 as much as possible and `*' characters are treated likewise in file names.
195
196 For example, M-x p-c-m expands to M-x partial-completion-mode since no other
197 command begins with that sequence of characters, and
198 \\[find-file] f_b.c TAB might complete to foo_bar.c if that file existed and no
199 other file in that directory begin with that sequence of characters.
200
201 Unless `PC-disable-includes' is non-nil, the `<...>' sequence is interpreted
202 specially in \\[find-file]. For example,
203 \\[find-file] <sys/time.h> RET finds the file `/usr/include/sys/time.h'.
204 See also the variable `PC-include-file-path'.
205
206 Partial Completion mode extends the meaning of `completion-auto-help' (which
207 see), so that if it is neither nil nor t, Emacs shows the `*Completions*'
208 buffer only on the second attempt to complete. That is, if TAB finds nothing
209 to complete, the first TAB just says \"Next char not unique\" and the
210 second TAB brings up the `*Completions*' buffer."
211 :global t :group 'partial-completion
212 ;; Deal with key bindings...
213 (PC-bindings partial-completion-mode)
214 ;; Deal with include file feature...
215 (cond ((not partial-completion-mode)
216 (remove-hook 'find-file-not-found-functions 'PC-look-for-include-file))
217 ((not PC-disable-includes)
218 (add-hook 'find-file-not-found-functions 'PC-look-for-include-file)))
219 ;; ... with some underhand redefining.
220 (cond ((not partial-completion-mode)
221 (ad-disable-advice 'read-file-name-internal 'around 'PC-include-file)
222 (ad-activate 'read-file-name-internal))
223 ((not PC-disable-includes)
224 (ad-enable-advice 'read-file-name-internal 'around 'PC-include-file)
225 (ad-activate 'read-file-name-internal)))
226 ;; Adjust the completion selection in *Completion* buffers to the way
227 ;; we work. The default minibuffer completion code only completes the
228 ;; text before point and leaves the text after point alone (new in
229 ;; Emacs-22). In contrast we use the whole text and we even sometimes
230 ;; move point to a place before EOB, to indicate the first position where
231 ;; there's a difference, so when the user uses choose-completion, we have
232 ;; to trick choose-completion into replacing the whole minibuffer text
233 ;; rather than only the text before point. --Stef
234 (funcall
235 (if partial-completion-mode 'add-hook 'remove-hook)
236 'choose-completion-string-functions
237 (lambda (&rest x) (goto-char (point-max)) nil))
238 ;; Build the env-completion and mapping table.
239 (when (and partial-completion-mode (null PC-env-vars-alist))
240 (setq PC-env-vars-alist
241 (mapcar (lambda (string)
242 (let ((d (string-match "=" string)))
243 (cons (concat "$" (substring string 0 d))
244 (and d (substring string (1+ d))))))
245 process-environment))))
246
247 \f
248 (defun PC-complete ()
249 "Like minibuffer-complete, but allows \"b--di\"-style abbreviations.
250 For example, \"M-x b--di\" would match `byte-recompile-directory', or any
251 name which consists of three or more words, the first beginning with \"b\"
252 and the third beginning with \"di\".
253
254 The pattern \"b--d\" is ambiguous for `byte-recompile-directory' and
255 `beginning-of-defun', so this would produce a list of completions
256 just like when normal Emacs completions are ambiguous.
257
258 Word-delimiters for the purposes of Partial Completion are \"-\", \"_\",
259 \".\", and SPC."
260 (interactive)
261 (if (PC-was-meta-key)
262 (minibuffer-complete)
263 ;; If the previous command was not this one,
264 ;; never scroll, always retry completion.
265 (or (eq last-command this-command)
266 (setq minibuffer-scroll-window nil))
267 (let ((window minibuffer-scroll-window))
268 ;; If there's a fresh completion window with a live buffer,
269 ;; and this command is repeated, scroll that window.
270 (if (and window (window-buffer window)
271 (buffer-name (window-buffer window)))
272 (with-current-buffer (window-buffer window)
273 (if (pos-visible-in-window-p (point-max) window)
274 (set-window-start window (point-min) nil)
275 (scroll-other-window)))
276 (PC-do-completion nil)))))
277
278
279 (defun PC-complete-word ()
280 "Like `minibuffer-complete-word', but allows \"b--di\"-style abbreviations.
281 See `PC-complete' for details.
282 This can be bound to other keys, like `-' and `.', if you wish."
283 (interactive)
284 (if (eq (PC-was-meta-key) PC-meta-flag)
285 (if (eq last-command-char ? )
286 (minibuffer-complete-word)
287 (self-insert-command 1))
288 (self-insert-command 1)
289 (if (eobp)
290 (PC-do-completion 'word))))
291
292
293 (defun PC-complete-space ()
294 "Like `minibuffer-complete-word', but allows \"b--di\"-style abbreviations.
295 See `PC-complete' for details.
296 This is suitable for binding to other keys which should act just like SPC."
297 (interactive)
298 (if (eq (PC-was-meta-key) PC-meta-flag)
299 (minibuffer-complete-word)
300 (insert " ")
301 (if (eobp)
302 (PC-do-completion 'word))))
303
304
305 (defun PC-complete-and-exit ()
306 "Like `minibuffer-complete-and-exit', but allows \"b--di\"-style abbreviations.
307 See `PC-complete' for details."
308 (interactive)
309 (if (eq (PC-was-meta-key) PC-meta-flag)
310 (minibuffer-complete-and-exit)
311 (PC-do-complete-and-exit)))
312
313 (defun PC-force-complete-and-exit ()
314 "Like `minibuffer-complete-and-exit', but allows \"b--di\"-style abbreviations.
315 See `PC-complete' for details."
316 (interactive)
317 (let ((minibuffer-completion-confirm nil))
318 (PC-do-complete-and-exit)))
319
320 (defun PC-do-complete-and-exit ()
321 (if (= (point-max) (minibuffer-prompt-end)) ; Duplicate the "bug" that Info-menu relies on...
322 (exit-minibuffer)
323 (let ((flag (PC-do-completion 'exit)))
324 (and flag
325 (if (or (eq flag 'complete)
326 (not minibuffer-completion-confirm))
327 (exit-minibuffer)
328 (PC-temp-minibuffer-message " [Confirm]"))))))
329
330
331 (defun PC-completion-help ()
332 "Like `minibuffer-completion-help', but allows \"b--di\"-style abbreviations.
333 See `PC-complete' for details."
334 (interactive)
335 (if (eq (PC-was-meta-key) PC-meta-flag)
336 (minibuffer-completion-help)
337 (PC-do-completion 'help)))
338
339 (defun PC-was-meta-key ()
340 (or (/= (length (this-command-keys)) 1)
341 (let ((key (aref (this-command-keys) 0)))
342 (if (integerp key)
343 (>= key 128)
344 (not (null (memq 'meta (event-modifiers key))))))))
345
346
347 (defvar PC-ignored-extensions 'empty-cache)
348 (defvar PC-delims 'empty-cache)
349 (defvar PC-ignored-regexp nil)
350 (defvar PC-word-failed-flag nil)
351 (defvar PC-delim-regex nil)
352 (defvar PC-ndelims-regex nil)
353 (defvar PC-delims-list nil)
354
355 (defvar PC-completion-as-file-name-predicate
356 (lambda () minibuffer-completing-file-name)
357 "A function testing whether a minibuffer completion now will work filename-style.
358 The function takes no arguments, and typically looks at the value
359 of `minibuffer-completion-table' and the minibuffer contents.")
360
361 (defun PC-do-completion (&optional mode beg end)
362 (or beg (setq beg (minibuffer-prompt-end)))
363 (or end (setq end (point-max)))
364 (let* ((table minibuffer-completion-table)
365 (pred minibuffer-completion-predicate)
366 (filename (funcall PC-completion-as-file-name-predicate))
367 (dirname nil)
368 (dirlength 0)
369 (str (buffer-substring beg end))
370 (incname (and filename (string-match "<\\([^\"<>]*\\)>?$" str)))
371 (ambig nil)
372 basestr origstr
373 env-on
374 regex
375 p offset
376 (poss nil)
377 helpposs
378 (case-fold-search completion-ignore-case))
379
380 ;; Check if buffer contents can already be considered complete
381 (if (and (eq mode 'exit)
382 (test-completion str table pred))
383 'complete
384
385 ;; Do substitutions in directory names
386 (and filename
387 (setq basestr (or (file-name-directory str) ""))
388 (setq dirlength (length basestr))
389 ;; Do substitutions in directory names
390 (setq p (substitute-in-file-name basestr))
391 (not (string-equal basestr p))
392 (setq str (concat p (file-name-nondirectory str)))
393 (progn
394 (delete-region beg end)
395 (insert str)
396 (setq end (+ beg (length str)))))
397
398 ;; Prepare various delimiter strings
399 (or (equal PC-word-delimiters PC-delims)
400 (setq PC-delims PC-word-delimiters
401 PC-delim-regex (concat "[" PC-delims "]")
402 PC-ndelims-regex (concat "[^" PC-delims "]*")
403 PC-delims-list (append PC-delims nil)))
404
405 ;; Add wildcards if necessary
406 (and filename
407 (let ((dir (file-name-directory str))
408 (file (file-name-nondirectory str))
409 ;; The base dir for file-completion is passed in `predicate'.
410 (default-directory (expand-file-name pred)))
411 (while (and (stringp dir) (not (file-directory-p dir)))
412 (setq dir (directory-file-name dir))
413 (setq file (concat (replace-regexp-in-string
414 PC-delim-regex "*\\&"
415 (file-name-nondirectory dir))
416 "*/" file))
417 (setq dir (file-name-directory dir)))
418 (setq origstr str str (concat dir file))))
419
420 ;; Look for wildcard expansions in directory name
421 (and filename
422 (string-match "\\*.*/" str)
423 (let ((pat str)
424 ;; The base dir for file-completion is passed in `predicate'.
425 (default-directory (expand-file-name pred))
426 files)
427 (setq p (1+ (string-match "/[^/]*\\'" pat)))
428 (while (setq p (string-match PC-delim-regex pat p))
429 (setq pat (concat (substring pat 0 p)
430 "*"
431 (substring pat p))
432 p (+ p 2)))
433 (setq files (PC-expand-many-files (concat pat "*")))
434 (if files
435 (let ((dir (file-name-directory (car files)))
436 (p files))
437 (while (and (setq p (cdr p))
438 (equal dir (file-name-directory (car p)))))
439 (if p
440 (setq filename nil table nil pred nil
441 ambig t)
442 (delete-region beg end)
443 (setq str (concat dir (file-name-nondirectory str)))
444 (insert str)
445 (setq end (+ beg (length str)))))
446 (if origstr
447 ;; If the wildcards were introduced by us, it's possible
448 ;; that read-file-name-internal (especially our
449 ;; PC-include-file advice) can still find matches for the
450 ;; original string even if we couldn't, so remove the
451 ;; added wildcards.
452 (setq str origstr)
453 (setq filename nil table nil pred nil)))))
454
455 ;; Strip directory name if appropriate
456 (if filename
457 (if incname
458 (setq basestr (substring str incname)
459 dirname (substring str 0 incname))
460 (setq basestr (file-name-nondirectory str)
461 dirname (file-name-directory str))
462 ;; Make sure str is consistent with its directory and basename
463 ;; parts. This is important on DOZe'NT systems when str only
464 ;; includes a drive letter, like in "d:".
465 (setq str (concat dirname basestr)))
466 (setq basestr str))
467
468 ;; Convert search pattern to a standard regular expression
469 (setq regex (regexp-quote basestr)
470 offset (if (and (> (length regex) 0)
471 (not (eq (aref basestr 0) ?\*))
472 (or (eq PC-first-char t)
473 (and PC-first-char filename))) 1 0)
474 p offset)
475 (while (setq p (string-match PC-delim-regex regex p))
476 (if (eq (aref regex p) ? )
477 (setq regex (concat (substring regex 0 p)
478 PC-ndelims-regex
479 PC-delim-regex
480 (substring regex (1+ p)))
481 p (+ p (length PC-ndelims-regex) (length PC-delim-regex)))
482 (let ((bump (if (memq (aref regex p)
483 '(?$ ?^ ?\. ?* ?+ ?? ?[ ?] ?\\))
484 -1 0)))
485 (setq regex (concat (substring regex 0 (+ p bump))
486 PC-ndelims-regex
487 (substring regex (+ p bump)))
488 p (+ p (length PC-ndelims-regex) 1)))))
489 (setq p 0)
490 (if filename
491 (while (setq p (string-match "\\\\\\*" regex p))
492 (setq regex (concat (substring regex 0 p)
493 "[^/]*"
494 (substring regex (+ p 2))))))
495 ;;(setq the-regex regex)
496 (setq regex (concat "\\`" regex))
497
498 (and (> (length basestr) 0)
499 (= (aref basestr 0) ?$)
500 (setq env-on t
501 table PC-env-vars-alist
502 pred nil))
503
504 ;; Find an initial list of possible completions
505 (if (not (setq p (string-match (concat PC-delim-regex
506 (if filename "\\|\\*" ""))
507 str
508 (+ (length dirname) offset))))
509
510 ;; Minibuffer contains no hyphens -- simple case!
511 (setq poss (all-completions (if env-on
512 basestr str)
513 table
514 pred))
515
516 ;; Use all-completions to do an initial cull. This is a big win,
517 ;; since all-completions is written in C!
518 (let ((compl (all-completions (if env-on
519 (file-name-nondirectory (substring str 0 p))
520 (substring str 0 p))
521 table
522 pred)))
523 (setq p compl)
524 (while p
525 (and (string-match regex (car p))
526 (progn
527 (set-text-properties 0 (length (car p)) '() (car p))
528 (setq poss (cons (car p) poss))))
529 (setq p (cdr p)))))
530
531 ;; Now we have a list of possible completions
532 (cond
533
534 ;; No valid completions found
535 ((null poss)
536 (if (and (eq mode 'word)
537 (not PC-word-failed-flag))
538 (let ((PC-word-failed-flag t))
539 (delete-backward-char 1)
540 (PC-do-completion 'word))
541 (beep)
542 (PC-temp-minibuffer-message (if ambig
543 " [Ambiguous dir name]"
544 (if (eq mode 'help)
545 " [No completions]"
546 " [No match]")))
547 nil))
548
549 ;; More than one valid completion found
550 ((or (cdr (setq helpposs poss))
551 (memq mode '(help word)))
552
553 ;; Handle completion-ignored-extensions
554 (and filename
555 (not (eq mode 'help))
556 (let ((p2 poss))
557
558 ;; Build a regular expression representing the extensions list
559 (or (equal completion-ignored-extensions PC-ignored-extensions)
560 (setq PC-ignored-regexp
561 (concat "\\("
562 (mapconcat
563 'regexp-quote
564 (setq PC-ignored-extensions
565 completion-ignored-extensions)
566 "\\|")
567 "\\)\\'")))
568
569 ;; Check if there are any without an ignored extension.
570 ;; Also ignore `.' and `..'.
571 (setq p nil)
572 (while p2
573 (or (string-match PC-ignored-regexp (car p2))
574 (string-match "\\(\\`\\|/\\)[.][.]?/?\\'" (car p2))
575 (setq p (cons (car p2) p)))
576 (setq p2 (cdr p2)))
577
578 ;; If there are "good" names, use them
579 (and p (setq poss p))))
580
581 ;; Is the actual string one of the possible completions?
582 (setq p (and (not (eq mode 'help)) poss))
583 (while (and p
584 (not (string-equal (car p) basestr)))
585 (setq p (cdr p)))
586 (and p (null mode)
587 (PC-temp-minibuffer-message " [Complete, but not unique]"))
588 (if (and p
589 (not (and (null mode)
590 (eq this-command last-command))))
591 t
592
593 ;; If ambiguous, try for a partial completion
594 (let ((improved nil)
595 prefix
596 (pt nil)
597 (skip "\\`"))
598
599 ;; Check if next few letters are the same in all cases
600 (if (and (not (eq mode 'help))
601 (setq prefix (try-completion "" (mapcar 'list poss))))
602 (let ((first t) i)
603 (if (eq mode 'word)
604 (setq prefix (PC-chop-word prefix basestr)))
605 (goto-char (+ beg (length dirname)))
606 (while (and (progn
607 (setq i 0)
608 (while (< i (length prefix))
609 (if (and (< (point) end)
610 (eq (aref prefix i)
611 (following-char)))
612 (forward-char 1)
613 (if (and (< (point) end)
614 (or (and (looking-at " ")
615 (memq (aref prefix i)
616 PC-delims-list))
617 (eq (downcase (aref prefix i))
618 (downcase
619 (following-char)))))
620 (progn
621 (delete-char 1)
622 (setq end (1- end)))
623 (and filename (looking-at "\\*")
624 (progn
625 (delete-char 1)
626 (setq end (1- end))))
627 (setq improved t))
628 (insert (substring prefix i (1+ i)))
629 (setq end (1+ end)))
630 (setq i (1+ i)))
631 (or pt (setq pt (point)))
632 (looking-at PC-delim-regex))
633 (setq skip (concat skip
634 (regexp-quote prefix)
635 PC-ndelims-regex)
636 prefix (try-completion
637 ""
638 (mapcar
639 (function
640 (lambda (x)
641 (list
642 (and (string-match skip x)
643 (substring
644 x
645 (match-end 0))))))
646 poss)))
647 (or (> i 0) (> (length prefix) 0))
648 (or (not (eq mode 'word))
649 (and first (> (length prefix) 0)
650 (setq first nil
651 prefix (substring prefix 0 1))))))
652 (goto-char (if (eq mode 'word) end
653 (or pt beg)))))
654
655 (if (and (eq mode 'word)
656 (not PC-word-failed-flag))
657
658 (if improved
659
660 ;; We changed it... would it be complete without the space?
661 (if (test-completion (buffer-substring 1 (1- end))
662 table pred)
663 (delete-region (1- end) end)))
664
665 (if improved
666
667 ;; We changed it... enough to be complete?
668 (and (eq mode 'exit)
669 (test-completion (field-string) table pred))
670
671 ;; If totally ambiguous, display a list of completions
672 (if (or (eq completion-auto-help t)
673 (and completion-auto-help
674 (eq last-command this-command))
675 (eq mode 'help))
676 (with-output-to-temp-buffer "*Completions*"
677 (display-completion-list (sort helpposs 'string-lessp))
678 (with-current-buffer standard-output
679 ;; Record which part of the buffer we are completing
680 ;; so that choosing a completion from the list
681 ;; knows how much old text to replace.
682 (setq completion-base-size dirlength)))
683 (PC-temp-minibuffer-message " [Next char not unique]"))
684 nil)))))
685
686 ;; Only one possible completion
687 (t
688 (if (and (equal basestr (car poss))
689 (not (and env-on filename)))
690 (if (null mode)
691 (PC-temp-minibuffer-message " [Sole completion]"))
692 (delete-region beg end)
693 (insert (format "%s"
694 (if filename
695 (substitute-in-file-name (concat dirname (car poss)))
696 (car poss)))))
697 t)))))
698
699 (defun PC-chop-word (new old)
700 (let ((i -1)
701 (j -1))
702 (while (and (setq i (string-match PC-delim-regex old (1+ i)))
703 (setq j (string-match PC-delim-regex new (1+ j)))))
704 (if (and j
705 (or (not PC-word-failed-flag)
706 (setq j (string-match PC-delim-regex new (1+ j)))))
707 (substring new 0 (1+ j))
708 new)))
709
710 (defvar PC-not-minibuffer nil)
711
712 (defun PC-temp-minibuffer-message (message)
713 "A Lisp version of `temp_minibuffer_message' from minibuf.c."
714 (cond (PC-not-minibuffer
715 (message message)
716 (sit-for 2)
717 (message ""))
718 ((fboundp 'temp-minibuffer-message)
719 (temp-minibuffer-message message))
720 (t
721 (let ((point-max (point-max)))
722 (save-excursion
723 (goto-char point-max)
724 (insert message))
725 (let ((inhibit-quit t))
726 (sit-for 2)
727 (delete-region point-max (point-max))
728 (when quit-flag
729 (setq quit-flag nil
730 unread-command-events '(7))))))))
731
732
733 (defun PC-lisp-complete-symbol ()
734 "Perform completion on Lisp symbol preceding point.
735 That symbol is compared against the symbols that exist
736 and any additional characters determined by what is there
737 are inserted.
738 If the symbol starts just after an open-parenthesis,
739 only symbols with function definitions are considered.
740 Otherwise, all symbols with function definitions, values
741 or properties are considered."
742 (interactive)
743 (let* ((end (point))
744 (beg (save-excursion
745 (with-syntax-table lisp-mode-syntax-table
746 (backward-sexp 1)
747 (while (= (char-syntax (following-char)) ?\')
748 (forward-char 1))
749 (point))))
750 (minibuffer-completion-table obarray)
751 (minibuffer-completion-predicate
752 (if (eq (char-after (1- beg)) ?\()
753 'fboundp
754 (function (lambda (sym)
755 (or (boundp sym) (fboundp sym)
756 (symbol-plist sym))))))
757 (PC-not-minibuffer t))
758 (PC-do-completion nil beg end)))
759
760 (defun PC-complete-as-file-name ()
761 "Perform completion on file names preceding point.
762 Environment vars are converted to their values."
763 (interactive)
764 (let* ((end (point))
765 (beg (if (re-search-backward "[^\\][ \t\n\"\`\'][^ \t\n\"\`\']"
766 (point-min) t)
767 (+ (point) 2)
768 (point-min)))
769 (minibuffer-completion-table 'read-file-name-internal)
770 (minibuffer-completion-predicate "")
771 (PC-not-minibuffer t))
772 (goto-char end)
773 (PC-do-completion nil beg end)))
774
775 ;; Use the shell to do globbing.
776 ;; This could now use file-expand-wildcards instead.
777
778 (defun PC-expand-many-files (name)
779 (with-current-buffer (generate-new-buffer " *Glob Output*")
780 (erase-buffer)
781 (shell-command (concat "echo " name) t)
782 (goto-char (point-min))
783 ;; CSH-style shells were known to output "No match", whereas
784 ;; SH-style shells tend to simply output `name' when no match is found.
785 (if (looking-at (concat ".*No match\\|\\(^\\| \\)\\("
786 (regexp-quote name)
787 "\\|"
788 (regexp-quote (expand-file-name name))
789 "\\)\\( \\|$\\)"))
790 nil
791 (insert "(\"")
792 (while (search-forward " " nil t)
793 (delete-backward-char 1)
794 (insert "\" \""))
795 (goto-char (point-max))
796 (delete-backward-char 1)
797 (insert "\")")
798 (goto-char (point-min))
799 (let ((files (read (current-buffer))) (p nil))
800 (kill-buffer (current-buffer))
801 (or (equal completion-ignored-extensions PC-ignored-extensions)
802 (setq PC-ignored-regexp
803 (concat "\\("
804 (mapconcat
805 'regexp-quote
806 (setq PC-ignored-extensions
807 completion-ignored-extensions)
808 "\\|")
809 "\\)\\'")))
810 (setq p nil)
811 (while files
812 ;; This whole process of going through to shell, to echo, and
813 ;; finally parsing the output is a hack. It breaks as soon as
814 ;; there are spaces in the file names or when the no-match
815 ;; message changes. To make up for it, we check that what we read
816 ;; indeed exists, so we may miss some files, but we at least won't
817 ;; list non-existent ones.
818 (or (not (file-exists-p (car files)))
819 (string-match PC-ignored-regexp (car files))
820 (setq p (cons (car files) p)))
821 (setq files (cdr files)))
822 p))))
823
824 ;; Facilities for loading C header files. This is independent from the
825 ;; main completion code. See also the variable `PC-include-file-path'
826 ;; at top of this file.
827
828 (defun PC-look-for-include-file ()
829 (if (string-match "[\"<]\\([^\"<>]*\\)[\">]?$" (buffer-file-name))
830 (let ((name (substring (buffer-file-name)
831 (match-beginning 1) (match-end 1)))
832 (punc (aref (buffer-file-name) (match-beginning 0)))
833 (path nil)
834 new-buf)
835 (kill-buffer (current-buffer))
836 (if (equal name "")
837 (with-current-buffer (car (buffer-list))
838 (save-excursion
839 (beginning-of-line)
840 (if (looking-at
841 "[ \t]*#[ \t]*include[ \t]+[<\"]\\(.+\\)[>\"][ \t]*[\n/]")
842 (setq name (buffer-substring (match-beginning 1)
843 (match-end 1))
844 punc (char-after (1- (match-beginning 1))))
845 ;; Suggested by Frank Siebenlist:
846 (if (or (looking-at
847 "[ \t]*([ \t]*load[ \t]+\"\\([^\"]+\\)\"")
848 (looking-at
849 "[ \t]*([ \t]*load-library[ \t]+\"\\([^\"]+\\)\"")
850 (looking-at
851 "[ \t]*([ \t]*require[ \t]+'\\([^\t )]+\\)[\t )]"))
852 (progn
853 (setq name (buffer-substring (match-beginning 1)
854 (match-end 1))
855 punc ?\<
856 path load-path)
857 (if (string-match "\\.elc$" name)
858 (setq name (substring name 0 -1))
859 (or (string-match "\\.el$" name)
860 (setq name (concat name ".el")))))
861 (error "Not on an #include line"))))))
862 (or (string-match "\\.[[:alnum:]]+$" name)
863 (setq name (concat name ".h")))
864 (if (eq punc ?\<)
865 (let ((path (or path (PC-include-file-path))))
866 (while (and path
867 (not (file-exists-p
868 (concat (file-name-as-directory (car path))
869 name))))
870 (setq path (cdr path)))
871 (if path
872 (setq name (concat (file-name-as-directory (car path)) name))
873 (error "No such include file: <%s>" name)))
874 (let ((dir (with-current-buffer (car (buffer-list))
875 default-directory)))
876 (if (file-exists-p (concat dir name))
877 (setq name (concat dir name))
878 (error "No such include file: `%s'" name))))
879 (setq new-buf (get-file-buffer name))
880 (if new-buf
881 ;; no need to verify last-modified time for this!
882 (set-buffer new-buf)
883 (set-buffer (create-file-buffer name))
884 (erase-buffer)
885 (insert-file-contents name t))
886 ;; Returning non-nil with the new buffer current
887 ;; is sufficient to tell find-file to use it.
888 t)
889 nil))
890
891 (defun PC-include-file-path ()
892 (or PC-include-file-path
893 (let ((env (getenv "INCPATH"))
894 (path nil)
895 pos)
896 (or env (error "No include file path specified"))
897 (while (setq pos (string-match ":[^:]+$" env))
898 (setq path (cons (substring env (1+ pos)) path)
899 env (substring env 0 pos)))
900 path)))
901
902 ;; This is adapted from lib-complete.el, by Mike Williams.
903 (defun PC-include-file-all-completions (file search-path &optional full)
904 "Return all completions for FILE in any directory on SEARCH-PATH.
905 If optional third argument FULL is non-nil, returned pathnames should be
906 absolute rather than relative to some directory on the SEARCH-PATH."
907 (setq search-path
908 (mapcar (lambda (dir)
909 (if dir (file-name-as-directory dir) default-directory))
910 search-path))
911 (if (file-name-absolute-p file)
912 ;; It's an absolute file name, so don't need search-path
913 (progn
914 (setq file (expand-file-name file))
915 (file-name-all-completions
916 (file-name-nondirectory file) (file-name-directory file)))
917 (let ((subdir (file-name-directory file))
918 (ndfile (file-name-nondirectory file))
919 file-lists)
920 ;; Append subdirectory part to each element of search-path
921 (if subdir
922 (setq search-path
923 (mapcar (lambda (dir) (concat dir subdir))
924 search-path)
925 file ))
926 ;; Make list of completions in each directory on search-path
927 (while search-path
928 (let* ((dir (car search-path))
929 (subdir (if full dir subdir)))
930 (if (file-directory-p dir)
931 (progn
932 (setq file-lists
933 (cons
934 (mapcar (lambda (file) (concat subdir file))
935 (file-name-all-completions ndfile
936 (car search-path)))
937 file-lists))))
938 (setq search-path (cdr search-path))))
939 ;; Compress out duplicates while building complete list (slloooow!)
940 (let ((sorted (sort (apply 'nconc file-lists)
941 (lambda (x y) (not (string-lessp x y)))))
942 compressed)
943 (while sorted
944 (if (equal (car sorted) (car compressed)) nil
945 (setq compressed (cons (car sorted) compressed)))
946 (setq sorted (cdr sorted)))
947 compressed))))
948
949 (defadvice read-file-name-internal (around PC-include-file disable)
950 (if (string-match "<\\([^\"<>]*\\)>?\\'" (ad-get-arg 0))
951 (let* ((string (ad-get-arg 0))
952 (action (ad-get-arg 2))
953 (name (match-string 1 string))
954 (str2 (substring string (match-beginning 0)))
955 (completion-table
956 (mapcar (lambda (x)
957 (format (if (string-match "/\\'" x) "<%s" "<%s>") x))
958 (PC-include-file-all-completions
959 name (PC-include-file-path)))))
960 (setq ad-return-value
961 (cond
962 ((not completion-table) nil)
963 ((eq action 'lambda) (test-completion str2 completion-table nil))
964 ((eq action nil) (try-completion str2 completion-table nil))
965 ((eq action t) (all-completions str2 completion-table nil)))))
966 ad-do-it))
967 \f
968
969 (provide 'complete)
970
971 ;; arch-tag: fc7e2768-ff44-4e22-b579-4d825b968458
972 ;;; complete.el ends here