1 ;;; completion.el --- dynamic word-completion code
2 ;; Copyright (C) 1990, 1993 Free Software Foundation, Inc.
6 ;; Author: Jim Salem <salem@think.com> and Brewster Kahle <brewster@think.com>
7 ;; of Thinking Machines Inc.
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to
23 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
27 ;;; What to put in .emacs
28 ;;;-----------------------
29 ;;; (load "completion")
30 ;;; (initialize-completions)
32 ;;;---------------------------------------------------------------------------
33 ;;; Documentation [Slightly out of date]
34 ;;;---------------------------------------------------------------------------
35 ;;; (also check the documentation string of the functions)
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
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
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 ;;; Loading this file (or calling initialize-completions) causes EMACS
84 ;;; to load a completions database for a saved completions file
85 ;;; (default: ~/.completions). When you exit, EMACS saves a copy of the
86 ;;; completions that you
87 ;;; often use. When you next start, EMACS loads in 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
106 ;;; a number :: rotate through the possible completions by that amount
107 ;;; `-' :: same as -1 (insert previous completion)
109 ;;; HOW THE DATABASE IS MAINTAINED
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
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]
142 ;;; The form `(initialize-completions)' initializes the completion system by
143 ;;; trying to load in the user's completions. After the first cal, 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.
179 ;;; Inserts a completion at point
181 ;;; initialize-completions
182 ;;; Loads the completions file and sets up so that exiting emacs will
185 ;;; save-completions-to-file &optional filename
186 ;;; load-completions-from-file &optional filename
188 ;;;-----------------------------------------------
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 ;;;-----------------------------------------------
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 Brewester 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 ;;;-----------------------------------------------
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 ;;;-----------------------------------------------
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)
276 ;;;---------------------------------------------------------------------------
277 ;;; User changeable parameters
278 ;;;---------------------------------------------------------------------------
280 (defvar enable-completion t
281 "*Non-nil means enable recording and saving of completions.
282 If nil, no new words added to the database or saved to the init file.")
284 (defvar save-completions-flag t
285 "*Non-nil means save most-used completions when exiting Emacs.
286 See also `saved-completions-retention-time'.")
288 (defvar save-completions-file-name "~/.completions"
289 "*The filename to save completions to.")
291 (defvar save-completions-retention-time 336
292 "*Discard a completion if unused for this many hours.
293 \(1 day = 24, 1 week = 168). If this is 0, non-permanent completions
294 will not be saved unless these are used. Default is two weeks.")
296 (defvar completion-on-separator-character nil
297 "*Non-nil means separator characters mark previous word as used.
298 This means the word will be saved as a completion.")
300 (defvar completions-file-versions-kept kept-new-versions
301 "*Number of versions to keep for the saved completions file.")
303 (defvar completion-prompt-speed-threshold 4800
304 "*Minimum output speed at which to display next potential completion.")
306 (defvar completion-cdabbrev-prompt-flag nil
307 "*If non-nil, the next completion prompt does a cdabbrev search.
308 This can be time consuming.")
310 (defvar completion-search-distance 15000
311 "*How far to search in the buffer when looking for completions.
312 In number of characters. If nil, search the whole buffer.")
314 (defvar completions-merging-modes '(lisp c)
315 "*List of modes {`c' or `lisp'} for automatic completions merging.
316 Definitions from visited files which have these modes
317 are automatically added to the completion database.")
319 ;;;(defvar *record-cmpl-statistics-p* nil
320 ;;; "*If non-nil, record completion statistics.")
322 ;;;(defvar *completion-auto-save-period* 1800
323 ;;; "*The period in seconds to wait for emacs to be idle before autosaving
324 ;;;the completions. Default is a 1/2 hour.")
326 (defconst completion-min-length nil ;; defined below in eval-when
327 "*The minimum length of a stored completion.
328 DON'T CHANGE WITHOUT RECOMPILING ! This is used by macros.")
330 (defconst completion-max-length nil ;; defined below in eval-when
331 "*The maximum length of a stored completion.
332 DON'T CHANGE WITHOUT RECOMPILING ! This is used by macros.")
334 (defconst completion-prefix-min-length nil ;; defined below in eval-when
335 "The minimum length of a completion search string.
336 DON'T CHANGE WITHOUT RECOMPILING ! This is used by macros.")
338 (defmacro eval-when-compile-load-eval (&rest body)
339 ;; eval everything before expanding
344 (defvar completion-gensym-counter 0)
345 (defun completion-gensym (&optional arg)
346 "Generate a new uninterned symbol.
347 The name is made by appending a number to PREFIX, default \"G\"."
348 (let ((prefix (if (stringp arg) arg "G"))
349 (num (if (integerp arg) arg
350 (prog1 completion-gensym-counter
351 (setq completion-gensym-counter (1+ completion-gensym-counter))))))
352 (make-symbol (format "%s%d" prefix num)))))
354 (defmacro completion-dolist (spec &rest body)
355 "(completion-dolist (VAR LIST [RESULT]) BODY...): loop over a list.
356 Evaluate BODY with VAR bound to each `car' from LIST, in turn.
357 Then evaluate RESULT to get return value, default nil."
358 (let ((temp (completion-gensym "--dolist-temp--")))
359 (append (list 'let (list (list temp (nth 1 spec)) (car spec))
360 (append (list 'while temp
361 (list 'setq (car spec) (list 'car temp)))
362 body (list (list 'setq temp
365 (cons (list 'setq (car spec) nil) (cdr (cdr spec)))
368 (defun completion-eval-when ()
369 (eval-when-compile-load-eval
370 ;; These vars. are defined at both compile and load time.
371 (setq completion-min-length 6)
372 (setq completion-max-length 200)
373 (setq completion-prefix-min-length 3)))
375 (completion-eval-when)
377 ;;;---------------------------------------------------------------------------
378 ;;; Internal Variables
379 ;;;---------------------------------------------------------------------------
381 (defvar cmpl-initialized-p nil
382 "Set to t when the completion system is initialized.
383 Indicates that the old completion file has been read in.")
385 (defvar cmpl-completions-accepted-p nil
386 "Set to t as soon as the first completion has been accepted.
387 Used to decide whether to save completions.")
389 (defvar cmpl-preceding-syntax)
391 ;;;---------------------------------------------------------------------------
393 ;;;---------------------------------------------------------------------------
395 ;;;-----------------------------------------------
397 ;;;-----------------------------------------------
399 (defun minibuffer-window-selected-p ()
400 "True iff the current window is the minibuffer."
401 (window-minibuffer-p (selected-window)))
403 ;; This used to be `(eval form)'. Eval FORM at run time now.
404 (defmacro cmpl-read-time-eval (form)
407 ;;;-----------------------------------------------
408 ;;; String case coercion
409 ;;;-----------------------------------------------
411 (defun cmpl-string-case-type (string)
412 "Returns :capitalized, :up, :down, :mixed, or :neither."
413 (let ((case-fold-search nil))
414 (cond ((string-match "[a-z]" string)
415 (cond ((string-match "[A-Z]" string)
416 (cond ((and (> (length string) 1)
417 (null (string-match "[A-Z]" string 1)))
423 (cond ((string-match "[A-Z]" string)
429 ;;; (cmpl-string-case-type "123ABCDEF456") --> :up
430 ;;; (cmpl-string-case-type "123abcdef456") --> :down
431 ;;; (cmpl-string-case-type "123aBcDeF456") --> :mixed
432 ;;; (cmpl-string-case-type "123456") --> :neither
433 ;;; (cmpl-string-case-type "Abcde123") --> :capitalized
435 (defun cmpl-coerce-string-case (string case-type)
436 (cond ((eq case-type ':down) (downcase string))
437 ((eq case-type ':up) (upcase string))
438 ((eq case-type ':capitalized)
439 (setq string (downcase string))
440 (aset string 0 (logand ?\337 (aref string 0)))
445 (defun cmpl-merge-string-cases (string-to-coerce given-string)
446 (let ((string-case-type (cmpl-string-case-type string-to-coerce))
448 (cond ((memq string-case-type '(:down :up :capitalized))
449 ;; Found string is in a standard case. Coerce to a type based on
451 (cmpl-coerce-string-case string-to-coerce
452 (cmpl-string-case-type given-string))
455 ;; If the found string is in some unusual case, just insert it
461 ;;; (cmpl-merge-string-cases "AbCdEf456" "abc") --> AbCdEf456
462 ;;; (cmpl-merge-string-cases "abcdef456" "ABC") --> ABCDEF456
463 ;;; (cmpl-merge-string-cases "ABCDEF456" "Abc") --> Abcdef456
464 ;;; (cmpl-merge-string-cases "ABCDEF456" "abc") --> abcdef456
467 (defun cmpl-hours-since-origin ()
468 (let ((time (current-time)))
470 (+ (* (/ (car time) 3600.0) (lsh 1 16))
471 (/ (nth 2 time) 3600.0)))))
473 ;;;---------------------------------------------------------------------------
474 ;;; "Symbol" parsing functions
475 ;;;---------------------------------------------------------------------------
476 ;;; The functions symbol-before-point, symbol-under-point, etc. quickly return
477 ;;; an appropriate symbol string. The strategy is to temporarily change
478 ;;; the syntax table to enable fast symbol searching. There are three classes
479 ;;; of syntax in these "symbol" syntax tables ::
481 ;;; syntax (?_) - "symbol" chars (e.g. alphanumerics)
482 ;;; syntax (?w) - symbol chars to ignore at end of words (e.g. period).
483 ;;; syntax (? ) - everything else
485 ;;; Thus by judicious use of scan-sexps and forward-word, we can get
486 ;;; the word we want relatively fast and without consing.
488 ;;; Why do we need a separate category for "symbol chars to ignore at ends" ?
489 ;;; For example, in LISP we want starting :'s trimmed
490 ;;; so keyword argument specifiers also define the keyword completion. And,
491 ;;; for example, in C we want `.' appearing in a structure ref. to
492 ;;; be kept intact in order to store the whole structure ref.; however, if
493 ;;; it appears at the end of a symbol it should be discarded because it is
494 ;;; probably used as a period.
496 ;;; Here is the default completion syntax ::
497 ;;; Symbol chars :: A-Z a-z 0-9 @ / \ * + ~ $ < > %
498 ;;; Symbol chars to ignore at ends :: _ : . -
499 ;;; Separator chars. :: <tab> <space> ! ^ & ( ) = ` | { } [ ] ; " ' #
500 ;;; , ? <Everything else>
502 ;;; Mode specific differences and notes ::
504 ;;; Symbol chars :: ! & ? = ^
507 ;;; Separator chars :: + * / : %
508 ;;; A note on the hyphen (`-'). Perhaps the hyphen should also be a separator
509 ;;; char., however, we wanted to have completion symbols include pointer
510 ;;; references. For example, "foo->bar" is a symbol as far as completion is
514 ;;; Separator chars :: + - * / :
516 ;;; Pathname diffs ->
517 ;;; Symbol chars :: .
518 ;;; Of course there is no pathname "mode" and in fact we have not implemented
519 ;;; this table. However, if there was such a mode, this is what it would look
522 ;;;-----------------------------------------------
523 ;;; Table definitions
524 ;;;-----------------------------------------------
526 (defun cmpl-make-standard-completion-syntax-table ()
527 (let ((table (make-vector 256 0)) ;; default syntax is whitespace
532 (modify-syntax-entry (+ ?a i) "_" table)
533 (modify-syntax-entry (+ ?A i) "_" table)
538 (modify-syntax-entry (+ ?0 i) "_" table)
541 (let ((symbol-chars '(?@ ?/ ?\\ ?* ?+ ?~ ?$ ?< ?> ?%))
542 (symbol-chars-ignore '(?_ ?- ?: ?.))
544 (completion-dolist (char symbol-chars)
545 (modify-syntax-entry char "_" table))
546 (completion-dolist (char symbol-chars-ignore)
547 (modify-syntax-entry char "w" table)
552 (defconst cmpl-standard-syntax-table (cmpl-make-standard-completion-syntax-table))
554 (defun cmpl-make-lisp-completion-syntax-table ()
555 (let ((table (copy-syntax-table cmpl-standard-syntax-table))
556 (symbol-chars '(?! ?& ?? ?= ?^))
558 (completion-dolist (char symbol-chars)
559 (modify-syntax-entry char "_" table))
562 (defun cmpl-make-c-completion-syntax-table ()
563 (let ((table (copy-syntax-table cmpl-standard-syntax-table))
564 (separator-chars '(?+ ?* ?/ ?: ?%))
566 (completion-dolist (char separator-chars)
567 (modify-syntax-entry char " " table))
570 (defun cmpl-make-fortran-completion-syntax-table ()
571 (let ((table (copy-syntax-table cmpl-standard-syntax-table))
572 (separator-chars '(?+ ?- ?* ?/ ?:))
574 (completion-dolist (char separator-chars)
575 (modify-syntax-entry char " " table))
578 (defconst cmpl-lisp-syntax-table (cmpl-make-lisp-completion-syntax-table))
579 (defconst cmpl-c-syntax-table (cmpl-make-c-completion-syntax-table))
580 (defconst cmpl-fortran-syntax-table (cmpl-make-fortran-completion-syntax-table))
582 (defvar cmpl-syntax-table cmpl-standard-syntax-table
583 "This variable holds the current completion syntax table.")
584 (make-variable-buffer-local 'cmpl-syntax-table)
586 ;;;-----------------------------------------------
587 ;;; Installing the appropriate mode tables
588 ;;;-----------------------------------------------
590 (add-hook 'lisp-mode-hook
592 (setq cmpl-syntax-table cmpl-lisp-syntax-table)))
594 (add-hook 'c-mode-hook
596 (setq cmpl-syntax-table cmpl-c-syntax-table)))
598 (add-hook 'fortran-mode-hook
600 (setq cmpl-syntax-table cmpl-fortran-syntax-table)
601 (completion-setup-fortran-mode)))
603 ;;;-----------------------------------------------
605 ;;;-----------------------------------------------
606 (defvar cmpl-symbol-start nil
607 "Holds first character of symbol, after any completion symbol function.")
608 (defvar cmpl-symbol-end nil
609 "Holds last character of symbol, after any completion symbol function.")
610 ;;; These are temp. vars. we use to avoid using let.
611 ;;; Why ? Small speed improvement.
612 (defvar cmpl-saved-syntax nil)
613 (defvar cmpl-saved-point nil)
615 (defun symbol-under-point ()
616 "Returns the symbol that the point is currently on.
617 But only if it is longer than `completion-min-length'."
618 (setq cmpl-saved-syntax (syntax-table))
619 (set-syntax-table cmpl-syntax-table)
621 ;; Cursor is on following-char and after preceding-char
622 ((memq (char-syntax (following-char)) '(?w ?_))
623 (setq cmpl-saved-point (point)
624 cmpl-symbol-start (scan-sexps (1+ cmpl-saved-point) -1)
625 cmpl-symbol-end (scan-sexps cmpl-saved-point 1))
626 ;; remove chars to ignore at the start
627 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
628 (goto-char cmpl-symbol-start)
630 (setq cmpl-symbol-start (point))
631 (goto-char cmpl-saved-point)
633 ;; remove chars to ignore at the end
634 (cond ((= (char-syntax (char-after (1- cmpl-symbol-end))) ?w)
635 (goto-char cmpl-symbol-end)
637 (setq cmpl-symbol-end (point))
638 (goto-char cmpl-saved-point)
641 (set-syntax-table cmpl-saved-syntax)
642 ;; Return completion if the length is reasonable
643 (if (and (<= (cmpl-read-time-eval completion-min-length)
644 (- cmpl-symbol-end cmpl-symbol-start))
645 (<= (- cmpl-symbol-end cmpl-symbol-start)
646 (cmpl-read-time-eval completion-max-length)))
647 (buffer-substring cmpl-symbol-start cmpl-symbol-end))
650 ;; restore table if no symbol
651 (set-syntax-table cmpl-saved-syntax)
655 ;;; tests for symbol-under-point
656 ;;; `^' indicates cursor pos. where value is returned
658 ;;; ^^^^^^^^^^^^^^^^ --> simple-word-test
659 ;;; _harder_word_test_
660 ;;; ^^^^^^^^^^^^^^^^^^ --> harder_word_test
663 ;;; /foo/bar/quux.hello
664 ;;; ^^^^^^^^^^^^^^^^^^^ --> /foo/bar/quux.hello
667 (defun symbol-before-point ()
668 "Returns a string of the symbol immediately before point.
669 Returns nil if there isn't one longer than `completion-min-length'."
670 ;; This is called when a word separator is typed so it must be FAST !
671 (setq cmpl-saved-syntax (syntax-table))
672 (set-syntax-table cmpl-syntax-table)
673 ;; Cursor is on following-char and after preceding-char
674 (cond ((= (setq cmpl-preceding-syntax (char-syntax (preceding-char))) ?_)
675 ;; No chars. to ignore at end
676 (setq cmpl-symbol-end (point)
677 cmpl-symbol-start (scan-sexps (1+ cmpl-symbol-end) -1)
679 ;; remove chars to ignore at the start
680 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
681 (goto-char cmpl-symbol-start)
683 (setq cmpl-symbol-start (point))
684 (goto-char cmpl-symbol-end)
687 (set-syntax-table cmpl-saved-syntax)
688 ;; return value if long enough
689 (if (>= cmpl-symbol-end
691 (cmpl-read-time-eval completion-min-length)))
692 (buffer-substring cmpl-symbol-start cmpl-symbol-end))
694 ((= cmpl-preceding-syntax ?w)
695 ;; chars to ignore at end
696 (setq cmpl-saved-point (point)
697 cmpl-symbol-start (scan-sexps (1+ cmpl-saved-point) -1))
698 ;; take off chars. from end
700 (setq cmpl-symbol-end (point))
701 ;; remove chars to ignore at the start
702 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
703 (goto-char cmpl-symbol-start)
705 (setq cmpl-symbol-start (point))
708 (goto-char cmpl-saved-point)
709 (set-syntax-table cmpl-saved-syntax)
710 ;; Return completion if the length is reasonable
711 (if (and (<= (cmpl-read-time-eval completion-min-length)
712 (- cmpl-symbol-end cmpl-symbol-start))
713 (<= (- cmpl-symbol-end cmpl-symbol-start)
714 (cmpl-read-time-eval completion-max-length)))
715 (buffer-substring cmpl-symbol-start cmpl-symbol-end))
718 ;; restore table if no symbol
719 (set-syntax-table cmpl-saved-syntax)
723 ;;; tests for symbol-before-point
724 ;;; `^' indicates cursor pos. where value is returned
729 ;;; ^ --> simple-word-test
730 ;;; _harder_word_test_
731 ;;; ^ --> harder_word_test
732 ;;; ^ --> harder_word_test
737 (defun symbol-under-or-before-point ()
738 ;;; This could be made slightly faster but it is better to avoid
739 ;;; copying all the code.
740 ;;; However, it is only used by the completion string prompter.
741 ;;; If it comes into common use, it could be rewritten.
742 (setq cmpl-saved-syntax (syntax-table))
743 (set-syntax-table cmpl-syntax-table)
744 (cond ((memq (char-syntax (following-char)) '(?w ?_))
745 (set-syntax-table cmpl-saved-syntax)
746 (symbol-under-point))
748 (set-syntax-table cmpl-saved-syntax)
749 (symbol-before-point))
753 (defun symbol-before-point-for-complete ()
754 ;; "Returns a string of the symbol immediately before point
755 ;; or nil if there isn't one. Like symbol-before-point but doesn't trim the
757 ;; Cursor is on following-char and after preceding-char
758 (setq cmpl-saved-syntax (syntax-table))
759 (set-syntax-table cmpl-syntax-table)
760 (cond ((memq (setq cmpl-preceding-syntax (char-syntax (preceding-char)))
762 (setq cmpl-symbol-end (point)
763 cmpl-symbol-start (scan-sexps (1+ cmpl-symbol-end) -1)
765 ;; remove chars to ignore at the start
766 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
767 (goto-char cmpl-symbol-start)
769 (setq cmpl-symbol-start (point))
770 (goto-char cmpl-symbol-end)
773 (set-syntax-table cmpl-saved-syntax)
774 ;; Return completion if the length is reasonable
775 (if (and (<= (cmpl-read-time-eval
776 completion-prefix-min-length)
777 (- cmpl-symbol-end cmpl-symbol-start))
778 (<= (- cmpl-symbol-end cmpl-symbol-start)
779 (cmpl-read-time-eval completion-max-length)))
780 (buffer-substring cmpl-symbol-start cmpl-symbol-end))
783 ;; restore table if no symbol
784 (set-syntax-table cmpl-saved-syntax)
788 ;;; tests for symbol-before-point-for-complete
789 ;;; `^' indicates cursor pos. where value is returned
794 ;;; ^ --> simple-word-test
795 ;;; _harder_word_test_
796 ;;; ^ --> harder_word_test
797 ;;; ^ --> harder_word_test_
804 ;;;---------------------------------------------------------------------------
805 ;;; Statistics Recording
806 ;;;---------------------------------------------------------------------------
808 ;;; Note that the guts of this has been turned off. The guts
809 ;;; are in completion-stats.el.
811 ;;;-----------------------------------------------
812 ;;; Conditionalizing code on *record-cmpl-statistics-p*
813 ;;;-----------------------------------------------
814 ;;; All statistics code outside this block should use this
815 (defmacro cmpl-statistics-block (&rest body))
816 ;;; "Only executes body if we are recording statistics."
818 ;;; (list* '*record-cmpl-statistics-p* body)
821 ;;;-----------------------------------------------
822 ;;; Completion Sources
823 ;;;-----------------------------------------------
826 (defconst cmpl-source-unknown 0)
827 (defconst cmpl-source-init-file 1)
828 (defconst cmpl-source-file-parsing 2)
829 (defconst cmpl-source-separator 3)
830 (defconst cmpl-source-cursor-moves 4)
831 (defconst cmpl-source-interactive 5)
832 (defconst cmpl-source-cdabbrev 6)
833 (defconst num-cmpl-sources 7)
834 (defvar current-completion-source cmpl-source-unknown)
838 ;;;---------------------------------------------------------------------------
839 ;;; Completion Method #2: dabbrev-expand style
840 ;;;---------------------------------------------------------------------------
842 ;;; This method is used if there are no useful stored completions. It is
843 ;;; based on dabbrev-expand with these differences :
844 ;;; 1) Faster (we don't use regexps)
845 ;;; 2) case coercion handled correctly
846 ;;; This is called cdabbrev to differentiate it.
847 ;;; We simply search backwards through the file looking for words which
848 ;;; start with the same letters we are trying to complete.
851 (defvar cdabbrev-completions-tried nil)
852 ;;; "A list of all the cdabbrev completions since the last reset.")
854 (defvar cdabbrev-current-point 0)
855 ;;; "The current point position the cdabbrev search is at.")
857 (defvar cdabbrev-current-window nil)
858 ;;; "The current window we are looking for cdabbrevs in. T if looking in
859 ;;; (other-buffer), NIL if no more cdabbrevs.")
861 (defvar cdabbrev-wrapped-p nil)
862 ;;; "T if the cdabbrev search has wrapped around the file.")
864 (defvar cdabbrev-abbrev-string "")
865 (defvar cdabbrev-start-point 0)
866 (defvar cdabbrev-stop-point)
868 ;;; Test strings for cdabbrev
869 ;;; cdat-upcase ;;same namestring
871 ;;; cdat2 ;;too short
872 ;;; cdat-1-2-3-4 ;;ok
873 ;;; a-cdat-1 ;;doesn't start correctly
877 (defun reset-cdabbrev (abbrev-string &optional initial-completions-tried)
878 "Resets the cdabbrev search to search for abbrev-string.
879 INITIAL-COMPLETIONS-TRIED is a list of downcased strings to ignore
881 (setq cdabbrev-abbrev-string abbrev-string
882 cdabbrev-completions-tried
883 (cons (downcase abbrev-string) initial-completions-tried)
885 (reset-cdabbrev-window t)
888 (defun set-cdabbrev-buffer ()
889 ;; cdabbrev-current-window must not be NIL
890 (set-buffer (if (eq cdabbrev-current-window t)
892 (window-buffer cdabbrev-current-window)))
896 (defun reset-cdabbrev-window (&optional initializep)
897 "Resets the cdabbrev search to search for abbrev-string."
900 (setq cdabbrev-current-window (selected-window))
902 ((eq cdabbrev-current-window t)
903 ;; Everything has failed
904 (setq cdabbrev-current-window nil))
905 (cdabbrev-current-window
906 (setq cdabbrev-current-window (next-window cdabbrev-current-window))
907 (if (eq cdabbrev-current-window (selected-window))
908 ;; No more windows, try other buffer.
909 (setq cdabbrev-current-window t)))
911 (if cdabbrev-current-window
913 (set-cdabbrev-buffer)
914 (setq cdabbrev-current-point (point)
915 cdabbrev-start-point cdabbrev-current-point
917 (if completion-search-distance
919 (- cdabbrev-start-point completion-search-distance))
921 cdabbrev-wrapped-p nil)
924 (defun next-cdabbrev ()
925 "Return the next possible cdabbrev expansion or nil if there isn't one.
926 `reset-cdabbrev' must've been called already.
927 This is sensitive to `case-fold-search'."
928 ;; note that case-fold-search affects the behavior of this function
929 ;; Bug: won't pick up an expansion that starts at the top of buffer
930 (if cdabbrev-current-window
934 downcase-expansion tried-list syntax saved-point-2)
938 ;; Switch to current completion buffer
939 (set-cdabbrev-buffer)
940 ;; Save current buffer state
941 (setq saved-point (point)
942 saved-syntax (syntax-table))
943 ;; Restore completion state
944 (set-syntax-table cmpl-syntax-table)
945 (goto-char cdabbrev-current-point)
946 ;; Loop looking for completions
948 ;; This code returns t if it should loop again
950 (;; search for the string
951 (search-backward cdabbrev-abbrev-string cdabbrev-stop-point t)
952 ;; return nil if the completion is valid
955 ;; does it start with a separator char ?
956 (or (= (setq syntax (char-syntax (preceding-char))) ? )
958 ;; symbol char to ignore at end. Are we at end ?
960 (setq saved-point-2 (point))
963 (= (char-syntax (preceding-char)) ? )
964 (goto-char saved-point-2)
966 ;; is the symbol long enough ?
967 (setq expansion (symbol-under-point))
968 ;; have we not tried this one before
970 ;; See if we've already used it
971 (setq tried-list cdabbrev-completions-tried
972 downcase-expansion (downcase expansion))
973 (while (and tried-list
974 (not (string-equal downcase-expansion
976 ;; Already tried, don't choose this one
977 (setq tried-list (cdr tried-list))
979 ;; at this point tried-list will be nil if this
980 ;; expansion has not yet been tried
987 ;; If already wrapped, then we've failed completely
991 (goto-char (setq cdabbrev-current-point
992 (if completion-search-distance
993 (min (point-max) (+ cdabbrev-start-point completion-search-distance))
996 (setq cdabbrev-wrapped-p t))
1001 (setq cdabbrev-completions-tried
1002 (cons downcase-expansion cdabbrev-completions-tried)
1003 cdabbrev-current-point (point))))
1005 (set-syntax-table saved-syntax)
1006 (goto-char saved-point)
1008 ;; If no expansion, go to next window
1010 (t (reset-cdabbrev-window)
1011 (next-cdabbrev))))))
1013 ;;; The following must be eval'd in the minibuffer ::
1014 ;;; (reset-cdabbrev "cdat")
1015 ;;; (next-cdabbrev) --> "cdat-simple"
1016 ;;; (next-cdabbrev) --> "cdat-1-2-3-4"
1017 ;;; (next-cdabbrev) --> "CDAT-UPCASE"
1018 ;;; (next-cdabbrev) --> "cdat-wrapping"
1019 ;;; (next-cdabbrev) --> "cdat_start_sym"
1020 ;;; (next-cdabbrev) --> nil
1021 ;;; (next-cdabbrev) --> nil
1022 ;;; (next-cdabbrev) --> nil
1028 ;;;---------------------------------------------------------------------------
1029 ;;; Completion Database
1030 ;;;---------------------------------------------------------------------------
1032 ;;; We use two storage modes for the two search types ::
1033 ;;; 1) Prefix {cmpl-prefix-obarray} for looking up possible completions
1034 ;;; Used by search-completion-next
1035 ;;; the value of the symbol is nil or a cons of head and tail pointers
1036 ;;; 2) Interning {cmpl-obarray} to see if it's in the database
1037 ;;; Used by find-exact-completion, completion-in-database-p
1038 ;;; The value of the symbol is the completion entry
1040 ;;; bad things may happen if this length is changed due to the way
1041 ;;; GNU implements obarrays
1042 (defconst cmpl-obarray-length 511)
1044 (defvar cmpl-prefix-obarray (make-vector cmpl-obarray-length 0)
1045 "An obarray used to store the downcased completion prefixes.
1046 Each symbol is bound to a list of completion entries.")
1048 (defvar cmpl-obarray (make-vector cmpl-obarray-length 0)
1049 "An obarray used to store the downcased completions.
1050 Each symbol is bound to a single completion entry.")
1052 ;;;-----------------------------------------------
1053 ;;; Completion Entry Structure Definition
1054 ;;;-----------------------------------------------
1056 ;;; A completion entry is a LIST of string, prefix-symbol num-uses, and
1057 ;;; last-use-time (the time the completion was last used)
1058 ;;; last-use-time is T if the string should be kept permanently
1059 ;;; num-uses is incremented everytime the completion is used.
1061 ;;; We chose lists because (car foo) is faster than (aref foo 0) and the
1062 ;;; creation time is about the same.
1066 (defmacro completion-string (completion-entry)
1067 (list 'car completion-entry))
1069 (defmacro completion-num-uses (completion-entry)
1070 ;; "The number of times it has used. Used to decide whether to save
1072 (list 'car (list 'cdr completion-entry)))
1074 (defmacro completion-last-use-time (completion-entry)
1075 ;; "The time it was last used. In hours since origin. Used to decide
1076 ;; whether to save it. T if one should always save it."
1077 (list 'nth 2 completion-entry))
1079 (defmacro completion-source (completion-entry)
1080 (list 'nth 3 completion-entry))
1083 (defmacro set-completion-string (completion-entry string)
1084 (list 'setcar completion-entry string))
1086 (defmacro set-completion-num-uses (completion-entry num-uses)
1087 (list 'setcar (list 'cdr completion-entry) num-uses))
1089 (defmacro set-completion-last-use-time (completion-entry last-use-time)
1090 (list 'setcar (list 'cdr (list 'cdr completion-entry)) last-use-time))
1093 (defun make-completion (string)
1094 "Returns a list of a completion entry."
1095 (list (list string 0 nil current-completion-source)))
1098 ;;(defmacro cmpl-prefix-entry-symbol (completion-entry)
1099 ;; (list 'car (list 'cdr completion-entry)))
1103 ;;;-----------------------------------------------
1104 ;;; Prefix symbol entry definition
1105 ;;;-----------------------------------------------
1106 ;;; A cons of (head . tail)
1110 (defmacro cmpl-prefix-entry-head (prefix-entry)
1111 (list 'car prefix-entry))
1113 (defmacro cmpl-prefix-entry-tail (prefix-entry)
1114 (list 'cdr prefix-entry))
1118 (defmacro set-cmpl-prefix-entry-head (prefix-entry new-head)
1119 (list 'setcar prefix-entry new-head))
1121 (defmacro set-cmpl-prefix-entry-tail (prefix-entry new-tail)
1122 (list 'setcdr prefix-entry new-tail))
1126 (defun make-cmpl-prefix-entry (completion-entry-list)
1127 "Makes a new prefix entry containing only completion-entry."
1128 (cons completion-entry-list completion-entry-list))
1130 ;;;-----------------------------------------------
1131 ;;; Completion Database - Utilities
1132 ;;;-----------------------------------------------
1134 (defun clear-all-completions ()
1135 "Initializes the completion storage. All existing completions are lost."
1137 (setq cmpl-prefix-obarray (make-vector cmpl-obarray-length 0))
1138 (setq cmpl-obarray (make-vector cmpl-obarray-length 0))
1139 (cmpl-statistics-block
1140 (record-clear-all-completions))
1143 (defvar completions-list-return-value)
1145 (defun list-all-completions ()
1146 "Returns a list of all the known completion entries."
1147 (let ((completions-list-return-value nil))
1148 (mapatoms 'list-all-completions-1 cmpl-prefix-obarray)
1149 completions-list-return-value))
1151 (defun list-all-completions-1 (prefix-symbol)
1152 (if (boundp prefix-symbol)
1153 (setq completions-list-return-value
1154 (append (cmpl-prefix-entry-head (symbol-value prefix-symbol))
1155 completions-list-return-value))))
1157 (defun list-all-completions-by-hash-bucket ()
1158 "Return list of lists of known completion entries, organized by hash bucket."
1159 (let ((completions-list-return-value nil))
1160 (mapatoms 'list-all-completions-by-hash-bucket-1 cmpl-prefix-obarray)
1161 completions-list-return-value))
1163 (defun list-all-completions-by-hash-bucket-1 (prefix-symbol)
1164 (if (boundp prefix-symbol)
1165 (setq completions-list-return-value
1166 (cons (cmpl-prefix-entry-head (symbol-value prefix-symbol))
1167 completions-list-return-value))))
1170 ;;;-----------------------------------------------
1171 ;;; Updating the database
1172 ;;;-----------------------------------------------
1174 ;;; These are the internal functions used to update the datebase
1177 (defvar completion-to-accept nil)
1178 ;;"Set to a string that is pending its acceptance."
1179 ;; this checked by the top level reading functions
1181 (defvar cmpl-db-downcase-string nil)
1182 ;; "Setup by find-exact-completion, etc. The given string, downcased."
1183 (defvar cmpl-db-symbol nil)
1184 ;; "The interned symbol corresponding to cmpl-db-downcase-string.
1185 ;; Set up by cmpl-db-symbol."
1186 (defvar cmpl-db-prefix-symbol nil)
1187 ;; "The interned prefix symbol corresponding to cmpl-db-downcase-string."
1188 (defvar cmpl-db-entry nil)
1189 (defvar cmpl-db-debug-p nil
1190 "Set to T if you want to debug the database.")
1193 (defun find-exact-completion (string)
1194 "Returns the completion entry for string or nil.
1195 Sets up `cmpl-db-downcase-string' and `cmpl-db-symbol'."
1196 (and (boundp (setq cmpl-db-symbol
1197 (intern (setq cmpl-db-downcase-string (downcase string))
1199 (symbol-value cmpl-db-symbol)
1202 (defun find-cmpl-prefix-entry (prefix-string)
1203 "Returns the prefix entry for string.
1204 Sets `cmpl-db-prefix-symbol'.
1205 Prefix-string must be exactly `completion-prefix-min-length' long
1206 and downcased. Sets up `cmpl-db-prefix-symbol'."
1207 (and (boundp (setq cmpl-db-prefix-symbol
1208 (intern prefix-string cmpl-prefix-obarray)))
1209 (symbol-value cmpl-db-prefix-symbol)))
1211 (defvar inside-locate-completion-entry nil)
1212 ;; used to trap lossage in silent error correction
1214 (defun locate-completion-entry (completion-entry prefix-entry)
1215 "Locates the completion entry.
1216 Returns a pointer to the element before the completion entry or nil if
1217 the completion entry is at the head.
1218 Must be called after `find-exact-completion'."
1219 (let ((prefix-list (cmpl-prefix-entry-head prefix-entry))
1223 ((not (eq (car prefix-list) completion-entry))
1224 ;; not already at head
1225 (while (and prefix-list
1226 (not (eq completion-entry
1227 (car (setq next-prefix-list (cdr prefix-list)))
1229 (setq prefix-list next-prefix-list))
1232 ;; Didn't find it. Database is messed up.
1234 ;; not found, error if debug mode
1235 (error "Completion entry exists but not on prefix list - %s"
1237 (inside-locate-completion-entry
1238 ;; recursive error: really scrod
1239 (locate-completion-db-error))
1242 (set cmpl-db-symbol nil)
1244 (locate-completion-entry-retry completion-entry)
1247 (defun locate-completion-entry-retry (old-entry)
1248 (let ((inside-locate-completion-entry t))
1249 (add-completion (completion-string old-entry)
1250 (completion-num-uses old-entry)
1251 (completion-last-use-time old-entry))
1252 (let* ((cmpl-entry (find-exact-completion (completion-string old-entry)))
1255 (find-cmpl-prefix-entry
1256 (substring cmpl-db-downcase-string
1257 0 completion-prefix-min-length))))
1259 (if (and cmpl-entry pref-entry)
1261 (locate-completion-entry cmpl-entry pref-entry)
1263 (locate-completion-db-error))
1266 (defun locate-completion-db-error ()
1267 ;; recursive error: really scrod
1268 (error "Completion database corrupted. Try M-x clear-all-completions. Send bug report.")
1272 (defun add-completion-to-tail-if-new (string)
1273 "If STRING is not in the database add it to appropriate prefix list.
1274 STRING is added to the end of the appropriate prefix list with
1275 num-uses = 0. The database is unchanged if it is there. STRING must be
1276 longer than `completion-prefix-min-length'.
1277 This must be very fast.
1278 Returns the completion entry."
1279 (or (find-exact-completion string)
1281 (let (;; create an entry
1282 (entry (make-completion string))
1284 (prefix-entry (find-cmpl-prefix-entry
1285 (substring cmpl-db-downcase-string 0
1286 (cmpl-read-time-eval
1287 completion-prefix-min-length))))
1289 ;; The next two forms should happen as a unit (atomically) but
1290 ;; no fatal errors should result if that is not the case.
1292 ;; These two should be atomic, but nothing fatal will happen
1294 (setcdr (cmpl-prefix-entry-tail prefix-entry) entry)
1295 (set-cmpl-prefix-entry-tail prefix-entry entry))
1297 (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))
1300 (cmpl-statistics-block
1301 (note-added-completion))
1303 (set cmpl-db-symbol (car entry))
1306 (defun add-completion-to-head (completion-string)
1307 "If COMPLETION-STRING is not in the database, add it to prefix list.
1308 We add COMPLETION-STRING to the head of the appropriate prefix list,
1309 or it to the head of the list.
1310 COMPLETION-STRING must be longer than `completion-prefix-min-length'.
1311 Updates the saved string with the supplied string.
1312 This must be very fast.
1313 Returns the completion entry."
1314 ;; Handle pending acceptance
1315 (if completion-to-accept (accept-completion))
1316 ;; test if already in database
1317 (if (setq cmpl-db-entry (find-exact-completion completion-string))
1319 (let* ((prefix-entry (find-cmpl-prefix-entry
1320 (substring cmpl-db-downcase-string 0
1321 (cmpl-read-time-eval
1322 completion-prefix-min-length))))
1323 (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry))
1324 (cmpl-ptr (cdr splice-ptr))
1327 (set-completion-string cmpl-db-entry completion-string)
1328 ;; move to head (if necessary)
1330 ;; These should all execute atomically but it is not fatal if
1333 (or (setcdr splice-ptr (cdr cmpl-ptr))
1334 ;; fix up tail if necessary
1335 (set-cmpl-prefix-entry-tail prefix-entry splice-ptr))
1336 ;; splice in at head
1337 (setcdr cmpl-ptr (cmpl-prefix-entry-head prefix-entry))
1338 (set-cmpl-prefix-entry-head prefix-entry cmpl-ptr)
1342 (let (;; create an entry
1343 (entry (make-completion completion-string))
1345 (prefix-entry (find-cmpl-prefix-entry
1346 (substring cmpl-db-downcase-string 0
1347 (cmpl-read-time-eval
1348 completion-prefix-min-length))))
1351 ;; Splice in at head
1352 (setcdr entry (cmpl-prefix-entry-head prefix-entry))
1353 (set-cmpl-prefix-entry-head prefix-entry entry))
1355 ;; Start new prefix entry
1356 (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))
1359 (cmpl-statistics-block
1360 (note-added-completion))
1361 ;; Add it to the symbol
1362 (set cmpl-db-symbol (car entry))
1365 (defun delete-completion (completion-string)
1366 "Deletes the completion from the database.
1367 String must be longer than `completion-prefix-min-length'."
1368 ;; Handle pending acceptance
1369 (if completion-to-accept (accept-completion))
1370 (if (setq cmpl-db-entry (find-exact-completion completion-string))
1372 (let* ((prefix-entry (find-cmpl-prefix-entry
1373 (substring cmpl-db-downcase-string 0
1374 (cmpl-read-time-eval
1375 completion-prefix-min-length))))
1376 (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry))
1378 ;; delete symbol reference
1379 (set cmpl-db-symbol nil)
1380 ;; remove from prefix list
1383 (or (setcdr splice-ptr (cdr (cdr splice-ptr)))
1384 ;; fix up tail if necessary
1385 (set-cmpl-prefix-entry-tail prefix-entry splice-ptr))
1389 (or (set-cmpl-prefix-entry-head
1390 prefix-entry (cdr (cmpl-prefix-entry-head prefix-entry)))
1391 ;; List is now empty
1392 (set cmpl-db-prefix-symbol nil))
1394 (cmpl-statistics-block
1395 (note-completion-deleted))
1397 (error "Unknown completion `%s'" completion-string)
1401 ;;; - Add and Find -
1402 ;;; (add-completion-to-head "banana") --> ("banana" 0 nil 0)
1403 ;;; (find-exact-completion "banana") --> ("banana" 0 nil 0)
1404 ;;; (find-exact-completion "bana") --> nil
1405 ;;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1406 ;;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1407 ;;; (add-completion-to-head "banish") --> ("banish" 0 nil 0)
1408 ;;; (find-exact-completion "banish") --> ("banish" 0 nil 0)
1409 ;;; (car (find-cmpl-prefix-entry "ban")) --> (("banish" ...) ("banana" ...))
1410 ;;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1411 ;;; (add-completion-to-head "banana") --> ("banana" 0 nil 0)
1412 ;;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
1413 ;;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
1416 ;;; (add-completion-to-head "banner") --> ("banner" 0 nil 0)
1417 ;;; (delete-completion "banner")
1418 ;;; (find-exact-completion "banner") --> nil
1419 ;;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
1420 ;;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
1421 ;;; (add-completion-to-head "banner") --> ("banner" 0 nil 0)
1422 ;;; (delete-completion "banana")
1423 ;;; (car (find-cmpl-prefix-entry "ban")) --> (("banner" ...) ("banish" ...))
1424 ;;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
1425 ;;; (delete-completion "banner")
1426 ;;; (delete-completion "banish")
1427 ;;; (find-cmpl-prefix-entry "ban") --> nil
1428 ;;; (delete-completion "banner") --> error
1431 ;;; (add-completion-to-tail-if-new "banana") --> ("banana" 0 nil 0)
1432 ;;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1433 ;;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
1434 ;;; (add-completion-to-tail-if-new "banish") --> ("banish" 0 nil 0)
1435 ;;; (car (find-cmpl-prefix-entry "ban")) -->(("banana" ...) ("banish" ...))
1436 ;;; (cdr (find-cmpl-prefix-entry "ban")) -->(("banish" ...))
1440 ;;;---------------------------------------------------------------------------
1441 ;;; Database Update :: Interface level routines
1442 ;;;---------------------------------------------------------------------------
1444 ;;; These lie on top of the database ref. functions but below the standard
1445 ;;; user interface level
1448 (defun interactive-completion-string-reader (prompt)
1449 (let* ((default (symbol-under-or-before-point))
1452 (format "%s: (default: %s) " prompt default)
1453 (format "%s: " prompt))
1455 (read (completing-read new-prompt cmpl-obarray))
1457 (if (zerop (length read)) (setq read (or default "")))
1461 (defun check-completion-length (string)
1462 (if (< (length string) completion-min-length)
1463 (error "The string `%s' is too short to be saved as a completion"
1467 (defun add-completion (string &optional num-uses last-use-time)
1468 "Add STRING to completion list, or move it to head of list.
1469 The completion is altered appropriately if num-uses and/or last-use-time is
1471 (interactive (interactive-completion-string-reader "Completion to add"))
1472 (check-completion-length string)
1473 (let* ((current-completion-source (if (interactive-p)
1474 cmpl-source-interactive
1475 current-completion-source))
1476 (entry (add-completion-to-head string)))
1478 (if num-uses (set-completion-num-uses entry num-uses))
1480 (set-completion-last-use-time entry last-use-time))
1483 (defun add-permanent-completion (string)
1484 "Add STRING if it isn't already listed, and mark it permanent."
1486 (interactive-completion-string-reader "Completion to add permanently"))
1487 (let ((current-completion-source (if (interactive-p)
1488 cmpl-source-interactive
1489 current-completion-source))
1491 (add-completion string nil t)
1494 (defun kill-completion (string)
1495 (interactive (interactive-completion-string-reader "Completion to kill"))
1496 (check-completion-length string)
1497 (delete-completion string)
1500 (defun accept-completion ()
1501 "Accepts the pending completion in `completion-to-accept'.
1502 This bumps num-uses. Called by `add-completion-to-head' and
1503 `completion-search-reset'."
1504 (let ((string completion-to-accept)
1505 ;; if this is added afresh here, then it must be a cdabbrev
1506 (current-completion-source cmpl-source-cdabbrev)
1509 (setq completion-to-accept nil)
1510 (setq entry (add-completion-to-head string))
1511 (set-completion-num-uses entry (1+ (completion-num-uses entry)))
1512 (setq cmpl-completions-accepted-p t)
1515 (defun use-completion-under-point ()
1516 "Add the completion symbol underneath the point into the completion buffer."
1517 (let ((string (and enable-completion (symbol-under-point)))
1518 (current-completion-source cmpl-source-cursor-moves))
1519 (if string (add-completion-to-head string))))
1521 (defun use-completion-before-point ()
1522 "Add the completion symbol before point into the completion buffer."
1523 (let ((string (and enable-completion (symbol-before-point)))
1524 (current-completion-source cmpl-source-cursor-moves))
1525 (if string (add-completion-to-head string))))
1527 (defun use-completion-under-or-before-point ()
1528 "Add the completion symbol before point into the completion buffer."
1529 (let ((string (and enable-completion (symbol-under-or-before-point)))
1530 (current-completion-source cmpl-source-cursor-moves))
1531 (if string (add-completion-to-head string))))
1533 (defun use-completion-before-separator ()
1534 "Add the completion symbol before point into the completion buffer.
1535 Completions added this way will automatically be saved if
1536 `completion-on-separator-character' is non-nil."
1537 (let ((string (and enable-completion (symbol-before-point)))
1538 (current-completion-source cmpl-source-separator)
1540 (cmpl-statistics-block
1541 (note-separator-character string)
1544 (setq entry (add-completion-to-head string))
1545 (if (and completion-on-separator-character
1546 (zerop (completion-num-uses entry)))
1548 (set-completion-num-uses entry 1)
1549 (setq cmpl-completions-accepted-p t)))))
1553 ;;; - Add and Find -
1554 ;;; (add-completion "banana" 5 10)
1555 ;;; (find-exact-completion "banana") --> ("banana" 5 10 0)
1556 ;;; (add-completion "banana" 6)
1557 ;;; (find-exact-completion "banana") --> ("banana" 6 10 0)
1558 ;;; (add-completion "banish")
1559 ;;; (car (find-cmpl-prefix-entry "ban")) --> (("banish" ...) ("banana" ...))
1562 ;;; (setq completion-to-accept "banana")
1563 ;;; (accept-completion)
1564 ;;; (find-exact-completion "banana") --> ("banana" 7 10)
1565 ;;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
1566 ;;; (setq completion-to-accept "banish")
1567 ;;; (add-completion "banner")
1568 ;;; (car (find-cmpl-prefix-entry "ban"))
1569 ;;; --> (("banner" ...) ("banish" 1 ...) ("banana" 7 ...))
1572 ;;; (kill-completion "banish")
1573 ;;; (car (find-cmpl-prefix-entry "ban")) --> (("banner" ...) ("banana" ...))
1576 ;;;---------------------------------------------------------------------------
1577 ;;; Searching the database
1578 ;;;---------------------------------------------------------------------------
1579 ;;; Functions outside this block must call completion-search-reset followed
1580 ;;; by calls to completion-search-next or completion-search-peek
1583 ;;; Status variables
1584 ;; Commented out to improve loading speed
1585 (defvar cmpl-test-string "")
1586 ;; "The current string used by completion-search-next."
1587 (defvar cmpl-test-regexp "")
1588 ;; "The current regexp used by completion-search-next.
1589 ;; (derived from cmpl-test-string)"
1590 (defvar cmpl-last-index 0)
1591 ;; "The last index that completion-search-next was called with."
1592 (defvar cmpl-cdabbrev-reset-p nil)
1593 ;; "Set to t when cdabbrevs have been reset."
1594 (defvar cmpl-next-possibilities nil)
1595 ;; "A pointer to the element BEFORE the next set of possible completions.
1596 ;; cadr of this is the cmpl-next-possibility"
1597 (defvar cmpl-starting-possibilities nil)
1598 ;; "The initial list of starting possibilities."
1599 (defvar cmpl-next-possibility nil)
1600 ;; "The cached next possibility."
1601 (defvar cmpl-tried-list nil)
1602 ;; "A downcased list of all the completions we have tried."
1605 (defun completion-search-reset (string)
1606 "Set up the for completion searching for STRING.
1607 STRING must be longer than `completion-prefix-min-length'."
1608 (if completion-to-accept (accept-completion))
1609 (setq cmpl-starting-possibilities
1610 (cmpl-prefix-entry-head
1611 (find-cmpl-prefix-entry
1612 (downcase (substring string 0 completion-prefix-min-length))))
1613 cmpl-test-string string
1614 cmpl-test-regexp (concat (regexp-quote string) "."))
1615 (completion-search-reset-1)
1618 (defun completion-search-reset-1 ()
1619 (setq cmpl-next-possibilities cmpl-starting-possibilities
1620 cmpl-next-possibility nil
1621 cmpl-cdabbrev-reset-p nil
1626 (defun completion-search-next (index)
1627 "Return the next completion entry.
1628 If INDEX is out of sequence, reset and start from the top.
1629 If there are no more entries, try cdabbrev and returns only a string."
1631 ((= index (setq cmpl-last-index (1+ cmpl-last-index)))
1632 (completion-search-peek t))
1634 (completion-search-reset-1)
1635 (setq cmpl-last-index index)
1636 ;; reverse the possibilities list
1637 (setq cmpl-next-possibilities (reverse cmpl-starting-possibilities))
1638 ;; do a "normal" search
1639 (while (and (completion-search-peek nil)
1640 (< (setq index (1+ index)) 0))
1641 (setq cmpl-next-possibility nil)
1643 (cond ((not cmpl-next-possibilities))
1644 ;; If no more possibilities, leave it that way
1645 ((= -1 cmpl-last-index)
1646 ;; next completion is at index 0. reset next-possibility list
1647 ;; to start at beginning
1648 (setq cmpl-next-possibilities cmpl-starting-possibilities))
1650 ;; otherwise point to one before current
1651 (setq cmpl-next-possibilities
1652 (nthcdr (- (length cmpl-starting-possibilities)
1653 (length cmpl-next-possibilities))
1654 cmpl-starting-possibilities))
1657 ;; non-negative index, reset and search
1659 (completion-search-reset-1)
1660 (setq cmpl-last-index index)
1661 (while (and (completion-search-peek t)
1662 (not (< (setq index (1- index)) 0)))
1663 (setq cmpl-next-possibility nil)
1667 cmpl-next-possibility
1668 (setq cmpl-next-possibility nil)
1672 (defun completion-search-peek (use-cdabbrev)
1673 "Returns the next completion entry without actually moving the pointers.
1674 Calling this again or calling `completion-search-next' results in the same
1675 string being returned. Depends on `case-fold-search'.
1676 If there are no more entries, try cdabbrev and then return only a string."
1678 ;; return the cached value if we have it
1679 (cmpl-next-possibility)
1680 ((and cmpl-next-possibilities
1681 ;; still a few possibilities left
1684 (and (not (eq 0 (string-match cmpl-test-regexp
1685 (completion-string (car cmpl-next-possibilities)))))
1686 (setq cmpl-next-possibilities (cdr cmpl-next-possibilities))
1688 cmpl-next-possibilities
1691 (setq cmpl-next-possibility (car cmpl-next-possibilities)
1692 cmpl-tried-list (cons (downcase (completion-string cmpl-next-possibility))
1694 cmpl-next-possibilities (cdr cmpl-next-possibilities)
1696 cmpl-next-possibility)
1698 ;; unsuccessful, use cdabbrev
1699 (cond ((not cmpl-cdabbrev-reset-p)
1700 (reset-cdabbrev cmpl-test-string cmpl-tried-list)
1701 (setq cmpl-cdabbrev-reset-p t)
1703 (setq cmpl-next-possibility (next-cdabbrev))
1705 ;; Completely unsuccessful, return nil
1709 ;;; - Add and Find -
1710 ;;; (add-completion "banana")
1711 ;;; (completion-search-reset "ban")
1712 ;;; (completion-search-next 0) --> "banana"
1714 ;;; - Discrimination -
1715 ;;; (add-completion "cumberland")
1716 ;;; (add-completion "cumberbund")
1718 ;;; (completion-search-reset "cumb")
1719 ;;; (completion-search-peek t) --> "cumberbund"
1720 ;;; (completion-search-next 0) --> "cumberbund"
1721 ;;; (completion-search-peek t) --> "cumberland"
1722 ;;; (completion-search-next 1) --> "cumberland"
1723 ;;; (completion-search-peek nil) --> nil
1724 ;;; (completion-search-next 2) --> "cumbering" {cdabbrev}
1725 ;;; (completion-search-next 3) --> nil or "cumming"{depends on context}
1726 ;;; (completion-search-next 1) --> "cumberland"
1727 ;;; (completion-search-peek t) --> "cumbering" {cdabbrev}
1730 ;;; (completion-search-next 1) --> "cumberland"
1731 ;;; (setq completion-to-accept "cumberland")
1732 ;;; (completion-search-reset "foo")
1733 ;;; (completion-search-reset "cum")
1734 ;;; (completion-search-next 0) --> "cumberland"
1737 ;;; (kill-completion "cumberland")
1739 ;;; (completion-search-reset "cum")
1740 ;;; (completion-search-next 0) --> "cumberbund"
1741 ;;; (completion-search-next 1) --> "cummings"
1743 ;;; - Ignoring Capitalization -
1744 ;;; (completion-search-reset "CuMb")
1745 ;;; (completion-search-next 0) --> "cumberbund"
1749 ;;;-----------------------------------------------
1751 ;;;-----------------------------------------------
1753 (defun completion-mode ()
1754 "Toggles whether or not to add new words to the completion database."
1756 (setq enable-completion (not enable-completion))
1757 (message "Completion mode is now %s." (if enable-completion "ON" "OFF"))
1760 (defvar cmpl-current-index 0)
1761 (defvar cmpl-original-string nil)
1762 (defvar cmpl-last-insert-location -1)
1763 (defvar cmpl-leave-point-at-start nil)
1765 (defun complete (&optional arg)
1766 "Fill out a completion of the word before point.
1767 Point is left at end. Consecutive calls rotate through all possibilities.
1769 control-u :: leave the point at the beginning of the completion rather
1771 a number :: rotate through the possible completions by that amount
1772 `-' :: same as -1 (insert previous completion)
1773 {See the comments at the top of `completion.el' for more info.}"
1775 ;;; Set up variables
1776 (cond ((eq last-command this-command)
1778 (delete-region cmpl-last-insert-location (point))
1779 ;; get next completion
1780 (setq cmpl-current-index (+ cmpl-current-index (or arg 1)))
1783 (if (not cmpl-initialized-p)
1784 (initialize-completions)) ;; make sure everything's loaded
1785 (cond ((consp current-prefix-arg) ;; control-u
1787 (setq cmpl-leave-point-at-start t)
1790 (setq cmpl-leave-point-at-start nil)
1793 (setq cmpl-original-string (symbol-before-point-for-complete))
1794 (cond ((not cmpl-original-string)
1795 (setq this-command 'failed-complete)
1796 (error "To complete, point must be after a symbol at least %d character long"
1797 completion-prefix-min-length)))
1799 (setq cmpl-current-index (if current-prefix-arg arg 0))
1801 (cmpl-statistics-block
1802 (note-complete-entered-afresh cmpl-original-string))
1804 (completion-search-reset cmpl-original-string)
1805 ;; erase what we've got
1806 (delete-region cmpl-symbol-start cmpl-symbol-end)
1809 ;; point is at the point to insert the new symbol
1810 ;; Get the next completion
1811 (let* ((print-status-p
1812 (and (>= baud-rate completion-prompt-speed-threshold)
1813 (not (minibuffer-window-selected-p))))
1814 (insert-point (point))
1815 (entry (completion-search-next cmpl-current-index))
1818 ;; entry is either a completion entry or a string (if cdabbrev)
1822 ;; Setup for proper case
1823 (setq string (if (stringp entry)
1824 entry (completion-string entry)))
1825 (setq string (cmpl-merge-string-cases
1826 string cmpl-original-string))
1830 (setq completion-to-accept string)
1831 ;; fixup and cache point
1832 (cond (cmpl-leave-point-at-start
1833 (setq cmpl-last-insert-location (point))
1834 (goto-char insert-point))
1836 (setq cmpl-last-insert-location insert-point))
1839 (cmpl-statistics-block
1840 (note-complete-inserted entry cmpl-current-index))
1841 ;; Done ! cmpl-stat-complete-successful
1842 ;;display the next completion
1844 ((and print-status-p
1845 ;; This updates the display and only prints if there
1849 (completion-search-peek
1850 completion-cdabbrev-prompt-flag)))
1851 (setq string (if (stringp entry)
1852 entry (completion-string entry)))
1853 (setq string (cmpl-merge-string-cases
1854 string cmpl-original-string))
1855 (message "Next completion: %s" string)
1858 (t;; none found, insert old
1859 (insert cmpl-original-string)
1860 ;; Don't accept completions
1861 (setq completion-to-accept nil)
1863 ;; This used to call cmpl19-sit-for, an undefined function.
1864 ;; I hope that sit-for does the right thing; I don't know -- rms.
1865 (if (and print-status-p (sit-for 0))
1866 (message "No %scompletions."
1867 (if (eq this-command last-command) "more " "")))
1869 (cmpl-statistics-block
1870 (record-complete-failed cmpl-current-index))
1871 ;; Pretend that we were never here
1872 (setq this-command 'failed-complete)
1875 ;;;-----------------------------------------------
1876 ;;; "Complete" Key Keybindings
1877 ;;;-----------------------------------------------
1879 (global-set-key "\M-\r" 'complete)
1880 (global-set-key [?\C-\r] 'complete)
1881 (define-key function-key-map [C-return] [?\C-\r])
1884 ;;; (add-completion "cumberland")
1885 ;;; (add-completion "cumberbund")
1892 ;;;---------------------------------------------------------------------------
1893 ;;; Parsing definitions from files into the database
1894 ;;;---------------------------------------------------------------------------
1896 ;;;-----------------------------------------------
1897 ;;; Top Level functions ::
1898 ;;;-----------------------------------------------
1901 (defun add-completions-from-file (file)
1902 "Parse possible completions from a file and add them to data base."
1903 (interactive "fFile: ")
1904 (setq file (expand-file-name file))
1905 (let* ((buffer (get-file-buffer file))
1906 (buffer-already-there-p buffer)
1908 (if (not buffer-already-there-p)
1909 (let ((completions-merging-modes nil))
1910 (setq buffer (find-file-noselect file))))
1914 (add-completions-from-buffer)
1916 (if (not buffer-already-there-p)
1917 (kill-buffer buffer)))))
1919 (defun add-completions-from-buffer ()
1921 (let ((current-completion-source cmpl-source-file-parsing)
1923 (cmpl-statistics-block
1924 (aref completion-add-count-vector cmpl-source-file-parsing)))
1927 (cond ((memq major-mode '(emacs-lisp-mode lisp-mode))
1928 (add-completions-from-lisp-buffer)
1931 ((memq major-mode '(c-mode))
1932 (add-completions-from-c-buffer)
1936 (error "Cannot parse completions in %s buffers"
1939 (cmpl-statistics-block
1940 (record-cmpl-parse-file
1942 (- (aref completion-add-count-vector cmpl-source-file-parsing)
1947 (defun cmpl-find-file-hook ()
1948 (cond (enable-completion
1949 (cond ((and (memq major-mode '(emacs-lisp-mode lisp-mode))
1950 (memq 'lisp completions-merging-modes)
1952 (add-completions-from-buffer))
1953 ((and (memq major-mode '(c-mode))
1954 (memq 'c completions-merging-modes)
1956 (add-completions-from-buffer)
1960 (add-hook 'find-file-hooks 'cmpl-find-file-hook)
1962 ;;;-----------------------------------------------
1963 ;;; Tags Table Completions
1964 ;;;-----------------------------------------------
1966 (defun add-completions-from-tags-table ()
1967 ;; Inspired by eero@media-lab.media.mit.edu
1968 "Add completions from the current tags table."
1970 (visit-tags-table-buffer) ;this will prompt if no tags-table
1972 (goto-char (point-min))
1976 (search-forward "\177")
1978 (and (setq string (symbol-under-point))
1979 (add-completion-to-tail-if-new string))
1986 ;;;-----------------------------------------------
1987 ;;; Lisp File completion parsing
1988 ;;;-----------------------------------------------
1989 ;;; This merely looks for phrases beginning with (def.... or
1990 ;;; (package:def ... and takes the next word.
1992 ;;; We tried using forward-lines and explicit searches but the regexp technique
1993 ;;; was faster. (About 100K characters per second)
1995 (defconst *lisp-def-regexp*
1996 "\n(\\(\\w*:\\)?def\\(\\w\\|\\s_\\)*\\s +(*"
1997 "A regexp that searches for lisp definition form."
2001 ;;; (and (string-match *lisp-def-regexp* "\n(defun foo") (match-end 0)) -> 8
2002 ;;; (and (string-match *lisp-def-regexp* "\n(si:def foo") (match-end 0)) -> 9
2003 ;;; (and (string-match *lisp-def-regexp* "\n(def-bar foo")(match-end 0)) -> 10
2004 ;;; (and (string-match *lisp-def-regexp* "\n(defun (foo") (match-end 0)) -> 9
2006 ;;; Parses all the definition names from a Lisp mode buffer and adds them to
2007 ;;; the completion database.
2008 (defun add-completions-from-lisp-buffer ()
2010 ;;; Sun-3/280 - 1500 to 3000 lines of lisp code per second
2013 (goto-char (point-min))
2016 (re-search-forward *lisp-def-regexp*)
2017 (and (setq string (symbol-under-point))
2018 (add-completion-to-tail-if-new string))
2024 ;;;-----------------------------------------------
2025 ;;; C file completion parsing
2026 ;;;-----------------------------------------------
2028 ;;; Looks for #define or [<storage class>] [<type>] <name>{,<name>}
2029 ;;; or structure, array or pointer defs.
2030 ;;; It gets most of the definition names.
2032 ;;; As you might suspect by now, we use some symbol table hackery
2034 ;;; Symbol separator chars (have whitespace syntax) --> , ; * = (
2035 ;;; Opening char --> [ {
2036 ;;; Closing char --> ] }
2037 ;;; opening and closing must be skipped over
2038 ;;; Whitespace chars (have symbol syntax)
2039 ;;; Everything else has word syntax
2041 (defun cmpl-make-c-def-completion-syntax-table ()
2042 (let ((table (make-vector 256 0))
2043 (whitespace-chars '(? ?\n ?\t ?\f ?\v ?\r))
2044 ;; unfortunately the ?( causes the parens to appear unbalanced
2045 (separator-chars '(?, ?* ?= ?\( ?\;
2048 ;; default syntax is whitespace
2051 (modify-syntax-entry i "w" table)
2053 (completion-dolist (char whitespace-chars)
2054 (modify-syntax-entry char "_" table))
2055 (completion-dolist (char separator-chars)
2056 (modify-syntax-entry char " " table))
2057 (modify-syntax-entry ?\[ "(]" table)
2058 (modify-syntax-entry ?\{ "(}" table)
2059 (modify-syntax-entry ?\] ")[" table)
2060 (modify-syntax-entry ?\} "){" table)
2063 (defconst cmpl-c-def-syntax-table (cmpl-make-c-def-completion-syntax-table))
2066 (defconst *c-def-regexp*
2067 ;; This stops on lines with possible definitions
2069 ;; This stops after the symbol to add.
2070 ;;"\n\\(#define\\s +.\\|\\(\\(\\w\\|\\s_\\)+\\b\\s *\\)+[(;,[*{=]\\)"
2071 ;; This stops before the symbol to add. {Test cases in parens. below}
2072 ;;"\n\\(\\(\\w\\|\\s_\\)+\\s *(\\|\\(\\(#define\\|auto\\|extern\\|register\\|static\\|int\\|long\\|short\\|unsigned\\|char\\|void\\|float\\|double\\|enum\\|struct\\|union\\|typedef\\)\\s +\\)+\\)"
2073 ;; this simple version picks up too much extraneous stuff
2074 ;; "\n\\(\\w\\|\\s_\\|#\\)\\B"
2075 "A regexp that searches for a definition form."
2078 ;(defconst *c-cont-regexp*
2079 ; "\\(\\w\\|\\s_\\)+\\b\\s *\\({\\|\\(\\[[0-9\t ]*\\]\\s *\\)*,\\(*\\|\\s \\)*\\b\\)"
2080 ; "This regexp should be used in a looking-at to parse for lists of variables.")
2082 ;(defconst *c-struct-regexp*
2083 ; "\\(*\\|\\s \\)*\\b"
2084 ; "This regexp should be used to test whether a symbol follows a structure definition.")
2086 ;(defun test-c-def-regexp (regexp string)
2087 ; (and (eq 0 (string-match regexp string)) (match-end 0))
2091 ;;; (test-c-def-regexp *c-def-regexp* "\n#define foo") -> 10 (9)
2092 ;;; (test-c-def-regexp *c-def-regexp* "\nfoo (x, y) {") -> 6 (6)
2093 ;;; (test-c-def-regexp *c-def-regexp* "\nint foo (x, y)") -> 10 (5)
2094 ;;; (test-c-def-regexp *c-def-regexp* "\n int foo (x, y)") -> nil
2095 ;;; (test-c-def-regexp *c-cont-regexp* "oo, bar") -> 4
2096 ;;; (test-c-def-regexp *c-cont-regexp* "oo, *bar") -> 5
2097 ;;; (test-c-def-regexp *c-cont-regexp* "a [5][6], bar") -> 10
2098 ;;; (test-c-def-regexp *c-cont-regexp* "oo(x,y)") -> nil
2099 ;;; (test-c-def-regexp *c-cont-regexp* "a [6] ,\t bar") -> 9
2100 ;;; (test-c-def-regexp *c-cont-regexp* "oo {trout =1} my_carp;") -> 14
2101 ;;; (test-c-def-regexp *c-cont-regexp* "truct_p complex foon") -> nil
2103 ;;; Parses all the definition names from a C mode buffer and adds them to the
2104 ;;; completion database.
2105 (defun add-completions-from-c-buffer ()
2107 ;; Sun 3/280-- 1250 lines/sec.
2109 (let (string next-point char
2110 (saved-syntax (syntax-table))
2113 (goto-char (point-min))
2114 (catch 'finish-add-completions
2117 ;; we loop here only when scan-sexps fails
2118 ;; (i.e. unbalance exps.)
2119 (set-syntax-table cmpl-c-def-syntax-table)
2122 (re-search-forward *c-def-regexp*)
2124 ((= (preceding-char) ?#)
2125 ;; preprocessor macro, see if it's one we handle
2126 (setq string (buffer-substring (point) (+ (point) 6)))
2127 (cond ((or (string-equal string "define")
2128 (string-equal string "ifdef ")
2130 ;; skip forward over definition symbol
2131 ;; and add it to database
2132 (and (forward-word 2)
2133 (setq string (symbol-before-point))
2135 (add-completion-to-tail-if-new string)
2139 (setq next-point (point))
2142 ;; scan to next separator char.
2143 (setq next-point (scan-sexps next-point 1))
2145 ;; position the point on the word we want to add
2146 (goto-char next-point)
2147 (while (= (setq char (following-char)) ?*)
2148 ;; handle pointer ref
2149 ;; move to next separator char.
2151 (setq next-point (scan-sexps (point) 1)))
2155 (if (setq string (symbol-under-point))
2156 ;; (push string foo)
2157 (add-completion-to-tail-if-new string)
2158 ;; Local TMC hack (useful for parsing paris.h)
2159 (if (and (looking-at "_AP") ;; "ansi prototype"
2163 (symbol-under-point))
2165 (add-completion-to-tail-if-new string)
2169 (goto-char next-point)
2170 ;; (push (format "%c" (following-char)) foo)
2171 (if (= (char-syntax char) ?\()
2172 ;; if on an opening delimiter, go to end
2173 (while (= (char-syntax char) ?\()
2174 (setq next-point (scan-sexps next-point 1)
2175 char (char-after next-point))
2178 ;; Current char is an end char.
2179 (setq next-point nil)
2182 (search-failed ;;done
2183 (throw 'finish-add-completions t)
2186 ;; Check for failure in scan-sexps
2187 (if (or (string-equal (nth 1 e)
2188 "Containing expression ends prematurely")
2189 (string-equal (nth 1 e) "Unbalanced parentheses"))
2190 ;; unbalanced paren., keep going
2193 (message "Error parsing C buffer for completions--please send bug report")
2194 (throw 'finish-add-completions t)
2197 (set-syntax-table saved-syntax)
2201 ;;;---------------------------------------------------------------------------
2203 ;;;---------------------------------------------------------------------------
2205 ;;; The version of save-completions-to-file called at kill-emacs time.
2206 (defun kill-emacs-save-completions ()
2207 (if (and save-completions-flag enable-completion cmpl-initialized-p)
2209 ((not cmpl-completions-accepted-p)
2210 (message "Completions database has not changed - not writing."))
2212 (save-completions-to-file)))))
2214 ;; There is no point bothering to change this again
2215 ;; unless the package changes so much that it matters
2216 ;; for people that have saved completions.
2217 (defconst completion-version "11")
2219 (defconst saved-cmpl-file-header
2220 ";;; Completion Initialization file.
2222 ;;; Format is (<string> . <last-use-time>)
2223 ;;; <string> is the completion
2224 ;;; <last-use-time> is the time the completion was last used
2225 ;;; If it is t, the completion will never be pruned from the file.
2226 ;;; Otherwise it is in hours since origin.
2229 (defun completion-backup-filename (filename)
2230 (concat filename ".BAK"))
2232 (defun save-completions-to-file (&optional filename)
2233 "Save completions in init file FILENAME.
2234 If file name is not specified, use `save-completions-file-name'."
2236 (setq filename (expand-file-name (or filename save-completions-file-name)))
2237 (if (file-writable-p filename)
2239 (if (not cmpl-initialized-p)
2240 (initialize-completions));; make sure everything's loaded
2241 (message "Saving completions to file %s" filename)
2243 (let* ((delete-old-versions t)
2244 (kept-old-versions 0)
2245 (kept-new-versions completions-file-versions-kept)
2247 (current-time (cmpl-hours-since-origin))
2251 (backup-filename (completion-backup-filename filename))
2255 (get-buffer-create " *completion-save-buffer*")
2256 (set-buffer " *completion-save-buffer*")
2257 (setq buffer-file-name filename)
2259 (if (not (verify-visited-file-modtime (current-buffer)))
2261 ;; file has changed on disk. Bring us up-to-date
2262 (message "Completion file has changed. Merging. . .")
2263 (load-completions-from-file filename t)
2264 (message "Merging finished. Saving completions to file %s" filename)))
2266 ;; prepare the buffer to be modified
2267 (clear-visited-file-modtime)
2270 (insert (format saved-cmpl-file-header completion-version))
2271 (completion-dolist (completion (list-all-completions))
2272 (setq total-in-db (1+ total-in-db))
2273 (setq last-use-time (completion-last-use-time completion))
2274 ;; Update num uses and maybe write completion to a file
2275 (cond ((or;; Write to file if
2277 (and (eq last-use-time t)
2278 (setq total-perm (1+ total-perm)))
2280 (if (> (completion-num-uses completion) 0)
2282 (setq last-use-time current-time)
2283 ;; or it was saved before and
2285 ;; save-completions-retention-time is nil
2286 (or (not save-completions-retention-time)
2287 ;; or time since last use is < ...retention-time*
2288 (< (- current-time last-use-time)
2289 save-completions-retention-time))
2292 (setq total-saved (1+ total-saved))
2293 (insert (prin1-to-string (cons (completion-string completion)
2294 last-use-time)) "\n")
2299 (let ((file-exists-p (file-exists-p filename)))
2302 ;; If file exists . . .
2303 ;; Save a backup(so GNU doesn't screw us when we're out of disk)
2304 ;; (GNU leaves a 0 length file if it gets a disk full error!)
2306 ;; If backup doesn't exit, Rename current to backup
2307 ;; {If backup exists the primary file is probably messed up}
2308 (or (file-exists-p backup-filename)
2309 (rename-file filename backup-filename))
2310 ;; Copy the backup back to the current name
2311 ;; (so versioning works)
2312 (copy-file backup-filename filename t)))
2316 ;; If successful, remove backup
2317 (delete-file backup-filename)))
2319 (set-buffer-modified-p nil)
2320 (message "Couldn't save completion file `%s'" filename)
2322 ;; Reset accepted-p flag
2323 (setq cmpl-completions-accepted-p nil)
2325 (cmpl-statistics-block
2326 (record-save-completions total-in-db total-perm total-saved))
2329 ;;;(defun autosave-completions ()
2330 ;;; (if (and save-completions-flag enable-completion cmpl-initialized-p
2331 ;;; *completion-auto-save-period*
2332 ;;; (> cmpl-emacs-idle-time *completion-auto-save-period*)
2333 ;;; cmpl-completions-accepted-p)
2334 ;;; (save-completions-to-file)))
2336 ;;;(add-hook 'cmpl-emacs-idle-time-hooks 'autosave-completions)
2338 (defun load-completions-from-file (&optional filename no-message-p)
2339 "Loads a completion init file FILENAME.
2340 If file is not specified, then use `save-completions-file-name'."
2342 (setq filename (expand-file-name (or filename save-completions-file-name)))
2343 (let* ((backup-filename (completion-backup-filename filename))
2344 (backup-readable-p (file-readable-p backup-filename))
2346 (if backup-readable-p (setq filename backup-filename))
2347 (if (file-readable-p filename)
2349 (if (not no-message-p)
2350 (message "Loading completions from %sfile %s . . ."
2351 (if backup-readable-p "backup " "") filename))
2353 (get-buffer-create " *completion-save-buffer*")
2354 (set-buffer " *completion-save-buffer*")
2355 (setq buffer-file-name filename)
2356 ;; prepare the buffer to be modified
2357 (clear-visited-file-modtime)
2360 (let ((insert-okay-p nil)
2361 (buffer (current-buffer))
2362 (current-time (cmpl-hours-since-origin))
2363 string num-uses entry last-use-time
2364 cmpl-entry cmpl-last-use-time
2365 (current-completion-source cmpl-source-init-file)
2367 (cmpl-statistics-block
2368 (aref completion-add-count-vector cmpl-source-file-parsing)))
2369 (total-in-file 0) (total-perm 0)
2371 ;; insert the file into a buffer
2373 (progn (insert-file-contents filename t)
2374 (setq insert-okay-p t))
2377 (message "File error trying to load completion file %s."
2382 (goto-char (point-min))
2386 (setq entry (read buffer))
2387 (setq total-in-file (1+ total-in-file))
2390 (stringp (setq string (car entry)))
2392 ((eq (setq last-use-time (cdr entry)) 'T)
2393 ;; handle case sensitivity
2394 (setq total-perm (1+ total-perm))
2395 (setq last-use-time t))
2396 ((eq last-use-time t)
2397 (setq total-perm (1+ total-perm)))
2398 ((integerp last-use-time))
2402 (setq cmpl-last-use-time
2403 (completion-last-use-time
2405 (add-completion-to-tail-if-new string))
2407 (if (or (eq last-use-time t)
2408 (and (> last-use-time 1000);;backcompatibility
2409 (not (eq cmpl-last-use-time t))
2410 (or (not cmpl-last-use-time)
2412 (> last-use-time cmpl-last-use-time))
2414 ;; update last-use-time
2415 (set-completion-last-use-time cmpl-entry last-use-time)
2419 (message "Error: invalid saved completion - %s"
2420 (prin1-to-string entry))
2421 ;; try to get back in sync
2422 (search-forward "\n(")
2425 (message "End of file while reading completions.")
2428 (if (= (point) (point-max))
2429 (if (not no-message-p)
2430 (message "Loading completions from file %s . . . Done."
2432 (message "End of file while reading completions.")
2436 (cmpl-statistics-block
2437 (record-load-completions
2438 total-in-file total-perm
2439 (- (aref completion-add-count-vector cmpl-source-init-file)
2444 (defun initialize-completions ()
2445 "Load the default completions file.
2446 Also sets up so that exiting emacs will automatically save the file."
2448 (cond ((not cmpl-initialized-p)
2449 (load-completions-from-file)
2451 (setq cmpl-initialized-p t)
2455 ;;;-----------------------------------------------
2456 ;;; Kill EMACS patch
2457 ;;;-----------------------------------------------
2459 (add-hook 'kill-emacs-hook
2461 (kill-emacs-save-completions)
2462 (cmpl-statistics-block
2463 (record-cmpl-kill-emacs))))
2465 ;;;-----------------------------------------------
2466 ;;; Kill region patch
2467 ;;;-----------------------------------------------
2469 (defun completion-kill-region (&optional beg end)
2470 "Kill between point and mark.
2471 The text is deleted but saved in the kill ring.
2472 The command \\[yank] can retrieve it from there.
2473 /(If you want to kill and then yank immediately, use \\[copy-region-as-kill].)
2475 This is the primitive for programs to kill text (as opposed to deleting it).
2476 Supply two arguments, character numbers indicating the stretch of text
2478 Any command that calls this function is a \"kill command\".
2479 If the previous command was also a kill command,
2480 the text killed this time appends to the text killed last time
2481 to make one entry in the kill ring.
2482 Patched to remove the most recent completion."
2484 (cond ((eq last-command 'complete)
2485 (delete-region (point) cmpl-last-insert-location)
2486 (insert cmpl-original-string)
2487 (setq completion-to-accept nil)
2488 (cmpl-statistics-block
2489 (record-complete-failed)))
2491 (kill-region beg end))))
2493 (global-set-key "\C-w" 'completion-kill-region)
2495 ;;;-----------------------------------------------
2496 ;;; Patches to self-insert-command.
2497 ;;;-----------------------------------------------
2499 ;;; Need 2 versions: generic separator chars. and space (to get auto fill
2502 ;;; All common separators (eg. space "(" ")" """) characters go through a
2503 ;;; function to add new words to the list of words to complete from:
2504 ;;; COMPLETION-SEPARATOR-SELF-INSERT-COMMAND (arg).
2505 ;;; If the character before this was an alpha-numeric then this adds the
2506 ;;; symbol before point to the completion list (using ADD-COMPLETION).
2508 (defun completion-separator-self-insert-command (arg)
2510 (use-completion-before-separator)
2511 (self-insert-command arg)
2514 (defun completion-separator-self-insert-autofilling (arg)
2516 (use-completion-before-separator)
2517 (self-insert-command arg)
2518 (and auto-fill-function
2519 (funcall auto-fill-function))
2522 ;;;-----------------------------------------------
2524 ;;;-----------------------------------------------
2526 ;;; Note that because of the way byte compiling works, none of
2527 ;;; the functions defined with this macro get byte compiled.
2529 (defmacro def-completion-wrapper (function-name type &optional new-name)
2530 "Add a call to update the completion database before function execution.
2531 TYPE is the type of the wrapper to be added. Can be :before or :under."
2532 (cond ((eq type ':separator)
2533 (list 'put (list 'quote function-name) ''completion-function
2534 ''use-completion-before-separator))
2536 (list 'put (list 'quote function-name) ''completion-function
2537 ''use-completion-before-point))
2538 ((eq type ':backward-under)
2539 (list 'put (list 'quote function-name) ''completion-function
2540 ''use-completion-backward-under))
2541 ((eq type ':backward)
2542 (list 'put (list 'quote function-name) ''completion-function
2543 ''use-completion-backward))
2545 (list 'put (list 'quote function-name) ''completion-function
2546 ''use-completion-under-point))
2547 ((eq type ':under-or-before)
2548 (list 'put (list 'quote function-name) ''completion-function
2549 ''use-completion-under-or-before-point))
2550 ((eq type ':minibuffer-separator)
2551 (list 'put (list 'quote function-name) ''completion-function
2552 ''use-completion-minibuffer-separator))))
2554 (defun use-completion-minibuffer-separator ()
2555 (let ((cmpl-syntax-table cmpl-standard-syntax-table))
2556 (use-completion-before-separator)))
2558 (defun use-completion-backward-under ()
2559 (use-completion-under-point)
2560 (if (eq last-command 'complete)
2561 ;; probably a failed completion if you have to back up
2562 (cmpl-statistics-block (record-complete-failed))))
2564 (defun use-completion-backward ()
2565 (if (eq last-command 'complete)
2566 ;; probably a failed completion if you have to back up
2567 (cmpl-statistics-block (record-complete-failed))))
2569 (defun completion-before-command ()
2570 (funcall (or (and (symbolp this-command)
2571 (get this-command 'completion-function))
2572 'use-completion-under-or-before-point)))
2573 (add-hook 'pre-command-hook 'completion-before-command)
2576 ;;;---------------------------------------------------------------------------
2577 ;;; Patches to standard keymaps insert completions
2578 ;;;---------------------------------------------------------------------------
2580 ;;;-----------------------------------------------
2582 ;;;-----------------------------------------------
2583 ;;; We've used the completion syntax table given as a guide.
2585 ;;; Global separator chars.
2586 ;;; We left out <tab> because there are too many special cases for it. Also,
2587 ;;; in normal coding it's rarely typed after a word.
2588 (global-set-key " " 'completion-separator-self-insert-autofilling)
2589 (global-set-key "!" 'completion-separator-self-insert-command)
2590 (global-set-key "%" 'completion-separator-self-insert-command)
2591 (global-set-key "^" 'completion-separator-self-insert-command)
2592 (global-set-key "&" 'completion-separator-self-insert-command)
2593 (global-set-key "(" 'completion-separator-self-insert-command)
2594 (global-set-key ")" 'completion-separator-self-insert-command)
2595 (global-set-key "=" 'completion-separator-self-insert-command)
2596 (global-set-key "`" 'completion-separator-self-insert-command)
2597 (global-set-key "|" 'completion-separator-self-insert-command)
2598 (global-set-key "{" 'completion-separator-self-insert-command)
2599 (global-set-key "}" 'completion-separator-self-insert-command)
2600 (global-set-key "[" 'completion-separator-self-insert-command)
2601 (global-set-key "]" 'completion-separator-self-insert-command)
2602 (global-set-key ";" 'completion-separator-self-insert-command)
2603 (global-set-key "\"" 'completion-separator-self-insert-command)
2604 (global-set-key "'" 'completion-separator-self-insert-command)
2605 (global-set-key "#" 'completion-separator-self-insert-command)
2606 (global-set-key "," 'completion-separator-self-insert-command)
2607 (global-set-key "?" 'completion-separator-self-insert-command)
2609 ;;; We include period and colon even though they are symbol chars because :
2610 ;;; - in text we want to pick up the last word in a sentence.
2611 ;;; - in C pointer refs. we want to pick up the first symbol
2612 ;;; - it won't make a difference for lisp mode (package names are short)
2613 (global-set-key "." 'completion-separator-self-insert-command)
2614 (global-set-key ":" 'completion-separator-self-insert-command)
2617 (define-key lisp-mode-map "!" 'self-insert-command)
2618 (define-key lisp-mode-map "&" 'self-insert-command)
2619 (define-key lisp-mode-map "%" 'self-insert-command)
2620 (define-key lisp-mode-map "?" 'self-insert-command)
2621 (define-key lisp-mode-map "=" 'self-insert-command)
2622 (define-key lisp-mode-map "^" 'self-insert-command)
2625 (def-completion-wrapper electric-c-semi :separator)
2626 (define-key c-mode-map "+" 'completion-separator-self-insert-command)
2627 (define-key c-mode-map "*" 'completion-separator-self-insert-command)
2628 (define-key c-mode-map "/" 'completion-separator-self-insert-command)
2630 ;;; FORTRAN mode diffs. (these are defined when fortran is called)
2631 (defun completion-setup-fortran-mode ()
2632 (define-key fortran-mode-map "+" 'completion-separator-self-insert-command)
2633 (define-key fortran-mode-map "-" 'completion-separator-self-insert-command)
2634 (define-key fortran-mode-map "*" 'completion-separator-self-insert-command)
2635 (define-key fortran-mode-map "/" 'completion-separator-self-insert-command)
2638 ;;;-----------------------------------------------
2639 ;;; End of line chars.
2640 ;;;-----------------------------------------------
2641 (def-completion-wrapper newline :separator)
2642 (def-completion-wrapper newline-and-indent :separator)
2643 (def-completion-wrapper comint-send-input :separator)
2644 (def-completion-wrapper exit-minibuffer :minibuffer-separator)
2645 (def-completion-wrapper eval-print-last-sexp :separator)
2646 (def-completion-wrapper eval-last-sexp :separator)
2647 ;;(def-completion-wrapper minibuffer-complete-and-exit :minibuffer)
2649 ;;;-----------------------------------------------
2651 ;;;-----------------------------------------------
2653 (def-completion-wrapper next-line :under-or-before)
2654 (def-completion-wrapper previous-line :under-or-before)
2655 (def-completion-wrapper beginning-of-buffer :under-or-before)
2656 (def-completion-wrapper end-of-buffer :under-or-before)
2657 (def-completion-wrapper beginning-of-line :under-or-before)
2658 (def-completion-wrapper end-of-line :under-or-before)
2659 (def-completion-wrapper forward-char :under-or-before)
2660 (def-completion-wrapper forward-word :under-or-before)
2661 (def-completion-wrapper forward-sexp :under-or-before)
2662 (def-completion-wrapper backward-char :backward-under)
2663 (def-completion-wrapper backward-word :backward-under)
2664 (def-completion-wrapper backward-sexp :backward-under)
2666 (def-completion-wrapper delete-backward-char :backward)
2667 (def-completion-wrapper delete-backward-char-untabify :backward)
2675 (cmpl-statistics-block
2676 (record-completion-file-loaded))
2678 ;;; completion.el ends here