Merge from origin/emacs-24
[emacs.git] / lisp / completion.el
blobd2d94e778d59454ede671391be89c2c581e9b75c
1 ;;; completion.el --- dynamic word-completion code
3 ;; Copyright (C) 1990, 1993, 1995, 1997, 2001-2014 Free Software
4 ;; Foundation, Inc.
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: abbrev convenience
8 ;; Author: Jim Salem <alem@bbnplanet.com> of Thinking Machines Inc.
9 ;; (ideas suggested by Brewster Kahle)
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; What to put in .emacs
29 ;;-----------------------
30 ;; (dynamic-completion-mode)
32 ;;---------------------------------------------------------------------------
33 ;; Documentation [Slightly out of date]
34 ;;---------------------------------------------------------------------------
35 ;; (also check the documentation string of the functions)
37 ;; Introduction
38 ;;---------------
40 ;; After you type a few characters, pressing the "complete" key inserts
41 ;; the rest of the word you are likely to type.
43 ;; This watches all the words that you type and remembers them. When
44 ;; typing a new word, pressing "complete" (meta-return) "completes" the
45 ;; word by inserting the most recently used word that begins with the
46 ;; same characters. If you press meta-return repeatedly, it cycles
47 ;; through all the words it knows about.
49 ;; If you like the completion then just continue typing, it is as if you
50 ;; entered the text by hand. If you want the inserted extra characters
51 ;; to go away, type control-w or delete. More options are described below.
53 ;; The guesses are made in the order of the most recently "used". Typing
54 ;; in a word and then typing a separator character (such as a space) "uses"
55 ;; the word. So does moving a cursor over the word. If no words are found,
56 ;; it uses an extended version of the dabbrev style completion.
58 ;; You automatically save the completions you use to a file between
59 ;; sessions.
61 ;; Completion enables programmers to enter longer, more descriptive
62 ;; variable names while typing fewer keystrokes than they normally would.
65 ;; Full documentation
66 ;;---------------------
68 ;; A "word" is any string containing characters with either word or symbol
69 ;; syntax. [E.G. Any alphanumeric string with hyphens, underscores, etc.]
70 ;; Unless you change the constants, you must type at least three characters
71 ;; for the word to be recognized. Only words longer than 6 characters are
72 ;; saved.
74 ;; When you load this file, completion will be on. I suggest you use the
75 ;; compiled version (because it is noticeably faster).
77 ;; M-x completion-mode toggles whether or not new words are added to the
78 ;; database by changing the value of enable-completion.
80 ;; SAVING/LOADING COMPLETIONS
81 ;; Completions are automatically saved from one session to another
82 ;; (unless save-completions-flag or enable-completion is nil).
83 ;; Activating this minor-mode (calling completion-initialize) loads
84 ;; a completions database for a saved completions file
85 ;; (default: ~/.completions). When you exit, Emacs saves a copy of the
86 ;; completions that you often use. When you next start, Emacs loads in
87 ;; the saved completion file.
89 ;; The number of completions saved depends loosely on
90 ;; *saved-completions-decay-factor*. Completions that have never been
91 ;; inserted via "complete" are not saved. You are encouraged to experiment
92 ;; with different functions (see compute-completion-min-num-uses).
94 ;; Some completions are permanent and are always saved out. These
95 ;; completions have their num-uses slot set to T. Use
96 ;; add-permanent-completion to do this
98 ;; Completions are saved only if enable-completion is T. The number of old
99 ;; versions kept of the saved completions file is controlled by
100 ;; completions-file-versions-kept.
102 ;; COMPLETE KEY OPTIONS
103 ;; The complete function takes a numeric arguments.
104 ;; control-u :: leave the point at the beginning of the completion rather
105 ;; than the middle.
106 ;; a number :: rotate through the possible completions by that amount
107 ;; `-' :: same as -1 (insert previous completion)
109 ;; HOW THE DATABASE IS MAINTAINED
110 ;; <write>
112 ;; UPDATING THE DATABASE MANUALLY
113 ;; m-x kill-completion
114 ;; kills the completion at point.
115 ;; m-x add-completion
116 ;; m-x add-permanent-completion
118 ;; UPDATING THE DATABASE FROM A SOURCE CODE FILE
119 ;; m-x add-completions-from-buffer
120 ;; Parses all the definition names from a C or LISP mode buffer and
121 ;; adds them to the completion database.
123 ;; m-x add-completions-from-lisp-file
124 ;; Parses all the definition names from a C or Lisp mode file and
125 ;; adds them to the completion database.
127 ;; UPDATING THE DATABASE FROM A TAGS TABLE
128 ;; m-x add-completions-from-tags-table
129 ;; Adds completions from the current tags-table-buffer.
131 ;; HOW A COMPLETION IS FOUND
132 ;; <write>
134 ;; STRING CASING
135 ;; Completion is string case independent if case-fold-search has its
136 ;; normal default of T. Also when the completion is inserted the case of the
137 ;; entry is coerced appropriately.
138 ;; [E.G. APP --> APPROPRIATELY app --> appropriately
139 ;; App --> Appropriately]
141 ;; INITIALIZATION
142 ;; The form `(completion-initialize)' initializes the completion system by
143 ;; trying to load in the user's completions. After the first call, further
144 ;; calls have no effect so one should be careful not to put the form in a
145 ;; site's standard site-init file.
147 ;;---------------------------------------------------------------------------
151 ;;---------------------------------------------------------------------------
152 ;; Functions you might like to call
153 ;;---------------------------------------------------------------------------
155 ;; add-completion string &optional num-uses
156 ;; Adds a new string to the database
158 ;; add-permanent-completion string
159 ;; Adds a new string to the database with num-uses = T
162 ;; kill-completion string
163 ;; Kills the completion from the database.
165 ;; clear-all-completions
166 ;; Clears the database
168 ;; list-all-completions
169 ;; Returns a list of all completions.
172 ;; next-completion string &optional index
173 ;; Returns a completion entry that starts with string.
175 ;; find-exact-completion string
176 ;; Returns a completion entry that exactly matches string.
178 ;; complete
179 ;; Inserts a completion at point
181 ;; completion-initialize
182 ;; Loads the completions file and sets up so that exiting emacs will
183 ;; save them.
185 ;; save-completions-to-file &optional filename
186 ;; load-completions-from-file &optional filename
188 ;;-----------------------------------------------
189 ;; Other functions
190 ;;-----------------------------------------------
192 ;; get-completion-list string
194 ;; These things are for manipulating the structure
195 ;; make-completion string num-uses
196 ;; completion-num-uses completion
197 ;; completion-string completion
198 ;; set-completion-num-uses completion num-uses
199 ;; set-completion-string completion string
203 ;;-----------------------------------------------
204 ;; To Do :: (anybody ?)
205 ;;-----------------------------------------------
207 ;; Implement Lookup and keyboard interface in C
208 ;; Add package prefix smarts (for Common Lisp)
209 ;; Add autoprompting of possible completions after every keystroke (fast
210 ;; terminals only !)
211 ;; Add doc. to texinfo
214 ;;-----------------------------------------------
215 ;;; Change Log:
216 ;;-----------------------------------------------
217 ;; Sometime in '84 Brewster implemented a somewhat buggy version for
218 ;; Symbolics LISPMs.
219 ;; Jan. '85 Jim became enamored of the idea and implemented a faster,
220 ;; more robust version.
221 ;; With input from many users at TMC, (rose, craig, and gls come to mind),
222 ;; the current style of interface was developed.
223 ;; 9/87, Jim and Brewster took terminals home. Yuck. After
224 ;; complaining for a while Brewster implemented a subset of the current
225 ;; LISPM version for GNU Emacs.
226 ;; 8/88 After complaining for a while (and with sufficient
227 ;; promised rewards), Jim reimplemented a version of GNU completion
228 ;; superior to that of the LISPM version.
230 ;;-----------------------------------------------
231 ;; Acknowledgments
232 ;;-----------------------------------------------
233 ;; Cliff Lasser (cal@think.com), Kevin Herbert (kph@cisco.com),
234 ;; eero@media-lab, kgk@cs.brown.edu, jla@ai.mit.edu,
236 ;;-----------------------------------------------
237 ;; Change Log
238 ;;-----------------------------------------------
239 ;; From version 9 to 10
240 ;; - Allowance for non-integral *completion-version* nos.
241 ;; - Fix cmpl-apply-as-top-level for keyboard macros
242 ;; - Fix broken completion merging (in save-completions-to-file)
243 ;; - More misc. fixes for version 19.0 of emacs
245 ;; From Version 8 to 9
246 ;; - Ported to version 19.0 of emacs (backcompatible with version 18)
247 ;; - Added add-completions-from-tags-table (with thanks to eero@media-lab)
249 ;; From Version 7 to 8
250 ;; - Misc. changes to comments
251 ;; - new completion key bindings: c-x o, M->, M-<, c-a, c-e
252 ;; - cdabbrev now checks all the visible window buffers and the "other buffer"
253 ;; - `%' is now a symbol character rather than a separator (except in C mode)
255 ;; From Version 6 to 7
256 ;; - Fixed bug with saving out .completion file the first time
258 ;; From Version 5 to 6
259 ;; - removed statistics recording
260 ;; - reworked advise to handle autoloads
261 ;; - Fixed fortran mode support
262 ;; - Added new cursor motion triggers
264 ;; From Version 4 to 5
265 ;; - doesn't bother saving if nothing has changed
266 ;; - auto-save if haven't used for a 1/2 hour
267 ;; - save period extended to two weeks
268 ;; - minor fix to capitalization code
269 ;; - added *completion-auto-save-period* to variables recorded.
270 ;; - added reenter protection to cmpl-record-statistics-filter
271 ;; - added backup protection to save-completions-to-file (prevents
272 ;; problems with disk full errors)
274 ;;; Code:
276 ;;---------------------------------------------------------------------------
277 ;; User changeable parameters
278 ;;---------------------------------------------------------------------------
280 (defgroup completion nil
281 "Dynamic word-completion code."
282 :group 'matching
283 :group 'convenience)
286 (defcustom enable-completion t
287 "Non-nil means enable recording and saving of completions.
288 If nil, no new words are added to the database or saved to the init file."
289 :type 'boolean
290 :group 'completion)
292 (defcustom save-completions-flag t
293 "Non-nil means save most-used completions when exiting Emacs.
294 See also `save-completions-retention-time'."
295 :type 'boolean
296 :group 'completion)
298 (defcustom save-completions-file-name
299 (locate-user-emacs-file "completions" ".completions")
300 "The filename to save completions to."
301 :type 'file
302 :group 'completion)
304 (defcustom save-completions-retention-time 336
305 "Discard a completion if unused for this many hours.
306 \(1 day = 24, 1 week = 168). If this is 0, non-permanent completions
307 will not be saved unless these are used. Default is two weeks."
308 :type 'integer
309 :group 'completion)
311 (defcustom completion-on-separator-character nil
312 "Non-nil means separator characters mark previous word as used.
313 This means the word will be saved as a completion."
314 :type 'boolean
315 :group 'completion)
317 (defcustom completions-file-versions-kept kept-new-versions
318 "Number of versions to keep for the saved completions file."
319 :type 'integer
320 :group 'completion)
322 (defcustom completion-prompt-speed-threshold 4800
323 "Minimum output speed at which to display next potential completion."
324 :type 'integer
325 :group 'completion)
327 (defcustom completion-cdabbrev-prompt-flag nil
328 "If non-nil, the next completion prompt does a cdabbrev search.
329 This can be time consuming."
330 :type 'boolean
331 :group 'completion)
333 (defcustom completion-search-distance 15000
334 "How far to search in the buffer when looking for completions.
335 In number of characters. If nil, search the whole buffer."
336 :type 'integer
337 :group 'completion)
339 (defcustom completions-merging-modes '(lisp c)
340 "List of modes {`c' or `lisp'} for automatic completions merging.
341 Definitions from visited files which have these modes
342 are automatically added to the completion database."
343 :type '(set (const lisp) (const c))
344 :group 'completion)
346 ;;(defvar *completion-auto-save-period* 1800
347 ;; "The period in seconds to wait for emacs to be idle before autosaving
348 ;;the completions. Default is a 1/2 hour.")
350 (defvar completion-min-length 6
351 "The minimum length of a stored completion.
352 DON'T CHANGE WITHOUT RECOMPILING ! This is used by macros.")
354 (defvar completion-max-length 200
355 "The maximum length of a stored completion.
356 DON'T CHANGE WITHOUT RECOMPILING ! This is used by macros.")
358 (defvar completion-prefix-min-length 3
359 "The minimum length of a completion search string.
360 DON'T CHANGE WITHOUT RECOMPILING ! This is used by macros.")
362 ;;---------------------------------------------------------------------------
363 ;; Internal Variables
364 ;;---------------------------------------------------------------------------
366 (defvar cmpl-initialized-p nil
367 "Set to t when the completion system is initialized.
368 Indicates that the old completion file has been read in.")
370 (defvar cmpl-completions-accepted-p nil
371 "Set to t as soon as the first completion has been accepted.
372 Used to decide whether to save completions.")
374 (defvar cmpl-preceding-syntax)
376 (defvar completion-string)
378 ;;---------------------------------------------------------------------------
379 ;; Low level tools
380 ;;---------------------------------------------------------------------------
382 ;;-----------------------------------------------
383 ;; String case coercion
384 ;;-----------------------------------------------
386 (defun cmpl-string-case-type (string)
387 "Return :capitalized, :up, :down, :mixed, or :neither for case of STRING."
388 (let ((case-fold-search nil))
389 (cond ((string-match "[[:lower:]]" string)
390 (cond ((string-match "[[:upper:]]" string)
391 (cond ((and (> (length string) 1)
392 (null (string-match "[[:upper:]]" string 1)))
393 :capitalized)
395 :mixed)))
396 (t :down)))
398 (cond ((string-match "[[:upper:]]" string)
399 :up)
400 (t :neither))))))
402 ;; Tests -
403 ;; (cmpl-string-case-type "123ABCDEF456") --> :up
404 ;; (cmpl-string-case-type "123abcdef456") --> :down
405 ;; (cmpl-string-case-type "123aBcDeF456") --> :mixed
406 ;; (cmpl-string-case-type "123456") --> :neither
407 ;; (cmpl-string-case-type "Abcde123") --> :capitalized
409 (defun cmpl-coerce-string-case (string case-type)
410 (cond ((eq case-type :down) (downcase string))
411 ((eq case-type :up) (upcase string))
412 ((eq case-type :capitalized)
413 (setq string (downcase string))
414 (aset string 0 (logand ?\337 (aref string 0)))
415 string)
416 (t string)))
418 (defun cmpl-merge-string-cases (string-to-coerce given-string)
419 (let ((string-case-type (cmpl-string-case-type string-to-coerce)))
420 (cond ((memq string-case-type '(:down :up :capitalized))
421 ;; Found string is in a standard case. Coerce to a type based on
422 ;; the given string
423 (cmpl-coerce-string-case string-to-coerce
424 (cmpl-string-case-type given-string)))
426 ;; If the found string is in some unusual case, just insert it
427 ;; as is
428 string-to-coerce))))
430 ;; Tests -
431 ;; (cmpl-merge-string-cases "AbCdEf456" "abc") --> AbCdEf456
432 ;; (cmpl-merge-string-cases "abcdef456" "ABC") --> ABCDEF456
433 ;; (cmpl-merge-string-cases "ABCDEF456" "Abc") --> Abcdef456
434 ;; (cmpl-merge-string-cases "ABCDEF456" "abc") --> abcdef456
437 (defun cmpl-hours-since-origin ()
438 (floor (float-time) 3600))
440 ;;---------------------------------------------------------------------------
441 ;; "Symbol" parsing functions
442 ;;---------------------------------------------------------------------------
443 ;; The functions symbol-before-point, symbol-under-point, etc. quickly return
444 ;; an appropriate symbol string. The strategy is to temporarily change
445 ;; the syntax table to enable fast symbol searching. There are three classes
446 ;; of syntax in these "symbol" syntax tables ::
448 ;; syntax (?_) - "symbol" chars (e.g. alphanumerics)
449 ;; syntax (?w) - symbol chars to ignore at end of words (e.g. period).
450 ;; syntax (? ) - everything else
452 ;; Thus by judicious use of scan-sexps and forward-word, we can get
453 ;; the word we want relatively fast and without consing.
455 ;; Why do we need a separate category for "symbol chars to ignore at ends" ?
456 ;; For example, in LISP we want starting :'s trimmed
457 ;; so keyword argument specifiers also define the keyword completion. And,
458 ;; for example, in C we want `.' appearing in a structure ref. to
459 ;; be kept intact in order to store the whole structure ref.; however, if
460 ;; it appears at the end of a symbol it should be discarded because it is
461 ;; probably used as a period.
463 ;; Here is the default completion syntax ::
464 ;; Symbol chars :: A-Z a-z 0-9 @ / \ * + ~ $ < > %
465 ;; Symbol chars to ignore at ends :: _ : . -
466 ;; Separator chars. :: <tab> <space> ! ^ & ( ) = ` | { } [ ] ; " ' #
467 ;; , ? <Everything else>
469 ;; Mode specific differences and notes ::
470 ;; LISP diffs ->
471 ;; Symbol chars :: ! & ? = ^
473 ;; C diffs ->
474 ;; Separator chars :: + * / : %
475 ;; A note on the hyphen (`-'). Perhaps the hyphen should also be a separator
476 ;; char., however, we wanted to have completion symbols include pointer
477 ;; references. For example, "foo->bar" is a symbol as far as completion is
478 ;; concerned.
480 ;; FORTRAN diffs ->
481 ;; Separator chars :: + - * / :
483 ;; Pathname diffs ->
484 ;; Symbol chars :: .
485 ;; Of course there is no pathname "mode" and in fact we have not implemented
486 ;; this table. However, if there was such a mode, this is what it would look
487 ;; like.
489 ;;-----------------------------------------------
490 ;; Table definitions
491 ;;-----------------------------------------------
493 (defconst completion-standard-syntax-table
494 (let ((table (make-syntax-table))
496 ;; Default syntax is whitespace.
497 (setq i 0)
498 (while (< i 256)
499 (modify-syntax-entry i " " table)
500 (setq i (1+ i)))
501 ;; alpha chars
502 (setq i 0)
503 (while (< i 26)
504 (modify-syntax-entry (+ ?a i) "_" table)
505 (modify-syntax-entry (+ ?A i) "_" table)
506 (setq i (1+ i)))
507 ;; digit chars.
508 (setq i 0)
509 (while (< i 10)
510 (modify-syntax-entry (+ ?0 i) "_" table)
511 (setq i (1+ i)))
512 ;; Other ones
513 (let ((symbol-chars '(?@ ?/ ?\\ ?* ?+ ?~ ?$ ?< ?> ?%))
514 (symbol-chars-ignore '(?_ ?- ?: ?.)))
515 (dolist (char symbol-chars)
516 (modify-syntax-entry char "_" table))
517 (dolist (char symbol-chars-ignore)
518 (modify-syntax-entry char "w" table)))
519 table))
521 (defvar completion-syntax-table completion-standard-syntax-table
522 "This variable holds the current completion syntax table.")
523 (make-variable-buffer-local 'completion-syntax-table)
525 ;;-----------------------------------------------
526 ;; Symbol functions
527 ;;-----------------------------------------------
528 (defvar cmpl-symbol-start nil
529 "Holds first character of symbol, after any completion symbol function.")
530 (defvar cmpl-symbol-end nil
531 "Holds last character of symbol, after any completion symbol function.")
533 (defun symbol-under-point ()
534 "Return the symbol that the point is currently on.
535 But only if it is longer than `completion-min-length'."
536 (with-syntax-table completion-syntax-table
537 (when (memq (char-syntax (following-char)) '(?w ?_))
538 ;; Cursor is on following-char and after preceding-char
539 (let ((saved-point (point)))
540 (setq cmpl-symbol-start (scan-sexps (1+ saved-point) -1)
541 cmpl-symbol-end (scan-sexps saved-point 1))
542 ;; Remove chars to ignore at the start.
543 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
544 (goto-char cmpl-symbol-start)
545 (forward-word 1)
546 (setq cmpl-symbol-start (point))
547 (goto-char saved-point)))
548 ;; Remove chars to ignore at the end.
549 (cond ((= (char-syntax (char-after (1- cmpl-symbol-end))) ?w)
550 (goto-char cmpl-symbol-end)
551 (forward-word -1)
552 (setq cmpl-symbol-end (point))
553 (goto-char saved-point)))
554 ;; Return completion if the length is reasonable.
555 (if (and (<= completion-min-length
556 (- cmpl-symbol-end cmpl-symbol-start))
557 (<= (- cmpl-symbol-end cmpl-symbol-start)
558 completion-max-length))
559 (buffer-substring-no-properties
560 cmpl-symbol-start cmpl-symbol-end))))))
562 ;; tests for symbol-under-point
563 ;; `^' indicates cursor pos. where value is returned
564 ;; simple-word-test
565 ;; ^^^^^^^^^^^^^^^^ --> simple-word-test
566 ;; _harder_word_test_
567 ;; ^^^^^^^^^^^^^^^^^^ --> harder_word_test
568 ;; .___.______.
569 ;; --> nil
570 ;; /foo/bar/quux.hello
571 ;; ^^^^^^^^^^^^^^^^^^^ --> /foo/bar/quux.hello
574 (defun symbol-before-point ()
575 "Return a string of the symbol immediately before point.
576 Returns nil if there isn't one longer than `completion-min-length'."
577 ;; This is called when a word separator is typed so it must be FAST !
578 (with-syntax-table completion-syntax-table
579 ;; Cursor is on following-char and after preceding-char
580 (cond ((= (setq cmpl-preceding-syntax (char-syntax (preceding-char))) ?_)
581 ;; Number of chars to ignore at end.
582 (setq cmpl-symbol-end (point)
583 cmpl-symbol-start (scan-sexps cmpl-symbol-end -1))
584 ;; Remove chars to ignore at the start.
585 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
586 (goto-char cmpl-symbol-start)
587 (forward-word 1)
588 (setq cmpl-symbol-start (point))
589 (goto-char cmpl-symbol-end)))
590 ;; Return value if long enough.
591 (if (>= cmpl-symbol-end
592 (+ cmpl-symbol-start completion-min-length))
593 (buffer-substring-no-properties
594 cmpl-symbol-start cmpl-symbol-end)))
595 ((= cmpl-preceding-syntax ?w)
596 ;; chars to ignore at end
597 (let ((saved-point (point)))
598 (setq cmpl-symbol-start (scan-sexps saved-point -1))
599 ;; take off chars. from end
600 (forward-word -1)
601 (setq cmpl-symbol-end (point))
602 ;; remove chars to ignore at the start
603 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
604 (goto-char cmpl-symbol-start)
605 (forward-word 1)
606 (setq cmpl-symbol-start (point))))
607 ;; Restore state.
608 (goto-char saved-point)
609 ;; Return completion if the length is reasonable
610 (if (and (<= completion-min-length
611 (- cmpl-symbol-end cmpl-symbol-start))
612 (<= (- cmpl-symbol-end cmpl-symbol-start)
613 completion-max-length))
614 (buffer-substring-no-properties
615 cmpl-symbol-start cmpl-symbol-end)))))))
617 ;; tests for symbol-before-point
618 ;; `^' indicates cursor pos. where value is returned
619 ;; simple-word-test
620 ;; ^ --> nil
621 ;; ^ --> nil
622 ;; ^ --> simple-w
623 ;; ^ --> simple-word-test
624 ;; _harder_word_test_
625 ;; ^ --> harder_word_test
626 ;; ^ --> harder_word_test
627 ;; ^ --> harder
628 ;; .___....
629 ;; --> nil
631 (defun symbol-under-or-before-point ()
632 ;; This could be made slightly faster but it is better to avoid
633 ;; copying all the code.
634 ;; However, it is only used by the completion string prompter.
635 ;; If it comes into common use, it could be rewritten.
636 (if (memq (with-syntax-table completion-syntax-table
637 (char-syntax (following-char)))
638 '(?w ?_))
639 (symbol-under-point)
640 (symbol-before-point)))
643 (defun symbol-before-point-for-complete ()
644 ;; "Returns a string of the symbol immediately before point
645 ;; or nil if there isn't one. Like symbol-before-point but doesn't trim the
646 ;; end chars."
647 ;; Cursor is on following-char and after preceding-char
648 (with-syntax-table completion-syntax-table
649 (cond ((memq (setq cmpl-preceding-syntax (char-syntax (preceding-char)))
650 '(?_ ?w))
651 (setq cmpl-symbol-end (point)
652 cmpl-symbol-start (scan-sexps cmpl-symbol-end -1))
653 ;; Remove chars to ignore at the start.
654 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
655 (goto-char cmpl-symbol-start)
656 (forward-word 1)
657 (setq cmpl-symbol-start (point))
658 (goto-char cmpl-symbol-end)))
659 ;; Return completion if the length is reasonable.
660 (if (and (<= completion-prefix-min-length
661 (- cmpl-symbol-end cmpl-symbol-start))
662 (<= (- cmpl-symbol-end cmpl-symbol-start)
663 completion-max-length))
664 (buffer-substring-no-properties
665 cmpl-symbol-start cmpl-symbol-end))))))
667 ;; tests for symbol-before-point-for-complete
668 ;; `^' indicates cursor pos. where value is returned
669 ;; simple-word-test
670 ;; ^ --> nil
671 ;; ^ --> nil
672 ;; ^ --> simple-w
673 ;; ^ --> simple-word-test
674 ;; _harder_word_test_
675 ;; ^ --> harder_word_test
676 ;; ^ --> harder_word_test_
677 ;; ^ --> harder_
678 ;; .___....
679 ;; --> nil
683 ;;---------------------------------------------------------------------------
684 ;; Statistics Recording
685 ;;---------------------------------------------------------------------------
687 ;; Note that the guts of this has been turned off. The guts
688 ;; are in completion-stats.el.
690 ;;-----------------------------------------------
691 ;; Completion Sources
692 ;;-----------------------------------------------
694 ;; ID numbers
695 (defconst cmpl-source-unknown 0)
696 (defconst cmpl-source-init-file 1)
697 (defconst cmpl-source-file-parsing 2)
698 (defconst cmpl-source-separator 3)
699 (defconst cmpl-source-cursor-moves 4)
700 (defconst cmpl-source-interactive 5)
701 (defconst cmpl-source-cdabbrev 6)
702 (defconst num-cmpl-sources 7)
703 (defvar current-completion-source cmpl-source-unknown)
707 ;;---------------------------------------------------------------------------
708 ;; Completion Method #2: dabbrev-expand style
709 ;;---------------------------------------------------------------------------
711 ;; This method is used if there are no useful stored completions. It is
712 ;; based on dabbrev-expand with these differences :
713 ;; 1) Faster (we don't use regexps)
714 ;; 2) case coercion handled correctly
715 ;; This is called cdabbrev to differentiate it.
716 ;; We simply search backwards through the file looking for words which
717 ;; start with the same letters we are trying to complete.
720 (defvar cdabbrev-completions-tried nil)
721 ;; "A list of all the cdabbrev completions since the last reset.")
723 (defvar cdabbrev-current-point 0)
724 ;; "The current point position the cdabbrev search is at.")
726 (defvar cdabbrev-current-window nil)
727 ;; "The current window we are looking for cdabbrevs in.
728 ;; Return t if looking in (other-buffer), nil if no more cdabbrevs.")
730 (defvar cdabbrev-wrapped-p nil)
731 ;; "Return t if the cdabbrev search has wrapped around the file.")
733 (defvar cdabbrev-abbrev-string "")
734 (defvar cdabbrev-start-point 0)
735 (defvar cdabbrev-stop-point)
737 ;; Test strings for cdabbrev
738 ;; cdat-upcase ;;same namestring
739 ;; CDAT-UPCASE ;;ok
740 ;; cdat2 ;;too short
741 ;; cdat-1-2-3-4 ;;ok
742 ;; a-cdat-1 ;;doesn't start correctly
743 ;; cdat-simple ;;ok
746 (defun reset-cdabbrev (abbrev-string &optional initial-completions-tried)
747 "Reset the cdabbrev search to search for ABBREV-STRING.
748 INITIAL-COMPLETIONS-TRIED is a list of downcased strings to ignore
749 during the search."
750 (setq cdabbrev-abbrev-string abbrev-string
751 cdabbrev-completions-tried
752 (cons (downcase abbrev-string) initial-completions-tried))
753 (reset-cdabbrev-window t))
755 (defun set-cdabbrev-buffer ()
756 ;; cdabbrev-current-window must not be nil
757 (set-buffer (if (eq cdabbrev-current-window t)
758 (other-buffer)
759 (window-buffer cdabbrev-current-window))))
762 (defun reset-cdabbrev-window (&optional initializep)
763 "Reset the cdabbrev search to search for abbrev-string."
764 ;; Set the window
765 (cond (initializep
766 (setq cdabbrev-current-window (selected-window)))
767 ((eq cdabbrev-current-window t)
768 ;; Everything has failed
769 (setq cdabbrev-current-window nil))
770 (cdabbrev-current-window
771 (setq cdabbrev-current-window (next-window cdabbrev-current-window))
772 (if (eq cdabbrev-current-window (selected-window))
773 ;; No more windows, try other buffer.
774 (setq cdabbrev-current-window t))))
775 (if cdabbrev-current-window
776 (save-excursion
777 (set-cdabbrev-buffer)
778 (setq cdabbrev-current-point (point)
779 cdabbrev-start-point cdabbrev-current-point
780 cdabbrev-stop-point
781 (if completion-search-distance
782 (max (point-min)
783 (- cdabbrev-start-point completion-search-distance))
784 (point-min))
785 cdabbrev-wrapped-p nil))))
787 (defun next-cdabbrev ()
788 "Return the next possible cdabbrev expansion or nil if there isn't one.
789 `reset-cdabbrev' must've been called already.
790 This is sensitive to `case-fold-search'."
791 ;; note that case-fold-search affects the behavior of this function
792 ;; Bug: won't pick up an expansion that starts at the top of buffer
793 (if cdabbrev-current-window
794 (let (saved-point
795 saved-syntax
796 (expansion nil)
797 downcase-expansion tried-list syntax saved-point-2)
798 (save-excursion
799 (unwind-protect
800 (progn
801 ;; Switch to current completion buffer
802 (set-cdabbrev-buffer)
803 ;; Save current buffer state
804 (setq saved-point (point)
805 saved-syntax (syntax-table))
806 ;; Restore completion state
807 (set-syntax-table completion-syntax-table)
808 (goto-char cdabbrev-current-point)
809 ;; Loop looking for completions
810 (while
811 ;; This code returns t if it should loop again
812 (cond
813 (;; search for the string
814 (search-backward cdabbrev-abbrev-string cdabbrev-stop-point t)
815 ;; return nil if the completion is valid
816 (not
817 (and
818 ;; does it start with a separator char ?
819 (or (= (setq syntax (char-syntax (preceding-char))) ? )
820 (and (= syntax ?w)
821 ;; symbol char to ignore at end. Are we at end ?
822 (progn
823 (setq saved-point-2 (point))
824 (forward-word -1)
825 (prog1
826 (= (char-syntax (preceding-char)) ? )
827 (goto-char saved-point-2)))))
828 ;; is the symbol long enough ?
829 (setq expansion (symbol-under-point))
830 ;; have we not tried this one before
831 (progn
832 ;; See if we've already used it
833 (setq tried-list cdabbrev-completions-tried
834 downcase-expansion (downcase expansion))
835 (while (and tried-list
836 (not (string-equal downcase-expansion
837 (car tried-list))))
838 ;; Already tried, don't choose this one
839 (setq tried-list (cdr tried-list)))
840 ;; at this point tried-list will be nil if this
841 ;; expansion has not yet been tried
842 (if tried-list
843 (setq expansion nil)
844 t)))))
845 ;; search failed
846 (cdabbrev-wrapped-p
847 ;; If already wrapped, then we've failed completely
848 nil)
850 ;; need to wrap
851 (goto-char (setq cdabbrev-current-point
852 (if completion-search-distance
853 (min (point-max) (+ cdabbrev-start-point completion-search-distance))
854 (point-max))))
856 (setq cdabbrev-wrapped-p t))))
857 ;; end of while loop
858 (cond (expansion
859 ;; successful
860 (setq cdabbrev-completions-tried
861 (cons downcase-expansion cdabbrev-completions-tried)
862 cdabbrev-current-point (point)))))
863 (set-syntax-table saved-syntax)
864 (goto-char saved-point)))
865 ;; If no expansion, go to next window
866 (cond (expansion)
867 (t (reset-cdabbrev-window)
868 (next-cdabbrev))))))
870 ;; The following must be eval'd in the minibuffer ::
871 ;; (reset-cdabbrev "cdat")
872 ;; (next-cdabbrev) --> "cdat-simple"
873 ;; (next-cdabbrev) --> "cdat-1-2-3-4"
874 ;; (next-cdabbrev) --> "CDAT-UPCASE"
875 ;; (next-cdabbrev) --> "cdat-wrapping"
876 ;; (next-cdabbrev) --> "cdat_start_sym"
877 ;; (next-cdabbrev) --> nil
878 ;; (next-cdabbrev) --> nil
879 ;; (next-cdabbrev) --> nil
881 ;; _cdat_start_sym
882 ;; cdat-wrapping
885 ;;---------------------------------------------------------------------------
886 ;; Completion Database
887 ;;---------------------------------------------------------------------------
889 ;; We use two storage modes for the two search types ::
890 ;; 1) Prefix {cmpl-prefix-obarray} for looking up possible completions
891 ;; Used by search-completion-next
892 ;; the value of the symbol is nil or a cons of head and tail pointers
893 ;; 2) Interning {cmpl-obarray} to see if it's in the database
894 ;; Used by find-exact-completion, completion-in-database-p
895 ;; The value of the symbol is the completion entry
897 ;; bad things may happen if this length is changed due to the way
898 ;; GNU implements obarrays
899 (defconst cmpl-obarray-length 511)
901 (defvar cmpl-prefix-obarray (make-vector cmpl-obarray-length 0)
902 "An obarray used to store the downcased completion prefixes.
903 Each symbol is bound to a list of completion entries.")
905 (defvar cmpl-obarray (make-vector cmpl-obarray-length 0)
906 "An obarray used to store the downcased completions.
907 Each symbol is bound to a single completion entry.")
909 ;;-----------------------------------------------
910 ;; Completion Entry Structure Definition
911 ;;-----------------------------------------------
913 ;; A completion entry is a LIST of string, prefix-symbol num-uses, and
914 ;; last-use-time (the time the completion was last used)
915 ;; last-use-time is t if the string should be kept permanently
916 ;; num-uses is incremented every time the completion is used.
918 ;; We chose lists because (car foo) is faster than (aref foo 0) and the
919 ;; creation time is about the same.
921 ;; READER MACROS
923 (defmacro completion-string (completion-entry)
924 (list 'car completion-entry))
926 (defmacro completion-num-uses (completion-entry)
927 ;; "The number of times it has used. Used to decide whether to save
928 ;; it."
929 (list 'car (list 'cdr completion-entry)))
931 (defmacro completion-last-use-time (completion-entry)
932 ;; "The time it was last used. In hours since origin. Used to decide
933 ;; whether to save it. t if one should always save it."
934 (list 'nth 2 completion-entry))
936 (defmacro completion-source (completion-entry)
937 (list 'nth 3 completion-entry))
939 ;; WRITER MACROS
940 (defmacro set-completion-string (completion-entry string)
941 (list 'setcar completion-entry string))
943 (defmacro set-completion-num-uses (completion-entry num-uses)
944 (list 'setcar (list 'cdr completion-entry) num-uses))
946 (defmacro set-completion-last-use-time (completion-entry last-use-time)
947 (list 'setcar (list 'cdr (list 'cdr completion-entry)) last-use-time))
949 ;; CONSTRUCTOR
950 (defun make-completion (string)
951 "Return a completion entry."
952 (list string 0 nil current-completion-source))
954 ;; Obsolete
955 ;;(defmacro cmpl-prefix-entry-symbol (completion-entry)
956 ;; (list 'car (list 'cdr completion-entry)))
960 ;;-----------------------------------------------
961 ;; Prefix symbol entry definition
962 ;;-----------------------------------------------
963 ;; A cons of (head . tail)
965 ;; READER Macros
967 (defalias 'cmpl-prefix-entry-head 'car)
969 (defalias 'cmpl-prefix-entry-tail 'cdr)
971 ;; WRITER Macros
973 (defmacro set-cmpl-prefix-entry-head (prefix-entry new-head)
974 (list 'setcar prefix-entry new-head))
976 (defmacro set-cmpl-prefix-entry-tail (prefix-entry new-tail)
977 (list 'setcdr prefix-entry new-tail))
979 ;; Constructor
981 (defun make-cmpl-prefix-entry (completion-entry-list)
982 "Make a new prefix entry containing only completion-entry."
983 (cons completion-entry-list completion-entry-list))
985 ;;-----------------------------------------------
986 ;; Completion Database - Utilities
987 ;;-----------------------------------------------
989 (defun clear-all-completions ()
990 "Initialize the completion storage. All existing completions are lost."
991 (interactive)
992 (setq cmpl-prefix-obarray (make-vector cmpl-obarray-length 0))
993 (setq cmpl-obarray (make-vector cmpl-obarray-length 0)))
995 (defvar completions-list-return-value)
997 (defun list-all-completions ()
998 "Return a list of all the known completion entries."
999 (let ((completions-list-return-value nil))
1000 (mapatoms 'list-all-completions-1 cmpl-prefix-obarray)
1001 completions-list-return-value))
1003 (defun list-all-completions-1 (prefix-symbol)
1004 (if (boundp prefix-symbol)
1005 (setq completions-list-return-value
1006 (append (cmpl-prefix-entry-head (symbol-value prefix-symbol))
1007 completions-list-return-value))))
1009 (defun list-all-completions-by-hash-bucket ()
1010 "Return list of lists of known completion entries, organized by hash bucket."
1011 (let ((completions-list-return-value nil))
1012 (mapatoms 'list-all-completions-by-hash-bucket-1 cmpl-prefix-obarray)
1013 completions-list-return-value))
1015 (defun list-all-completions-by-hash-bucket-1 (prefix-symbol)
1016 (if (boundp prefix-symbol)
1017 (setq completions-list-return-value
1018 (cons (cmpl-prefix-entry-head (symbol-value prefix-symbol))
1019 completions-list-return-value))))
1022 ;;-----------------------------------------------
1023 ;; Updating the database
1024 ;;-----------------------------------------------
1026 ;; These are the internal functions used to update the datebase
1029 (defvar completion-to-accept nil
1030 "Set to a string that is pending its acceptance.")
1031 ;; this checked by the top level reading functions
1033 (defvar cmpl-db-downcase-string nil
1034 "Setup by `find-exact-completion', etc. The given string, downcased.")
1035 (defvar cmpl-db-symbol nil
1036 "The interned symbol corresponding to `cmpl-db-downcase-string'.
1037 Set up by `cmpl-db-symbol'.")
1038 (defvar cmpl-db-prefix-symbol nil
1039 "The interned prefix symbol corresponding to `cmpl-db-downcase-string'.")
1040 (defvar cmpl-db-entry nil)
1041 (defvar cmpl-db-debug-p nil
1042 "Set to t if you want to debug the database.")
1044 ;; READS
1045 (defun find-exact-completion (string)
1046 "Return the completion entry for STRING or nil.
1047 Sets up `cmpl-db-downcase-string' and `cmpl-db-symbol'."
1048 (and (boundp (setq cmpl-db-symbol
1049 (intern (setq cmpl-db-downcase-string (downcase string))
1050 cmpl-obarray)))
1051 (symbol-value cmpl-db-symbol)))
1053 (defun find-cmpl-prefix-entry (prefix-string)
1054 "Return the prefix entry for string.
1055 Sets `cmpl-db-prefix-symbol'.
1056 Prefix-string must be exactly `completion-prefix-min-length' long
1057 and downcased. Sets up `cmpl-db-prefix-symbol'."
1058 (and (boundp (setq cmpl-db-prefix-symbol
1059 (intern prefix-string cmpl-prefix-obarray)))
1060 (symbol-value cmpl-db-prefix-symbol)))
1062 (defvar inside-locate-completion-entry nil)
1063 ;; used to trap lossage in silent error correction
1065 (defun locate-completion-entry (completion-entry prefix-entry)
1066 "Locate the completion entry.
1067 Returns a pointer to the element before the completion entry or nil if
1068 the completion entry is at the head.
1069 Must be called after `find-exact-completion'."
1070 (let ((prefix-list (cmpl-prefix-entry-head prefix-entry))
1071 next-prefix-list)
1072 (cond
1073 ((not (eq (car prefix-list) completion-entry))
1074 ;; not already at head
1075 (while (and prefix-list
1076 (not (eq completion-entry
1077 (car (setq next-prefix-list (cdr prefix-list))))))
1078 (setq prefix-list next-prefix-list))
1079 (cond (;; found
1080 prefix-list)
1081 ;; Didn't find it. Database is messed up.
1082 (cmpl-db-debug-p
1083 ;; not found, error if debug mode
1084 (error "Completion entry exists but not on prefix list - %s"
1085 completion-string))
1086 (inside-locate-completion-entry
1087 ;; recursive error: really scrod
1088 (locate-completion-db-error))
1090 ;; Patch out
1091 (set cmpl-db-symbol nil)
1092 ;; Retry
1093 (locate-completion-entry-retry completion-entry)))))))
1095 (defun locate-completion-entry-retry (old-entry)
1096 (let ((inside-locate-completion-entry t))
1097 (add-completion (completion-string old-entry)
1098 (completion-num-uses old-entry)
1099 (completion-last-use-time old-entry))
1100 (let* ((cmpl-entry (find-exact-completion (completion-string old-entry)))
1101 (pref-entry
1102 (if cmpl-entry
1103 (find-cmpl-prefix-entry
1104 (substring cmpl-db-downcase-string
1105 0 completion-prefix-min-length)))))
1106 (if (and cmpl-entry pref-entry)
1107 ;; try again
1108 (locate-completion-entry cmpl-entry pref-entry)
1109 ;; still losing
1110 (locate-completion-db-error)))))
1112 (defun locate-completion-db-error ()
1113 ;; recursive error: really scrod
1114 (error "Completion database corrupted. Try M-x clear-all-completions. Send bug report"))
1116 ;; WRITES
1117 (defun add-completion-to-tail-if-new (string)
1118 "If STRING is not in the database add it to appropriate prefix list.
1119 STRING is added to the end of the appropriate prefix list with
1120 num-uses = 0. The database is unchanged if it is there. STRING must be
1121 longer than `completion-prefix-min-length'.
1122 This must be very fast.
1123 Returns the completion entry."
1124 (or (find-exact-completion string)
1125 ;; not there
1126 (let (;; create an entry
1127 (entry (list (make-completion string)))
1128 ;; setup the prefix
1129 (prefix-entry (find-cmpl-prefix-entry
1130 (substring cmpl-db-downcase-string 0
1131 completion-prefix-min-length))))
1132 ;; The next two forms should happen as a unit (atomically) but
1133 ;; no fatal errors should result if that is not the case.
1134 (cond (prefix-entry
1135 ;; These two should be atomic, but nothing fatal will happen
1136 ;; if they're not.
1137 (setcdr (cmpl-prefix-entry-tail prefix-entry) entry)
1138 (set-cmpl-prefix-entry-tail prefix-entry entry))
1140 (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))))
1141 ;; set symbol
1142 (set cmpl-db-symbol (car entry)))))
1144 (defun add-completion-to-head (completion-string)
1145 "If COMPLETION-STRING is not in the database, add it to prefix list.
1146 We add COMPLETION-STRING to the head of the appropriate prefix list,
1147 or to the head of the list.
1148 COMPLETION-STRING must be longer than `completion-prefix-min-length'.
1149 Updates the saved string with the supplied string.
1150 This must be very fast.
1151 Returns the completion entry."
1152 ;; Handle pending acceptance
1153 (if completion-to-accept (accept-completion))
1154 ;; test if already in database
1155 (if (setq cmpl-db-entry (find-exact-completion completion-string))
1156 ;; found
1157 (let* ((prefix-entry (find-cmpl-prefix-entry
1158 (substring cmpl-db-downcase-string 0
1159 completion-prefix-min-length)))
1160 (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry))
1161 (cmpl-ptr (cdr splice-ptr)))
1162 ;; update entry
1163 (set-completion-string cmpl-db-entry completion-string)
1164 ;; move to head (if necessary)
1165 (cond (splice-ptr
1166 ;; These should all execute atomically but it is not fatal if
1167 ;; they don't.
1168 ;; splice it out
1169 (or (setcdr splice-ptr (cdr cmpl-ptr))
1170 ;; fix up tail if necessary
1171 (set-cmpl-prefix-entry-tail prefix-entry splice-ptr))
1172 ;; splice in at head
1173 (setcdr cmpl-ptr (cmpl-prefix-entry-head prefix-entry))
1174 (set-cmpl-prefix-entry-head prefix-entry cmpl-ptr)))
1175 cmpl-db-entry)
1176 ;; not there
1177 (let (;; create an entry
1178 (entry (list (make-completion completion-string)))
1179 ;; setup the prefix
1180 (prefix-entry (find-cmpl-prefix-entry
1181 (substring cmpl-db-downcase-string 0
1182 completion-prefix-min-length))))
1183 (cond (prefix-entry
1184 ;; Splice in at head
1185 (setcdr entry (cmpl-prefix-entry-head prefix-entry))
1186 (set-cmpl-prefix-entry-head prefix-entry entry))
1188 ;; Start new prefix entry
1189 (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))))
1190 ;; Add it to the symbol
1191 (set cmpl-db-symbol (car entry)))))
1193 (defun delete-completion (completion-string)
1194 "Delete the completion from the database.
1195 String must be longer than `completion-prefix-min-length'."
1196 ;; Handle pending acceptance
1197 (if completion-to-accept (accept-completion))
1198 (if (setq cmpl-db-entry (find-exact-completion completion-string))
1199 ;; found
1200 (let* ((prefix-entry (find-cmpl-prefix-entry
1201 (substring cmpl-db-downcase-string 0
1202 completion-prefix-min-length)))
1203 (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry)))
1204 ;; delete symbol reference
1205 (set cmpl-db-symbol nil)
1206 ;; remove from prefix list
1207 (cond (splice-ptr
1208 ;; not at head
1209 (or (setcdr splice-ptr (cdr (cdr splice-ptr)))
1210 ;; fix up tail if necessary
1211 (set-cmpl-prefix-entry-tail prefix-entry splice-ptr)))
1213 ;; at head
1214 (or (set-cmpl-prefix-entry-head
1215 prefix-entry (cdr (cmpl-prefix-entry-head prefix-entry)))
1216 ;; List is now empty
1217 (set cmpl-db-prefix-symbol nil)))))
1218 (error "Unknown completion `%s'" completion-string)))
1220 ;; Tests --
1221 ;; - Add and Find -
1222 ;; (add-completion-to-head "banana") --> ("banana" 0 nil 0)
1223 ;; (find-exact-completion "banana") --> ("banana" 0 nil 0)
1224 ;; (find-exact-completion "bana") --> nil
1225 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1226 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1227 ;; (add-completion-to-head "banish") --> ("banish" 0 nil 0)
1228 ;; (find-exact-completion "banish") --> ("banish" 0 nil 0)
1229 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banish" ...) ("banana" ...))
1230 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1231 ;; (add-completion-to-head "banana") --> ("banana" 0 nil 0)
1232 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
1233 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
1235 ;; - Deleting -
1236 ;; (add-completion-to-head "banner") --> ("banner" 0 nil 0)
1237 ;; (delete-completion "banner")
1238 ;; (find-exact-completion "banner") --> nil
1239 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
1240 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
1241 ;; (add-completion-to-head "banner") --> ("banner" 0 nil 0)
1242 ;; (delete-completion "banana")
1243 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banner" ...) ("banish" ...))
1244 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
1245 ;; (delete-completion "banner")
1246 ;; (delete-completion "banish")
1247 ;; (find-cmpl-prefix-entry "ban") --> nil
1248 ;; (delete-completion "banner") --> error
1250 ;; - Tail -
1251 ;; (add-completion-to-tail-if-new "banana") --> ("banana" 0 nil 0)
1252 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1253 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1254 ;; (add-completion-to-tail-if-new "banish") --> ("banish" 0 nil 0)
1255 ;; (car (find-cmpl-prefix-entry "ban")) -->(("banana" ...) ("banish" ...))
1256 ;; (cdr (find-cmpl-prefix-entry "ban")) -->(("banish" ...))
1260 ;;---------------------------------------------------------------------------
1261 ;; Database Update :: Interface level routines
1262 ;;---------------------------------------------------------------------------
1264 ;; These lie on top of the database ref. functions but below the standard
1265 ;; user interface level
1268 (defun interactive-completion-string-reader (prompt)
1269 (let* ((default (symbol-under-or-before-point))
1270 (new-prompt
1271 (if default
1272 (format "%s (default %s): " prompt default)
1273 (format "%s: " prompt)))
1274 (read (completing-read new-prompt cmpl-obarray)))
1275 (if (zerop (length read)) (setq read (or default "")))
1276 (list read)))
1278 (defun check-completion-length (string)
1279 (if (< (length string) completion-min-length)
1280 (user-error "The string `%s' is too short to be saved as a completion"
1281 string)
1282 (list string)))
1284 (defun add-completion (string &optional num-uses last-use-time)
1285 "Add STRING to completion list, or move it to head of list.
1286 The completion is altered appropriately if NUM-USES and/or LAST-USE-TIME
1287 are specified."
1288 (interactive (interactive-completion-string-reader "Completion to add"))
1289 (check-completion-length string)
1290 (let* ((current-completion-source (if (called-interactively-p 'interactive)
1291 cmpl-source-interactive
1292 current-completion-source))
1293 (entry (add-completion-to-head string)))
1295 (if num-uses (set-completion-num-uses entry num-uses))
1296 (if last-use-time
1297 (set-completion-last-use-time entry last-use-time))))
1299 (defun add-permanent-completion (string)
1300 "Add STRING if it isn't already listed, and mark it permanent."
1301 (interactive
1302 (interactive-completion-string-reader "Completion to add permanently"))
1303 (let ((current-completion-source (if (called-interactively-p 'interactive)
1304 cmpl-source-interactive
1305 current-completion-source)))
1306 (add-completion string nil t)))
1308 (defun kill-completion (string)
1309 (interactive (interactive-completion-string-reader "Completion to kill"))
1310 (check-completion-length string)
1311 (delete-completion string))
1313 (defun accept-completion ()
1314 "Accepts the pending completion in `completion-to-accept'.
1315 This bumps num-uses. Called by `add-completion-to-head' and
1316 `completion-search-reset'."
1317 (let ((string completion-to-accept)
1318 ;; if this is added afresh here, then it must be a cdabbrev
1319 (current-completion-source cmpl-source-cdabbrev)
1320 entry)
1321 (setq completion-to-accept nil)
1322 (setq entry (add-completion-to-head string))
1323 (set-completion-num-uses entry (1+ (completion-num-uses entry)))
1324 (setq cmpl-completions-accepted-p t)))
1326 (defun use-completion-under-point ()
1327 "Add the completion symbol underneath the point into the completion buffer."
1328 (let ((string (and enable-completion (symbol-under-point)))
1329 (current-completion-source cmpl-source-cursor-moves))
1330 (if string (add-completion-to-head string))))
1332 (defun use-completion-before-point ()
1333 "Add the completion symbol before point into the completion buffer."
1334 (let ((string (and enable-completion (symbol-before-point)))
1335 (current-completion-source cmpl-source-cursor-moves))
1336 (if string (add-completion-to-head string))))
1338 (defun use-completion-under-or-before-point ()
1339 "Add the completion symbol before point into the completion buffer."
1340 (let ((string (and enable-completion (symbol-under-or-before-point)))
1341 (current-completion-source cmpl-source-cursor-moves))
1342 (if string (add-completion-to-head string))))
1344 (defun use-completion-before-separator ()
1345 "Add the completion symbol before point into the completion buffer.
1346 Completions added this way will automatically be saved if
1347 `completion-on-separator-character' is non-nil."
1348 (let ((string (and enable-completion (symbol-before-point)))
1349 (current-completion-source cmpl-source-separator)
1350 entry)
1351 (cond (string
1352 (setq entry (add-completion-to-head string))
1353 (if (and completion-on-separator-character
1354 (zerop (completion-num-uses entry)))
1355 (progn
1356 (set-completion-num-uses entry 1)
1357 (setq cmpl-completions-accepted-p t)))))))
1359 ;; Tests --
1360 ;; - Add and Find -
1361 ;; (add-completion "banana" 5 10)
1362 ;; (find-exact-completion "banana") --> ("banana" 5 10 0)
1363 ;; (add-completion "banana" 6)
1364 ;; (find-exact-completion "banana") --> ("banana" 6 10 0)
1365 ;; (add-completion "banish")
1366 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banish" ...) ("banana" ...))
1368 ;; - Accepting -
1369 ;; (setq completion-to-accept "banana")
1370 ;; (accept-completion)
1371 ;; (find-exact-completion "banana") --> ("banana" 7 10)
1372 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
1373 ;; (setq completion-to-accept "banish")
1374 ;; (add-completion "banner")
1375 ;; (car (find-cmpl-prefix-entry "ban"))
1376 ;; --> (("banner" ...) ("banish" 1 ...) ("banana" 7 ...))
1378 ;; - Deleting -
1379 ;; (kill-completion "banish")
1380 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banner" ...) ("banana" ...))
1383 ;;---------------------------------------------------------------------------
1384 ;; Searching the database
1385 ;;---------------------------------------------------------------------------
1386 ;; Functions outside this block must call completion-search-reset followed
1387 ;; by calls to completion-search-next or completion-search-peek
1390 ;; Status variables
1391 ;; Commented out to improve loading speed
1392 (defvar cmpl-test-string "")
1393 ;; "The current string used by completion-search-next."
1394 (defvar cmpl-test-regexp "")
1395 ;; "The current regexp used by completion-search-next.
1396 ;; (derived from cmpl-test-string)"
1397 (defvar cmpl-last-index 0)
1398 ;; "The last index that completion-search-next was called with."
1399 (defvar cmpl-cdabbrev-reset-p nil)
1400 ;; "Set to t when cdabbrevs have been reset."
1401 (defvar cmpl-next-possibilities nil)
1402 ;; "A pointer to the element BEFORE the next set of possible completions.
1403 ;; cadr of this is the cmpl-next-possibility"
1404 (defvar cmpl-starting-possibilities nil)
1405 ;; "The initial list of starting possibilities."
1406 (defvar cmpl-next-possibility nil)
1407 ;; "The cached next possibility."
1408 (defvar cmpl-tried-list nil)
1409 ;; "A downcased list of all the completions we have tried."
1412 (defun completion-search-reset (string)
1413 "Set up the for completion searching for STRING.
1414 STRING must be longer than `completion-prefix-min-length'."
1415 (if completion-to-accept (accept-completion))
1416 (setq cmpl-starting-possibilities
1417 (cmpl-prefix-entry-head
1418 (find-cmpl-prefix-entry
1419 (downcase (substring string 0 completion-prefix-min-length))))
1420 cmpl-test-string string
1421 cmpl-test-regexp (concat (regexp-quote string) "."))
1422 (completion-search-reset-1))
1424 (defun completion-search-reset-1 ()
1425 (setq cmpl-next-possibilities cmpl-starting-possibilities
1426 cmpl-next-possibility nil
1427 cmpl-cdabbrev-reset-p nil
1428 cmpl-last-index -1
1429 cmpl-tried-list nil))
1431 (defun completion-search-next (index)
1432 "Return the next completion entry.
1433 If INDEX is out of sequence, reset and start from the top.
1434 If there are no more entries, try cdabbrev and return only a string."
1435 (cond
1436 ((= index (setq cmpl-last-index (1+ cmpl-last-index)))
1437 (completion-search-peek t))
1438 ((< index 0)
1439 (completion-search-reset-1)
1440 (setq cmpl-last-index index)
1441 ;; reverse the possibilities list
1442 (setq cmpl-next-possibilities (reverse cmpl-starting-possibilities))
1443 ;; do a "normal" search
1444 (while (and (completion-search-peek nil)
1445 (< (setq index (1+ index)) 0))
1446 (setq cmpl-next-possibility nil))
1447 (cond ((not cmpl-next-possibilities))
1448 ;; If no more possibilities, leave it that way
1449 ((= -1 cmpl-last-index)
1450 ;; next completion is at index 0. reset next-possibility list
1451 ;; to start at beginning
1452 (setq cmpl-next-possibilities cmpl-starting-possibilities))
1454 ;; otherwise point to one before current
1455 (setq cmpl-next-possibilities
1456 (nthcdr (- (length cmpl-starting-possibilities)
1457 (length cmpl-next-possibilities))
1458 cmpl-starting-possibilities)))))
1460 ;; non-negative index, reset and search
1461 ;;(prin1 'reset)
1462 (completion-search-reset-1)
1463 (setq cmpl-last-index index)
1464 (while (and (completion-search-peek t)
1465 (not (< (setq index (1- index)) 0)))
1466 (setq cmpl-next-possibility nil))))
1467 (prog1
1468 cmpl-next-possibility
1469 (setq cmpl-next-possibility nil)))
1472 (defun completion-search-peek (use-cdabbrev)
1473 "Return the next completion entry without actually moving the pointers.
1474 Calling this again or calling `completion-search-next' results in the same
1475 string being returned. Depends on `case-fold-search'.
1476 If there are no more entries, try cdabbrev and then return only a string."
1477 (cond
1478 ;; return the cached value if we have it
1479 (cmpl-next-possibility)
1480 ((and cmpl-next-possibilities
1481 ;; still a few possibilities left
1482 (progn
1483 (while
1484 (and (not (eq 0 (string-match cmpl-test-regexp
1485 (completion-string (car cmpl-next-possibilities)))))
1486 (setq cmpl-next-possibilities (cdr cmpl-next-possibilities))))
1487 cmpl-next-possibilities))
1488 ;; successful match
1489 (setq cmpl-next-possibility (car cmpl-next-possibilities)
1490 cmpl-tried-list (cons (downcase (completion-string cmpl-next-possibility))
1491 cmpl-tried-list)
1492 cmpl-next-possibilities (cdr cmpl-next-possibilities))
1493 cmpl-next-possibility)
1494 (use-cdabbrev
1495 ;; unsuccessful, use cdabbrev
1496 (cond ((not cmpl-cdabbrev-reset-p)
1497 (reset-cdabbrev cmpl-test-string cmpl-tried-list)
1498 (setq cmpl-cdabbrev-reset-p t)))
1499 (setq cmpl-next-possibility (next-cdabbrev)))
1500 ;; Completely unsuccessful, return nil
1503 ;; Tests --
1504 ;; - Add and Find -
1505 ;; (add-completion "banana")
1506 ;; (completion-search-reset "ban")
1507 ;; (completion-search-next 0) --> "banana"
1509 ;; - Discrimination -
1510 ;; (add-completion "cumberland")
1511 ;; (add-completion "cumberbund")
1512 ;; cumbering
1513 ;; (completion-search-reset "cumb")
1514 ;; (completion-search-peek t) --> "cumberbund"
1515 ;; (completion-search-next 0) --> "cumberbund"
1516 ;; (completion-search-peek t) --> "cumberland"
1517 ;; (completion-search-next 1) --> "cumberland"
1518 ;; (completion-search-peek nil) --> nil
1519 ;; (completion-search-next 2) --> "cumbering" {cdabbrev}
1520 ;; (completion-search-next 3) --> nil or "cumming"{depends on context}
1521 ;; (completion-search-next 1) --> "cumberland"
1522 ;; (completion-search-peek t) --> "cumbering" {cdabbrev}
1524 ;; - Accepting -
1525 ;; (completion-search-next 1) --> "cumberland"
1526 ;; (setq completion-to-accept "cumberland")
1527 ;; (completion-search-reset "foo")
1528 ;; (completion-search-reset "cum")
1529 ;; (completion-search-next 0) --> "cumberland"
1531 ;; - Deleting -
1532 ;; (kill-completion "cumberland")
1533 ;; cummings
1534 ;; (completion-search-reset "cum")
1535 ;; (completion-search-next 0) --> "cumberbund"
1536 ;; (completion-search-next 1) --> "cummings"
1538 ;; - Ignoring Capitalization -
1539 ;; (completion-search-reset "CuMb")
1540 ;; (completion-search-next 0) --> "cumberbund"
1544 ;;-----------------------------------------------
1545 ;; COMPLETE
1546 ;;-----------------------------------------------
1548 (defun completion-mode ()
1549 "Toggle whether or not to add new words to the completion database."
1550 (interactive)
1551 (setq enable-completion (not enable-completion))
1552 (message "Completion mode is now %s." (if enable-completion "ON" "OFF")))
1554 (defvar cmpl-current-index 0)
1555 (defvar cmpl-original-string nil)
1556 (defvar cmpl-last-insert-location -1)
1557 (defvar cmpl-leave-point-at-start nil)
1559 (defun complete (&optional arg)
1560 "Fill out a completion of the word before point.
1561 Point is left at end. Consecutive calls rotate through all possibilities.
1562 Prefix args ::
1563 control-u :: leave the point at the beginning of the completion rather
1564 than at the end.
1565 a number :: rotate through the possible completions by that amount
1566 `-' :: same as -1 (insert previous completion)
1567 {See the comments at the top of `completion.el' for more info.}"
1568 (interactive "*p")
1569 ;;; Set up variables
1570 (cond ((eq last-command this-command)
1571 ;; Undo last one
1572 (delete-region cmpl-last-insert-location (point))
1573 ;; get next completion
1574 (setq cmpl-current-index (+ cmpl-current-index (or arg 1))))
1576 (if (not cmpl-initialized-p)
1577 (completion-initialize)) ;; make sure everything's loaded
1578 (cond ((consp current-prefix-arg) ;; control-u
1579 (setq arg 0)
1580 (setq cmpl-leave-point-at-start t))
1582 (setq cmpl-leave-point-at-start nil)))
1583 ;; get string
1584 (setq cmpl-original-string (symbol-before-point-for-complete))
1585 (cond ((not cmpl-original-string)
1586 (setq this-command 'failed-complete)
1587 (error "To complete, point must be after a symbol at least %d character long"
1588 completion-prefix-min-length)))
1589 ;; get index
1590 (setq cmpl-current-index (if current-prefix-arg arg 0))
1591 ;; reset database
1592 (completion-search-reset cmpl-original-string)
1593 ;; erase what we've got
1594 (delete-region cmpl-symbol-start cmpl-symbol-end)))
1596 ;; point is at the point to insert the new symbol
1597 ;; Get the next completion
1598 (let* ((print-status-p
1599 (and (>= baud-rate completion-prompt-speed-threshold)
1600 (not (window-minibuffer-p))))
1601 (insert-point (point))
1602 (entry (completion-search-next cmpl-current-index))
1603 string)
1604 ;; entry is either a completion entry or a string (if cdabbrev)
1606 ;; If found, insert
1607 (cond (entry
1608 ;; Setup for proper case
1609 (setq string (if (stringp entry)
1610 entry (completion-string entry)))
1611 (setq string (cmpl-merge-string-cases
1612 string cmpl-original-string))
1613 ;; insert
1614 (insert string)
1615 ;; accept it
1616 (setq completion-to-accept string)
1617 ;; fixup and cache point
1618 (cond (cmpl-leave-point-at-start
1619 (setq cmpl-last-insert-location (point))
1620 (goto-char insert-point))
1621 (t;; point at end,
1622 (setq cmpl-last-insert-location insert-point)))
1623 ;; Done ! cmpl-stat-complete-successful
1624 ;;display the next completion
1625 (cond
1626 ((and print-status-p
1627 ;; This updates the display and only prints if there
1628 ;; is no typeahead
1629 (sit-for 0)
1630 (setq entry
1631 (completion-search-peek
1632 completion-cdabbrev-prompt-flag)))
1633 (setq string (if (stringp entry)
1634 entry (completion-string entry)))
1635 (setq string (cmpl-merge-string-cases
1636 string cmpl-original-string))
1637 (message "Next completion: %s" string))))
1638 (t;; none found, insert old
1639 (insert cmpl-original-string)
1640 ;; Don't accept completions
1641 (setq completion-to-accept nil)
1642 ;; print message
1643 ;; This used to call cmpl19-sit-for, an undefined function.
1644 ;; I hope that sit-for does the right thing; I don't know -- rms.
1645 (if (and print-status-p (sit-for 0))
1646 (message "No %scompletions."
1647 (if (eq this-command last-command) "more " "")))
1648 ;; Pretend that we were never here
1649 (setq this-command 'failed-complete)))))
1651 ;;---------------------------------------------------------------------------
1652 ;; Parsing definitions from files into the database
1653 ;;---------------------------------------------------------------------------
1655 ;;-----------------------------------------------
1656 ;; Top Level functions ::
1657 ;;-----------------------------------------------
1659 ;; User interface
1660 (defun add-completions-from-file (file)
1661 "Parse possible completions from a FILE and add them to database."
1662 (interactive "fFile: ")
1663 (setq file (expand-file-name file))
1664 (let* ((buffer (get-file-buffer file))
1665 (buffer-already-there-p buffer))
1666 (if (not buffer-already-there-p)
1667 (let ((completions-merging-modes nil))
1668 (setq buffer (find-file-noselect file))))
1669 (unwind-protect
1670 (with-current-buffer buffer
1671 (add-completions-from-buffer))
1672 (if (not buffer-already-there-p)
1673 (kill-buffer buffer)))))
1675 (defun add-completions-from-buffer ()
1676 (interactive)
1677 (let ((current-completion-source cmpl-source-file-parsing))
1678 (cond ((memq major-mode '(emacs-lisp-mode lisp-mode))
1679 (add-completions-from-lisp-buffer))
1680 ((memq major-mode '(c-mode))
1681 (add-completions-from-c-buffer))
1683 (error "Cannot parse completions in %s buffers"
1684 major-mode)))))
1686 ;; Find file hook
1687 (defun completion-find-file-hook ()
1688 (cond (enable-completion
1689 (cond ((and (memq major-mode '(emacs-lisp-mode lisp-mode))
1690 (memq 'lisp completions-merging-modes))
1691 (add-completions-from-buffer))
1692 ((and (memq major-mode '(c-mode))
1693 (memq 'c completions-merging-modes))
1694 (add-completions-from-buffer))))))
1696 ;;-----------------------------------------------
1697 ;; Tags Table Completions
1698 ;;-----------------------------------------------
1700 (defun add-completions-from-tags-table ()
1701 ;; Inspired by eero@media-lab.media.mit.edu
1702 "Add completions from the current tags table."
1703 (interactive)
1704 (visit-tags-table-buffer) ;this will prompt if no tags-table
1705 (save-excursion
1706 (goto-char (point-min))
1707 (let (string)
1708 (condition-case nil
1709 (while t
1710 (search-forward "\177")
1711 (backward-char 3)
1712 (and (setq string (symbol-under-point))
1713 (add-completion-to-tail-if-new string))
1714 (forward-char 3))
1715 (search-failed)))))
1718 ;;-----------------------------------------------
1719 ;; Lisp File completion parsing
1720 ;;-----------------------------------------------
1721 ;; This merely looks for phrases beginning with (def.... or
1722 ;; (package:def ... and takes the next word.
1724 ;; We tried using forward-lines and explicit searches but the regexp technique
1725 ;; was faster. (About 100K characters per second)
1727 (defconst *lisp-def-regexp*
1728 "\n(\\(\\w*:\\)?def\\(\\w\\|\\s_\\)*\\s +(*"
1729 "A regexp that searches for Lisp definition form.")
1731 ;; Tests -
1732 ;; (and (string-match *lisp-def-regexp* "\n(defun foo") (match-end 0)) -> 8
1733 ;; (and (string-match *lisp-def-regexp* "\n(si:def foo") (match-end 0)) -> 9
1734 ;; (and (string-match *lisp-def-regexp* "\n(def-bar foo")(match-end 0)) -> 10
1735 ;; (and (string-match *lisp-def-regexp* "\n(defun (foo") (match-end 0)) -> 9
1737 ;; Parses all the definition names from a Lisp mode buffer and adds them to
1738 ;; the completion database.
1739 (defun add-completions-from-lisp-buffer ()
1740 ;;; Benchmarks
1741 ;;; Sun-3/280 - 1500 to 3000 lines of lisp code per second
1742 (let (string)
1743 (save-excursion
1744 (goto-char (point-min))
1745 (condition-case nil
1746 (while t
1747 (re-search-forward *lisp-def-regexp*)
1748 (and (setq string (symbol-under-point))
1749 (add-completion-to-tail-if-new string)))
1750 (search-failed)))))
1753 ;;-----------------------------------------------
1754 ;; C file completion parsing
1755 ;;-----------------------------------------------
1756 ;; C :
1757 ;; Looks for #define or [<storage class>] [<type>] <name>{,<name>}
1758 ;; or structure, array or pointer defs.
1759 ;; It gets most of the definition names.
1761 ;; As you might suspect by now, we use some symbol table hackery
1763 ;; Symbol separator chars (have whitespace syntax) --> , ; * = (
1764 ;; Opening char --> [ {
1765 ;; Closing char --> ] }
1766 ;; opening and closing must be skipped over
1767 ;; Whitespace chars (have symbol syntax)
1768 ;; Everything else has word syntax
1770 (defconst completion-c-def-syntax-table
1771 (let ((table (make-syntax-table))
1772 (whitespace-chars '(? ?\n ?\t ?\f ?\v ?\r))
1773 ;; unfortunately the ?( causes the parens to appear unbalanced
1774 (separator-chars '(?, ?* ?= ?\( ?\;))
1776 ;; default syntax is whitespace
1777 (setq i 0)
1778 (while (< i 256)
1779 (modify-syntax-entry i "w" table)
1780 (setq i (1+ i)))
1781 (dolist (char whitespace-chars)
1782 (modify-syntax-entry char "_" table))
1783 (dolist (char separator-chars)
1784 (modify-syntax-entry char " " table))
1785 (modify-syntax-entry ?\[ "(]" table)
1786 (modify-syntax-entry ?\{ "(}" table)
1787 (modify-syntax-entry ?\] ")[" table)
1788 (modify-syntax-entry ?\} "){" table)
1789 table))
1791 ;; Regexps
1792 (defconst *c-def-regexp*
1793 ;; This stops on lines with possible definitions
1794 "\n[_a-zA-Z#]"
1795 ;; This stops after the symbol to add.
1796 ;;"\n\\(#define\\s +.\\|\\(\\(\\w\\|\\s_\\)+\\b\\s *\\)+[(;,[*{=]\\)"
1797 ;; This stops before the symbol to add. {Test cases in parens. below}
1798 ;;"\n\\(\\(\\w\\|\\s_\\)+\\s *(\\|\\(\\(#define\\|auto\\|extern\\|register\\|static\\|int\\|long\\|short\\|unsigned\\|char\\|void\\|float\\|double\\|enum\\|struct\\|union\\|typedef\\)\\s +\\)+\\)"
1799 ;; this simple version picks up too much extraneous stuff
1800 ;; "\n\\(\\w\\|\\s_\\|#\\)\\B"
1801 "A regexp that searches for a definition form.")
1803 ;(defconst *c-cont-regexp*
1804 ; "\\(\\w\\|\\s_\\)+\\b\\s *\\({\\|\\(\\[[0-9\t ]*\\]\\s *\\)*,\\(*\\|\\s \\)*\\b\\)"
1805 ; "This regexp should be used in a looking-at to parse for lists of variables.")
1807 ;(defconst *c-struct-regexp*
1808 ; "\\(*\\|\\s \\)*\\b"
1809 ; "This regexp should be used to test whether a symbol follows a structure definition.")
1811 ;(defun test-c-def-regexp (regexp string)
1812 ; (and (eq 0 (string-match regexp string)) (match-end 0))
1815 ;; Tests -
1816 ;; (test-c-def-regexp *c-def-regexp* "\n#define foo") -> 10 (9)
1817 ;; (test-c-def-regexp *c-def-regexp* "\nfoo (x, y) {") -> 6 (6)
1818 ;; (test-c-def-regexp *c-def-regexp* "\nint foo (x, y)") -> 10 (5)
1819 ;; (test-c-def-regexp *c-def-regexp* "\n int foo (x, y)") -> nil
1820 ;; (test-c-def-regexp *c-cont-regexp* "oo, bar") -> 4
1821 ;; (test-c-def-regexp *c-cont-regexp* "oo, *bar") -> 5
1822 ;; (test-c-def-regexp *c-cont-regexp* "a [5][6], bar") -> 10
1823 ;; (test-c-def-regexp *c-cont-regexp* "oo(x,y)") -> nil
1824 ;; (test-c-def-regexp *c-cont-regexp* "a [6] ,\t bar") -> 9
1825 ;; (test-c-def-regexp *c-cont-regexp* "oo {trout =1} my_carp;") -> 14
1826 ;; (test-c-def-regexp *c-cont-regexp* "truct_p complex foon") -> nil
1828 ;; Parses all the definition names from a C mode buffer and adds them to the
1829 ;; completion database.
1830 (defun add-completions-from-c-buffer ()
1831 ;; Benchmark --
1832 ;; Sun 3/280-- 1250 lines/sec.
1834 (let (string next-point char)
1835 (save-excursion
1836 (goto-char (point-min))
1837 (catch 'finish-add-completions
1838 (with-syntax-table completion-c-def-syntax-table
1839 (while t
1840 ;; we loop here only when scan-sexps fails
1841 ;; (i.e. unbalance exps.)
1842 (condition-case e
1843 (while t
1844 (re-search-forward *c-def-regexp*)
1845 (cond
1846 ((= (preceding-char) ?#)
1847 ;; preprocessor macro, see if it's one we handle
1848 (cond ((looking-at "\\(define\\|ifdef\\)\\>")
1849 ;; skip forward over definition symbol
1850 ;; and add it to database
1851 (and (forward-word 2)
1852 (setq string (symbol-before-point))
1853 ;;(push string foo)
1854 (add-completion-to-tail-if-new string)))))
1856 ;; C definition
1857 (setq next-point (point))
1858 (while (and
1859 next-point
1860 ;; scan to next separator char.
1861 (setq next-point (scan-sexps next-point 1)))
1862 ;; position the point on the word we want to add
1863 (goto-char next-point)
1864 (while (= (setq char (following-char)) ?*)
1865 ;; handle pointer ref
1866 ;; move to next separator char.
1867 (goto-char
1868 (setq next-point (scan-sexps (point) 1))))
1869 (forward-word -1)
1870 ;; add to database
1871 (if (setq string (symbol-under-point))
1872 ;; (push string foo)
1873 (add-completion-to-tail-if-new string)
1874 ;; Local TMC hack (useful for parsing paris.h)
1875 (if (and (looking-at "_AP") ;; "ansi prototype"
1876 (progn
1877 (forward-word -1)
1878 (setq string
1879 (symbol-under-point))))
1880 (add-completion-to-tail-if-new string)))
1881 ;; go to next
1882 (goto-char next-point)
1883 ;; (push (format "%c" (following-char)) foo)
1884 (if (= (char-syntax char) ?\()
1885 ;; if on an opening delimiter, go to end
1886 (while (= (char-syntax char) ?\()
1887 (setq next-point (scan-sexps next-point 1)
1888 char (char-after next-point)))
1889 (or (= char ?,)
1890 ;; Current char is an end char.
1891 (setq next-point nil)))))))
1892 (search-failed ;;done
1893 (throw 'finish-add-completions t))
1894 (error
1895 ;; Check for failure in scan-sexps
1896 (if (member (nth 1 e)
1897 '("Containing expression ends prematurely"
1898 "Unbalanced parentheses"))
1899 ;; unbalanced paren., keep going
1900 ;;(ding)
1901 (forward-line 1)
1902 (message "Error parsing C buffer for completions--please send bug report")
1903 (throw 'finish-add-completions t))))))))))
1906 ;;---------------------------------------------------------------------------
1907 ;; Init files
1908 ;;---------------------------------------------------------------------------
1910 ;; The version of save-completions-to-file called at kill-emacs time.
1911 (defun kill-emacs-save-completions ()
1912 (if (and save-completions-flag enable-completion cmpl-initialized-p)
1913 (cond
1914 ((not cmpl-completions-accepted-p)
1915 (message "Completions database has not changed - not writing."))
1917 (save-completions-to-file)))))
1919 ;; There is no point bothering to change this again
1920 ;; unless the package changes so much that it matters
1921 ;; for people that have saved completions.
1922 (defconst completion-version "11")
1924 (defconst saved-cmpl-file-header
1925 ";;; Completion Initialization file.
1926 ;; Version = %s
1927 ;; Format is (<string> . <last-use-time>)
1928 ;; <string> is the completion
1929 ;; <last-use-time> is the time the completion was last used
1930 ;; If it is t, the completion will never be pruned from the file.
1931 ;; Otherwise it is in hours since origin.
1932 \n")
1934 (defun completion-backup-filename (filename)
1935 (concat filename ".BAK"))
1937 (defun save-completions-to-file (&optional filename)
1938 "Save completions in init file FILENAME.
1939 If file name is not specified, use `save-completions-file-name'."
1940 (interactive)
1941 (setq filename (expand-file-name (or filename save-completions-file-name)))
1942 (if (file-writable-p filename)
1943 (progn
1944 (if (not cmpl-initialized-p)
1945 (completion-initialize)) ;; make sure everything's loaded
1946 (message "Saving completions to file %s" filename)
1948 (let* ((delete-old-versions t)
1949 (kept-old-versions 0)
1950 (kept-new-versions completions-file-versions-kept)
1951 last-use-time
1952 (this-use-time (cmpl-hours-since-origin))
1953 (total-in-db 0)
1954 (total-perm 0)
1955 (total-saved 0)
1956 (backup-filename (completion-backup-filename filename)))
1958 (with-current-buffer (get-buffer-create " *completion-save-buffer*")
1959 (setq buffer-file-name filename)
1961 (if (not (verify-visited-file-modtime (current-buffer)))
1962 (progn
1963 ;; file has changed on disk. Bring us up-to-date
1964 (message "Completion file has changed. Merging. . .")
1965 (load-completions-from-file filename t)
1966 (message "Merging finished. Saving completions to file %s" filename)))
1968 ;; prepare the buffer to be modified
1969 (clear-visited-file-modtime)
1970 (erase-buffer)
1971 ;; (/ 1 0)
1972 (insert (format saved-cmpl-file-header completion-version))
1973 (dolist (completion (list-all-completions))
1974 (setq total-in-db (1+ total-in-db))
1975 (setq last-use-time (completion-last-use-time completion))
1976 ;; Update num uses and maybe write completion to a file
1977 (cond ((or;; Write to file if
1978 ;; permanent
1979 (and (eq last-use-time t)
1980 (setq total-perm (1+ total-perm)))
1981 ;; or if
1982 (if (> (completion-num-uses completion) 0)
1983 ;; it's been used
1984 (setq last-use-time this-use-time)
1985 ;; or it was saved before and
1986 (and last-use-time
1987 ;; save-completions-retention-time is nil
1988 (or (not save-completions-retention-time)
1989 ;; or time since last use is < ...retention-time*
1990 (< (- this-use-time last-use-time)
1991 save-completions-retention-time)))))
1992 ;; write to file
1993 (setq total-saved (1+ total-saved))
1994 (insert (prin1-to-string (cons (completion-string completion)
1995 last-use-time)) "\n"))))
1997 ;; write the buffer
1998 (condition-case nil
1999 (let ((file-exists-p (file-exists-p filename)))
2000 (if file-exists-p
2001 (progn
2002 ;; If file exists . . .
2003 ;; Save a backup(so GNU doesn't screw us when we're out of disk)
2004 ;; (GNU leaves a 0 length file if it gets a disk full error!)
2006 ;; If backup doesn't exit, Rename current to backup
2007 ;; {If backup exists the primary file is probably messed up}
2008 (or (file-exists-p backup-filename)
2009 (rename-file filename backup-filename))
2010 ;; Copy the backup back to the current name
2011 ;; (so versioning works)
2012 (copy-file backup-filename filename t)))
2013 ;; Save it
2014 (save-buffer)
2015 (if file-exists-p
2016 ;; If successful, remove backup
2017 (delete-file backup-filename)))
2018 (error
2019 (set-buffer-modified-p nil)
2020 (message "Couldn't save completion file `%s'" filename)))
2021 ;; Reset accepted-p flag
2022 (setq cmpl-completions-accepted-p nil) )))))
2024 ;;(defun auto-save-completions ()
2025 ;; (if (and save-completions-flag enable-completion cmpl-initialized-p
2026 ;; *completion-auto-save-period*
2027 ;; (> cmpl-emacs-idle-time *completion-auto-save-period*)
2028 ;; cmpl-completions-accepted-p)
2029 ;; (save-completions-to-file)))
2031 ;;(add-hook 'cmpl-emacs-idle-time-hooks 'auto-save-completions)
2033 (defun load-completions-from-file (&optional filename no-message-p)
2034 "Load a completion init file FILENAME.
2035 If file is not specified, then use `save-completions-file-name'."
2036 (interactive)
2037 (setq filename (expand-file-name (or filename save-completions-file-name)))
2038 (let* ((backup-filename (completion-backup-filename filename))
2039 (backup-readable-p (file-readable-p backup-filename)))
2040 (if backup-readable-p (setq filename backup-filename))
2041 (if (file-readable-p filename)
2042 (progn
2043 (if (not no-message-p)
2044 (message "Loading completions from %sfile %s . . ."
2045 (if backup-readable-p "backup " "") filename))
2046 (with-current-buffer (get-buffer-create " *completion-save-buffer*")
2047 (setq buffer-file-name filename)
2048 ;; prepare the buffer to be modified
2049 (clear-visited-file-modtime)
2050 (erase-buffer)
2052 (let ((insert-okay-p nil)
2053 (buffer (current-buffer))
2054 string entry last-use-time
2055 cmpl-entry cmpl-last-use-time
2056 (current-completion-source cmpl-source-init-file)
2057 (total-in-file 0) (total-perm 0))
2058 ;; insert the file into a buffer
2059 (condition-case nil
2060 (progn (insert-file-contents filename t)
2061 (setq insert-okay-p t))
2063 (file-error
2064 (message "File error trying to load completion file %s."
2065 filename)))
2066 ;; parse it
2067 (if insert-okay-p
2068 (progn
2069 (goto-char (point-min))
2071 (condition-case nil
2072 (while t
2073 (setq entry (read buffer))
2074 (setq total-in-file (1+ total-in-file))
2075 (cond
2076 ((and (consp entry)
2077 (stringp (setq string (car entry)))
2078 (cond
2079 ((eq (setq last-use-time (cdr entry)) 'T)
2080 ;; handle case sensitivity
2081 (setq total-perm (1+ total-perm))
2082 (setq last-use-time t))
2083 ((eq last-use-time t)
2084 (setq total-perm (1+ total-perm)))
2085 ((integerp last-use-time))))
2086 ;; Valid entry
2087 ;; add it in
2088 (setq cmpl-last-use-time
2089 (completion-last-use-time
2090 (setq cmpl-entry
2091 (add-completion-to-tail-if-new string))))
2092 (if (or (eq last-use-time t)
2093 (and (> last-use-time 1000);;backcompatibility
2094 (not (eq cmpl-last-use-time t))
2095 (or (not cmpl-last-use-time)
2096 ;; more recent
2097 (> last-use-time cmpl-last-use-time))))
2098 ;; update last-use-time
2099 (set-completion-last-use-time cmpl-entry last-use-time)))
2101 ;; Bad format
2102 (message "Error: invalid saved completion - %s"
2103 (prin1-to-string entry))
2104 ;; try to get back in sync
2105 (search-forward "\n("))))
2106 (search-failed
2107 (message "End of file while reading completions."))
2108 (end-of-file
2109 (if (= (point) (point-max))
2110 (if (not no-message-p)
2111 (message "Loading completions from file %s . . . Done."
2112 filename))
2113 (message "End of file while reading completions."))))))
2114 ))))))
2116 (defun completion-initialize ()
2117 "Load the default completions file.
2118 Also sets up so that exiting Emacs will automatically save the file."
2119 (interactive)
2120 (unless cmpl-initialized-p
2121 (load-completions-from-file)
2122 (setq cmpl-initialized-p t)))
2124 ;;-----------------------------------------------
2125 ;; Kill region patch
2126 ;;-----------------------------------------------
2128 (defun completion-kill-region (&optional beg end)
2129 "Kill between point and mark.
2130 The text is deleted but saved in the kill ring.
2131 The command \\[yank] can retrieve it from there.
2132 /(If you want to kill and then yank immediately, use \\[copy-region-as-kill].)
2134 This is the primitive for programs to kill text (as opposed to deleting it).
2135 Supply two arguments, character positions indicating the stretch of text
2136 to be killed.
2137 Any command that calls this function is a \"kill command\".
2138 If the previous command was also a kill command,
2139 the text killed this time appends to the text killed last time
2140 to make one entry in the kill ring.
2141 Patched to remove the most recent completion."
2142 (interactive "r")
2143 (cond ((eq last-command 'complete)
2144 (delete-region (point) cmpl-last-insert-location)
2145 (insert cmpl-original-string)
2146 (setq completion-to-accept nil))
2148 (kill-region beg end))))
2151 ;;-----------------------------------------------
2152 ;; Patches to self-insert-command.
2153 ;;-----------------------------------------------
2155 ;; Need 2 versions: generic separator chars. and space (to get auto fill
2156 ;; to work)
2158 ;; All common separators (eg. space "(" ")" """) characters go through a
2159 ;; function to add new words to the list of words to complete from:
2160 ;; COMPLETION-SEPARATOR-SELF-INSERT-COMMAND (arg).
2161 ;; If the character before this was an alpha-numeric then this adds the
2162 ;; symbol before point to the completion list (using ADD-COMPLETION).
2164 (defun completion-separator-self-insert-command (arg)
2165 (interactive "p")
2166 (if (command-remapping 'self-insert-command)
2167 (funcall (command-remapping 'self-insert-command) arg)
2168 (use-completion-before-separator)
2169 (self-insert-command arg)))
2171 (defun completion-separator-self-insert-autofilling (arg)
2172 (interactive "p")
2173 (if (command-remapping 'self-insert-command)
2174 (funcall (command-remapping 'self-insert-command) arg)
2175 (use-completion-before-separator)
2176 (self-insert-command arg)
2177 (and auto-fill-function
2178 (funcall auto-fill-function))))
2180 ;;-----------------------------------------------
2181 ;; Wrapping Macro
2182 ;;-----------------------------------------------
2184 ;; Note that because of the way byte compiling works, none of
2185 ;; the functions defined with this macro get byte compiled.
2187 (defun completion-def-wrapper (function-name type)
2188 "Add a call to update the completion database before function execution.
2189 TYPE is the type of the wrapper to be added. Can be :before or :under."
2190 (put function-name 'completion-function
2191 (cdr (assq type
2192 '((:separator . use-completion-before-separator)
2193 (:before . use-completion-before-point)
2194 (:backward-under . use-completion-backward-under)
2195 (:backward . use-completion-backward)
2196 (:under . use-completion-under-point)
2197 (:under-or-before . use-completion-under-or-before-point)
2198 (:minibuffer-separator
2199 . use-completion-minibuffer-separator))))))
2201 (defun use-completion-minibuffer-separator ()
2202 (let ((completion-syntax-table completion-standard-syntax-table))
2203 (use-completion-before-separator)))
2205 (defun use-completion-backward-under ()
2206 (use-completion-under-point))
2208 (defun use-completion-backward ()
2209 nil)
2211 (defun completion-before-command ()
2212 (funcall (or (and (symbolp this-command)
2213 (get this-command 'completion-function))
2214 'use-completion-under-or-before-point)))
2216 ;; Lisp mode diffs.
2218 (defconst completion-lisp-syntax-table
2219 (let ((table (copy-syntax-table completion-standard-syntax-table))
2220 (symbol-chars '(?! ?& ?? ?= ?^)))
2221 (dolist (char symbol-chars)
2222 (modify-syntax-entry char "_" table))
2223 table))
2225 (defun completion-lisp-mode-hook ()
2226 (setq completion-syntax-table completion-lisp-syntax-table)
2227 ;; Lisp Mode diffs
2228 (local-set-key "!" 'self-insert-command)
2229 (local-set-key "&" 'self-insert-command)
2230 (local-set-key "%" 'self-insert-command)
2231 (local-set-key "?" 'self-insert-command)
2232 (local-set-key "=" 'self-insert-command)
2233 (local-set-key "^" 'self-insert-command))
2235 ;; C mode diffs.
2237 (defconst completion-c-syntax-table
2238 (let ((table (copy-syntax-table completion-standard-syntax-table))
2239 (separator-chars '(?+ ?* ?/ ?: ?%)))
2240 (dolist (char separator-chars)
2241 (modify-syntax-entry char " " table))
2242 table))
2244 (completion-def-wrapper 'electric-c-semi :separator)
2245 (defun completion-c-mode-hook ()
2246 (setq completion-syntax-table completion-c-syntax-table)
2247 (local-set-key "+" 'completion-separator-self-insert-command)
2248 (local-set-key "*" 'completion-separator-self-insert-command)
2249 (local-set-key "/" 'completion-separator-self-insert-command))
2251 ;; FORTRAN mode diffs. (these are defined when fortran is called)
2253 (defconst completion-fortran-syntax-table
2254 (let ((table (copy-syntax-table completion-standard-syntax-table))
2255 (separator-chars '(?+ ?- ?* ?/ ?:)))
2256 (dolist (char separator-chars)
2257 (modify-syntax-entry char " " table))
2258 table))
2260 (defun completion-setup-fortran-mode ()
2261 (setq completion-syntax-table completion-fortran-syntax-table)
2262 (local-set-key "+" 'completion-separator-self-insert-command)
2263 (local-set-key "-" 'completion-separator-self-insert-command)
2264 (local-set-key "*" 'completion-separator-self-insert-command)
2265 (local-set-key "/" 'completion-separator-self-insert-command))
2267 ;; Enable completion mode.
2269 (defvar fortran-mode-hook)
2271 (defvar completion-saved-bindings nil)
2273 ;;;###autoload
2274 (define-minor-mode dynamic-completion-mode
2275 "Toggle dynamic word-completion on or off.
2276 With a prefix argument ARG, enable the mode if ARG is positive,
2277 and disable it otherwise. If called from Lisp, enable the mode
2278 if ARG is omitted or nil."
2279 :global t
2280 :group 'completion
2281 ;; This is always good, not specific to dynamic-completion-mode.
2282 (define-key function-key-map [C-return] [?\C-\r])
2284 (dolist (x '((find-file-hook . completion-find-file-hook)
2285 (pre-command-hook . completion-before-command)
2286 ;; Save completions when killing Emacs.
2287 (kill-emacs-hook . kill-emacs-save-completions)
2289 ;; Install the appropriate mode tables.
2290 (lisp-mode-hook . completion-lisp-mode-hook)
2291 (c-mode-hook . completion-c-mode-hook)
2292 (fortran-mode-hook . completion-setup-fortran-mode)))
2293 (if dynamic-completion-mode
2294 (add-hook (car x) (cdr x))
2295 (remove-hook (car x) (cdr x))))
2297 ;; "Complete" Key Keybindings. We don't want to use a minor-mode
2298 ;; map because these have too high a priority. We could/should
2299 ;; probably change the interpretation of minor-mode-map-alist such
2300 ;; that a map has lower precedence if the symbol is not buffer-local.
2301 (while completion-saved-bindings
2302 (let ((binding (pop completion-saved-bindings)))
2303 (global-set-key (car binding) (cdr binding))))
2304 (when dynamic-completion-mode
2305 (dolist (binding
2306 '(("\M-\r" . complete)
2307 ([?\C-\r] . complete)
2309 ;; Tests -
2310 ;; (add-completion "cumberland")
2311 ;; (add-completion "cumberbund")
2312 ;; cum
2313 ;; Cumber
2314 ;; cumbering
2315 ;; cumb
2317 ;; Patches to standard keymaps insert completions
2318 ([remap kill-region] . completion-kill-region)
2320 ;; Separators
2321 ;; We've used the completion syntax table given as a guide.
2323 ;; Global separator chars.
2324 ;; We left out <tab> because there are too many special
2325 ;; cases for it. Also, in normal coding it's rarely typed
2326 ;; after a word.
2327 (" " . completion-separator-self-insert-autofilling)
2328 ("!" . completion-separator-self-insert-command)
2329 ("%" . completion-separator-self-insert-command)
2330 ("^" . completion-separator-self-insert-command)
2331 ("&" . completion-separator-self-insert-command)
2332 ("(" . completion-separator-self-insert-command)
2333 (")" . completion-separator-self-insert-command)
2334 ("=" . completion-separator-self-insert-command)
2335 ("`" . completion-separator-self-insert-command)
2336 ("|" . completion-separator-self-insert-command)
2337 ("{" . completion-separator-self-insert-command)
2338 ("}" . completion-separator-self-insert-command)
2339 ("[" . completion-separator-self-insert-command)
2340 ("]" . completion-separator-self-insert-command)
2341 (";" . completion-separator-self-insert-command)
2342 ("\"". completion-separator-self-insert-command)
2343 ("'" . completion-separator-self-insert-command)
2344 ("#" . completion-separator-self-insert-command)
2345 ("," . completion-separator-self-insert-command)
2346 ("?" . completion-separator-self-insert-command)
2348 ;; We include period and colon even though they are symbol
2349 ;; chars because :
2350 ;; - in text we want to pick up the last word in a sentence.
2351 ;; - in C pointer refs. we want to pick up the first symbol
2352 ;; - it won't make a difference for lisp mode (package names
2353 ;; are short)
2354 ("." . completion-separator-self-insert-command)
2355 (":" . completion-separator-self-insert-command)))
2356 (push (cons (car binding) (lookup-key global-map (car binding)))
2357 completion-saved-bindings)
2358 (global-set-key (car binding) (cdr binding)))
2360 ;; Tests --
2361 ;; foobarbiz
2362 ;; foobar
2363 ;; fooquux
2364 ;; fooper
2366 (completion-initialize)))
2368 ;;-----------------------------------------------
2369 ;; End of line chars.
2370 ;;-----------------------------------------------
2371 (completion-def-wrapper 'newline :separator)
2372 (completion-def-wrapper 'newline-and-indent :separator)
2373 (completion-def-wrapper 'comint-send-input :separator)
2374 (completion-def-wrapper 'exit-minibuffer :minibuffer-separator)
2375 (completion-def-wrapper 'eval-print-last-sexp :separator)
2376 (completion-def-wrapper 'eval-last-sexp :separator)
2377 ;;(completion-def-wrapper 'minibuffer-complete-and-exit :minibuffer)
2379 ;;-----------------------------------------------
2380 ;; Cursor movement
2381 ;;-----------------------------------------------
2383 (completion-def-wrapper 'next-line :under-or-before)
2384 (completion-def-wrapper 'previous-line :under-or-before)
2385 (completion-def-wrapper 'beginning-of-buffer :under-or-before)
2386 (completion-def-wrapper 'end-of-buffer :under-or-before)
2387 (completion-def-wrapper 'beginning-of-line :under-or-before)
2388 (completion-def-wrapper 'end-of-line :under-or-before)
2389 (completion-def-wrapper 'forward-char :under-or-before)
2390 (completion-def-wrapper 'forward-word :under-or-before)
2391 (completion-def-wrapper 'forward-sexp :under-or-before)
2392 (completion-def-wrapper 'backward-char :backward-under)
2393 (completion-def-wrapper 'backward-word :backward-under)
2394 (completion-def-wrapper 'backward-sexp :backward-under)
2396 (completion-def-wrapper 'delete-backward-char :backward)
2397 (completion-def-wrapper 'delete-backward-char-untabify :backward)
2399 ;; Old names, non-namespace-clean.
2400 (defvaralias 'cmpl-syntax-table 'completion-syntax-table)
2401 (defalias 'initialize-completions 'completion-initialize)
2403 (provide 'completion)
2405 ;;; completion.el ends here