Minor improvement in section "Pages" of the usere manual
[emacs.git] / lisp / completion.el
bloba5c8158d1b3b94710db6a4ba55640db9e0397293
1 ;;; completion.el --- dynamic word-completion code
3 ;; Copyright (C) 1990, 1993, 1995, 1997, 2001-2018 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 <https://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 cmpl--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-strictly 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-strictly -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-strictly 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-strictly -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-strictly 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-strictly 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-strictly -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 cmpl--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 (let ((cmpl--completion-string completion-string))
1153 ;; Handle pending acceptance
1154 (if completion-to-accept (accept-completion))
1155 ;; test if already in database
1156 (if (setq cmpl-db-entry (find-exact-completion completion-string))
1157 ;; found
1158 (let* ((prefix-entry (find-cmpl-prefix-entry
1159 (substring cmpl-db-downcase-string 0
1160 completion-prefix-min-length)))
1161 (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry))
1162 (cmpl-ptr (cdr splice-ptr)))
1163 ;; update entry
1164 (set-completion-string cmpl-db-entry completion-string)
1165 ;; move to head (if necessary)
1166 (cond (splice-ptr
1167 ;; These should all execute atomically but it is not fatal if
1168 ;; they don't.
1169 ;; splice it out
1170 (or (setcdr splice-ptr (cdr cmpl-ptr))
1171 ;; fix up tail if necessary
1172 (set-cmpl-prefix-entry-tail prefix-entry splice-ptr))
1173 ;; splice in at head
1174 (setcdr cmpl-ptr (cmpl-prefix-entry-head prefix-entry))
1175 (set-cmpl-prefix-entry-head prefix-entry cmpl-ptr)))
1176 cmpl-db-entry)
1177 ;; not there
1178 (let ( ;; create an entry
1179 (entry (list (make-completion completion-string)))
1180 ;; setup the prefix
1181 (prefix-entry (find-cmpl-prefix-entry
1182 (substring cmpl-db-downcase-string 0
1183 completion-prefix-min-length))))
1184 (cond (prefix-entry
1185 ;; Splice in at head
1186 (setcdr entry (cmpl-prefix-entry-head prefix-entry))
1187 (set-cmpl-prefix-entry-head prefix-entry entry))
1189 ;; Start new prefix entry
1190 (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))))
1191 ;; Add it to the symbol
1192 (set cmpl-db-symbol (car entry))))))
1194 (defun delete-completion (completion-string)
1195 "Delete the completion from the database.
1196 String must be longer than `completion-prefix-min-length'."
1197 ;; Handle pending acceptance
1198 (let ((cmpl--completion-string completion-string))
1199 (if completion-to-accept (accept-completion))
1200 (if (setq cmpl-db-entry (find-exact-completion completion-string))
1201 ;; found
1202 (let* ((prefix-entry (find-cmpl-prefix-entry
1203 (substring cmpl-db-downcase-string 0
1204 completion-prefix-min-length)))
1205 (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry)))
1206 ;; delete symbol reference
1207 (set cmpl-db-symbol nil)
1208 ;; remove from prefix list
1209 (cond (splice-ptr
1210 ;; not at head
1211 (or (setcdr splice-ptr (cdr (cdr splice-ptr)))
1212 ;; fix up tail if necessary
1213 (set-cmpl-prefix-entry-tail prefix-entry splice-ptr)))
1215 ;; at head
1216 (or (set-cmpl-prefix-entry-head
1217 prefix-entry (cdr (cmpl-prefix-entry-head prefix-entry)))
1218 ;; List is now empty
1219 (set cmpl-db-prefix-symbol nil)))))
1220 (error "Unknown completion `%s'" completion-string))))
1222 ;; Tests --
1223 ;; - Add and Find -
1224 ;; (add-completion-to-head "banana") --> ("banana" 0 nil 0)
1225 ;; (find-exact-completion "banana") --> ("banana" 0 nil 0)
1226 ;; (find-exact-completion "bana") --> nil
1227 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1228 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1229 ;; (add-completion-to-head "banish") --> ("banish" 0 nil 0)
1230 ;; (find-exact-completion "banish") --> ("banish" 0 nil 0)
1231 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banish" ...) ("banana" ...))
1232 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1233 ;; (add-completion-to-head "banana") --> ("banana" 0 nil 0)
1234 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
1235 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
1237 ;; - Deleting -
1238 ;; (add-completion-to-head "banner") --> ("banner" 0 nil 0)
1239 ;; (delete-completion "banner")
1240 ;; (find-exact-completion "banner") --> nil
1241 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
1242 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
1243 ;; (add-completion-to-head "banner") --> ("banner" 0 nil 0)
1244 ;; (delete-completion "banana")
1245 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banner" ...) ("banish" ...))
1246 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
1247 ;; (delete-completion "banner")
1248 ;; (delete-completion "banish")
1249 ;; (find-cmpl-prefix-entry "ban") --> nil
1250 ;; (delete-completion "banner") --> error
1252 ;; - Tail -
1253 ;; (add-completion-to-tail-if-new "banana") --> ("banana" 0 nil 0)
1254 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1255 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1256 ;; (add-completion-to-tail-if-new "banish") --> ("banish" 0 nil 0)
1257 ;; (car (find-cmpl-prefix-entry "ban")) -->(("banana" ...) ("banish" ...))
1258 ;; (cdr (find-cmpl-prefix-entry "ban")) -->(("banish" ...))
1262 ;;---------------------------------------------------------------------------
1263 ;; Database Update :: Interface level routines
1264 ;;---------------------------------------------------------------------------
1266 ;; These lie on top of the database ref. functions but below the standard
1267 ;; user interface level
1270 (defun interactive-completion-string-reader (prompt)
1271 (let* ((default (symbol-under-or-before-point))
1272 (new-prompt
1273 (if default
1274 (format "%s (default %s): " prompt default)
1275 (format "%s: " prompt)))
1276 (read (completing-read new-prompt cmpl-obarray)))
1277 (if (zerop (length read)) (setq read (or default "")))
1278 (list read)))
1280 (defun check-completion-length (string)
1281 (if (< (length string) completion-min-length)
1282 (user-error "The string `%s' is too short to be saved as a completion"
1283 string)
1284 (list string)))
1286 (defun add-completion (string &optional num-uses last-use-time)
1287 "Add STRING to completion list, or move it to head of list.
1288 The completion is altered appropriately if NUM-USES and/or LAST-USE-TIME
1289 are specified."
1290 (interactive (interactive-completion-string-reader "Completion to add"))
1291 (check-completion-length string)
1292 (let* ((current-completion-source (if (called-interactively-p 'interactive)
1293 cmpl-source-interactive
1294 current-completion-source))
1295 (entry (add-completion-to-head string)))
1297 (if num-uses (set-completion-num-uses entry num-uses))
1298 (if last-use-time
1299 (set-completion-last-use-time entry last-use-time))))
1301 (defun add-permanent-completion (string)
1302 "Add STRING if it isn't already listed, and mark it permanent."
1303 (interactive
1304 (interactive-completion-string-reader "Completion to add permanently"))
1305 (let ((current-completion-source (if (called-interactively-p 'interactive)
1306 cmpl-source-interactive
1307 current-completion-source)))
1308 (add-completion string nil t)))
1310 (defun kill-completion (string)
1311 (interactive (interactive-completion-string-reader "Completion to kill"))
1312 (check-completion-length string)
1313 (delete-completion string))
1315 (defun accept-completion ()
1316 "Accept the pending completion in `completion-to-accept'.
1317 This bumps num-uses. Called by `add-completion-to-head' and
1318 `completion-search-reset'."
1319 (let ((string completion-to-accept)
1320 ;; if this is added afresh here, then it must be a cdabbrev
1321 (current-completion-source cmpl-source-cdabbrev)
1322 entry)
1323 (setq completion-to-accept nil)
1324 (setq entry (add-completion-to-head string))
1325 (set-completion-num-uses entry (1+ (completion-num-uses entry)))
1326 (setq cmpl-completions-accepted-p t)))
1328 (defun use-completion-under-point ()
1329 "Add the completion symbol underneath the point into the completion buffer."
1330 (let ((string (and enable-completion (symbol-under-point)))
1331 (current-completion-source cmpl-source-cursor-moves))
1332 (if string (add-completion-to-head string))))
1334 (defun use-completion-before-point ()
1335 "Add the completion symbol before point into the completion buffer."
1336 (let ((string (and enable-completion (symbol-before-point)))
1337 (current-completion-source cmpl-source-cursor-moves))
1338 (if string (add-completion-to-head string))))
1340 (defun use-completion-under-or-before-point ()
1341 "Add the completion symbol before point into the completion buffer."
1342 (let ((string (and enable-completion (symbol-under-or-before-point)))
1343 (current-completion-source cmpl-source-cursor-moves))
1344 (if string (add-completion-to-head string))))
1346 (defun use-completion-before-separator ()
1347 "Add the completion symbol before point into the completion buffer.
1348 Completions added this way will automatically be saved if
1349 `completion-on-separator-character' is non-nil."
1350 (let ((string (and enable-completion (symbol-before-point)))
1351 (current-completion-source cmpl-source-separator)
1352 entry)
1353 (cond (string
1354 (setq entry (add-completion-to-head string))
1355 (if (and completion-on-separator-character
1356 (zerop (completion-num-uses entry)))
1357 (progn
1358 (set-completion-num-uses entry 1)
1359 (setq cmpl-completions-accepted-p t)))))))
1361 ;; Tests --
1362 ;; - Add and Find -
1363 ;; (add-completion "banana" 5 10)
1364 ;; (find-exact-completion "banana") --> ("banana" 5 10 0)
1365 ;; (add-completion "banana" 6)
1366 ;; (find-exact-completion "banana") --> ("banana" 6 10 0)
1367 ;; (add-completion "banish")
1368 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banish" ...) ("banana" ...))
1370 ;; - Accepting -
1371 ;; (setq completion-to-accept "banana")
1372 ;; (accept-completion)
1373 ;; (find-exact-completion "banana") --> ("banana" 7 10)
1374 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
1375 ;; (setq completion-to-accept "banish")
1376 ;; (add-completion "banner")
1377 ;; (car (find-cmpl-prefix-entry "ban"))
1378 ;; --> (("banner" ...) ("banish" 1 ...) ("banana" 7 ...))
1380 ;; - Deleting -
1381 ;; (kill-completion "banish")
1382 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banner" ...) ("banana" ...))
1385 ;;---------------------------------------------------------------------------
1386 ;; Searching the database
1387 ;;---------------------------------------------------------------------------
1388 ;; Functions outside this block must call completion-search-reset followed
1389 ;; by calls to completion-search-next or completion-search-peek
1392 ;; Status variables
1393 ;; Commented out to improve loading speed
1394 (defvar cmpl-test-string "")
1395 ;; "The current string used by completion-search-next."
1396 (defvar cmpl-test-regexp "")
1397 ;; "The current regexp used by completion-search-next.
1398 ;; (derived from cmpl-test-string)"
1399 (defvar cmpl-last-index 0)
1400 ;; "The last index that completion-search-next was called with."
1401 (defvar cmpl-cdabbrev-reset-p nil)
1402 ;; "Set to t when cdabbrevs have been reset."
1403 (defvar cmpl-next-possibilities nil)
1404 ;; "A pointer to the element BEFORE the next set of possible completions.
1405 ;; cadr of this is the cmpl-next-possibility"
1406 (defvar cmpl-starting-possibilities nil)
1407 ;; "The initial list of starting possibilities."
1408 (defvar cmpl-next-possibility nil)
1409 ;; "The cached next possibility."
1410 (defvar cmpl-tried-list nil)
1411 ;; "A downcased list of all the completions we have tried."
1414 (defun completion-search-reset (string)
1415 "Set up the for completion searching for STRING.
1416 STRING must be longer than `completion-prefix-min-length'."
1417 (if completion-to-accept (accept-completion))
1418 (setq cmpl-starting-possibilities
1419 (cmpl-prefix-entry-head
1420 (find-cmpl-prefix-entry
1421 (downcase (substring string 0 completion-prefix-min-length))))
1422 cmpl-test-string string
1423 cmpl-test-regexp (concat (regexp-quote string) "."))
1424 (completion-search-reset-1))
1426 (defun completion-search-reset-1 ()
1427 (setq cmpl-next-possibilities cmpl-starting-possibilities
1428 cmpl-next-possibility nil
1429 cmpl-cdabbrev-reset-p nil
1430 cmpl-last-index -1
1431 cmpl-tried-list nil))
1433 (defun completion-search-next (index)
1434 "Return the next completion entry.
1435 If INDEX is out of sequence, reset and start from the top.
1436 If there are no more entries, try cdabbrev and return only a string."
1437 (cond
1438 ((= index (setq cmpl-last-index (1+ cmpl-last-index)))
1439 (completion-search-peek t))
1440 ((< index 0)
1441 (completion-search-reset-1)
1442 (setq cmpl-last-index index)
1443 ;; reverse the possibilities list
1444 (setq cmpl-next-possibilities (reverse cmpl-starting-possibilities))
1445 ;; do a "normal" search
1446 (while (and (completion-search-peek nil)
1447 (< (setq index (1+ index)) 0))
1448 (setq cmpl-next-possibility nil))
1449 (cond ((not cmpl-next-possibilities))
1450 ;; If no more possibilities, leave it that way
1451 ((= -1 cmpl-last-index)
1452 ;; next completion is at index 0. reset next-possibility list
1453 ;; to start at beginning
1454 (setq cmpl-next-possibilities cmpl-starting-possibilities))
1456 ;; otherwise point to one before current
1457 (setq cmpl-next-possibilities
1458 (nthcdr (- (length cmpl-starting-possibilities)
1459 (length cmpl-next-possibilities))
1460 cmpl-starting-possibilities)))))
1462 ;; non-negative index, reset and search
1463 ;;(prin1 'reset)
1464 (completion-search-reset-1)
1465 (setq cmpl-last-index index)
1466 (while (and (completion-search-peek t)
1467 (not (< (setq index (1- index)) 0)))
1468 (setq cmpl-next-possibility nil))))
1469 (prog1
1470 cmpl-next-possibility
1471 (setq cmpl-next-possibility nil)))
1474 (defun completion-search-peek (use-cdabbrev)
1475 "Return the next completion entry without actually moving the pointers.
1476 Calling this again or calling `completion-search-next' results in the same
1477 string being returned. Depends on `case-fold-search'.
1478 If there are no more entries, try cdabbrev and then return only a string."
1479 (cond
1480 ;; return the cached value if we have it
1481 (cmpl-next-possibility)
1482 ((and cmpl-next-possibilities
1483 ;; still a few possibilities left
1484 (progn
1485 (while
1486 (and (not (eq 0 (string-match cmpl-test-regexp
1487 (completion-string (car cmpl-next-possibilities)))))
1488 (setq cmpl-next-possibilities (cdr cmpl-next-possibilities))))
1489 cmpl-next-possibilities))
1490 ;; successful match
1491 (setq cmpl-next-possibility (car cmpl-next-possibilities)
1492 cmpl-tried-list (cons (downcase (completion-string cmpl-next-possibility))
1493 cmpl-tried-list)
1494 cmpl-next-possibilities (cdr cmpl-next-possibilities))
1495 cmpl-next-possibility)
1496 (use-cdabbrev
1497 ;; unsuccessful, use cdabbrev
1498 (cond ((not cmpl-cdabbrev-reset-p)
1499 (reset-cdabbrev cmpl-test-string cmpl-tried-list)
1500 (setq cmpl-cdabbrev-reset-p t)))
1501 (setq cmpl-next-possibility (next-cdabbrev)))
1502 ;; Completely unsuccessful, return nil
1505 ;; Tests --
1506 ;; - Add and Find -
1507 ;; (add-completion "banana")
1508 ;; (completion-search-reset "ban")
1509 ;; (completion-search-next 0) --> "banana"
1511 ;; - Discrimination -
1512 ;; (add-completion "cumberland")
1513 ;; (add-completion "cumberbund")
1514 ;; cumbering
1515 ;; (completion-search-reset "cumb")
1516 ;; (completion-search-peek t) --> "cumberbund"
1517 ;; (completion-search-next 0) --> "cumberbund"
1518 ;; (completion-search-peek t) --> "cumberland"
1519 ;; (completion-search-next 1) --> "cumberland"
1520 ;; (completion-search-peek nil) --> nil
1521 ;; (completion-search-next 2) --> "cumbering" {cdabbrev}
1522 ;; (completion-search-next 3) --> nil or "cumming"{depends on context}
1523 ;; (completion-search-next 1) --> "cumberland"
1524 ;; (completion-search-peek t) --> "cumbering" {cdabbrev}
1526 ;; - Accepting -
1527 ;; (completion-search-next 1) --> "cumberland"
1528 ;; (setq completion-to-accept "cumberland")
1529 ;; (completion-search-reset "foo")
1530 ;; (completion-search-reset "cum")
1531 ;; (completion-search-next 0) --> "cumberland"
1533 ;; - Deleting -
1534 ;; (kill-completion "cumberland")
1535 ;; cummings
1536 ;; (completion-search-reset "cum")
1537 ;; (completion-search-next 0) --> "cumberbund"
1538 ;; (completion-search-next 1) --> "cummings"
1540 ;; - Ignoring Capitalization -
1541 ;; (completion-search-reset "CuMb")
1542 ;; (completion-search-next 0) --> "cumberbund"
1546 ;;-----------------------------------------------
1547 ;; COMPLETE
1548 ;;-----------------------------------------------
1550 (defun completion-mode ()
1551 "Toggle whether or not to add new words to the completion database."
1552 (interactive)
1553 (setq enable-completion (not enable-completion))
1554 (message "Completion mode is now %s." (if enable-completion "ON" "OFF")))
1556 (defvar cmpl-current-index 0)
1557 (defvar cmpl-original-string nil)
1558 (defvar cmpl-last-insert-location -1)
1559 (defvar cmpl-leave-point-at-start nil)
1561 (defun complete (&optional arg)
1562 "Fill out a completion of the word before point.
1563 Point is left at end. Consecutive calls rotate through all possibilities.
1564 Prefix args ::
1565 control-u :: leave the point at the beginning of the completion rather
1566 than at the end.
1567 a number :: rotate through the possible completions by that amount
1568 `-' :: same as -1 (insert previous completion)
1569 {See the comments at the top of `completion.el' for more info.}"
1570 (interactive "*p")
1571 ;;; Set up variables
1572 (cond ((eq last-command this-command)
1573 ;; Undo last one
1574 (delete-region cmpl-last-insert-location (point))
1575 ;; get next completion
1576 (setq cmpl-current-index (+ cmpl-current-index (or arg 1))))
1578 (if (not cmpl-initialized-p)
1579 (completion-initialize)) ;; make sure everything's loaded
1580 (cond ((consp current-prefix-arg) ;; control-u
1581 (setq arg 0)
1582 (setq cmpl-leave-point-at-start t))
1584 (setq cmpl-leave-point-at-start nil)))
1585 ;; get string
1586 (setq cmpl-original-string (symbol-before-point-for-complete))
1587 (cond ((not cmpl-original-string)
1588 (setq this-command 'failed-complete)
1589 (error "To complete, point must be after a symbol at least %d character long"
1590 completion-prefix-min-length)))
1591 ;; get index
1592 (setq cmpl-current-index (if current-prefix-arg arg 0))
1593 ;; reset database
1594 (completion-search-reset cmpl-original-string)
1595 ;; erase what we've got
1596 (delete-region cmpl-symbol-start cmpl-symbol-end)))
1598 ;; point is at the point to insert the new symbol
1599 ;; Get the next completion
1600 (let* ((print-status-p
1601 (and (>= baud-rate completion-prompt-speed-threshold)
1602 (not (window-minibuffer-p))))
1603 (insert-point (point))
1604 (entry (completion-search-next cmpl-current-index))
1605 string)
1606 ;; entry is either a completion entry or a string (if cdabbrev)
1608 ;; If found, insert
1609 (cond (entry
1610 ;; Setup for proper case
1611 (setq string (if (stringp entry)
1612 entry (completion-string entry)))
1613 (setq string (cmpl-merge-string-cases
1614 string cmpl-original-string))
1615 ;; insert
1616 (insert string)
1617 ;; accept it
1618 (setq completion-to-accept string)
1619 ;; fixup and cache point
1620 (cond (cmpl-leave-point-at-start
1621 (setq cmpl-last-insert-location (point))
1622 (goto-char insert-point))
1623 (t;; point at end,
1624 (setq cmpl-last-insert-location insert-point)))
1625 ;; Done ! cmpl-stat-complete-successful
1626 ;;display the next completion
1627 (cond
1628 ((and print-status-p
1629 ;; This updates the display and only prints if there
1630 ;; is no typeahead
1631 (sit-for 0)
1632 (setq entry
1633 (completion-search-peek
1634 completion-cdabbrev-prompt-flag)))
1635 (setq string (if (stringp entry)
1636 entry (completion-string entry)))
1637 (setq string (cmpl-merge-string-cases
1638 string cmpl-original-string))
1639 (message "Next completion: %s" string))))
1640 (t;; none found, insert old
1641 (insert cmpl-original-string)
1642 ;; Don't accept completions
1643 (setq completion-to-accept nil)
1644 ;; print message
1645 ;; This used to call cmpl19-sit-for, an undefined function.
1646 ;; I hope that sit-for does the right thing; I don't know -- rms.
1647 (if (and print-status-p (sit-for 0))
1648 (message "No %scompletions."
1649 (if (eq this-command last-command) "more " "")))
1650 ;; Pretend that we were never here
1651 (setq this-command 'failed-complete)))))
1653 ;;---------------------------------------------------------------------------
1654 ;; Parsing definitions from files into the database
1655 ;;---------------------------------------------------------------------------
1657 ;;-----------------------------------------------
1658 ;; Top Level functions ::
1659 ;;-----------------------------------------------
1661 ;; User interface
1662 (defun add-completions-from-file (file)
1663 "Parse possible completions from a FILE and add them to database."
1664 (interactive "fFile: ")
1665 (setq file (expand-file-name file))
1666 (let* ((buffer (get-file-buffer file))
1667 (buffer-already-there-p buffer))
1668 (if (not buffer-already-there-p)
1669 (let ((completions-merging-modes nil))
1670 (setq buffer (find-file-noselect file))))
1671 (unwind-protect
1672 (with-current-buffer buffer
1673 (add-completions-from-buffer))
1674 (if (not buffer-already-there-p)
1675 (kill-buffer buffer)))))
1677 (defun add-completions-from-buffer ()
1678 (interactive)
1679 (let ((current-completion-source cmpl-source-file-parsing))
1680 (cond ((memq major-mode '(emacs-lisp-mode lisp-mode))
1681 (add-completions-from-lisp-buffer))
1682 ((memq major-mode '(c-mode))
1683 (add-completions-from-c-buffer))
1685 (error "Cannot parse completions in %s buffers"
1686 major-mode)))))
1688 ;; Find file hook
1689 (defun completion-find-file-hook ()
1690 (cond (enable-completion
1691 (cond ((and (memq major-mode '(emacs-lisp-mode lisp-mode))
1692 (memq 'lisp completions-merging-modes))
1693 (add-completions-from-buffer))
1694 ((and (memq major-mode '(c-mode))
1695 (memq 'c completions-merging-modes))
1696 (add-completions-from-buffer))))))
1698 ;;-----------------------------------------------
1699 ;; Tags Table Completions
1700 ;;-----------------------------------------------
1702 (defun add-completions-from-tags-table ()
1703 ;; Inspired by eero@media-lab.media.mit.edu
1704 "Add completions from the current tags table."
1705 (interactive)
1706 (visit-tags-table-buffer) ;this will prompt if no tags-table
1707 (save-excursion
1708 (goto-char (point-min))
1709 (let (string)
1710 (condition-case nil
1711 (while t
1712 (search-forward "\177")
1713 (backward-char 3)
1714 (and (setq string (symbol-under-point))
1715 (add-completion-to-tail-if-new string))
1716 (forward-char 3))
1717 (search-failed)))))
1720 ;;-----------------------------------------------
1721 ;; Lisp File completion parsing
1722 ;;-----------------------------------------------
1723 ;; This merely looks for phrases beginning with (def.... or
1724 ;; (package:def ... and takes the next word.
1726 ;; We tried using forward-lines and explicit searches but the regexp technique
1727 ;; was faster. (About 100K characters per second)
1729 (defconst *lisp-def-regexp*
1730 "\n(\\(\\w*:\\)?def\\(\\w\\|\\s_\\)*\\s +(*"
1731 "A regexp that searches for Lisp definition form.")
1733 ;; Tests -
1734 ;; (and (string-match *lisp-def-regexp* "\n(defun foo") (match-end 0)) -> 8
1735 ;; (and (string-match *lisp-def-regexp* "\n(si:def foo") (match-end 0)) -> 9
1736 ;; (and (string-match *lisp-def-regexp* "\n(def-bar foo")(match-end 0)) -> 10
1737 ;; (and (string-match *lisp-def-regexp* "\n(defun (foo") (match-end 0)) -> 9
1739 ;; Parses all the definition names from a Lisp mode buffer and adds them to
1740 ;; the completion database.
1741 (defun add-completions-from-lisp-buffer ()
1742 ;;; Benchmarks
1743 ;;; Sun-3/280 - 1500 to 3000 lines of lisp code per second
1744 (let (string)
1745 (save-excursion
1746 (goto-char (point-min))
1747 (condition-case nil
1748 (while t
1749 (re-search-forward *lisp-def-regexp*)
1750 (and (setq string (symbol-under-point))
1751 (add-completion-to-tail-if-new string)))
1752 (search-failed)))))
1755 ;;-----------------------------------------------
1756 ;; C file completion parsing
1757 ;;-----------------------------------------------
1758 ;; C :
1759 ;; Looks for #define or [<storage class>] [<type>] <name>{,<name>}
1760 ;; or structure, array or pointer defs.
1761 ;; It gets most of the definition names.
1763 ;; As you might suspect by now, we use some symbol table hackery
1765 ;; Symbol separator chars (have whitespace syntax) --> , ; * = (
1766 ;; Opening char --> [ {
1767 ;; Closing char --> ] }
1768 ;; opening and closing must be skipped over
1769 ;; Whitespace chars (have symbol syntax)
1770 ;; Everything else has word syntax
1772 (defconst completion-c-def-syntax-table
1773 (let ((table (make-syntax-table))
1774 (whitespace-chars '(? ?\n ?\t ?\f ?\v ?\r))
1775 ;; unfortunately the ?( causes the parens to appear unbalanced
1776 (separator-chars '(?, ?* ?= ?\( ?\;))
1778 ;; default syntax is whitespace
1779 (setq i 0)
1780 (while (< i 256)
1781 (modify-syntax-entry i "w" table)
1782 (setq i (1+ i)))
1783 (dolist (char whitespace-chars)
1784 (modify-syntax-entry char "_" table))
1785 (dolist (char separator-chars)
1786 (modify-syntax-entry char " " table))
1787 (modify-syntax-entry ?\[ "(]" table)
1788 (modify-syntax-entry ?\{ "(}" table)
1789 (modify-syntax-entry ?\] ")[" table)
1790 (modify-syntax-entry ?\} "){" table)
1791 table))
1793 ;; Regexps
1794 (defconst *c-def-regexp*
1795 ;; This stops on lines with possible definitions
1796 "\n[_a-zA-Z#]"
1797 ;; This stops after the symbol to add.
1798 ;;"\n\\(#define\\s +.\\|\\(\\(\\w\\|\\s_\\)+\\b\\s *\\)+[(;,[*{=]\\)"
1799 ;; This stops before the symbol to add. {Test cases in parens. below}
1800 ;;"\n\\(\\(\\w\\|\\s_\\)+\\s *(\\|\\(\\(#define\\|auto\\|extern\\|register\\|static\\|int\\|long\\|short\\|unsigned\\|char\\|void\\|float\\|double\\|enum\\|struct\\|union\\|typedef\\)\\s +\\)+\\)"
1801 ;; this simple version picks up too much extraneous stuff
1802 ;; "\n\\(\\w\\|\\s_\\|#\\)\\B"
1803 "A regexp that searches for a definition form.")
1805 ;(defconst *c-cont-regexp*
1806 ; "\\(\\w\\|\\s_\\)+\\b\\s *\\({\\|\\(\\[[0-9\t ]*\\]\\s *\\)*,\\(*\\|\\s \\)*\\b\\)"
1807 ; "This regexp should be used in a looking-at to parse for lists of variables.")
1809 ;(defconst *c-struct-regexp*
1810 ; "\\(*\\|\\s \\)*\\b"
1811 ; "This regexp should be used to test whether a symbol follows a structure definition.")
1813 ;(defun test-c-def-regexp (regexp string)
1814 ; (and (eq 0 (string-match regexp string)) (match-end 0))
1817 ;; Tests -
1818 ;; (test-c-def-regexp *c-def-regexp* "\n#define foo") -> 10 (9)
1819 ;; (test-c-def-regexp *c-def-regexp* "\nfoo (x, y) {") -> 6 (6)
1820 ;; (test-c-def-regexp *c-def-regexp* "\nint foo (x, y)") -> 10 (5)
1821 ;; (test-c-def-regexp *c-def-regexp* "\n int foo (x, y)") -> nil
1822 ;; (test-c-def-regexp *c-cont-regexp* "oo, bar") -> 4
1823 ;; (test-c-def-regexp *c-cont-regexp* "oo, *bar") -> 5
1824 ;; (test-c-def-regexp *c-cont-regexp* "a [5][6], bar") -> 10
1825 ;; (test-c-def-regexp *c-cont-regexp* "oo(x,y)") -> nil
1826 ;; (test-c-def-regexp *c-cont-regexp* "a [6] ,\t bar") -> 9
1827 ;; (test-c-def-regexp *c-cont-regexp* "oo {trout =1} my_carp;") -> 14
1828 ;; (test-c-def-regexp *c-cont-regexp* "truct_p complex foon") -> nil
1830 ;; Parses all the definition names from a C mode buffer and adds them to the
1831 ;; completion database.
1832 (defun add-completions-from-c-buffer ()
1833 ;; Benchmark --
1834 ;; Sun 3/280-- 1250 lines/sec.
1836 (let (string next-point char)
1837 (save-excursion
1838 (goto-char (point-min))
1839 (catch 'finish-add-completions
1840 (with-syntax-table completion-c-def-syntax-table
1841 (while t
1842 ;; we loop here only when scan-sexps fails
1843 ;; (i.e. unbalance exps.)
1844 (condition-case e
1845 (while t
1846 (re-search-forward *c-def-regexp*)
1847 (cond
1848 ((= (preceding-char) ?#)
1849 ;; preprocessor macro, see if it's one we handle
1850 (cond ((looking-at "\\(define\\|ifdef\\)\\>")
1851 ;; skip forward over definition symbol
1852 ;; and add it to database
1853 (and (forward-word-strictly 2)
1854 (setq string (symbol-before-point))
1855 ;;(push string foo)
1856 (add-completion-to-tail-if-new string)))))
1858 ;; C definition
1859 (setq next-point (point))
1860 (while (and
1861 next-point
1862 ;; scan to next separator char.
1863 (setq next-point (scan-sexps next-point 1)))
1864 ;; position the point on the word we want to add
1865 (goto-char next-point)
1866 (while (= (setq char (following-char)) ?*)
1867 ;; handle pointer ref
1868 ;; move to next separator char.
1869 (goto-char
1870 (setq next-point (scan-sexps (point) 1))))
1871 (forward-word-strictly -1)
1872 ;; add to database
1873 (if (setq string (symbol-under-point))
1874 ;; (push string foo)
1875 (add-completion-to-tail-if-new string)
1876 ;; Local TMC hack (useful for parsing paris.h)
1877 (if (and (looking-at "_AP") ;; "ansi prototype"
1878 (progn
1879 (forward-word-strictly -1)
1880 (setq string
1881 (symbol-under-point))))
1882 (add-completion-to-tail-if-new string)))
1883 ;; go to next
1884 (goto-char next-point)
1885 ;; (push (format "%c" (following-char)) foo)
1886 (if (= (char-syntax char) ?\()
1887 ;; if on an opening delimiter, go to end
1888 (while (= (char-syntax char) ?\()
1889 (setq next-point (scan-sexps next-point 1)
1890 char (char-after next-point)))
1891 (or (= char ?,)
1892 ;; Current char is an end char.
1893 (setq next-point nil)))))))
1894 (search-failed ;;done
1895 (throw 'finish-add-completions t))
1896 (error
1897 ;; Check for failure in scan-sexps
1898 (if (member (nth 1 e)
1899 '("Containing expression ends prematurely"
1900 "Unbalanced parentheses"))
1901 ;; unbalanced paren., keep going
1902 ;;(ding)
1903 (forward-line 1)
1904 (message "Error parsing C buffer for completions--please send bug report")
1905 (throw 'finish-add-completions t))))))))))
1908 ;;---------------------------------------------------------------------------
1909 ;; Init files
1910 ;;---------------------------------------------------------------------------
1912 ;; The version of save-completions-to-file called at kill-emacs time.
1913 (defun kill-emacs-save-completions ()
1914 (if (and save-completions-flag enable-completion cmpl-initialized-p)
1915 (cond
1916 ((not cmpl-completions-accepted-p)
1917 (message "Completions database has not changed - not writing."))
1919 (save-completions-to-file)))))
1921 ;; There is no point bothering to change this again
1922 ;; unless the package changes so much that it matters
1923 ;; for people that have saved completions.
1924 (defconst completion-version "11")
1926 (defconst saved-cmpl-file-header
1927 ";;; Completion Initialization file.
1928 ;; Version = %s
1929 ;; Format is (<string> . <last-use-time>)
1930 ;; <string> is the completion
1931 ;; <last-use-time> is the time the completion was last used
1932 ;; If it is t, the completion will never be pruned from the file.
1933 ;; Otherwise it is in hours since origin.
1934 \n")
1936 (defun completion-backup-filename (filename)
1937 (concat filename ".BAK"))
1939 (defun save-completions-to-file (&optional filename)
1940 "Save completions in init file FILENAME.
1941 If file name is not specified, use `save-completions-file-name'."
1942 (interactive)
1943 (setq filename (expand-file-name (or filename save-completions-file-name)))
1944 (if (file-writable-p filename)
1945 (progn
1946 (if (not cmpl-initialized-p)
1947 (completion-initialize)) ;; make sure everything's loaded
1948 (message "Saving completions to file %s" filename)
1950 (let* ((delete-old-versions t)
1951 (kept-old-versions 0)
1952 (kept-new-versions completions-file-versions-kept)
1953 last-use-time
1954 (this-use-time (cmpl-hours-since-origin))
1955 (total-in-db 0)
1956 (total-perm 0)
1957 (total-saved 0)
1958 (backup-filename (completion-backup-filename filename)))
1960 (with-current-buffer (get-buffer-create " *completion-save-buffer*")
1961 (setq buffer-file-name filename)
1963 (if (not (verify-visited-file-modtime (current-buffer)))
1964 (progn
1965 ;; file has changed on disk. Bring us up-to-date
1966 (message "Completion file has changed. Merging. . .")
1967 (load-completions-from-file filename t)
1968 (message "Merging finished. Saving completions to file %s" filename)))
1970 ;; prepare the buffer to be modified
1971 (clear-visited-file-modtime)
1972 (erase-buffer)
1973 ;; (/ 1 0)
1974 (insert (format saved-cmpl-file-header completion-version))
1975 (dolist (completion (list-all-completions))
1976 (setq total-in-db (1+ total-in-db))
1977 (setq last-use-time (completion-last-use-time completion))
1978 ;; Update num uses and maybe write completion to a file
1979 (cond ((or;; Write to file if
1980 ;; permanent
1981 (and (eq last-use-time t)
1982 (setq total-perm (1+ total-perm)))
1983 ;; or if
1984 (if (> (completion-num-uses completion) 0)
1985 ;; it's been used
1986 (setq last-use-time this-use-time)
1987 ;; or it was saved before and
1988 (and last-use-time
1989 ;; save-completions-retention-time is nil
1990 (or (not save-completions-retention-time)
1991 ;; or time since last use is < ...retention-time*
1992 (< (- this-use-time last-use-time)
1993 save-completions-retention-time)))))
1994 ;; write to file
1995 (setq total-saved (1+ total-saved))
1996 (insert (prin1-to-string (cons (completion-string completion)
1997 last-use-time)) "\n"))))
1999 ;; write the buffer
2000 (condition-case nil
2001 (let ((file-exists-p (file-exists-p filename)))
2002 (if file-exists-p
2003 (progn
2004 ;; If file exists . . .
2005 ;; Save a backup(so GNU doesn't screw us when we're out of disk)
2006 ;; (GNU leaves a 0 length file if it gets a disk full error!)
2008 ;; If backup doesn't exit, Rename current to backup
2009 ;; {If backup exists the primary file is probably messed up}
2010 (or (file-exists-p backup-filename)
2011 (rename-file filename backup-filename))
2012 ;; Copy the backup back to the current name
2013 ;; (so versioning works)
2014 (copy-file backup-filename filename t)))
2015 ;; Save it
2016 (save-buffer)
2017 (if file-exists-p
2018 ;; If successful, remove backup
2019 (delete-file backup-filename)))
2020 (error
2021 (set-buffer-modified-p nil)
2022 (message "Couldn't save completion file `%s'" filename)))
2023 ;; Reset accepted-p flag
2024 (setq cmpl-completions-accepted-p nil) )))))
2026 ;;(defun auto-save-completions ()
2027 ;; (if (and save-completions-flag enable-completion cmpl-initialized-p
2028 ;; *completion-auto-save-period*
2029 ;; (> cmpl-emacs-idle-time *completion-auto-save-period*)
2030 ;; cmpl-completions-accepted-p)
2031 ;; (save-completions-to-file)))
2033 ;;(add-hook 'cmpl-emacs-idle-time-hooks 'auto-save-completions)
2035 (defun load-completions-from-file (&optional filename no-message-p)
2036 "Load a completion init file FILENAME.
2037 If file is not specified, then use `save-completions-file-name'."
2038 (interactive)
2039 (setq filename (expand-file-name (or filename save-completions-file-name)))
2040 (let* ((backup-filename (completion-backup-filename filename))
2041 (backup-readable-p (file-readable-p backup-filename)))
2042 (if backup-readable-p (setq filename backup-filename))
2043 (if (file-readable-p filename)
2044 (progn
2045 (if (not no-message-p)
2046 (message "Loading completions from %sfile %s . . ."
2047 (if backup-readable-p "backup " "") filename))
2048 (with-current-buffer (get-buffer-create " *completion-save-buffer*")
2049 (setq buffer-file-name filename)
2050 ;; prepare the buffer to be modified
2051 (clear-visited-file-modtime)
2052 (erase-buffer)
2054 (let ((insert-okay-p nil)
2055 (buffer (current-buffer))
2056 string entry last-use-time
2057 cmpl-entry cmpl-last-use-time
2058 (current-completion-source cmpl-source-init-file)
2059 (total-in-file 0) (total-perm 0))
2060 ;; insert the file into a buffer
2061 (condition-case nil
2062 (progn (insert-file-contents filename t)
2063 (setq insert-okay-p t))
2065 (file-error
2066 (message "File error trying to load completion file %s."
2067 filename)))
2068 ;; parse it
2069 (if insert-okay-p
2070 (progn
2071 (goto-char (point-min))
2073 (condition-case nil
2074 (while t
2075 (setq entry (read buffer))
2076 (setq total-in-file (1+ total-in-file))
2077 (cond
2078 ((and (consp entry)
2079 (stringp (setq string (car entry)))
2080 (cond
2081 ((eq (setq last-use-time (cdr entry)) 'T)
2082 ;; handle case sensitivity
2083 (setq total-perm (1+ total-perm))
2084 (setq last-use-time t))
2085 ((eq last-use-time t)
2086 (setq total-perm (1+ total-perm)))
2087 ((integerp last-use-time))))
2088 ;; Valid entry
2089 ;; add it in
2090 (setq cmpl-last-use-time
2091 (completion-last-use-time
2092 (setq cmpl-entry
2093 (add-completion-to-tail-if-new string))))
2094 (if (or (eq last-use-time t)
2095 (and (> last-use-time 1000);;backcompatibility
2096 (not (eq cmpl-last-use-time t))
2097 (or (not cmpl-last-use-time)
2098 ;; more recent
2099 (> last-use-time cmpl-last-use-time))))
2100 ;; update last-use-time
2101 (set-completion-last-use-time cmpl-entry last-use-time)))
2103 ;; Bad format
2104 (message "Error: invalid saved completion - %s"
2105 (prin1-to-string entry))
2106 ;; try to get back in sync
2107 (search-forward "\n("))))
2108 (search-failed
2109 (message "End of file while reading completions."))
2110 (end-of-file
2111 (if (= (point) (point-max))
2112 (if (not no-message-p)
2113 (message "Loading completions from file %s . . . Done."
2114 filename))
2115 (message "End of file while reading completions."))))))
2116 ))))))
2118 (defun completion-initialize ()
2119 "Load the default completions file.
2120 Also sets up so that exiting Emacs will automatically save the file."
2121 (interactive)
2122 (unless cmpl-initialized-p
2123 (load-completions-from-file)
2124 (setq cmpl-initialized-p t)))
2126 ;;-----------------------------------------------
2127 ;; Kill region patch
2128 ;;-----------------------------------------------
2130 (defun completion-kill-region (&optional beg end)
2131 "Kill between point and mark.
2132 The text is deleted but saved in the kill ring.
2133 The command \\[yank] can retrieve it from there.
2134 /(If you want to kill and then yank immediately, use \\[copy-region-as-kill].)
2136 This is the primitive for programs to kill text (as opposed to deleting it).
2137 Supply two arguments, character positions indicating the stretch of text
2138 to be killed.
2139 Any command that calls this function is a \"kill command\".
2140 If the previous command was also a kill command,
2141 the text killed this time appends to the text killed last time
2142 to make one entry in the kill ring.
2143 Patched to remove the most recent completion."
2144 (interactive "r")
2145 (cond ((eq last-command 'complete)
2146 (delete-region (point) cmpl-last-insert-location)
2147 (insert cmpl-original-string)
2148 (setq completion-to-accept nil))
2150 (kill-region beg end))))
2153 ;;-----------------------------------------------
2154 ;; Patches to self-insert-command.
2155 ;;-----------------------------------------------
2157 ;; Need 2 versions: generic separator chars. and space (to get auto fill
2158 ;; to work)
2160 ;; All common separators (eg. space "(" ")" """) characters go through a
2161 ;; function to add new words to the list of words to complete from.
2162 ;; If the character before this was an alpha-numeric then this adds the
2163 ;; symbol before point to the completion list (using ADD-COMPLETION).
2165 (defvar completion-separator-chars
2166 (append " !%^&()=`|{}[];\\'#,?"
2167 ;; We include period and colon even though they are symbol
2168 ;; chars because :
2169 ;; - in text we want to pick up the last word in a sentence.
2170 ;; - in C pointer refs. we want to pick up the first symbol
2171 ;; - it won't make a difference for lisp mode (package names
2172 ;; are short)
2173 ".:" nil))
2175 (defun completion--post-self-insert ()
2176 (when (memq last-command-event completion-separator-chars)
2177 (let ((after-pos (electric--after-char-pos)))
2178 (when after-pos
2179 (save-excursion
2180 (goto-char (1- after-pos))
2181 (use-completion-before-separator))))))
2183 ;;-----------------------------------------------
2184 ;; Wrapping Macro
2185 ;;-----------------------------------------------
2187 ;; Note that because of the way byte compiling works, none of
2188 ;; the functions defined with this macro get byte compiled.
2190 (defun completion-def-wrapper (function-name type)
2191 "Add a call to update the completion database before function execution.
2192 TYPE is the type of the wrapper to be added. Can be :before or :under."
2193 (put function-name 'completion-function
2194 (cdr (assq type
2195 '((:separator . use-completion-before-separator)
2196 (:before . use-completion-before-point)
2197 (:backward-under . use-completion-backward-under)
2198 (:backward . use-completion-backward)
2199 (:under . use-completion-under-point)
2200 (:under-or-before . use-completion-under-or-before-point)
2201 (:minibuffer-separator
2202 . use-completion-minibuffer-separator))))))
2204 (defun use-completion-minibuffer-separator ()
2205 (let ((completion-syntax-table completion-standard-syntax-table))
2206 (use-completion-before-separator)))
2208 (defun use-completion-backward-under ()
2209 (use-completion-under-point))
2211 (defun use-completion-backward ()
2212 nil)
2214 (defun completion-before-command ()
2215 (funcall (or (and (symbolp this-command)
2216 (get this-command 'completion-function))
2217 'use-completion-under-or-before-point)))
2219 ;; Lisp mode diffs.
2221 (defconst completion-lisp-syntax-table
2222 (let ((table (copy-syntax-table completion-standard-syntax-table))
2223 (symbol-chars '(?! ?& ?? ?= ?^)))
2224 (dolist (char symbol-chars)
2225 (modify-syntax-entry char "_" table))
2226 table))
2228 (defun completion-lisp-mode-hook ()
2229 (setq completion-syntax-table completion-lisp-syntax-table)
2230 ;; Lisp Mode diffs
2231 (setq-local completion-separator-chars
2232 (cl-set-difference completion-separator-chars
2233 (append "!&%?=^" nil))))
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 (setq-local completion-separator-chars
2248 (append "+*/" completion-separator-chars)))
2250 ;; FORTRAN mode diffs. (these are defined when fortran is called)
2252 (defconst completion-fortran-syntax-table
2253 (let ((table (copy-syntax-table completion-standard-syntax-table))
2254 (separator-chars '(?+ ?- ?* ?/ ?:)))
2255 (dolist (char separator-chars)
2256 (modify-syntax-entry char " " table))
2257 table))
2259 (defun completion-setup-fortran-mode ()
2260 (setq completion-syntax-table completion-fortran-syntax-table)
2261 (setq-local completion-separator-chars
2262 (append "+-*/" completion-separator-chars)))
2264 ;; Enable completion mode.
2266 (defvar fortran-mode-hook)
2268 (defvar completion-saved-bindings nil)
2270 ;;;###autoload
2271 (define-minor-mode dynamic-completion-mode
2272 "Toggle dynamic word-completion on or off.
2273 With a prefix argument ARG, enable the mode if ARG is positive,
2274 and disable it otherwise. If called from Lisp, enable the mode
2275 if ARG is omitted or nil."
2276 :global t
2277 :group 'completion
2278 ;; This is always good, not specific to dynamic-completion-mode.
2279 (define-key function-key-map [C-return] [?\C-\r])
2281 (dolist (x `((find-file-hook . ,#'completion-find-file-hook)
2282 (pre-command-hook . ,#'completion-before-command)
2283 ;; Save completions when killing Emacs.
2284 (kill-emacs-hook . ,#'kill-emacs-save-completions)
2285 (post-self-insert-hook . ,#'completion--post-self-insert)
2287 ;; Install the appropriate mode tables.
2288 (lisp-mode-hook . ,#'completion-lisp-mode-hook)
2289 (c-mode-hook . ,#'completion-c-mode-hook)
2290 (fortran-mode-hook . ,#'completion-setup-fortran-mode)))
2291 (if dynamic-completion-mode
2292 (add-hook (car x) (cdr x))
2293 (remove-hook (car x) (cdr x))))
2295 ;; "Complete" Key Keybindings. We don't want to use a minor-mode
2296 ;; map because these have too high a priority. We could/should
2297 ;; probably change the interpretation of minor-mode-map-alist such
2298 ;; that a map has lower precedence if the symbol is not buffer-local.
2299 (while completion-saved-bindings
2300 (let ((binding (pop completion-saved-bindings)))
2301 (global-set-key (car binding) (cdr binding))))
2302 (when dynamic-completion-mode
2303 (dolist (binding
2304 '(("\M-\r" . complete)
2305 ([?\C-\r] . complete)
2307 ;; Tests -
2308 ;; (add-completion "cumberland")
2309 ;; (add-completion "cumberbund")
2310 ;; cum
2311 ;; Cumber
2312 ;; cumbering
2313 ;; cumb
2315 ;; Patches to standard keymaps insert completions
2316 ([remap kill-region] . completion-kill-region)))
2317 (push (cons (car binding) (lookup-key global-map (car binding)))
2318 completion-saved-bindings)
2319 (global-set-key (car binding) (cdr binding)))
2321 ;; Tests --
2322 ;; foobarbiz
2323 ;; foobar
2324 ;; fooquux
2325 ;; fooper
2327 (completion-initialize)))
2329 ;;-----------------------------------------------
2330 ;; End of line chars.
2331 ;;-----------------------------------------------
2332 (completion-def-wrapper 'newline :separator)
2333 (completion-def-wrapper 'newline-and-indent :separator)
2334 (completion-def-wrapper 'comint-send-input :separator)
2335 (completion-def-wrapper 'exit-minibuffer :minibuffer-separator)
2336 (completion-def-wrapper 'eval-print-last-sexp :separator)
2337 (completion-def-wrapper 'eval-last-sexp :separator)
2338 ;;(completion-def-wrapper 'minibuffer-complete-and-exit :minibuffer)
2340 ;;-----------------------------------------------
2341 ;; Cursor movement
2342 ;;-----------------------------------------------
2344 (completion-def-wrapper 'next-line :under-or-before)
2345 (completion-def-wrapper 'previous-line :under-or-before)
2346 (completion-def-wrapper 'beginning-of-buffer :under-or-before)
2347 (completion-def-wrapper 'end-of-buffer :under-or-before)
2348 (completion-def-wrapper 'beginning-of-line :under-or-before)
2349 (completion-def-wrapper 'end-of-line :under-or-before)
2350 (completion-def-wrapper 'forward-char :under-or-before)
2351 (completion-def-wrapper 'forward-word :under-or-before)
2352 (completion-def-wrapper 'forward-sexp :under-or-before)
2353 (completion-def-wrapper 'backward-char :backward-under)
2354 (completion-def-wrapper 'backward-word :backward-under)
2355 (completion-def-wrapper 'backward-sexp :backward-under)
2357 (completion-def-wrapper 'delete-backward-char :backward)
2358 (completion-def-wrapper 'delete-backward-char-untabify :backward)
2360 ;; Old names, non-namespace-clean.
2361 (defvaralias 'cmpl-syntax-table 'completion-syntax-table)
2362 (defalias 'initialize-completions 'completion-initialize)
2364 (provide 'completion)
2366 ;;; completion.el ends here