(gnus-blocked-images): Clarify privacy implications
[emacs.git] / lisp / completion.el
blob2ddf0999e433a82a48f22ac2a9250f2570683d67
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 ;; Old name, non-namespace-clean.
522 (defvaralias 'cmpl-syntax-table 'completion-syntax-table)
524 (defvar completion-syntax-table completion-standard-syntax-table
525 "This variable holds the current completion syntax table.")
526 (make-variable-buffer-local 'completion-syntax-table)
528 ;;-----------------------------------------------
529 ;; Symbol functions
530 ;;-----------------------------------------------
531 (defvar cmpl-symbol-start nil
532 "Holds first character of symbol, after any completion symbol function.")
533 (defvar cmpl-symbol-end nil
534 "Holds last character of symbol, after any completion symbol function.")
536 (defun symbol-under-point ()
537 "Return the symbol that the point is currently on.
538 But only if it is longer than `completion-min-length'."
539 (with-syntax-table completion-syntax-table
540 (when (memq (char-syntax (following-char)) '(?w ?_))
541 ;; Cursor is on following-char and after preceding-char
542 (let ((saved-point (point)))
543 (setq cmpl-symbol-start (scan-sexps (1+ saved-point) -1)
544 cmpl-symbol-end (scan-sexps saved-point 1))
545 ;; Remove chars to ignore at the start.
546 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
547 (goto-char cmpl-symbol-start)
548 (forward-word-strictly 1)
549 (setq cmpl-symbol-start (point))
550 (goto-char saved-point)))
551 ;; Remove chars to ignore at the end.
552 (cond ((= (char-syntax (char-after (1- cmpl-symbol-end))) ?w)
553 (goto-char cmpl-symbol-end)
554 (forward-word-strictly -1)
555 (setq cmpl-symbol-end (point))
556 (goto-char saved-point)))
557 ;; Return completion if the length is reasonable.
558 (if (and (<= completion-min-length
559 (- cmpl-symbol-end cmpl-symbol-start))
560 (<= (- cmpl-symbol-end cmpl-symbol-start)
561 completion-max-length))
562 (buffer-substring-no-properties
563 cmpl-symbol-start cmpl-symbol-end))))))
565 ;; tests for symbol-under-point
566 ;; `^' indicates cursor pos. where value is returned
567 ;; simple-word-test
568 ;; ^^^^^^^^^^^^^^^^ --> simple-word-test
569 ;; _harder_word_test_
570 ;; ^^^^^^^^^^^^^^^^^^ --> harder_word_test
571 ;; .___.______.
572 ;; --> nil
573 ;; /foo/bar/quux.hello
574 ;; ^^^^^^^^^^^^^^^^^^^ --> /foo/bar/quux.hello
577 (defun symbol-before-point ()
578 "Return a string of the symbol immediately before point.
579 Returns nil if there isn't one longer than `completion-min-length'."
580 ;; This is called when a word separator is typed so it must be FAST !
581 (with-syntax-table completion-syntax-table
582 ;; Cursor is on following-char and after preceding-char
583 (cond ((= (setq cmpl-preceding-syntax (char-syntax (preceding-char))) ?_)
584 ;; Number of chars to ignore at end.
585 (setq cmpl-symbol-end (point)
586 cmpl-symbol-start (scan-sexps cmpl-symbol-end -1))
587 ;; Remove chars to ignore at the start.
588 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
589 (goto-char cmpl-symbol-start)
590 (forward-word-strictly 1)
591 (setq cmpl-symbol-start (point))
592 (goto-char cmpl-symbol-end)))
593 ;; Return value if long enough.
594 (if (>= cmpl-symbol-end
595 (+ cmpl-symbol-start completion-min-length))
596 (buffer-substring-no-properties
597 cmpl-symbol-start cmpl-symbol-end)))
598 ((= cmpl-preceding-syntax ?w)
599 ;; chars to ignore at end
600 (let ((saved-point (point)))
601 (setq cmpl-symbol-start (scan-sexps saved-point -1))
602 ;; take off chars. from end
603 (forward-word-strictly -1)
604 (setq cmpl-symbol-end (point))
605 ;; remove chars to ignore at the start
606 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
607 (goto-char cmpl-symbol-start)
608 (forward-word-strictly 1)
609 (setq cmpl-symbol-start (point))))
610 ;; Restore state.
611 (goto-char saved-point)
612 ;; Return completion if the length is reasonable
613 (if (and (<= completion-min-length
614 (- cmpl-symbol-end cmpl-symbol-start))
615 (<= (- cmpl-symbol-end cmpl-symbol-start)
616 completion-max-length))
617 (buffer-substring-no-properties
618 cmpl-symbol-start cmpl-symbol-end)))))))
620 ;; tests for symbol-before-point
621 ;; `^' indicates cursor pos. where value is returned
622 ;; simple-word-test
623 ;; ^ --> nil
624 ;; ^ --> nil
625 ;; ^ --> simple-w
626 ;; ^ --> simple-word-test
627 ;; _harder_word_test_
628 ;; ^ --> harder_word_test
629 ;; ^ --> harder_word_test
630 ;; ^ --> harder
631 ;; .___....
632 ;; --> nil
634 (defun symbol-under-or-before-point ()
635 ;; This could be made slightly faster but it is better to avoid
636 ;; copying all the code.
637 ;; However, it is only used by the completion string prompter.
638 ;; If it comes into common use, it could be rewritten.
639 (if (memq (with-syntax-table completion-syntax-table
640 (char-syntax (following-char)))
641 '(?w ?_))
642 (symbol-under-point)
643 (symbol-before-point)))
646 (defun symbol-before-point-for-complete ()
647 ;; "Returns a string of the symbol immediately before point
648 ;; or nil if there isn't one. Like symbol-before-point but doesn't trim the
649 ;; end chars."
650 ;; Cursor is on following-char and after preceding-char
651 (with-syntax-table completion-syntax-table
652 (cond ((memq (setq cmpl-preceding-syntax (char-syntax (preceding-char)))
653 '(?_ ?w))
654 (setq cmpl-symbol-end (point)
655 cmpl-symbol-start (scan-sexps cmpl-symbol-end -1))
656 ;; Remove chars to ignore at the start.
657 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
658 (goto-char cmpl-symbol-start)
659 (forward-word-strictly 1)
660 (setq cmpl-symbol-start (point))
661 (goto-char cmpl-symbol-end)))
662 ;; Return completion if the length is reasonable.
663 (if (and (<= completion-prefix-min-length
664 (- cmpl-symbol-end cmpl-symbol-start))
665 (<= (- cmpl-symbol-end cmpl-symbol-start)
666 completion-max-length))
667 (buffer-substring-no-properties
668 cmpl-symbol-start cmpl-symbol-end))))))
670 ;; tests for symbol-before-point-for-complete
671 ;; `^' indicates cursor pos. where value is returned
672 ;; simple-word-test
673 ;; ^ --> nil
674 ;; ^ --> nil
675 ;; ^ --> simple-w
676 ;; ^ --> simple-word-test
677 ;; _harder_word_test_
678 ;; ^ --> harder_word_test
679 ;; ^ --> harder_word_test_
680 ;; ^ --> harder_
681 ;; .___....
682 ;; --> nil
686 ;;---------------------------------------------------------------------------
687 ;; Statistics Recording
688 ;;---------------------------------------------------------------------------
690 ;; Note that the guts of this has been turned off. The guts
691 ;; are in completion-stats.el.
693 ;;-----------------------------------------------
694 ;; Completion Sources
695 ;;-----------------------------------------------
697 ;; ID numbers
698 (defconst cmpl-source-unknown 0)
699 (defconst cmpl-source-init-file 1)
700 (defconst cmpl-source-file-parsing 2)
701 (defconst cmpl-source-separator 3)
702 (defconst cmpl-source-cursor-moves 4)
703 (defconst cmpl-source-interactive 5)
704 (defconst cmpl-source-cdabbrev 6)
705 (defconst num-cmpl-sources 7)
706 (defvar current-completion-source cmpl-source-unknown)
710 ;;---------------------------------------------------------------------------
711 ;; Completion Method #2: dabbrev-expand style
712 ;;---------------------------------------------------------------------------
714 ;; This method is used if there are no useful stored completions. It is
715 ;; based on dabbrev-expand with these differences :
716 ;; 1) Faster (we don't use regexps)
717 ;; 2) case coercion handled correctly
718 ;; This is called cdabbrev to differentiate it.
719 ;; We simply search backwards through the file looking for words which
720 ;; start with the same letters we are trying to complete.
723 (defvar cdabbrev-completions-tried nil)
724 ;; "A list of all the cdabbrev completions since the last reset.")
726 (defvar cdabbrev-current-point 0)
727 ;; "The current point position the cdabbrev search is at.")
729 (defvar cdabbrev-current-window nil)
730 ;; "The current window we are looking for cdabbrevs in.
731 ;; Return t if looking in (other-buffer), nil if no more cdabbrevs.")
733 (defvar cdabbrev-wrapped-p nil)
734 ;; "Return t if the cdabbrev search has wrapped around the file.")
736 (defvar cdabbrev-abbrev-string "")
737 (defvar cdabbrev-start-point 0)
738 (defvar cdabbrev-stop-point)
740 ;; Test strings for cdabbrev
741 ;; cdat-upcase ;;same namestring
742 ;; CDAT-UPCASE ;;ok
743 ;; cdat2 ;;too short
744 ;; cdat-1-2-3-4 ;;ok
745 ;; a-cdat-1 ;;doesn't start correctly
746 ;; cdat-simple ;;ok
749 (defun reset-cdabbrev (abbrev-string &optional initial-completions-tried)
750 "Reset the cdabbrev search to search for ABBREV-STRING.
751 INITIAL-COMPLETIONS-TRIED is a list of downcased strings to ignore
752 during the search."
753 (setq cdabbrev-abbrev-string abbrev-string
754 cdabbrev-completions-tried
755 (cons (downcase abbrev-string) initial-completions-tried))
756 (reset-cdabbrev-window t))
758 (defun set-cdabbrev-buffer ()
759 ;; cdabbrev-current-window must not be nil
760 (set-buffer (if (eq cdabbrev-current-window t)
761 (other-buffer)
762 (window-buffer cdabbrev-current-window))))
765 (defun reset-cdabbrev-window (&optional initializep)
766 "Reset the cdabbrev search to search for abbrev-string."
767 ;; Set the window
768 (cond (initializep
769 (setq cdabbrev-current-window (selected-window)))
770 ((eq cdabbrev-current-window t)
771 ;; Everything has failed
772 (setq cdabbrev-current-window nil))
773 (cdabbrev-current-window
774 (setq cdabbrev-current-window (next-window cdabbrev-current-window))
775 (if (eq cdabbrev-current-window (selected-window))
776 ;; No more windows, try other buffer.
777 (setq cdabbrev-current-window t))))
778 (if cdabbrev-current-window
779 (save-excursion
780 (set-cdabbrev-buffer)
781 (setq cdabbrev-current-point (point)
782 cdabbrev-start-point cdabbrev-current-point
783 cdabbrev-stop-point
784 (if completion-search-distance
785 (max (point-min)
786 (- cdabbrev-start-point completion-search-distance))
787 (point-min))
788 cdabbrev-wrapped-p nil))))
790 (defun next-cdabbrev ()
791 "Return the next possible cdabbrev expansion or nil if there isn't one.
792 `reset-cdabbrev' must've been called already.
793 This is sensitive to `case-fold-search'."
794 ;; note that case-fold-search affects the behavior of this function
795 ;; Bug: won't pick up an expansion that starts at the top of buffer
796 (if cdabbrev-current-window
797 (let (saved-point
798 saved-syntax
799 (expansion nil)
800 downcase-expansion tried-list syntax saved-point-2)
801 (save-excursion
802 (unwind-protect
803 (progn
804 ;; Switch to current completion buffer
805 (set-cdabbrev-buffer)
806 ;; Save current buffer state
807 (setq saved-point (point)
808 saved-syntax (syntax-table))
809 ;; Restore completion state
810 (set-syntax-table completion-syntax-table)
811 (goto-char cdabbrev-current-point)
812 ;; Loop looking for completions
813 (while
814 ;; This code returns t if it should loop again
815 (cond
816 (;; search for the string
817 (search-backward cdabbrev-abbrev-string cdabbrev-stop-point t)
818 ;; return nil if the completion is valid
819 (not
820 (and
821 ;; does it start with a separator char ?
822 (or (= (setq syntax (char-syntax (preceding-char))) ? )
823 (and (= syntax ?w)
824 ;; symbol char to ignore at end. Are we at end ?
825 (progn
826 (setq saved-point-2 (point))
827 (forward-word-strictly -1)
828 (prog1
829 (= (char-syntax (preceding-char)) ? )
830 (goto-char saved-point-2)))))
831 ;; is the symbol long enough ?
832 (setq expansion (symbol-under-point))
833 ;; have we not tried this one before
834 (progn
835 ;; See if we've already used it
836 (setq tried-list cdabbrev-completions-tried
837 downcase-expansion (downcase expansion))
838 (while (and tried-list
839 (not (string-equal downcase-expansion
840 (car tried-list))))
841 ;; Already tried, don't choose this one
842 (setq tried-list (cdr tried-list)))
843 ;; at this point tried-list will be nil if this
844 ;; expansion has not yet been tried
845 (if tried-list
846 (setq expansion nil)
847 t)))))
848 ;; search failed
849 (cdabbrev-wrapped-p
850 ;; If already wrapped, then we've failed completely
851 nil)
853 ;; need to wrap
854 (goto-char (setq cdabbrev-current-point
855 (if completion-search-distance
856 (min (point-max) (+ cdabbrev-start-point completion-search-distance))
857 (point-max))))
859 (setq cdabbrev-wrapped-p t))))
860 ;; end of while loop
861 (cond (expansion
862 ;; successful
863 (setq cdabbrev-completions-tried
864 (cons downcase-expansion cdabbrev-completions-tried)
865 cdabbrev-current-point (point)))))
866 (set-syntax-table saved-syntax)
867 (goto-char saved-point)))
868 ;; If no expansion, go to next window
869 (cond (expansion)
870 (t (reset-cdabbrev-window)
871 (next-cdabbrev))))))
873 ;; The following must be eval'd in the minibuffer ::
874 ;; (reset-cdabbrev "cdat")
875 ;; (next-cdabbrev) --> "cdat-simple"
876 ;; (next-cdabbrev) --> "cdat-1-2-3-4"
877 ;; (next-cdabbrev) --> "CDAT-UPCASE"
878 ;; (next-cdabbrev) --> "cdat-wrapping"
879 ;; (next-cdabbrev) --> "cdat_start_sym"
880 ;; (next-cdabbrev) --> nil
881 ;; (next-cdabbrev) --> nil
882 ;; (next-cdabbrev) --> nil
884 ;; _cdat_start_sym
885 ;; cdat-wrapping
888 ;;---------------------------------------------------------------------------
889 ;; Completion Database
890 ;;---------------------------------------------------------------------------
892 ;; We use two storage modes for the two search types ::
893 ;; 1) Prefix {cmpl-prefix-obarray} for looking up possible completions
894 ;; Used by search-completion-next
895 ;; the value of the symbol is nil or a cons of head and tail pointers
896 ;; 2) Interning {cmpl-obarray} to see if it's in the database
897 ;; Used by find-exact-completion, completion-in-database-p
898 ;; The value of the symbol is the completion entry
900 ;; bad things may happen if this length is changed due to the way
901 ;; GNU implements obarrays
902 (defconst cmpl-obarray-length 511)
904 (defvar cmpl-prefix-obarray (make-vector cmpl-obarray-length 0)
905 "An obarray used to store the downcased completion prefixes.
906 Each symbol is bound to a list of completion entries.")
908 (defvar cmpl-obarray (make-vector cmpl-obarray-length 0)
909 "An obarray used to store the downcased completions.
910 Each symbol is bound to a single completion entry.")
912 ;;-----------------------------------------------
913 ;; Completion Entry Structure Definition
914 ;;-----------------------------------------------
916 ;; A completion entry is a LIST of string, prefix-symbol num-uses, and
917 ;; last-use-time (the time the completion was last used)
918 ;; last-use-time is t if the string should be kept permanently
919 ;; num-uses is incremented every time the completion is used.
921 ;; We chose lists because (car foo) is faster than (aref foo 0) and the
922 ;; creation time is about the same.
924 ;; READER MACROS
926 (defmacro completion-string (completion-entry)
927 (list 'car completion-entry))
929 (defmacro completion-num-uses (completion-entry)
930 ;; "The number of times it has used. Used to decide whether to save
931 ;; it."
932 (list 'car (list 'cdr completion-entry)))
934 (defmacro completion-last-use-time (completion-entry)
935 ;; "The time it was last used. In hours since origin. Used to decide
936 ;; whether to save it. t if one should always save it."
937 (list 'nth 2 completion-entry))
939 (defmacro completion-source (completion-entry)
940 (list 'nth 3 completion-entry))
942 ;; WRITER MACROS
943 (defmacro set-completion-string (completion-entry string)
944 (list 'setcar completion-entry string))
946 (defmacro set-completion-num-uses (completion-entry num-uses)
947 (list 'setcar (list 'cdr completion-entry) num-uses))
949 (defmacro set-completion-last-use-time (completion-entry last-use-time)
950 (list 'setcar (list 'cdr (list 'cdr completion-entry)) last-use-time))
952 ;; CONSTRUCTOR
953 (defun make-completion (string)
954 "Return a completion entry."
955 (list string 0 nil current-completion-source))
957 ;; Obsolete
958 ;;(defmacro cmpl-prefix-entry-symbol (completion-entry)
959 ;; (list 'car (list 'cdr completion-entry)))
963 ;;-----------------------------------------------
964 ;; Prefix symbol entry definition
965 ;;-----------------------------------------------
966 ;; A cons of (head . tail)
968 ;; READER Macros
970 (defalias 'cmpl-prefix-entry-head 'car)
972 (defalias 'cmpl-prefix-entry-tail 'cdr)
974 ;; WRITER Macros
976 (defmacro set-cmpl-prefix-entry-head (prefix-entry new-head)
977 (list 'setcar prefix-entry new-head))
979 (defmacro set-cmpl-prefix-entry-tail (prefix-entry new-tail)
980 (list 'setcdr prefix-entry new-tail))
982 ;; Constructor
984 (defun make-cmpl-prefix-entry (completion-entry-list)
985 "Make a new prefix entry containing only completion-entry."
986 (cons completion-entry-list completion-entry-list))
988 ;;-----------------------------------------------
989 ;; Completion Database - Utilities
990 ;;-----------------------------------------------
992 (defun clear-all-completions ()
993 "Initialize the completion storage. All existing completions are lost."
994 (interactive)
995 (setq cmpl-prefix-obarray (make-vector cmpl-obarray-length 0))
996 (setq cmpl-obarray (make-vector cmpl-obarray-length 0)))
998 (defvar completions-list-return-value)
1000 (defun list-all-completions ()
1001 "Return a list of all the known completion entries."
1002 (let ((completions-list-return-value nil))
1003 (mapatoms 'list-all-completions-1 cmpl-prefix-obarray)
1004 completions-list-return-value))
1006 (defun list-all-completions-1 (prefix-symbol)
1007 (if (boundp prefix-symbol)
1008 (setq completions-list-return-value
1009 (append (cmpl-prefix-entry-head (symbol-value prefix-symbol))
1010 completions-list-return-value))))
1012 (defun list-all-completions-by-hash-bucket ()
1013 "Return list of lists of known completion entries, organized by hash bucket."
1014 (let ((completions-list-return-value nil))
1015 (mapatoms 'list-all-completions-by-hash-bucket-1 cmpl-prefix-obarray)
1016 completions-list-return-value))
1018 (defun list-all-completions-by-hash-bucket-1 (prefix-symbol)
1019 (if (boundp prefix-symbol)
1020 (setq completions-list-return-value
1021 (cons (cmpl-prefix-entry-head (symbol-value prefix-symbol))
1022 completions-list-return-value))))
1025 ;;-----------------------------------------------
1026 ;; Updating the database
1027 ;;-----------------------------------------------
1029 ;; These are the internal functions used to update the datebase
1032 (defvar completion-to-accept nil
1033 "Set to a string that is pending its acceptance.")
1034 ;; this checked by the top level reading functions
1036 (defvar cmpl-db-downcase-string nil
1037 "Setup by `find-exact-completion', etc. The given string, downcased.")
1038 (defvar cmpl-db-symbol nil
1039 "The interned symbol corresponding to `cmpl-db-downcase-string'.
1040 Set up by `cmpl-db-symbol'.")
1041 (defvar cmpl-db-prefix-symbol nil
1042 "The interned prefix symbol corresponding to `cmpl-db-downcase-string'.")
1043 (defvar cmpl-db-entry nil)
1044 (defvar cmpl-db-debug-p nil
1045 "Set to t if you want to debug the database.")
1047 ;; READS
1048 (defun find-exact-completion (string)
1049 "Return the completion entry for STRING or nil.
1050 Sets up `cmpl-db-downcase-string' and `cmpl-db-symbol'."
1051 (and (boundp (setq cmpl-db-symbol
1052 (intern (setq cmpl-db-downcase-string (downcase string))
1053 cmpl-obarray)))
1054 (symbol-value cmpl-db-symbol)))
1056 (defun find-cmpl-prefix-entry (prefix-string)
1057 "Return the prefix entry for string.
1058 Sets `cmpl-db-prefix-symbol'.
1059 Prefix-string must be exactly `completion-prefix-min-length' long
1060 and downcased. Sets up `cmpl-db-prefix-symbol'."
1061 (and (boundp (setq cmpl-db-prefix-symbol
1062 (intern prefix-string cmpl-prefix-obarray)))
1063 (symbol-value cmpl-db-prefix-symbol)))
1065 (defvar inside-locate-completion-entry nil)
1066 ;; used to trap lossage in silent error correction
1068 (defun locate-completion-entry (completion-entry prefix-entry)
1069 "Locate the completion entry.
1070 Returns a pointer to the element before the completion entry or nil if
1071 the completion entry is at the head.
1072 Must be called after `find-exact-completion'."
1073 (let ((prefix-list (cmpl-prefix-entry-head prefix-entry))
1074 next-prefix-list)
1075 (cond
1076 ((not (eq (car prefix-list) completion-entry))
1077 ;; not already at head
1078 (while (and prefix-list
1079 (not (eq completion-entry
1080 (car (setq next-prefix-list (cdr prefix-list))))))
1081 (setq prefix-list next-prefix-list))
1082 (cond (;; found
1083 prefix-list)
1084 ;; Didn't find it. Database is messed up.
1085 (cmpl-db-debug-p
1086 ;; not found, error if debug mode
1087 (error "Completion entry exists but not on prefix list - %s"
1088 cmpl--completion-string))
1089 (inside-locate-completion-entry
1090 ;; recursive error: really scrod
1091 (locate-completion-db-error))
1093 ;; Patch out
1094 (set cmpl-db-symbol nil)
1095 ;; Retry
1096 (locate-completion-entry-retry completion-entry)))))))
1098 (defun locate-completion-entry-retry (old-entry)
1099 (let ((inside-locate-completion-entry t))
1100 (add-completion (completion-string old-entry)
1101 (completion-num-uses old-entry)
1102 (completion-last-use-time old-entry))
1103 (let* ((cmpl-entry (find-exact-completion (completion-string old-entry)))
1104 (pref-entry
1105 (if cmpl-entry
1106 (find-cmpl-prefix-entry
1107 (substring cmpl-db-downcase-string
1108 0 completion-prefix-min-length)))))
1109 (if (and cmpl-entry pref-entry)
1110 ;; try again
1111 (locate-completion-entry cmpl-entry pref-entry)
1112 ;; still losing
1113 (locate-completion-db-error)))))
1115 (defun locate-completion-db-error ()
1116 ;; recursive error: really scrod
1117 (error "Completion database corrupted. Try M-x clear-all-completions. Send bug report"))
1119 ;; WRITES
1120 (defun add-completion-to-tail-if-new (string)
1121 "If STRING is not in the database add it to appropriate prefix list.
1122 STRING is added to the end of the appropriate prefix list with
1123 num-uses = 0. The database is unchanged if it is there. STRING must be
1124 longer than `completion-prefix-min-length'.
1125 This must be very fast.
1126 Returns the completion entry."
1127 (or (find-exact-completion string)
1128 ;; not there
1129 (let (;; create an entry
1130 (entry (list (make-completion string)))
1131 ;; setup the prefix
1132 (prefix-entry (find-cmpl-prefix-entry
1133 (substring cmpl-db-downcase-string 0
1134 completion-prefix-min-length))))
1135 ;; The next two forms should happen as a unit (atomically) but
1136 ;; no fatal errors should result if that is not the case.
1137 (cond (prefix-entry
1138 ;; These two should be atomic, but nothing fatal will happen
1139 ;; if they're not.
1140 (setcdr (cmpl-prefix-entry-tail prefix-entry) entry)
1141 (set-cmpl-prefix-entry-tail prefix-entry entry))
1143 (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))))
1144 ;; set symbol
1145 (set cmpl-db-symbol (car entry)))))
1147 (defun add-completion-to-head (completion-string)
1148 "If COMPLETION-STRING is not in the database, add it to prefix list.
1149 We add COMPLETION-STRING to the head of the appropriate prefix list,
1150 or to the head of the list.
1151 COMPLETION-STRING must be longer than `completion-prefix-min-length'.
1152 Updates the saved string with the supplied string.
1153 This must be very fast.
1154 Returns the completion entry."
1155 (let ((cmpl--completion-string completion-string))
1156 ;; Handle pending acceptance
1157 (if completion-to-accept (accept-completion))
1158 ;; test if already in database
1159 (if (setq cmpl-db-entry (find-exact-completion completion-string))
1160 ;; found
1161 (let* ((prefix-entry (find-cmpl-prefix-entry
1162 (substring cmpl-db-downcase-string 0
1163 completion-prefix-min-length)))
1164 (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry))
1165 (cmpl-ptr (cdr splice-ptr)))
1166 ;; update entry
1167 (set-completion-string cmpl-db-entry completion-string)
1168 ;; move to head (if necessary)
1169 (cond (splice-ptr
1170 ;; These should all execute atomically but it is not fatal if
1171 ;; they don't.
1172 ;; splice it out
1173 (or (setcdr splice-ptr (cdr cmpl-ptr))
1174 ;; fix up tail if necessary
1175 (set-cmpl-prefix-entry-tail prefix-entry splice-ptr))
1176 ;; splice in at head
1177 (setcdr cmpl-ptr (cmpl-prefix-entry-head prefix-entry))
1178 (set-cmpl-prefix-entry-head prefix-entry cmpl-ptr)))
1179 cmpl-db-entry)
1180 ;; not there
1181 (let ( ;; create an entry
1182 (entry (list (make-completion completion-string)))
1183 ;; setup the prefix
1184 (prefix-entry (find-cmpl-prefix-entry
1185 (substring cmpl-db-downcase-string 0
1186 completion-prefix-min-length))))
1187 (cond (prefix-entry
1188 ;; Splice in at head
1189 (setcdr entry (cmpl-prefix-entry-head prefix-entry))
1190 (set-cmpl-prefix-entry-head prefix-entry entry))
1192 ;; Start new prefix entry
1193 (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))))
1194 ;; Add it to the symbol
1195 (set cmpl-db-symbol (car entry))))))
1197 (defun delete-completion (completion-string)
1198 "Delete the completion from the database.
1199 String must be longer than `completion-prefix-min-length'."
1200 ;; Handle pending acceptance
1201 (let ((cmpl--completion-string completion-string))
1202 (if completion-to-accept (accept-completion))
1203 (if (setq cmpl-db-entry (find-exact-completion completion-string))
1204 ;; found
1205 (let* ((prefix-entry (find-cmpl-prefix-entry
1206 (substring cmpl-db-downcase-string 0
1207 completion-prefix-min-length)))
1208 (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry)))
1209 ;; delete symbol reference
1210 (set cmpl-db-symbol nil)
1211 ;; remove from prefix list
1212 (cond (splice-ptr
1213 ;; not at head
1214 (or (setcdr splice-ptr (cdr (cdr splice-ptr)))
1215 ;; fix up tail if necessary
1216 (set-cmpl-prefix-entry-tail prefix-entry splice-ptr)))
1218 ;; at head
1219 (or (set-cmpl-prefix-entry-head
1220 prefix-entry (cdr (cmpl-prefix-entry-head prefix-entry)))
1221 ;; List is now empty
1222 (set cmpl-db-prefix-symbol nil)))))
1223 (error "Unknown completion `%s'" completion-string))))
1225 ;; Tests --
1226 ;; - Add and Find -
1227 ;; (add-completion-to-head "banana") --> ("banana" 0 nil 0)
1228 ;; (find-exact-completion "banana") --> ("banana" 0 nil 0)
1229 ;; (find-exact-completion "bana") --> nil
1230 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1231 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1232 ;; (add-completion-to-head "banish") --> ("banish" 0 nil 0)
1233 ;; (find-exact-completion "banish") --> ("banish" 0 nil 0)
1234 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banish" ...) ("banana" ...))
1235 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1236 ;; (add-completion-to-head "banana") --> ("banana" 0 nil 0)
1237 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
1238 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
1240 ;; - Deleting -
1241 ;; (add-completion-to-head "banner") --> ("banner" 0 nil 0)
1242 ;; (delete-completion "banner")
1243 ;; (find-exact-completion "banner") --> nil
1244 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
1245 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
1246 ;; (add-completion-to-head "banner") --> ("banner" 0 nil 0)
1247 ;; (delete-completion "banana")
1248 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banner" ...) ("banish" ...))
1249 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
1250 ;; (delete-completion "banner")
1251 ;; (delete-completion "banish")
1252 ;; (find-cmpl-prefix-entry "ban") --> nil
1253 ;; (delete-completion "banner") --> error
1255 ;; - Tail -
1256 ;; (add-completion-to-tail-if-new "banana") --> ("banana" 0 nil 0)
1257 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1258 ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1259 ;; (add-completion-to-tail-if-new "banish") --> ("banish" 0 nil 0)
1260 ;; (car (find-cmpl-prefix-entry "ban")) -->(("banana" ...) ("banish" ...))
1261 ;; (cdr (find-cmpl-prefix-entry "ban")) -->(("banish" ...))
1265 ;;---------------------------------------------------------------------------
1266 ;; Database Update :: Interface level routines
1267 ;;---------------------------------------------------------------------------
1269 ;; These lie on top of the database ref. functions but below the standard
1270 ;; user interface level
1273 (defun interactive-completion-string-reader (prompt)
1274 (let* ((default (symbol-under-or-before-point))
1275 (new-prompt
1276 (if default
1277 (format "%s (default %s): " prompt default)
1278 (format "%s: " prompt)))
1279 (read (completing-read new-prompt cmpl-obarray)))
1280 (if (zerop (length read)) (setq read (or default "")))
1281 (list read)))
1283 (defun check-completion-length (string)
1284 (if (< (length string) completion-min-length)
1285 (user-error "The string `%s' is too short to be saved as a completion"
1286 string)
1287 (list string)))
1289 (defun add-completion (string &optional num-uses last-use-time)
1290 "Add STRING to completion list, or move it to head of list.
1291 The completion is altered appropriately if NUM-USES and/or LAST-USE-TIME
1292 are specified."
1293 (interactive (interactive-completion-string-reader "Completion to add"))
1294 (check-completion-length string)
1295 (let* ((current-completion-source (if (called-interactively-p 'interactive)
1296 cmpl-source-interactive
1297 current-completion-source))
1298 (entry (add-completion-to-head string)))
1300 (if num-uses (set-completion-num-uses entry num-uses))
1301 (if last-use-time
1302 (set-completion-last-use-time entry last-use-time))))
1304 (defun add-permanent-completion (string)
1305 "Add STRING if it isn't already listed, and mark it permanent."
1306 (interactive
1307 (interactive-completion-string-reader "Completion to add permanently"))
1308 (let ((current-completion-source (if (called-interactively-p 'interactive)
1309 cmpl-source-interactive
1310 current-completion-source)))
1311 (add-completion string nil t)))
1313 (defun kill-completion (string)
1314 (interactive (interactive-completion-string-reader "Completion to kill"))
1315 (check-completion-length string)
1316 (delete-completion string))
1318 (defun accept-completion ()
1319 "Accept the pending completion in `completion-to-accept'.
1320 This bumps num-uses. Called by `add-completion-to-head' and
1321 `completion-search-reset'."
1322 (let ((string completion-to-accept)
1323 ;; if this is added afresh here, then it must be a cdabbrev
1324 (current-completion-source cmpl-source-cdabbrev)
1325 entry)
1326 (setq completion-to-accept nil)
1327 (setq entry (add-completion-to-head string))
1328 (set-completion-num-uses entry (1+ (completion-num-uses entry)))
1329 (setq cmpl-completions-accepted-p t)))
1331 (defun use-completion-under-point ()
1332 "Add the completion symbol underneath the point into the completion buffer."
1333 (let ((string (and enable-completion (symbol-under-point)))
1334 (current-completion-source cmpl-source-cursor-moves))
1335 (if string (add-completion-to-head string))))
1337 (defun use-completion-before-point ()
1338 "Add the completion symbol before point into the completion buffer."
1339 (let ((string (and enable-completion (symbol-before-point)))
1340 (current-completion-source cmpl-source-cursor-moves))
1341 (if string (add-completion-to-head string))))
1343 (defun use-completion-under-or-before-point ()
1344 "Add the completion symbol before point into the completion buffer."
1345 (let ((string (and enable-completion (symbol-under-or-before-point)))
1346 (current-completion-source cmpl-source-cursor-moves))
1347 (if string (add-completion-to-head string))))
1349 (defun use-completion-before-separator ()
1350 "Add the completion symbol before point into the completion buffer.
1351 Completions added this way will automatically be saved if
1352 `completion-on-separator-character' is non-nil."
1353 (let ((string (and enable-completion (symbol-before-point)))
1354 (current-completion-source cmpl-source-separator)
1355 entry)
1356 (cond (string
1357 (setq entry (add-completion-to-head string))
1358 (if (and completion-on-separator-character
1359 (zerop (completion-num-uses entry)))
1360 (progn
1361 (set-completion-num-uses entry 1)
1362 (setq cmpl-completions-accepted-p t)))))))
1364 ;; Tests --
1365 ;; - Add and Find -
1366 ;; (add-completion "banana" 5 10)
1367 ;; (find-exact-completion "banana") --> ("banana" 5 10 0)
1368 ;; (add-completion "banana" 6)
1369 ;; (find-exact-completion "banana") --> ("banana" 6 10 0)
1370 ;; (add-completion "banish")
1371 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banish" ...) ("banana" ...))
1373 ;; - Accepting -
1374 ;; (setq completion-to-accept "banana")
1375 ;; (accept-completion)
1376 ;; (find-exact-completion "banana") --> ("banana" 7 10)
1377 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
1378 ;; (setq completion-to-accept "banish")
1379 ;; (add-completion "banner")
1380 ;; (car (find-cmpl-prefix-entry "ban"))
1381 ;; --> (("banner" ...) ("banish" 1 ...) ("banana" 7 ...))
1383 ;; - Deleting -
1384 ;; (kill-completion "banish")
1385 ;; (car (find-cmpl-prefix-entry "ban")) --> (("banner" ...) ("banana" ...))
1388 ;;---------------------------------------------------------------------------
1389 ;; Searching the database
1390 ;;---------------------------------------------------------------------------
1391 ;; Functions outside this block must call completion-search-reset followed
1392 ;; by calls to completion-search-next or completion-search-peek
1395 ;; Status variables
1396 ;; Commented out to improve loading speed
1397 (defvar cmpl-test-string "")
1398 ;; "The current string used by completion-search-next."
1399 (defvar cmpl-test-regexp "")
1400 ;; "The current regexp used by completion-search-next.
1401 ;; (derived from cmpl-test-string)"
1402 (defvar cmpl-last-index 0)
1403 ;; "The last index that completion-search-next was called with."
1404 (defvar cmpl-cdabbrev-reset-p nil)
1405 ;; "Set to t when cdabbrevs have been reset."
1406 (defvar cmpl-next-possibilities nil)
1407 ;; "A pointer to the element BEFORE the next set of possible completions.
1408 ;; cadr of this is the cmpl-next-possibility"
1409 (defvar cmpl-starting-possibilities nil)
1410 ;; "The initial list of starting possibilities."
1411 (defvar cmpl-next-possibility nil)
1412 ;; "The cached next possibility."
1413 (defvar cmpl-tried-list nil)
1414 ;; "A downcased list of all the completions we have tried."
1417 (defun completion-search-reset (string)
1418 "Set up the for completion searching for STRING.
1419 STRING must be longer than `completion-prefix-min-length'."
1420 (if completion-to-accept (accept-completion))
1421 (setq cmpl-starting-possibilities
1422 (cmpl-prefix-entry-head
1423 (find-cmpl-prefix-entry
1424 (downcase (substring string 0 completion-prefix-min-length))))
1425 cmpl-test-string string
1426 cmpl-test-regexp (concat (regexp-quote string) "."))
1427 (completion-search-reset-1))
1429 (defun completion-search-reset-1 ()
1430 (setq cmpl-next-possibilities cmpl-starting-possibilities
1431 cmpl-next-possibility nil
1432 cmpl-cdabbrev-reset-p nil
1433 cmpl-last-index -1
1434 cmpl-tried-list nil))
1436 (defun completion-search-next (index)
1437 "Return the next completion entry.
1438 If INDEX is out of sequence, reset and start from the top.
1439 If there are no more entries, try cdabbrev and return only a string."
1440 (cond
1441 ((= index (setq cmpl-last-index (1+ cmpl-last-index)))
1442 (completion-search-peek t))
1443 ((< index 0)
1444 (completion-search-reset-1)
1445 (setq cmpl-last-index index)
1446 ;; reverse the possibilities list
1447 (setq cmpl-next-possibilities (reverse cmpl-starting-possibilities))
1448 ;; do a "normal" search
1449 (while (and (completion-search-peek nil)
1450 (< (setq index (1+ index)) 0))
1451 (setq cmpl-next-possibility nil))
1452 (cond ((not cmpl-next-possibilities))
1453 ;; If no more possibilities, leave it that way
1454 ((= -1 cmpl-last-index)
1455 ;; next completion is at index 0. reset next-possibility list
1456 ;; to start at beginning
1457 (setq cmpl-next-possibilities cmpl-starting-possibilities))
1459 ;; otherwise point to one before current
1460 (setq cmpl-next-possibilities
1461 (nthcdr (- (length cmpl-starting-possibilities)
1462 (length cmpl-next-possibilities))
1463 cmpl-starting-possibilities)))))
1465 ;; non-negative index, reset and search
1466 ;;(prin1 'reset)
1467 (completion-search-reset-1)
1468 (setq cmpl-last-index index)
1469 (while (and (completion-search-peek t)
1470 (not (< (setq index (1- index)) 0)))
1471 (setq cmpl-next-possibility nil))))
1472 (prog1
1473 cmpl-next-possibility
1474 (setq cmpl-next-possibility nil)))
1477 (defun completion-search-peek (use-cdabbrev)
1478 "Return the next completion entry without actually moving the pointers.
1479 Calling this again or calling `completion-search-next' results in the same
1480 string being returned. Depends on `case-fold-search'.
1481 If there are no more entries, try cdabbrev and then return only a string."
1482 (cond
1483 ;; return the cached value if we have it
1484 (cmpl-next-possibility)
1485 ((and cmpl-next-possibilities
1486 ;; still a few possibilities left
1487 (progn
1488 (while
1489 (and (not (eq 0 (string-match cmpl-test-regexp
1490 (completion-string (car cmpl-next-possibilities)))))
1491 (setq cmpl-next-possibilities (cdr cmpl-next-possibilities))))
1492 cmpl-next-possibilities))
1493 ;; successful match
1494 (setq cmpl-next-possibility (car cmpl-next-possibilities)
1495 cmpl-tried-list (cons (downcase (completion-string cmpl-next-possibility))
1496 cmpl-tried-list)
1497 cmpl-next-possibilities (cdr cmpl-next-possibilities))
1498 cmpl-next-possibility)
1499 (use-cdabbrev
1500 ;; unsuccessful, use cdabbrev
1501 (cond ((not cmpl-cdabbrev-reset-p)
1502 (reset-cdabbrev cmpl-test-string cmpl-tried-list)
1503 (setq cmpl-cdabbrev-reset-p t)))
1504 (setq cmpl-next-possibility (next-cdabbrev)))
1505 ;; Completely unsuccessful, return nil
1508 ;; Tests --
1509 ;; - Add and Find -
1510 ;; (add-completion "banana")
1511 ;; (completion-search-reset "ban")
1512 ;; (completion-search-next 0) --> "banana"
1514 ;; - Discrimination -
1515 ;; (add-completion "cumberland")
1516 ;; (add-completion "cumberbund")
1517 ;; cumbering
1518 ;; (completion-search-reset "cumb")
1519 ;; (completion-search-peek t) --> "cumberbund"
1520 ;; (completion-search-next 0) --> "cumberbund"
1521 ;; (completion-search-peek t) --> "cumberland"
1522 ;; (completion-search-next 1) --> "cumberland"
1523 ;; (completion-search-peek nil) --> nil
1524 ;; (completion-search-next 2) --> "cumbering" {cdabbrev}
1525 ;; (completion-search-next 3) --> nil or "cumming"{depends on context}
1526 ;; (completion-search-next 1) --> "cumberland"
1527 ;; (completion-search-peek t) --> "cumbering" {cdabbrev}
1529 ;; - Accepting -
1530 ;; (completion-search-next 1) --> "cumberland"
1531 ;; (setq completion-to-accept "cumberland")
1532 ;; (completion-search-reset "foo")
1533 ;; (completion-search-reset "cum")
1534 ;; (completion-search-next 0) --> "cumberland"
1536 ;; - Deleting -
1537 ;; (kill-completion "cumberland")
1538 ;; cummings
1539 ;; (completion-search-reset "cum")
1540 ;; (completion-search-next 0) --> "cumberbund"
1541 ;; (completion-search-next 1) --> "cummings"
1543 ;; - Ignoring Capitalization -
1544 ;; (completion-search-reset "CuMb")
1545 ;; (completion-search-next 0) --> "cumberbund"
1549 ;;-----------------------------------------------
1550 ;; COMPLETE
1551 ;;-----------------------------------------------
1553 (defun completion-mode ()
1554 "Toggle whether or not to add new words to the completion database."
1555 (interactive)
1556 (setq enable-completion (not enable-completion))
1557 (message "Completion mode is now %s." (if enable-completion "ON" "OFF")))
1559 (defvar cmpl-current-index 0)
1560 (defvar cmpl-original-string nil)
1561 (defvar cmpl-last-insert-location -1)
1562 (defvar cmpl-leave-point-at-start nil)
1564 (defun complete (&optional arg)
1565 "Fill out a completion of the word before point.
1566 Point is left at end. Consecutive calls rotate through all possibilities.
1567 Prefix args ::
1568 control-u :: leave the point at the beginning of the completion rather
1569 than at the end.
1570 a number :: rotate through the possible completions by that amount
1571 `-' :: same as -1 (insert previous completion)
1572 {See the comments at the top of `completion.el' for more info.}"
1573 (interactive "*p")
1574 ;;; Set up variables
1575 (cond ((eq last-command this-command)
1576 ;; Undo last one
1577 (delete-region cmpl-last-insert-location (point))
1578 ;; get next completion
1579 (setq cmpl-current-index (+ cmpl-current-index (or arg 1))))
1581 (if (not cmpl-initialized-p)
1582 (completion-initialize)) ;; make sure everything's loaded
1583 (cond ((consp current-prefix-arg) ;; control-u
1584 (setq arg 0)
1585 (setq cmpl-leave-point-at-start t))
1587 (setq cmpl-leave-point-at-start nil)))
1588 ;; get string
1589 (setq cmpl-original-string (symbol-before-point-for-complete))
1590 (cond ((not cmpl-original-string)
1591 (setq this-command 'failed-complete)
1592 (error "To complete, point must be after a symbol at least %d character long"
1593 completion-prefix-min-length)))
1594 ;; get index
1595 (setq cmpl-current-index (if current-prefix-arg arg 0))
1596 ;; reset database
1597 (completion-search-reset cmpl-original-string)
1598 ;; erase what we've got
1599 (delete-region cmpl-symbol-start cmpl-symbol-end)))
1601 ;; point is at the point to insert the new symbol
1602 ;; Get the next completion
1603 (let* ((print-status-p
1604 (and (>= baud-rate completion-prompt-speed-threshold)
1605 (not (window-minibuffer-p))))
1606 (insert-point (point))
1607 (entry (completion-search-next cmpl-current-index))
1608 string)
1609 ;; entry is either a completion entry or a string (if cdabbrev)
1611 ;; If found, insert
1612 (cond (entry
1613 ;; Setup for proper case
1614 (setq string (if (stringp entry)
1615 entry (completion-string entry)))
1616 (setq string (cmpl-merge-string-cases
1617 string cmpl-original-string))
1618 ;; insert
1619 (insert string)
1620 ;; accept it
1621 (setq completion-to-accept string)
1622 ;; fixup and cache point
1623 (cond (cmpl-leave-point-at-start
1624 (setq cmpl-last-insert-location (point))
1625 (goto-char insert-point))
1626 (t;; point at end,
1627 (setq cmpl-last-insert-location insert-point)))
1628 ;; Done ! cmpl-stat-complete-successful
1629 ;;display the next completion
1630 (cond
1631 ((and print-status-p
1632 ;; This updates the display and only prints if there
1633 ;; is no typeahead
1634 (sit-for 0)
1635 (setq entry
1636 (completion-search-peek
1637 completion-cdabbrev-prompt-flag)))
1638 (setq string (if (stringp entry)
1639 entry (completion-string entry)))
1640 (setq string (cmpl-merge-string-cases
1641 string cmpl-original-string))
1642 (message "Next completion: %s" string))))
1643 (t;; none found, insert old
1644 (insert cmpl-original-string)
1645 ;; Don't accept completions
1646 (setq completion-to-accept nil)
1647 ;; print message
1648 ;; This used to call cmpl19-sit-for, an undefined function.
1649 ;; I hope that sit-for does the right thing; I don't know -- rms.
1650 (if (and print-status-p (sit-for 0))
1651 (message "No %scompletions."
1652 (if (eq this-command last-command) "more " "")))
1653 ;; Pretend that we were never here
1654 (setq this-command 'failed-complete)))))
1656 ;;---------------------------------------------------------------------------
1657 ;; Parsing definitions from files into the database
1658 ;;---------------------------------------------------------------------------
1660 ;;-----------------------------------------------
1661 ;; Top Level functions ::
1662 ;;-----------------------------------------------
1664 ;; User interface
1665 (defun add-completions-from-file (file)
1666 "Parse possible completions from a FILE and add them to database."
1667 (interactive "fFile: ")
1668 (setq file (expand-file-name file))
1669 (let* ((buffer (get-file-buffer file))
1670 (buffer-already-there-p buffer))
1671 (if (not buffer-already-there-p)
1672 (let ((completions-merging-modes nil))
1673 (setq buffer (find-file-noselect file))))
1674 (unwind-protect
1675 (with-current-buffer buffer
1676 (add-completions-from-buffer))
1677 (if (not buffer-already-there-p)
1678 (kill-buffer buffer)))))
1680 (defun add-completions-from-buffer ()
1681 (interactive)
1682 (let ((current-completion-source cmpl-source-file-parsing))
1683 (cond ((memq major-mode '(emacs-lisp-mode lisp-mode))
1684 (add-completions-from-lisp-buffer))
1685 ((memq major-mode '(c-mode))
1686 (add-completions-from-c-buffer))
1688 (error "Cannot parse completions in %s buffers"
1689 major-mode)))))
1691 ;; Find file hook
1692 (defun completion-find-file-hook ()
1693 (cond (enable-completion
1694 (cond ((and (memq major-mode '(emacs-lisp-mode lisp-mode))
1695 (memq 'lisp completions-merging-modes))
1696 (add-completions-from-buffer))
1697 ((and (memq major-mode '(c-mode))
1698 (memq 'c completions-merging-modes))
1699 (add-completions-from-buffer))))))
1701 ;;-----------------------------------------------
1702 ;; Tags Table Completions
1703 ;;-----------------------------------------------
1705 (defun add-completions-from-tags-table ()
1706 ;; Inspired by eero@media-lab.media.mit.edu
1707 "Add completions from the current tags table."
1708 (interactive)
1709 (visit-tags-table-buffer) ;this will prompt if no tags-table
1710 (save-excursion
1711 (goto-char (point-min))
1712 (let (string)
1713 (condition-case nil
1714 (while t
1715 (search-forward "\177")
1716 (backward-char 3)
1717 (and (setq string (symbol-under-point))
1718 (add-completion-to-tail-if-new string))
1719 (forward-char 3))
1720 (search-failed)))))
1723 ;;-----------------------------------------------
1724 ;; Lisp File completion parsing
1725 ;;-----------------------------------------------
1726 ;; This merely looks for phrases beginning with (def.... or
1727 ;; (package:def ... and takes the next word.
1729 ;; We tried using forward-lines and explicit searches but the regexp technique
1730 ;; was faster. (About 100K characters per second)
1732 (defconst *lisp-def-regexp*
1733 "\n(\\(\\w*:\\)?def\\(\\w\\|\\s_\\)*\\s +(*"
1734 "A regexp that searches for Lisp definition form.")
1736 ;; Tests -
1737 ;; (and (string-match *lisp-def-regexp* "\n(defun foo") (match-end 0)) -> 8
1738 ;; (and (string-match *lisp-def-regexp* "\n(si:def foo") (match-end 0)) -> 9
1739 ;; (and (string-match *lisp-def-regexp* "\n(def-bar foo")(match-end 0)) -> 10
1740 ;; (and (string-match *lisp-def-regexp* "\n(defun (foo") (match-end 0)) -> 9
1742 ;; Parses all the definition names from a Lisp mode buffer and adds them to
1743 ;; the completion database.
1744 (defun add-completions-from-lisp-buffer ()
1745 ;;; Benchmarks
1746 ;;; Sun-3/280 - 1500 to 3000 lines of lisp code per second
1747 (let (string)
1748 (save-excursion
1749 (goto-char (point-min))
1750 (condition-case nil
1751 (while t
1752 (re-search-forward *lisp-def-regexp*)
1753 (and (setq string (symbol-under-point))
1754 (add-completion-to-tail-if-new string)))
1755 (search-failed)))))
1758 ;;-----------------------------------------------
1759 ;; C file completion parsing
1760 ;;-----------------------------------------------
1761 ;; C :
1762 ;; Looks for #define or [<storage class>] [<type>] <name>{,<name>}
1763 ;; or structure, array or pointer defs.
1764 ;; It gets most of the definition names.
1766 ;; As you might suspect by now, we use some symbol table hackery
1768 ;; Symbol separator chars (have whitespace syntax) --> , ; * = (
1769 ;; Opening char --> [ {
1770 ;; Closing char --> ] }
1771 ;; opening and closing must be skipped over
1772 ;; Whitespace chars (have symbol syntax)
1773 ;; Everything else has word syntax
1775 (defconst completion-c-def-syntax-table
1776 (let ((table (make-syntax-table))
1777 (whitespace-chars '(? ?\n ?\t ?\f ?\v ?\r))
1778 ;; unfortunately the ?( causes the parens to appear unbalanced
1779 (separator-chars '(?, ?* ?= ?\( ?\;))
1781 ;; default syntax is whitespace
1782 (setq i 0)
1783 (while (< i 256)
1784 (modify-syntax-entry i "w" table)
1785 (setq i (1+ i)))
1786 (dolist (char whitespace-chars)
1787 (modify-syntax-entry char "_" table))
1788 (dolist (char separator-chars)
1789 (modify-syntax-entry char " " table))
1790 (modify-syntax-entry ?\[ "(]" table)
1791 (modify-syntax-entry ?\{ "(}" table)
1792 (modify-syntax-entry ?\] ")[" table)
1793 (modify-syntax-entry ?\} "){" table)
1794 table))
1796 ;; Regexps
1797 (defconst *c-def-regexp*
1798 ;; This stops on lines with possible definitions
1799 "\n[_a-zA-Z#]"
1800 ;; This stops after the symbol to add.
1801 ;;"\n\\(#define\\s +.\\|\\(\\(\\w\\|\\s_\\)+\\b\\s *\\)+[(;,[*{=]\\)"
1802 ;; This stops before the symbol to add. {Test cases in parens. below}
1803 ;;"\n\\(\\(\\w\\|\\s_\\)+\\s *(\\|\\(\\(#define\\|auto\\|extern\\|register\\|static\\|int\\|long\\|short\\|unsigned\\|char\\|void\\|float\\|double\\|enum\\|struct\\|union\\|typedef\\)\\s +\\)+\\)"
1804 ;; this simple version picks up too much extraneous stuff
1805 ;; "\n\\(\\w\\|\\s_\\|#\\)\\B"
1806 "A regexp that searches for a definition form.")
1808 ;(defconst *c-cont-regexp*
1809 ; "\\(\\w\\|\\s_\\)+\\b\\s *\\({\\|\\(\\[[0-9\t ]*\\]\\s *\\)*,\\(*\\|\\s \\)*\\b\\)"
1810 ; "This regexp should be used in a looking-at to parse for lists of variables.")
1812 ;(defconst *c-struct-regexp*
1813 ; "\\(*\\|\\s \\)*\\b"
1814 ; "This regexp should be used to test whether a symbol follows a structure definition.")
1816 ;(defun test-c-def-regexp (regexp string)
1817 ; (and (eq 0 (string-match regexp string)) (match-end 0))
1820 ;; Tests -
1821 ;; (test-c-def-regexp *c-def-regexp* "\n#define foo") -> 10 (9)
1822 ;; (test-c-def-regexp *c-def-regexp* "\nfoo (x, y) {") -> 6 (6)
1823 ;; (test-c-def-regexp *c-def-regexp* "\nint foo (x, y)") -> 10 (5)
1824 ;; (test-c-def-regexp *c-def-regexp* "\n int foo (x, y)") -> nil
1825 ;; (test-c-def-regexp *c-cont-regexp* "oo, bar") -> 4
1826 ;; (test-c-def-regexp *c-cont-regexp* "oo, *bar") -> 5
1827 ;; (test-c-def-regexp *c-cont-regexp* "a [5][6], bar") -> 10
1828 ;; (test-c-def-regexp *c-cont-regexp* "oo(x,y)") -> nil
1829 ;; (test-c-def-regexp *c-cont-regexp* "a [6] ,\t bar") -> 9
1830 ;; (test-c-def-regexp *c-cont-regexp* "oo {trout =1} my_carp;") -> 14
1831 ;; (test-c-def-regexp *c-cont-regexp* "truct_p complex foon") -> nil
1833 ;; Parses all the definition names from a C mode buffer and adds them to the
1834 ;; completion database.
1835 (defun add-completions-from-c-buffer ()
1836 ;; Benchmark --
1837 ;; Sun 3/280-- 1250 lines/sec.
1839 (let (string next-point char)
1840 (save-excursion
1841 (goto-char (point-min))
1842 (catch 'finish-add-completions
1843 (with-syntax-table completion-c-def-syntax-table
1844 (while t
1845 ;; we loop here only when scan-sexps fails
1846 ;; (i.e. unbalance exps.)
1847 (condition-case e
1848 (while t
1849 (re-search-forward *c-def-regexp*)
1850 (cond
1851 ((= (preceding-char) ?#)
1852 ;; preprocessor macro, see if it's one we handle
1853 (cond ((looking-at "\\(define\\|ifdef\\)\\>")
1854 ;; skip forward over definition symbol
1855 ;; and add it to database
1856 (and (forward-word-strictly 2)
1857 (setq string (symbol-before-point))
1858 ;;(push string foo)
1859 (add-completion-to-tail-if-new string)))))
1861 ;; C definition
1862 (setq next-point (point))
1863 (while (and
1864 next-point
1865 ;; scan to next separator char.
1866 (setq next-point (scan-sexps next-point 1)))
1867 ;; position the point on the word we want to add
1868 (goto-char next-point)
1869 (while (= (setq char (following-char)) ?*)
1870 ;; handle pointer ref
1871 ;; move to next separator char.
1872 (goto-char
1873 (setq next-point (scan-sexps (point) 1))))
1874 (forward-word-strictly -1)
1875 ;; add to database
1876 (if (setq string (symbol-under-point))
1877 ;; (push string foo)
1878 (add-completion-to-tail-if-new string)
1879 ;; Local TMC hack (useful for parsing paris.h)
1880 (if (and (looking-at "_AP") ;; "ansi prototype"
1881 (progn
1882 (forward-word-strictly -1)
1883 (setq string
1884 (symbol-under-point))))
1885 (add-completion-to-tail-if-new string)))
1886 ;; go to next
1887 (goto-char next-point)
1888 ;; (push (format "%c" (following-char)) foo)
1889 (if (= (char-syntax char) ?\()
1890 ;; if on an opening delimiter, go to end
1891 (while (= (char-syntax char) ?\()
1892 (setq next-point (scan-sexps next-point 1)
1893 char (char-after next-point)))
1894 (or (= char ?,)
1895 ;; Current char is an end char.
1896 (setq next-point nil)))))))
1897 (search-failed ;;done
1898 (throw 'finish-add-completions t))
1899 (error
1900 ;; Check for failure in scan-sexps
1901 (if (member (nth 1 e)
1902 '("Containing expression ends prematurely"
1903 "Unbalanced parentheses"))
1904 ;; unbalanced paren., keep going
1905 ;;(ding)
1906 (forward-line 1)
1907 (message "Error parsing C buffer for completions--please send bug report")
1908 (throw 'finish-add-completions t))))))))))
1911 ;;---------------------------------------------------------------------------
1912 ;; Init files
1913 ;;---------------------------------------------------------------------------
1915 ;; The version of save-completions-to-file called at kill-emacs time.
1916 (defun kill-emacs-save-completions ()
1917 (if (and save-completions-flag enable-completion cmpl-initialized-p)
1918 (cond
1919 ((not cmpl-completions-accepted-p)
1920 (message "Completions database has not changed - not writing."))
1922 (save-completions-to-file)))))
1924 ;; There is no point bothering to change this again
1925 ;; unless the package changes so much that it matters
1926 ;; for people that have saved completions.
1927 (defconst completion-version "11")
1929 (defconst saved-cmpl-file-header
1930 ";;; Completion Initialization file.
1931 ;; Version = %s
1932 ;; Format is (<string> . <last-use-time>)
1933 ;; <string> is the completion
1934 ;; <last-use-time> is the time the completion was last used
1935 ;; If it is t, the completion will never be pruned from the file.
1936 ;; Otherwise it is in hours since origin.
1937 \n")
1939 (defun completion-backup-filename (filename)
1940 (concat filename ".BAK"))
1942 (defun save-completions-to-file (&optional filename)
1943 "Save completions in init file FILENAME.
1944 If file name is not specified, use `save-completions-file-name'."
1945 (interactive)
1946 (setq filename (expand-file-name (or filename save-completions-file-name)))
1947 (if (file-writable-p filename)
1948 (progn
1949 (if (not cmpl-initialized-p)
1950 (completion-initialize)) ;; make sure everything's loaded
1951 (message "Saving completions to file %s" filename)
1953 (let* ((delete-old-versions t)
1954 (kept-old-versions 0)
1955 (kept-new-versions completions-file-versions-kept)
1956 last-use-time
1957 (this-use-time (cmpl-hours-since-origin))
1958 (total-in-db 0)
1959 (total-perm 0)
1960 (total-saved 0)
1961 (backup-filename (completion-backup-filename filename)))
1963 (with-current-buffer (get-buffer-create " *completion-save-buffer*")
1964 (setq buffer-file-name filename)
1966 (if (not (verify-visited-file-modtime (current-buffer)))
1967 (progn
1968 ;; file has changed on disk. Bring us up-to-date
1969 (message "Completion file has changed. Merging. . .")
1970 (load-completions-from-file filename t)
1971 (message "Merging finished. Saving completions to file %s" filename)))
1973 ;; prepare the buffer to be modified
1974 (clear-visited-file-modtime)
1975 (erase-buffer)
1976 ;; (/ 1 0)
1977 (insert (format saved-cmpl-file-header completion-version))
1978 (dolist (completion (list-all-completions))
1979 (setq total-in-db (1+ total-in-db))
1980 (setq last-use-time (completion-last-use-time completion))
1981 ;; Update num uses and maybe write completion to a file
1982 (cond ((or;; Write to file if
1983 ;; permanent
1984 (and (eq last-use-time t)
1985 (setq total-perm (1+ total-perm)))
1986 ;; or if
1987 (if (> (completion-num-uses completion) 0)
1988 ;; it's been used
1989 (setq last-use-time this-use-time)
1990 ;; or it was saved before and
1991 (and last-use-time
1992 ;; save-completions-retention-time is nil
1993 (or (not save-completions-retention-time)
1994 ;; or time since last use is < ...retention-time*
1995 (< (- this-use-time last-use-time)
1996 save-completions-retention-time)))))
1997 ;; write to file
1998 (setq total-saved (1+ total-saved))
1999 (insert (prin1-to-string (cons (completion-string completion)
2000 last-use-time)) "\n"))))
2002 ;; write the buffer
2003 (condition-case nil
2004 (let ((file-exists-p (file-exists-p filename)))
2005 (if file-exists-p
2006 (progn
2007 ;; If file exists . . .
2008 ;; Save a backup(so GNU doesn't screw us when we're out of disk)
2009 ;; (GNU leaves a 0 length file if it gets a disk full error!)
2011 ;; If backup doesn't exit, Rename current to backup
2012 ;; {If backup exists the primary file is probably messed up}
2013 (or (file-exists-p backup-filename)
2014 (rename-file filename backup-filename))
2015 ;; Copy the backup back to the current name
2016 ;; (so versioning works)
2017 (copy-file backup-filename filename t)))
2018 ;; Save it
2019 (save-buffer)
2020 (if file-exists-p
2021 ;; If successful, remove backup
2022 (delete-file backup-filename)))
2023 (error
2024 (set-buffer-modified-p nil)
2025 (message "Couldn't save completion file `%s'" filename)))
2026 ;; Reset accepted-p flag
2027 (setq cmpl-completions-accepted-p nil) )))))
2029 ;;(defun auto-save-completions ()
2030 ;; (if (and save-completions-flag enable-completion cmpl-initialized-p
2031 ;; *completion-auto-save-period*
2032 ;; (> cmpl-emacs-idle-time *completion-auto-save-period*)
2033 ;; cmpl-completions-accepted-p)
2034 ;; (save-completions-to-file)))
2036 ;;(add-hook 'cmpl-emacs-idle-time-hooks 'auto-save-completions)
2038 (defun load-completions-from-file (&optional filename no-message-p)
2039 "Load a completion init file FILENAME.
2040 If file is not specified, then use `save-completions-file-name'."
2041 (interactive)
2042 (setq filename (expand-file-name (or filename save-completions-file-name)))
2043 (let* ((backup-filename (completion-backup-filename filename))
2044 (backup-readable-p (file-readable-p backup-filename)))
2045 (if backup-readable-p (setq filename backup-filename))
2046 (if (file-readable-p filename)
2047 (progn
2048 (if (not no-message-p)
2049 (message "Loading completions from %sfile %s . . ."
2050 (if backup-readable-p "backup " "") filename))
2051 (with-current-buffer (get-buffer-create " *completion-save-buffer*")
2052 (setq buffer-file-name filename)
2053 ;; prepare the buffer to be modified
2054 (clear-visited-file-modtime)
2055 (erase-buffer)
2057 (let ((insert-okay-p nil)
2058 (buffer (current-buffer))
2059 string entry last-use-time
2060 cmpl-entry cmpl-last-use-time
2061 (current-completion-source cmpl-source-init-file)
2062 (total-in-file 0) (total-perm 0))
2063 ;; insert the file into a buffer
2064 (condition-case nil
2065 (progn (insert-file-contents filename t)
2066 (setq insert-okay-p t))
2068 (file-error
2069 (message "File error trying to load completion file %s."
2070 filename)))
2071 ;; parse it
2072 (if insert-okay-p
2073 (progn
2074 (goto-char (point-min))
2076 (condition-case nil
2077 (while t
2078 (setq entry (read buffer))
2079 (setq total-in-file (1+ total-in-file))
2080 (cond
2081 ((and (consp entry)
2082 (stringp (setq string (car entry)))
2083 (cond
2084 ((eq (setq last-use-time (cdr entry)) 'T)
2085 ;; handle case sensitivity
2086 (setq total-perm (1+ total-perm))
2087 (setq last-use-time t))
2088 ((eq last-use-time t)
2089 (setq total-perm (1+ total-perm)))
2090 ((integerp last-use-time))))
2091 ;; Valid entry
2092 ;; add it in
2093 (setq cmpl-last-use-time
2094 (completion-last-use-time
2095 (setq cmpl-entry
2096 (add-completion-to-tail-if-new string))))
2097 (if (or (eq last-use-time t)
2098 (and (> last-use-time 1000);;backcompatibility
2099 (not (eq cmpl-last-use-time t))
2100 (or (not cmpl-last-use-time)
2101 ;; more recent
2102 (> last-use-time cmpl-last-use-time))))
2103 ;; update last-use-time
2104 (set-completion-last-use-time cmpl-entry last-use-time)))
2106 ;; Bad format
2107 (message "Error: invalid saved completion - %s"
2108 (prin1-to-string entry))
2109 ;; try to get back in sync
2110 (search-forward "\n("))))
2111 (search-failed
2112 (message "End of file while reading completions."))
2113 (end-of-file
2114 (if (= (point) (point-max))
2115 (if (not no-message-p)
2116 (message "Loading completions from file %s . . . Done."
2117 filename))
2118 (message "End of file while reading completions."))))))
2119 ))))))
2121 (defun completion-initialize ()
2122 "Load the default completions file.
2123 Also sets up so that exiting Emacs will automatically save the file."
2124 (interactive)
2125 (unless cmpl-initialized-p
2126 (load-completions-from-file)
2127 (setq cmpl-initialized-p t)))
2129 ;;-----------------------------------------------
2130 ;; Kill region patch
2131 ;;-----------------------------------------------
2133 (defun completion-kill-region (&optional beg end)
2134 "Kill between point and mark.
2135 The text is deleted but saved in the kill ring.
2136 The command \\[yank] can retrieve it from there.
2137 /(If you want to kill and then yank immediately, use \\[copy-region-as-kill].)
2139 This is the primitive for programs to kill text (as opposed to deleting it).
2140 Supply two arguments, character positions indicating the stretch of text
2141 to be killed.
2142 Any command that calls this function is a \"kill command\".
2143 If the previous command was also a kill command,
2144 the text killed this time appends to the text killed last time
2145 to make one entry in the kill ring.
2146 Patched to remove the most recent completion."
2147 (interactive "r")
2148 (cond ((eq last-command 'complete)
2149 (delete-region (point) cmpl-last-insert-location)
2150 (insert cmpl-original-string)
2151 (setq completion-to-accept nil))
2153 (kill-region beg end))))
2156 ;;-----------------------------------------------
2157 ;; Patches to self-insert-command.
2158 ;;-----------------------------------------------
2160 ;; Need 2 versions: generic separator chars. and space (to get auto fill
2161 ;; to work)
2163 ;; All common separators (eg. space "(" ")" """) characters go through a
2164 ;; function to add new words to the list of words to complete from.
2165 ;; If the character before this was an alpha-numeric then this adds the
2166 ;; symbol before point to the completion list (using ADD-COMPLETION).
2168 (defvar completion-separator-chars
2169 (append " !%^&()=`|{}[];\\'#,?"
2170 ;; We include period and colon even though they are symbol
2171 ;; chars because :
2172 ;; - in text we want to pick up the last word in a sentence.
2173 ;; - in C pointer refs. we want to pick up the first symbol
2174 ;; - it won't make a difference for lisp mode (package names
2175 ;; are short)
2176 ".:" nil))
2178 (defun completion--post-self-insert ()
2179 (when (memq last-command-event completion-separator-chars)
2180 (let ((after-pos (electric--after-char-pos)))
2181 (when after-pos
2182 (save-excursion
2183 (goto-char (1- after-pos))
2184 (use-completion-before-separator))))))
2186 ;;-----------------------------------------------
2187 ;; Wrapping Macro
2188 ;;-----------------------------------------------
2190 ;; Note that because of the way byte compiling works, none of
2191 ;; the functions defined with this macro get byte compiled.
2193 (defun completion-def-wrapper (function-name type)
2194 "Add a call to update the completion database before function execution.
2195 TYPE is the type of the wrapper to be added. Can be :before or :under."
2196 (put function-name 'completion-function
2197 (cdr (assq type
2198 '((:separator . use-completion-before-separator)
2199 (:before . use-completion-before-point)
2200 (:backward-under . use-completion-backward-under)
2201 (:backward . use-completion-backward)
2202 (:under . use-completion-under-point)
2203 (:under-or-before . use-completion-under-or-before-point)
2204 (:minibuffer-separator
2205 . use-completion-minibuffer-separator))))))
2207 (defun use-completion-minibuffer-separator ()
2208 (let ((completion-syntax-table completion-standard-syntax-table))
2209 (use-completion-before-separator)))
2211 (defun use-completion-backward-under ()
2212 (use-completion-under-point))
2214 (defun use-completion-backward ()
2215 nil)
2217 (defun completion-before-command ()
2218 (funcall (or (and (symbolp this-command)
2219 (get this-command 'completion-function))
2220 'use-completion-under-or-before-point)))
2222 ;; Lisp mode diffs.
2224 (defconst completion-lisp-syntax-table
2225 (let ((table (copy-syntax-table completion-standard-syntax-table))
2226 (symbol-chars '(?! ?& ?? ?= ?^)))
2227 (dolist (char symbol-chars)
2228 (modify-syntax-entry char "_" table))
2229 table))
2231 (declare-function cl-set-difference "cl-seq" (cl-list1 cl-list2 &rest cl-keys))
2233 (defun completion-lisp-mode-hook ()
2234 (require 'cl-lib)
2235 (setq completion-syntax-table completion-lisp-syntax-table)
2236 ;; Lisp Mode diffs
2237 (setq-local completion-separator-chars
2238 (cl-set-difference completion-separator-chars
2239 (append "!&%?=^" nil))))
2241 ;; C mode diffs.
2243 (defconst completion-c-syntax-table
2244 (let ((table (copy-syntax-table completion-standard-syntax-table))
2245 (separator-chars '(?+ ?* ?/ ?: ?%)))
2246 (dolist (char separator-chars)
2247 (modify-syntax-entry char " " table))
2248 table))
2250 (completion-def-wrapper 'electric-c-semi :separator)
2251 (defun completion-c-mode-hook ()
2252 (setq completion-syntax-table completion-c-syntax-table)
2253 (setq-local completion-separator-chars
2254 (append "+*/" completion-separator-chars)))
2256 ;; FORTRAN mode diffs. (these are defined when fortran is called)
2258 (defconst completion-fortran-syntax-table
2259 (let ((table (copy-syntax-table completion-standard-syntax-table))
2260 (separator-chars '(?+ ?- ?* ?/ ?:)))
2261 (dolist (char separator-chars)
2262 (modify-syntax-entry char " " table))
2263 table))
2265 (defun completion-setup-fortran-mode ()
2266 (setq completion-syntax-table completion-fortran-syntax-table)
2267 (setq-local completion-separator-chars
2268 (append "+-*/" completion-separator-chars)))
2270 ;; Enable completion mode.
2272 (defvar fortran-mode-hook)
2274 (defvar completion-saved-bindings nil)
2276 ;;;###autoload
2277 (define-minor-mode dynamic-completion-mode
2278 "Toggle dynamic word-completion on or off.
2279 With a prefix argument ARG, enable the mode if ARG is positive,
2280 and disable it otherwise. If called from Lisp, enable the mode
2281 if ARG is omitted or nil."
2282 :global t
2283 :group 'completion
2284 ;; This is always good, not specific to dynamic-completion-mode.
2285 (define-key function-key-map [C-return] [?\C-\r])
2287 (dolist (x `((find-file-hook . ,#'completion-find-file-hook)
2288 (pre-command-hook . ,#'completion-before-command)
2289 ;; Save completions when killing Emacs.
2290 (kill-emacs-hook . ,#'kill-emacs-save-completions)
2291 (post-self-insert-hook . ,#'completion--post-self-insert)
2293 ;; Install the appropriate mode tables.
2294 (lisp-mode-hook . ,#'completion-lisp-mode-hook)
2295 (c-mode-hook . ,#'completion-c-mode-hook)
2296 (fortran-mode-hook . ,#'completion-setup-fortran-mode)))
2297 (if dynamic-completion-mode
2298 (add-hook (car x) (cdr x))
2299 (remove-hook (car x) (cdr x))))
2301 ;; "Complete" Key Keybindings. We don't want to use a minor-mode
2302 ;; map because these have too high a priority. We could/should
2303 ;; probably change the interpretation of minor-mode-map-alist such
2304 ;; that a map has lower precedence if the symbol is not buffer-local.
2305 (while completion-saved-bindings
2306 (let ((binding (pop completion-saved-bindings)))
2307 (global-set-key (car binding) (cdr binding))))
2308 (when dynamic-completion-mode
2309 (dolist (binding
2310 '(("\M-\r" . complete)
2311 ([?\C-\r] . complete)
2313 ;; Tests -
2314 ;; (add-completion "cumberland")
2315 ;; (add-completion "cumberbund")
2316 ;; cum
2317 ;; Cumber
2318 ;; cumbering
2319 ;; cumb
2321 ;; Patches to standard keymaps insert completions
2322 ([remap kill-region] . completion-kill-region)))
2323 (push (cons (car binding) (lookup-key global-map (car binding)))
2324 completion-saved-bindings)
2325 (global-set-key (car binding) (cdr binding)))
2327 ;; Tests --
2328 ;; foobarbiz
2329 ;; foobar
2330 ;; fooquux
2331 ;; fooper
2333 (completion-initialize)))
2335 ;;-----------------------------------------------
2336 ;; End of line chars.
2337 ;;-----------------------------------------------
2338 (completion-def-wrapper 'newline :separator)
2339 (completion-def-wrapper 'newline-and-indent :separator)
2340 (completion-def-wrapper 'comint-send-input :separator)
2341 (completion-def-wrapper 'exit-minibuffer :minibuffer-separator)
2342 (completion-def-wrapper 'eval-print-last-sexp :separator)
2343 (completion-def-wrapper 'eval-last-sexp :separator)
2344 ;;(completion-def-wrapper 'minibuffer-complete-and-exit :minibuffer)
2346 ;;-----------------------------------------------
2347 ;; Cursor movement
2348 ;;-----------------------------------------------
2350 (completion-def-wrapper 'next-line :under-or-before)
2351 (completion-def-wrapper 'previous-line :under-or-before)
2352 (completion-def-wrapper 'beginning-of-buffer :under-or-before)
2353 (completion-def-wrapper 'end-of-buffer :under-or-before)
2354 (completion-def-wrapper 'beginning-of-line :under-or-before)
2355 (completion-def-wrapper 'end-of-line :under-or-before)
2356 (completion-def-wrapper 'forward-char :under-or-before)
2357 (completion-def-wrapper 'forward-word :under-or-before)
2358 (completion-def-wrapper 'forward-sexp :under-or-before)
2359 (completion-def-wrapper 'backward-char :backward-under)
2360 (completion-def-wrapper 'backward-word :backward-under)
2361 (completion-def-wrapper 'backward-sexp :backward-under)
2363 (completion-def-wrapper 'delete-backward-char :backward)
2364 (completion-def-wrapper 'delete-backward-char-untabify :backward)
2366 ;; Old name, non-namespace-clean.
2367 (defalias 'initialize-completions 'completion-initialize)
2369 (provide 'completion)
2371 ;;; completion.el ends here