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)
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.
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
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.
90 (defgroup partial-completion nil
91 "Partial Completion of items."
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
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."
113 :group 'partial-completion)
115 (defcustom PC-word-delimiters "-_. "
116 "A string of characters treated as word delimiters for completion.
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')."
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."
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))
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 "\r" 'minibuffer-complete-and-exit)
157 (define-key must-match-map "\n" 'minibuffer-complete-and-exit)
159 (define-key global-map [remap lisp-complete-symbol] nil))
161 (define-key read-expression-map "\e\t" 'PC-lisp-complete-symbol)
163 (define-key completion-map "\t" 'PC-complete)
164 (define-key completion-map " " 'PC-complete-word)
165 (define-key completion-map "?" 'PC-completion-help)
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)
173 (define-key must-match-map "\r" 'PC-complete-and-exit)
174 (define-key must-match-map "\n" 'PC-complete-and-exit)
176 (define-key must-match-map "\e\r" 'PC-complete-and-exit)
177 (define-key must-match-map "\e\n" 'PC-complete-and-exit)
179 (define-key global-map [remap lisp-complete-symbol] 'PC-lisp-complete-symbol)))))
181 (defvar PC-do-completion-end nil
182 "Internal variable used by `PC-do-completion'.")
184 (make-variable-buffer-local 'PC-do-completion-end)
186 (defvar PC-goto-end nil
187 "Internal variable set in `PC-do-completion', used in
188 `choose-completion-string-functions'.")
190 (make-variable-buffer-local 'PC-goto-end)
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.
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.
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.
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'.
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 ;; ... with some underhand redefining.
226 (cond ((not partial-completion-mode)
227 (ad-disable-advice 'read-file-name-internal 'around 'PC-include-file)
228 (ad-activate 'read-file-name-internal))
229 ((not PC-disable-includes)
230 (ad-enable-advice 'read-file-name-internal 'around 'PC-include-file)
231 (ad-activate 'read-file-name-internal)))
232 ;; Adjust the completion selection in *Completion* buffers to the way
233 ;; we work. The default minibuffer completion code only completes the
234 ;; text before point and leaves the text after point alone (new in
235 ;; Emacs-22). In contrast we use the whole text and we even sometimes
236 ;; move point to a place before EOB, to indicate the first position where
237 ;; there's a difference, so when the user uses choose-completion, we have
238 ;; to trick choose-completion into replacing the whole minibuffer text
239 ;; rather than only the text before point. --Stef
241 (if partial-completion-mode 'add-hook 'remove-hook)
242 'choose-completion-string-functions
243 (lambda (choice buffer mini-p base-size)
244 ;; When completing M-: (lisp- ) with point before the ), it is
245 ;; not appropriate to go to point-max (unlike the filename case).
246 (if (and (not PC-goto-end)
248 (goto-char (point-max))
249 ;; Need a similar hack for the non-minibuffer-case -- gm.
250 (when PC-do-completion-end
251 (goto-char PC-do-completion-end)
252 (setq PC-do-completion-end nil)))
253 (setq PC-goto-end nil)
255 ;; Build the env-completion and mapping table.
256 (when (and partial-completion-mode (null PC-env-vars-alist))
257 (setq PC-env-vars-alist
258 (mapcar (lambda (string)
259 (let ((d (string-match "=" string)))
260 (cons (concat "$" (substring string 0 d))
261 (and d (substring string (1+ d))))))
262 process-environment))))
265 (defun PC-complete ()
266 "Like minibuffer-complete, but allows \"b--di\"-style abbreviations.
267 For example, \"M-x b--di\" would match `byte-recompile-directory', or any
268 name which consists of three or more words, the first beginning with \"b\"
269 and the third beginning with \"di\".
271 The pattern \"b--d\" is ambiguous for `byte-recompile-directory' and
272 `beginning-of-defun', so this would produce a list of completions
273 just like when normal Emacs completions are ambiguous.
275 Word-delimiters for the purposes of Partial Completion are \"-\", \"_\",
278 (if (PC-was-meta-key)
279 (minibuffer-complete)
280 ;; If the previous command was not this one,
281 ;; never scroll, always retry completion.
282 (or (eq last-command this-command)
283 (setq minibuffer-scroll-window nil))
284 (let ((window minibuffer-scroll-window))
285 ;; If there's a fresh completion window with a live buffer,
286 ;; and this command is repeated, scroll that window.
287 (if (and window (window-buffer window)
288 (buffer-name (window-buffer window)))
289 (with-current-buffer (window-buffer window)
290 (if (pos-visible-in-window-p (point-max) window)
291 (set-window-start window (point-min) nil)
292 (scroll-other-window)))
293 (PC-do-completion nil)))))
296 (defun PC-complete-word ()
297 "Like `minibuffer-complete-word', but allows \"b--di\"-style abbreviations.
298 See `PC-complete' for details.
299 This can be bound to other keys, like `-' and `.', if you wish."
301 (if (eq (PC-was-meta-key) PC-meta-flag)
302 (if (eq last-command-char ? )
303 (minibuffer-complete-word)
304 (self-insert-command 1))
305 (self-insert-command 1)
307 (PC-do-completion 'word))))
310 (defun PC-complete-space ()
311 "Like `minibuffer-complete-word', but allows \"b--di\"-style abbreviations.
312 See `PC-complete' for details.
313 This is suitable for binding to other keys which should act just like SPC."
315 (if (eq (PC-was-meta-key) PC-meta-flag)
316 (minibuffer-complete-word)
319 (PC-do-completion 'word))))
322 (defun PC-complete-and-exit ()
323 "Like `minibuffer-complete-and-exit', but allows \"b--di\"-style abbreviations.
324 See `PC-complete' for details."
326 (if (eq (PC-was-meta-key) PC-meta-flag)
327 (minibuffer-complete-and-exit)
328 (PC-do-complete-and-exit)))
330 (defun PC-force-complete-and-exit ()
331 "Like `minibuffer-complete-and-exit', but allows \"b--di\"-style abbreviations.
332 See `PC-complete' for details."
334 (let ((minibuffer-completion-confirm nil))
335 (PC-do-complete-and-exit)))
337 (defun PC-do-complete-and-exit ()
338 (if (= (point-max) (minibuffer-prompt-end)) ; Duplicate the "bug" that Info-menu relies on...
340 (let ((flag (PC-do-completion 'exit)))
342 (if (or (eq flag 'complete)
343 (not minibuffer-completion-confirm))
345 (PC-temp-minibuffer-message " [Confirm]"))))))
348 (defun PC-completion-help ()
349 "Like `minibuffer-completion-help', but allows \"b--di\"-style abbreviations.
350 See `PC-complete' for details."
352 (if (eq (PC-was-meta-key) PC-meta-flag)
353 (minibuffer-completion-help)
354 (PC-do-completion 'help)))
356 (defun PC-was-meta-key ()
357 (or (/= (length (this-command-keys)) 1)
358 (let ((key (aref (this-command-keys) 0)))
361 (not (null (memq 'meta (event-modifiers key))))))))
364 (defvar PC-ignored-extensions 'empty-cache)
365 (defvar PC-delims 'empty-cache)
366 (defvar PC-ignored-regexp nil)
367 (defvar PC-word-failed-flag nil)
368 (defvar PC-delim-regex nil)
369 (defvar PC-ndelims-regex nil)
370 (defvar PC-delims-list nil)
372 (defvar PC-completion-as-file-name-predicate
373 (lambda () minibuffer-completing-file-name)
374 "A function testing whether a minibuffer completion now will work filename-style.
375 The function takes no arguments, and typically looks at the value
376 of `minibuffer-completion-table' and the minibuffer contents.")
378 ;; Returns the sequence of non-delimiter characters that follow regexp in string.
379 (defun PC-chunk-after (string regexp)
380 (if (not (string-match regexp string))
381 (let ((message (format "String %s didn't match regexp %s" string regexp)))
384 (let ((result (substring string (match-end 0))))
385 ;; result may contain multiple chunks
386 (if (string-match PC-delim-regex result)
387 (setq result (substring result 0 (match-beginning 0))))
390 (defun test-completion-ignore-case (str table pred)
391 "Like `test-completion', but ignores case when possible."
392 ;; Binding completion-ignore-case to nil ensures, for compatibility with
393 ;; standard completion, that the return value is exactly one of the
394 ;; possibilities. Do this binding only if pred is nil, out of paranoia;
395 ;; perhaps it is safe even if pred is non-nil.
397 (test-completion str table pred)
398 (let ((completion-ignore-case nil))
399 (test-completion str table pred))))
401 ;; The following function is an attempt to work around two problems:
403 ;; (1) When complete.el was written, (try-completion "" '(("") (""))) used to
404 ;; return the value "". With a change from 2002-07-07 it returns t which caused
405 ;; `PC-lisp-complete-symbol' to fail with a "Wrong type argument: sequencep, t"
406 ;; error. `PC-try-completion' returns STRING in this case.
408 ;; (2) (try-completion "" '((""))) returned t before the above-mentioned change.
409 ;; Since `PC-chop-word' operates on the return value of `try-completion' this
410 ;; case might have provoked a similar error as in (1). `PC-try-completion'
411 ;; returns "" instead. I don't know whether this is a real problem though.
413 ;; Since `PC-try-completion' is not a guaranteed to fix these bugs reliably, you
414 ;; should try to look at the following discussions when you encounter problems:
415 ;; - emacs-pretest-bug ("Partial Completion" starting 2007-02-23),
416 ;; - emacs-devel ("[address-of-OP: Partial completion]" starting 2007-02-24),
417 ;; - emacs-devel ("[address-of-OP: EVAL and mouse selection in *Completions*]"
418 ;; starting 2007-03-05).
419 (defun PC-try-completion (string alist &optional predicate)
420 "Like `try-completion' but return STRING instead of t."
421 (let ((result (try-completion string alist predicate)))
422 (if (eq result t) string result)))
424 ;; TODO document MODE magic...
425 (defun PC-do-completion (&optional mode beg end goto-end)
426 "Internal function to do the work of partial completion.
427 Text to be completed lies between BEG and END. Normally when
428 replacing text in the minibuffer, this function replaces up to
429 point-max (as is appropriate for completing a file name). If
430 GOTO-END is non-nil, however, it instead replaces up to END."
431 (or beg (setq beg (minibuffer-prompt-end)))
432 (or end (setq end (point-max)))
433 (let* ((table minibuffer-completion-table)
434 (pred minibuffer-completion-predicate)
435 (filename (funcall PC-completion-as-file-name-predicate))
436 (dirname nil) ; non-nil only if a filename is being completed
437 ;; The following used to be "(dirlength 0)" which caused the erasure of
438 ;; the entire buffer text before `point' when inserting a completion
441 (str (buffer-substring beg end))
442 (incname (and filename (string-match "<\\([^\"<>]*\\)>?$" str)))
450 (case-fold-search completion-ignore-case))
452 ;; Check if buffer contents can already be considered complete
453 (if (and (eq mode 'exit)
454 (test-completion str table pred))
456 ;; If completion-ignore-case is non-nil, insert the
457 ;; completion string since that may have a different case.
458 (when completion-ignore-case
459 (setq str (PC-try-completion str table pred))
460 (delete-region beg end)
464 ;; Do substitutions in directory names
466 (setq basestr (or (file-name-directory str) ""))
467 (setq dirlength (length basestr))
468 ;; Do substitutions in directory names
469 (setq p (substitute-in-file-name basestr))
470 (not (string-equal basestr p))
471 (setq str (concat p (file-name-nondirectory str)))
473 (delete-region beg end)
475 (setq end (+ beg (length str)))))
477 ;; Prepare various delimiter strings
478 (or (equal PC-word-delimiters PC-delims)
479 (setq PC-delims PC-word-delimiters
480 PC-delim-regex (concat "[" PC-delims "]")
481 PC-ndelims-regex (concat "[^" PC-delims "]*")
482 PC-delims-list (append PC-delims nil)))
484 ;; Add wildcards if necessary
486 (let ((dir (file-name-directory str))
487 (file (file-name-nondirectory str))
488 ;; The base dir for file-completion is passed in `predicate'.
489 (default-directory (expand-file-name pred)))
490 (while (and (stringp dir) (not (file-directory-p dir)))
491 (setq dir (directory-file-name dir))
492 (setq file (concat (replace-regexp-in-string
493 PC-delim-regex "*\\&"
494 (file-name-nondirectory dir))
496 (setq dir (file-name-directory dir)))
497 (setq origstr str str (concat dir file))))
499 ;; Look for wildcard expansions in directory name
501 (string-match "\\*.*/" str)
503 ;; The base dir for file-completion is passed in `predicate'.
504 (default-directory (expand-file-name pred))
506 (setq p (1+ (string-match "/[^/]*\\'" pat)))
507 (while (setq p (string-match PC-delim-regex pat p))
508 (setq pat (concat (substring pat 0 p)
512 (setq files (PC-expand-many-files (concat pat "*")))
514 (let ((dir (file-name-directory (car files)))
516 (while (and (setq p (cdr p))
517 (equal dir (file-name-directory (car p)))))
519 (setq filename nil table nil pred nil
521 (delete-region beg end)
522 (setq str (concat dir (file-name-nondirectory str)))
524 (setq end (+ beg (length str)))))
526 ;; If the wildcards were introduced by us, it's possible
527 ;; that read-file-name-internal (especially our
528 ;; PC-include-file advice) can still find matches for the
529 ;; original string even if we couldn't, so remove the
532 (setq filename nil table nil pred nil)))))
534 ;; Strip directory name if appropriate
537 (setq basestr (substring str incname)
538 dirname (substring str 0 incname))
539 (setq basestr (file-name-nondirectory str)
540 dirname (file-name-directory str))
541 ;; Make sure str is consistent with its directory and basename
542 ;; parts. This is important on DOZe'NT systems when str only
543 ;; includes a drive letter, like in "d:".
544 (setq str (concat dirname basestr)))
547 ;; Convert search pattern to a standard regular expression
548 (setq regex (regexp-quote basestr)
549 offset (if (and (> (length regex) 0)
550 (not (eq (aref basestr 0) ?\*))
551 (or (eq PC-first-char t)
552 (and PC-first-char filename))) 1 0)
554 (while (setq p (string-match PC-delim-regex regex p))
555 (if (eq (aref regex p) ? )
556 (setq regex (concat (substring regex 0 p)
559 (substring regex (1+ p)))
560 p (+ p (length PC-ndelims-regex) (length PC-delim-regex)))
561 (let ((bump (if (memq (aref regex p)
562 '(?$ ?^ ?\. ?* ?+ ?? ?[ ?] ?\\))
564 (setq regex (concat (substring regex 0 (+ p bump))
566 (substring regex (+ p bump)))
567 p (+ p (length PC-ndelims-regex) 1)))))
570 (while (setq p (string-match "\\\\\\*" regex p))
571 (setq regex (concat (substring regex 0 p)
573 (substring regex (+ p 2))))))
574 ;;(setq the-regex regex)
575 (setq regex (concat "\\`" regex))
577 (and (> (length basestr) 0)
578 (= (aref basestr 0) ?$)
580 table PC-env-vars-alist
583 ;; Find an initial list of possible completions
584 (if (not (setq p (string-match (concat PC-delim-regex
585 (if filename "\\|\\*" ""))
587 (+ (length dirname) offset))))
589 ;; Minibuffer contains no hyphens -- simple case!
590 (setq poss (all-completions (if env-on
595 ;; Use all-completions to do an initial cull. This is a big win,
596 ;; since all-completions is written in C!
597 (let ((compl (all-completions (if env-on
598 (file-name-nondirectory (substring str 0 p))
604 (and (string-match regex (car p))
606 (set-text-properties 0 (length (car p)) '() (car p))
607 (setq poss (cons (car p) poss))))
610 ;; If table had duplicates, they can be here.
613 ;; Handle completion-ignored-extensions
615 (not (eq mode 'help))
618 ;; Build a regular expression representing the extensions list
619 (or (equal completion-ignored-extensions PC-ignored-extensions)
620 (setq PC-ignored-regexp
624 (setq PC-ignored-extensions
625 completion-ignored-extensions)
629 ;; Check if there are any without an ignored extension.
630 ;; Also ignore `.' and `..'.
633 (or (string-match PC-ignored-regexp (car p2))
634 (string-match "\\(\\`\\|/\\)[.][.]?/?\\'" (car p2))
635 (setq p (cons (car p2) p)))
638 ;; If there are "good" names, use them
639 (and p (setq poss p))))
641 ;; Now we have a list of possible completions
644 ;; No valid completions found
646 (if (and (eq mode 'word)
647 (not PC-word-failed-flag))
648 (let ((PC-word-failed-flag t))
649 (delete-backward-char 1)
650 (PC-do-completion 'word))
652 (PC-temp-minibuffer-message (if ambig
653 " [Ambiguous dir name]"
659 ;; More than one valid completion found
660 ((or (cdr (setq helpposs poss))
661 (memq mode '(help word)))
663 ;; Is the actual string one of the possible completions?
664 (setq p (and (not (eq mode 'help)) poss))
666 (not (string-equal (car p) basestr)))
669 (PC-temp-minibuffer-message " [Complete, but not unique]"))
671 (not (and (null mode)
672 (eq this-command last-command))))
675 ;; If ambiguous, try for a partial completion
681 ;; Check if next few letters are the same in all cases
682 (if (and (not (eq mode 'help))
683 (setq prefix (PC-try-completion
684 (PC-chunk-after basestr skip) poss)))
686 ;; Retain capitalization of user input even if
687 ;; completion-ignore-case is set.
689 (setq prefix (PC-chop-word prefix basestr)))
690 (goto-char (+ beg (length dirname)))
692 (setq i 0) ; index into prefix string
693 (while (< i (length prefix))
694 (if (and (< (point) end)
695 (eq (downcase (aref prefix i))
696 (downcase (following-char))))
697 ;; same char (modulo case); no action
699 (if (and (< (point) end)
700 (and (looking-at " ")
701 (memq (aref prefix i)
703 ;; replace " " by the actual delimiter
706 (insert (substring prefix i (1+ i))))
707 ;; insert a new character
709 (and filename (looking-at "\\*")
712 (setq end (1- end))))
714 (insert (substring prefix i (1+ i)))
715 (setq end (1+ end)))))
717 (or pt (setq pt (point)))
718 (looking-at PC-delim-regex))
719 (setq skip (concat skip
720 (regexp-quote prefix)
722 prefix (PC-try-completion
724 ;; not basestr, because that does
725 ;; not reflect insertions
727 (+ beg (length dirname)) end)
731 (when (string-match skip x)
732 (substring x (match-end 0))))
734 (or (> i 0) (> (length prefix) 0))
735 (or (not (eq mode 'word))
736 (and first (> (length prefix) 0)
738 prefix (substring prefix 0 1))))))
739 (goto-char (if (eq mode 'word) end
742 (if (and (eq mode 'word)
743 (not PC-word-failed-flag))
747 ;; We changed it... would it be complete without the space?
748 (if (test-completion (buffer-substring 1 (1- end))
750 (delete-region (1- end) end)))
754 ;; We changed it... enough to be complete?
756 (test-completion-ignore-case (field-string) table pred))
758 ;; If totally ambiguous, display a list of completions
759 (if (or (eq completion-auto-help t)
760 (and completion-auto-help
761 (eq last-command this-command))
763 (let ((prompt-end (minibuffer-prompt-end)))
764 (with-output-to-temp-buffer "*Completions*"
765 (display-completion-list (sort helpposs 'string-lessp))
766 (setq PC-do-completion-end end
767 PC-goto-end goto-end)
768 (with-current-buffer standard-output
769 ;; Record which part of the buffer we are completing
770 ;; so that choosing a completion from the list
771 ;; knows how much old text to replace.
772 ;; This was briefly nil in the non-dirname case.
773 ;; However, if one calls PC-lisp-complete-symbol
774 ;; on "(ne-f" with point on the hyphen, PC offers
775 ;; all completions starting with "(ne", some of
776 ;; which do not match the "-f" part (maybe it
777 ;; should not, but it does). In such cases,
778 ;; completion gets confused trying to figure out
779 ;; how much to replace, so we tell it explicitly
780 ;; (ie, the number of chars in the buffer before beg).
782 ;; Note that choose-completion-string-functions
783 ;; plays around with point.
784 (setq completion-base-size (if dirname
786 (- beg prompt-end))))))
787 (PC-temp-minibuffer-message " [Next char not unique]"))
790 ;; Only one possible completion
792 (if (and (equal basestr (car poss))
793 (not (and env-on filename)))
795 (PC-temp-minibuffer-message " [Sole completion]"))
796 (delete-region beg end)
799 (substitute-in-file-name (concat dirname (car poss)))
803 (defun PC-chop-word (new old)
806 (while (and (setq i (string-match PC-delim-regex old (1+ i)))
807 (setq j (string-match PC-delim-regex new (1+ j)))))
809 (or (not PC-word-failed-flag)
810 (setq j (string-match PC-delim-regex new (1+ j)))))
811 (substring new 0 (1+ j))
814 (defvar PC-not-minibuffer nil)
816 (defun PC-temp-minibuffer-message (message)
817 "A Lisp version of `temp_minibuffer_message' from minibuf.c."
818 (cond (PC-not-minibuffer
822 ((fboundp 'temp-minibuffer-message)
823 (temp-minibuffer-message message))
825 (let ((point-max (point-max)))
827 (goto-char point-max)
829 (let ((inhibit-quit t))
831 (delete-region point-max (point-max))
834 unread-command-events '(7))))))))
836 ;; Does not need to be buffer-local (?) because only used when one
837 ;; PC-l-c-s immediately follows another.
838 (defvar PC-lisp-complete-end nil
839 "Internal variable used by `PC-lisp-complete-symbol'.")
841 (defun PC-lisp-complete-symbol ()
842 "Perform completion on Lisp symbol preceding point.
843 That symbol is compared against the symbols that exist
844 and any additional characters determined by what is there
846 If the symbol starts just after an open-parenthesis,
847 only symbols with function definitions are considered.
848 Otherwise, all symbols with function definitions, values
849 or properties are considered."
852 ;; To complete the word under point, rather than just the portion
853 ;; before point, use this:
855 ;;; (with-syntax-table lisp-mode-syntax-table
859 (with-syntax-table lisp-mode-syntax-table
861 (while (= (char-syntax (following-char)) ?\')
864 (minibuffer-completion-table obarray)
865 (minibuffer-completion-predicate
866 (if (eq (char-after (1- beg)) ?\()
868 (function (lambda (sym)
869 (or (boundp sym) (fboundp sym)
870 (symbol-plist sym))))))
871 (PC-not-minibuffer t))
872 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-03/msg01211.html
874 ;; This deals with cases like running PC-l-c-s on "M-: (n-f".
875 ;; The first call to PC-l-c-s expands this to "(ne-f", and moves
876 ;; point to the hyphen [1]. If one calls PC-l-c-s immediately after,
877 ;; then without the last-command check, one is offered all
878 ;; completions of "(ne", which is presumably not what one wants.
880 ;; This is arguably (at least, it seems to be the existing intended
881 ;; behaviour) what one _does_ want if point has been explicitly
882 ;; positioned on the hyphen. Note that if PC-do-completion (qv) binds
883 ;; completion-base-size to nil, then completion does not replace the
884 ;; correct amount of text in such cases.
886 ;; Neither of these problems occur when using PC for filenames in the
887 ;; minibuffer, because in that case PC-do-completion is called without
888 ;; an explicit value for END, and so uses (point-max). This is fine for
889 ;; a filename, because the end of the filename must be at the end of
890 ;; the minibuffer. The same is not true for lisp symbols.
892 ;; [1] An alternate fix would be to not move point to the hyphen
893 ;; in such cases, but that would make the behaviour different from
894 ;; that for filenames. It seems PC moves point to the site of the
895 ;; first difference between the possible completions.
897 ;; Alternatively alternatively, maybe end should be computed in
898 ;; the same way as beg. That would change the behaviour though.
899 (if (equal last-command 'PC-lisp-complete-symbol)
900 (PC-do-completion nil beg PC-lisp-complete-end t)
901 (if PC-lisp-complete-end
902 (move-marker PC-lisp-complete-end end)
903 (setq PC-lisp-complete-end (copy-marker end t)))
904 (PC-do-completion nil beg end t))))
906 (defun PC-complete-as-file-name ()
907 "Perform completion on file names preceding point.
908 Environment vars are converted to their values."
911 (beg (if (re-search-backward "[^\\][ \t\n\"\`\'][^ \t\n\"\`\']"
915 (minibuffer-completion-table 'read-file-name-internal)
916 (minibuffer-completion-predicate "")
917 (PC-not-minibuffer t))
919 (PC-do-completion nil beg end)))
921 ;; Use the shell to do globbing.
922 ;; This could now use file-expand-wildcards instead.
924 (defun PC-expand-many-files (name)
925 (with-current-buffer (generate-new-buffer " *Glob Output*")
927 (when (and (file-name-absolute-p name)
928 (not (file-directory-p default-directory)))
929 ;; If the current working directory doesn't exist `shell-command'
930 ;; signals an error. So if the file names we're looking for don't
931 ;; depend on the working directory, switch to a valid directory first.
932 (setq default-directory "/"))
933 (shell-command (concat "echo " name) t)
934 (goto-char (point-min))
935 ;; CSH-style shells were known to output "No match", whereas
936 ;; SH-style shells tend to simply output `name' when no match is found.
937 (if (looking-at (concat ".*No match\\|\\(^\\| \\)\\("
940 (regexp-quote (expand-file-name name))
944 (while (search-forward " " nil t)
945 (delete-backward-char 1)
947 (goto-char (point-max))
948 (delete-backward-char 1)
950 (goto-char (point-min))
951 (let ((files (read (current-buffer))) (p nil))
952 (kill-buffer (current-buffer))
953 (or (equal completion-ignored-extensions PC-ignored-extensions)
954 (setq PC-ignored-regexp
958 (setq PC-ignored-extensions
959 completion-ignored-extensions)
964 ;; This whole process of going through to shell, to echo, and
965 ;; finally parsing the output is a hack. It breaks as soon as
966 ;; there are spaces in the file names or when the no-match
967 ;; message changes. To make up for it, we check that what we read
968 ;; indeed exists, so we may miss some files, but we at least won't
969 ;; list non-existent ones.
970 (or (not (file-exists-p (car files)))
971 (string-match PC-ignored-regexp (car files))
972 (setq p (cons (car files) p)))
973 (setq files (cdr files)))
976 ;; Facilities for loading C header files. This is independent from the
977 ;; main completion code. See also the variable `PC-include-file-path'
978 ;; at top of this file.
980 (defun PC-look-for-include-file ()
981 (if (string-match "[\"<]\\([^\"<>]*\\)[\">]?$" (buffer-file-name))
982 (let ((name (substring (buffer-file-name)
983 (match-beginning 1) (match-end 1)))
984 (punc (aref (buffer-file-name) (match-beginning 0)))
987 (kill-buffer (current-buffer))
989 (with-current-buffer (car (buffer-list))
993 "[ \t]*#[ \t]*include[ \t]+[<\"]\\(.+\\)[>\"][ \t]*[\n/]")
994 (setq name (buffer-substring (match-beginning 1)
996 punc (char-after (1- (match-beginning 1))))
997 ;; Suggested by Frank Siebenlist:
999 "[ \t]*([ \t]*load[ \t]+\"\\([^\"]+\\)\"")
1001 "[ \t]*([ \t]*load-library[ \t]+\"\\([^\"]+\\)\"")
1003 "[ \t]*([ \t]*require[ \t]+'\\([^\t )]+\\)[\t )]"))
1005 (setq name (buffer-substring (match-beginning 1)
1009 (if (string-match "\\.elc$" name)
1010 (setq name (substring name 0 -1))
1011 (or (string-match "\\.el$" name)
1012 (setq name (concat name ".el")))))
1013 (error "Not on an #include line"))))))
1014 (or (string-match "\\.[[:alnum:]]+$" name)
1015 (setq name (concat name ".h")))
1017 (let ((path (or path (PC-include-file-path))))
1020 (concat (file-name-as-directory (car path))
1022 (setq path (cdr path)))
1024 (setq name (concat (file-name-as-directory (car path)) name))
1025 (error "No such include file: <%s>" name)))
1026 (let ((dir (with-current-buffer (car (buffer-list))
1027 default-directory)))
1028 (if (file-exists-p (concat dir name))
1029 (setq name (concat dir name))
1030 (error "No such include file: `%s'" name))))
1031 (setq new-buf (get-file-buffer name))
1033 ;; no need to verify last-modified time for this!
1034 (set-buffer new-buf)
1035 (set-buffer (create-file-buffer name))
1037 (insert-file-contents name t))
1038 ;; Returning non-nil with the new buffer current
1039 ;; is sufficient to tell find-file to use it.
1043 (defun PC-include-file-path ()
1044 (or PC-include-file-path
1045 (let ((env (getenv "INCPATH"))
1048 (or env (error "No include file path specified"))
1049 (while (setq pos (string-match ":[^:]+$" env))
1050 (setq path (cons (substring env (1+ pos)) path)
1051 env (substring env 0 pos)))
1054 ;; This is adapted from lib-complete.el, by Mike Williams.
1055 (defun PC-include-file-all-completions (file search-path &optional full)
1056 "Return all completions for FILE in any directory on SEARCH-PATH.
1057 If optional third argument FULL is non-nil, returned pathnames should be
1058 absolute rather than relative to some directory on the SEARCH-PATH."
1060 (mapcar (lambda (dir)
1061 (if dir (file-name-as-directory dir) default-directory))
1063 (if (file-name-absolute-p file)
1064 ;; It's an absolute file name, so don't need search-path
1066 (setq file (expand-file-name file))
1067 (file-name-all-completions
1068 (file-name-nondirectory file) (file-name-directory file)))
1069 (let ((subdir (file-name-directory file))
1070 (ndfile (file-name-nondirectory file))
1072 ;; Append subdirectory part to each element of search-path
1075 (mapcar (lambda (dir) (concat dir subdir))
1078 ;; Make list of completions in each directory on search-path
1080 (let* ((dir (car search-path))
1081 (subdir (if full dir subdir)))
1082 (if (file-directory-p dir)
1086 (mapcar (lambda (file) (concat subdir file))
1087 (file-name-all-completions ndfile
1090 (setq search-path (cdr search-path))))
1091 ;; Compress out duplicates while building complete list (slloooow!)
1092 (let ((sorted (sort (apply 'nconc file-lists)
1093 (lambda (x y) (not (string-lessp x y)))))
1096 (if (equal (car sorted) (car compressed)) nil
1097 (setq compressed (cons (car sorted) compressed)))
1098 (setq sorted (cdr sorted)))
1101 (defadvice read-file-name-internal (around PC-include-file disable)
1102 (if (string-match "<\\([^\"<>]*\\)>?\\'" (ad-get-arg 0))
1103 (let* ((string (ad-get-arg 0))
1104 (action (ad-get-arg 2))
1105 (name (match-string 1 string))
1106 (str2 (substring string (match-beginning 0)))
1109 (format (if (string-match "/\\'" x) "<%s" "<%s>") x))
1110 (PC-include-file-all-completions
1111 name (PC-include-file-path)))))
1112 (setq ad-return-value
1114 ((not completion-table) nil)
1115 ((eq action 'lambda) (test-completion str2 completion-table nil))
1116 ((eq action nil) (PC-try-completion str2 completion-table nil))
1117 ((eq action t) (all-completions str2 completion-table nil)))))
1123 ;; arch-tag: fc7e2768-ff44-4e22-b579-4d825b968458
1124 ;;; complete.el ends here