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