]> code.delx.au - gnu-emacs/blob - lisp/complete.el
(longlines-wrap-region): Avoid marking buffer as modified.
[gnu-emacs] / lisp / complete.el
1 ;;; complete.el --- partial completion mechanism plus other goodies
2
3 ;; Copyright (C) 1990, 1991, 1992, 1993, 1999, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5
6 ;; Author: Dave Gillespie <daveg@synaptics.com>
7 ;; Keywords: abbrev convenience
8 ;; Special thanks to Hallvard Furuseth for his many ideas and contributions.
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 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 read-expression-map "\e\t" 'lisp-complete-symbol)
151
152 (define-key completion-map "\t" 'minibuffer-complete)
153 (define-key completion-map " " 'minibuffer-complete-word)
154 (define-key completion-map "?" 'minibuffer-completion-help)
155
156 (define-key must-match-map "\r" 'minibuffer-complete-and-exit)
157 (define-key must-match-map "\n" 'minibuffer-complete-and-exit)
158
159 (define-key global-map [remap lisp-complete-symbol] nil))
160 (PC-default-bindings
161 (define-key read-expression-map "\e\t" 'PC-lisp-complete-symbol)
162
163 (define-key completion-map "\t" 'PC-complete)
164 (define-key completion-map " " 'PC-complete-word)
165 (define-key completion-map "?" 'PC-completion-help)
166
167 (define-key completion-map "\e\t" 'PC-complete)
168 (define-key completion-map "\e " 'PC-complete-word)
169 (define-key completion-map "\e\r" 'PC-force-complete-and-exit)
170 (define-key completion-map "\e\n" 'PC-force-complete-and-exit)
171 (define-key completion-map "\e?" 'PC-completion-help)
172
173 (define-key must-match-map "\r" 'PC-complete-and-exit)
174 (define-key must-match-map "\n" 'PC-complete-and-exit)
175
176 (define-key must-match-map "\e\r" 'PC-complete-and-exit)
177 (define-key must-match-map "\e\n" 'PC-complete-and-exit)
178
179 (define-key global-map [remap lisp-complete-symbol] 'PC-lisp-complete-symbol)))))
180
181 (defvar PC-do-completion-end nil
182 "Internal variable used by `PC-do-completion'.")
183
184 (make-variable-buffer-local 'PC-do-completion-end)
185
186 (defvar PC-goto-end nil
187 "Internal variable set in `PC-do-completion', used in
188 `choose-completion-string-functions'.")
189
190 (make-variable-buffer-local 'PC-goto-end)
191
192 ;;;###autoload
193 (define-minor-mode partial-completion-mode
194 "Toggle Partial Completion mode.
195 With prefix ARG, turn Partial Completion mode on if ARG is positive.
196
197 When Partial Completion mode is enabled, TAB (or M-TAB if `PC-meta-flag' is
198 nil) is enhanced so that if some string is divided into words and each word is
199 delimited by a character in `PC-word-delimiters', partial words are completed
200 as much as possible and `*' characters are treated likewise in file names.
201
202 For example, M-x p-c-m expands to M-x partial-completion-mode since no other
203 command begins with that sequence of characters, and
204 \\[find-file] f_b.c TAB might complete to foo_bar.c if that file existed and no
205 other file in that directory begins with that sequence of characters.
206
207 Unless `PC-disable-includes' is non-nil, the `<...>' sequence is interpreted
208 specially in \\[find-file]. For example,
209 \\[find-file] <sys/time.h> RET finds the file `/usr/include/sys/time.h'.
210 See also the variable `PC-include-file-path'.
211
212 Partial Completion mode extends the meaning of `completion-auto-help' (which
213 see), so that if it is neither nil nor t, Emacs shows the `*Completions*'
214 buffer only on the second attempt to complete. That is, if TAB finds nothing
215 to complete, the first TAB just says \"Next char not unique\" and the
216 second TAB brings up the `*Completions*' buffer."
217 :global t :group 'partial-completion
218 ;; Deal with key bindings...
219 (PC-bindings partial-completion-mode)
220 ;; Deal with include file feature...
221 (cond ((not partial-completion-mode)
222 (remove-hook 'find-file-not-found-functions 'PC-look-for-include-file))
223 ((not PC-disable-includes)
224 (add-hook 'find-file-not-found-functions 'PC-look-for-include-file)))
225 ;; ... 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
240 (funcall
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)
247 mini-p)
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)
254 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))))
263
264 \f
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\".
270
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.
274
275 Word-delimiters for the purposes of Partial Completion are \"-\", \"_\",
276 \".\", and SPC."
277 (interactive)
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)))))
294
295
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."
300 (interactive)
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)
306 (if (eobp)
307 (PC-do-completion 'word))))
308
309
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."
314 (interactive)
315 (if (eq (PC-was-meta-key) PC-meta-flag)
316 (minibuffer-complete-word)
317 (insert " ")
318 (if (eobp)
319 (PC-do-completion 'word))))
320
321
322 (defun PC-complete-and-exit ()
323 "Like `minibuffer-complete-and-exit', but allows \"b--di\"-style abbreviations.
324 See `PC-complete' for details."
325 (interactive)
326 (if (eq (PC-was-meta-key) PC-meta-flag)
327 (minibuffer-complete-and-exit)
328 (PC-do-complete-and-exit)))
329
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."
333 (interactive)
334 (let ((minibuffer-completion-confirm nil))
335 (PC-do-complete-and-exit)))
336
337 (defun PC-do-complete-and-exit ()
338 (if (= (point-max) (minibuffer-prompt-end)) ; Duplicate the "bug" that Info-menu relies on...
339 (exit-minibuffer)
340 (let ((flag (PC-do-completion 'exit)))
341 (and flag
342 (if (or (eq flag 'complete)
343 (not minibuffer-completion-confirm))
344 (exit-minibuffer)
345 (PC-temp-minibuffer-message " [Confirm]"))))))
346
347
348 (defun PC-completion-help ()
349 "Like `minibuffer-completion-help', but allows \"b--di\"-style abbreviations.
350 See `PC-complete' for details."
351 (interactive)
352 (if (eq (PC-was-meta-key) PC-meta-flag)
353 (minibuffer-completion-help)
354 (PC-do-completion 'help)))
355
356 (defun PC-was-meta-key ()
357 (or (/= (length (this-command-keys)) 1)
358 (let ((key (aref (this-command-keys) 0)))
359 (if (integerp key)
360 (>= key 128)
361 (not (null (memq 'meta (event-modifiers key))))))))
362
363
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)
371
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.")
377
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)))
382 (message message)
383 (error message)))
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))))
388 result))
389
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.
396 (if pred
397 (test-completion str table pred)
398 (let ((completion-ignore-case nil))
399 (test-completion str table pred))))
400
401 ;; The following function is an attempt to work around two problems:
402
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.
407
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.
412
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)))
423
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
439 ;; into a buffer.
440 dirlength
441 (str (buffer-substring beg end))
442 (incname (and filename (string-match "<\\([^\"<>]*\\)>?$" str)))
443 (ambig nil)
444 basestr origstr
445 env-on
446 regex
447 p offset
448 (poss nil)
449 helpposs
450 (case-fold-search completion-ignore-case))
451
452 ;; Check if buffer contents can already be considered complete
453 (if (and (eq mode 'exit)
454 (test-completion str table pred))
455 (progn
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)
461 (insert str))
462 'complete)
463
464 ;; Do substitutions in directory names
465 (and filename
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)))
472 (progn
473 (delete-region beg end)
474 (insert str)
475 (setq end (+ beg (length str)))))
476
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)))
483
484 ;; Add wildcards if necessary
485 (and filename
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))
495 "*/" file))
496 (setq dir (file-name-directory dir)))
497 (setq origstr str str (concat dir file))))
498
499 ;; Look for wildcard expansions in directory name
500 (and filename
501 (string-match "\\*.*/" str)
502 (let ((pat str)
503 ;; The base dir for file-completion is passed in `predicate'.
504 (default-directory (expand-file-name pred))
505 files)
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)
509 "*"
510 (substring pat p))
511 p (+ p 2)))
512 (setq files (PC-expand-many-files (concat pat "*")))
513 (if files
514 (let ((dir (file-name-directory (car files)))
515 (p files))
516 (while (and (setq p (cdr p))
517 (equal dir (file-name-directory (car p)))))
518 (if p
519 (setq filename nil table nil pred nil
520 ambig t)
521 (delete-region beg end)
522 (setq str (concat dir (file-name-nondirectory str)))
523 (insert str)
524 (setq end (+ beg (length str)))))
525 (if origstr
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
530 ;; added wildcards.
531 (setq str origstr)
532 (setq filename nil table nil pred nil)))))
533
534 ;; Strip directory name if appropriate
535 (if filename
536 (if incname
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)))
545 (setq basestr str))
546
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)
553 p offset)
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)
557 PC-ndelims-regex
558 PC-delim-regex
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 '(?$ ?^ ?\. ?* ?+ ?? ?[ ?] ?\\))
563 -1 0)))
564 (setq regex (concat (substring regex 0 (+ p bump))
565 PC-ndelims-regex
566 (substring regex (+ p bump)))
567 p (+ p (length PC-ndelims-regex) 1)))))
568 (setq p 0)
569 (if filename
570 (while (setq p (string-match "\\\\\\*" regex p))
571 (setq regex (concat (substring regex 0 p)
572 "[^/]*"
573 (substring regex (+ p 2))))))
574 ;;(setq the-regex regex)
575 (setq regex (concat "\\`" regex))
576
577 (and (> (length basestr) 0)
578 (= (aref basestr 0) ?$)
579 (setq env-on t
580 table PC-env-vars-alist
581 pred nil))
582
583 ;; Find an initial list of possible completions
584 (if (not (setq p (string-match (concat PC-delim-regex
585 (if filename "\\|\\*" ""))
586 str
587 (+ (length dirname) offset))))
588
589 ;; Minibuffer contains no hyphens -- simple case!
590 (setq poss (all-completions (if env-on
591 basestr str)
592 table
593 pred))
594
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))
599 (substring str 0 p))
600 table
601 pred)))
602 (setq p compl)
603 (while p
604 (and (string-match regex (car p))
605 (progn
606 (set-text-properties 0 (length (car p)) '() (car p))
607 (setq poss (cons (car p) poss))))
608 (setq p (cdr p)))))
609
610 ;; If table had duplicates, they can be here.
611 (delete-dups poss)
612
613 ;; Handle completion-ignored-extensions
614 (and filename
615 (not (eq mode 'help))
616 (let ((p2 poss))
617
618 ;; Build a regular expression representing the extensions list
619 (or (equal completion-ignored-extensions PC-ignored-extensions)
620 (setq PC-ignored-regexp
621 (concat "\\("
622 (mapconcat
623 'regexp-quote
624 (setq PC-ignored-extensions
625 completion-ignored-extensions)
626 "\\|")
627 "\\)\\'")))
628
629 ;; Check if there are any without an ignored extension.
630 ;; Also ignore `.' and `..'.
631 (setq p nil)
632 (while p2
633 (or (string-match PC-ignored-regexp (car p2))
634 (string-match "\\(\\`\\|/\\)[.][.]?/?\\'" (car p2))
635 (setq p (cons (car p2) p)))
636 (setq p2 (cdr p2)))
637
638 ;; If there are "good" names, use them
639 (and p (setq poss p))))
640
641 ;; Now we have a list of possible completions
642 (cond
643
644 ;; No valid completions found
645 ((null poss)
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))
651 (beep)
652 (PC-temp-minibuffer-message (if ambig
653 " [Ambiguous dir name]"
654 (if (eq mode 'help)
655 " [No completions]"
656 " [No match]")))
657 nil))
658
659 ;; More than one valid completion found
660 ((or (cdr (setq helpposs poss))
661 (memq mode '(help word)))
662
663 ;; Is the actual string one of the possible completions?
664 (setq p (and (not (eq mode 'help)) poss))
665 (while (and p
666 (not (string-equal (car p) basestr)))
667 (setq p (cdr p)))
668 (and p (null mode)
669 (PC-temp-minibuffer-message " [Complete, but not unique]"))
670 (if (and p
671 (not (and (null mode)
672 (eq this-command last-command))))
673 t
674
675 ;; If ambiguous, try for a partial completion
676 (let ((improved nil)
677 prefix
678 (pt nil)
679 (skip "\\`"))
680
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)))
685 (let ((first t) i)
686 ;; Retain capitalization of user input even if
687 ;; completion-ignore-case is set.
688 (if (eq mode 'word)
689 (setq prefix (PC-chop-word prefix basestr)))
690 (goto-char (+ beg (length dirname)))
691 (while (and (progn
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
698 (forward-char 1)
699 (if (and (< (point) end)
700 (and (looking-at " ")
701 (memq (aref prefix i)
702 PC-delims-list)))
703 ;; replace " " by the actual delimiter
704 (progn
705 (delete-char 1)
706 (insert (substring prefix i (1+ i))))
707 ;; insert a new character
708 (progn
709 (and filename (looking-at "\\*")
710 (progn
711 (delete-char 1)
712 (setq end (1- end))))
713 (setq improved t)
714 (insert (substring prefix i (1+ i)))
715 (setq end (1+ end)))))
716 (setq i (1+ i)))
717 (or pt (setq pt (point)))
718 (looking-at PC-delim-regex))
719 (setq skip (concat skip
720 (regexp-quote prefix)
721 PC-ndelims-regex)
722 prefix (PC-try-completion
723 (PC-chunk-after
724 ;; not basestr, because that does
725 ;; not reflect insertions
726 (buffer-substring
727 (+ beg (length dirname)) end)
728 skip)
729 (mapcar
730 (lambda (x)
731 (when (string-match skip x)
732 (substring x (match-end 0))))
733 poss)))
734 (or (> i 0) (> (length prefix) 0))
735 (or (not (eq mode 'word))
736 (and first (> (length prefix) 0)
737 (setq first nil
738 prefix (substring prefix 0 1))))))
739 (goto-char (if (eq mode 'word) end
740 (or pt beg)))))
741
742 (if (and (eq mode 'word)
743 (not PC-word-failed-flag))
744
745 (if improved
746
747 ;; We changed it... would it be complete without the space?
748 (if (test-completion (buffer-substring 1 (1- end))
749 table pred)
750 (delete-region (1- end) end)))
751
752 (if improved
753
754 ;; We changed it... enough to be complete?
755 (and (eq mode 'exit)
756 (test-completion-ignore-case (field-string) table pred))
757
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))
762 (eq mode 'help))
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).
781 ;;
782 ;; Note that choose-completion-string-functions
783 ;; plays around with point.
784 (setq completion-base-size (if dirname
785 dirlength
786 (- beg prompt-end))))))
787 (PC-temp-minibuffer-message " [Next char not unique]"))
788 nil)))))
789
790 ;; Only one possible completion
791 (t
792 (if (and (equal basestr (car poss))
793 (not (and env-on filename)))
794 (if (null mode)
795 (PC-temp-minibuffer-message " [Sole completion]"))
796 (delete-region beg end)
797 (insert (format "%s"
798 (if filename
799 (substitute-in-file-name (concat dirname (car poss)))
800 (car poss)))))
801 t)))))
802
803 (defun PC-chop-word (new old)
804 (let ((i -1)
805 (j -1))
806 (while (and (setq i (string-match PC-delim-regex old (1+ i)))
807 (setq j (string-match PC-delim-regex new (1+ j)))))
808 (if (and 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))
812 new)))
813
814 (defvar PC-not-minibuffer nil)
815
816 (defun PC-temp-minibuffer-message (message)
817 "A Lisp version of `temp_minibuffer_message' from minibuf.c."
818 (cond (PC-not-minibuffer
819 (message message)
820 (sit-for 2)
821 (message ""))
822 ((fboundp 'temp-minibuffer-message)
823 (temp-minibuffer-message message))
824 (t
825 (let ((point-max (point-max)))
826 (save-excursion
827 (goto-char point-max)
828 (insert message))
829 (let ((inhibit-quit t))
830 (sit-for 2)
831 (delete-region point-max (point-max))
832 (when quit-flag
833 (setq quit-flag nil
834 unread-command-events '(7))))))))
835
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'.")
840
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
845 are inserted.
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."
850 (interactive)
851 (let* ((end (point))
852 ;; To complete the word under point, rather than just the portion
853 ;; before point, use this:
854 ;;; (save-excursion
855 ;;; (with-syntax-table lisp-mode-syntax-table
856 ;;; (forward-sexp 1)
857 ;;; (point))))
858 (beg (save-excursion
859 (with-syntax-table lisp-mode-syntax-table
860 (backward-sexp 1)
861 (while (= (char-syntax (following-char)) ?\')
862 (forward-char 1))
863 (point))))
864 (minibuffer-completion-table obarray)
865 (minibuffer-completion-predicate
866 (if (eq (char-after (1- beg)) ?\()
867 'fboundp
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
873 ;;
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.
879 ;;
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.
885 ;;
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.
891 ;;
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.
896 ;;
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))))
905
906 (defun PC-complete-as-file-name ()
907 "Perform completion on file names preceding point.
908 Environment vars are converted to their values."
909 (interactive)
910 (let* ((end (point))
911 (beg (if (re-search-backward "[^\\][ \t\n\"\`\'][^ \t\n\"\`\']"
912 (point-min) t)
913 (+ (point) 2)
914 (point-min)))
915 (minibuffer-completion-table 'read-file-name-internal)
916 (minibuffer-completion-predicate "")
917 (PC-not-minibuffer t))
918 (goto-char end)
919 (PC-do-completion nil beg end)))
920
921 ;; Use the shell to do globbing.
922 ;; This could now use file-expand-wildcards instead.
923
924 (defun PC-expand-many-files (name)
925 (with-current-buffer (generate-new-buffer " *Glob Output*")
926 (erase-buffer)
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\\|\\(^\\| \\)\\("
938 (regexp-quote name)
939 "\\|"
940 (regexp-quote (expand-file-name name))
941 "\\)\\( \\|$\\)"))
942 nil
943 (insert "(\"")
944 (while (search-forward " " nil t)
945 (delete-backward-char 1)
946 (insert "\" \""))
947 (goto-char (point-max))
948 (delete-backward-char 1)
949 (insert "\")")
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
955 (concat "\\("
956 (mapconcat
957 'regexp-quote
958 (setq PC-ignored-extensions
959 completion-ignored-extensions)
960 "\\|")
961 "\\)\\'")))
962 (setq p nil)
963 (while files
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)))
974 p))))
975
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.
979
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)))
985 (path nil)
986 new-buf)
987 (kill-buffer (current-buffer))
988 (if (equal name "")
989 (with-current-buffer (car (buffer-list))
990 (save-excursion
991 (beginning-of-line)
992 (if (looking-at
993 "[ \t]*#[ \t]*include[ \t]+[<\"]\\(.+\\)[>\"][ \t]*[\n/]")
994 (setq name (buffer-substring (match-beginning 1)
995 (match-end 1))
996 punc (char-after (1- (match-beginning 1))))
997 ;; Suggested by Frank Siebenlist:
998 (if (or (looking-at
999 "[ \t]*([ \t]*load[ \t]+\"\\([^\"]+\\)\"")
1000 (looking-at
1001 "[ \t]*([ \t]*load-library[ \t]+\"\\([^\"]+\\)\"")
1002 (looking-at
1003 "[ \t]*([ \t]*require[ \t]+'\\([^\t )]+\\)[\t )]"))
1004 (progn
1005 (setq name (buffer-substring (match-beginning 1)
1006 (match-end 1))
1007 punc ?\<
1008 path load-path)
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")))
1016 (if (eq punc ?\<)
1017 (let ((path (or path (PC-include-file-path))))
1018 (while (and path
1019 (not (file-exists-p
1020 (concat (file-name-as-directory (car path))
1021 name))))
1022 (setq path (cdr path)))
1023 (if 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))
1032 (if new-buf
1033 ;; no need to verify last-modified time for this!
1034 (set-buffer new-buf)
1035 (set-buffer (create-file-buffer name))
1036 (erase-buffer)
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.
1040 t)
1041 nil))
1042
1043 (defun PC-include-file-path ()
1044 (or PC-include-file-path
1045 (let ((env (getenv "INCPATH"))
1046 (path nil)
1047 pos)
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)))
1052 path)))
1053
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."
1059 (setq search-path
1060 (mapcar (lambda (dir)
1061 (if dir (file-name-as-directory dir) default-directory))
1062 search-path))
1063 (if (file-name-absolute-p file)
1064 ;; It's an absolute file name, so don't need search-path
1065 (progn
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))
1071 file-lists)
1072 ;; Append subdirectory part to each element of search-path
1073 (if subdir
1074 (setq search-path
1075 (mapcar (lambda (dir) (concat dir subdir))
1076 search-path)
1077 file ))
1078 ;; Make list of completions in each directory on search-path
1079 (while search-path
1080 (let* ((dir (car search-path))
1081 (subdir (if full dir subdir)))
1082 (if (file-directory-p dir)
1083 (progn
1084 (setq file-lists
1085 (cons
1086 (mapcar (lambda (file) (concat subdir file))
1087 (file-name-all-completions ndfile
1088 (car search-path)))
1089 file-lists))))
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)))))
1094 compressed)
1095 (while sorted
1096 (if (equal (car sorted) (car compressed)) nil
1097 (setq compressed (cons (car sorted) compressed)))
1098 (setq sorted (cdr sorted)))
1099 compressed))))
1100
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)))
1107 (completion-table
1108 (mapcar (lambda (x)
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
1113 (cond
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)))))
1118 ad-do-it))
1119 \f
1120
1121 (provide 'complete)
1122
1123 ;; arch-tag: fc7e2768-ff44-4e22-b579-4d825b968458
1124 ;;; complete.el ends here