]> code.delx.au - gnu-emacs/blob - lisp/completion.el
Don't use cl. Eliminate use of when, unless,
[gnu-emacs] / lisp / completion.el
1 ;;; completion.el --- dynamic word-completion code
2 ;; Copyright (C) 1990, 1993 Free Software Foundation, Inc.
3
4 ;; Maintainer: FSF
5 ;; Keywords: abbrev
6 ;; Author: Jim Salem <salem@think.com> and Brewster Kahle <brewster@think.com>
7 ;; of Thinking Machines Inc.
8
9 ;; This file is part of GNU Emacs.
10
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)
14 ;; any later version.
15
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.
20
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.
24
25 ;;; Commentary:
26 ;;;
27 ;;; What to put in .emacs
28 ;;;-----------------------
29 ;;; (load "completion")
30 ;;; (initialize-completions)
31 \f
32 ;;;---------------------------------------------------------------------------
33 ;;; Documentation [Slightly out of date]
34 ;;;---------------------------------------------------------------------------
35 ;;; (also check the documentation string of the functions)
36 ;;;
37 ;;; Introduction
38 ;;;---------------
39 ;;;
40 ;;; After you type a few characters, pressing the "complete" key inserts
41 ;;; the rest of the word you are likely to type.
42 ;;;
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.
48 ;;;
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.
52 ;;;
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.
57 ;;;
58 ;;; You automatically save the completions you use to a file between
59 ;;; sessions.
60 ;;;
61 ;;; Completion enables programmers to enter longer, more descriptive
62 ;;; variable names while typing fewer keystrokes than they normally would.
63 ;;;
64 ;;;
65 ;;; Full documentation
66 ;;;---------------------
67 ;;;
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.
73 ;;;
74 ;;; When you load this file, completion will be on. I suggest you use the
75 ;;; compiled version (because it is noticeably faster).
76 ;;;
77 ;;; M-X completion-mode toggles whether or not new words are added to the
78 ;;; database by changing the value of enable-completion.
79 ;;;
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.
88 ;;;
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).
93 ;;;
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
97 ;;;
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.
101 ;;;
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)
108 ;;;
109 ;;; HOW THE DATABASE IS MAINTAINED
110 ;;; <write>
111 ;;;
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
117 ;;;
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.
122 ;;;
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.
126 ;;;
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.
130 ;;;
131 ;;; HOW A COMPLETION IS FOUND
132 ;;; <write>
133 ;;;
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]
140 ;;;
141 ;;; INITIALIZATION
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.
146 ;;;
147 ;;;---------------------------------------------------------------------------
148 ;;;
149 ;;;
150 \f
151 ;;;---------------------------------------------------------------------------
152 ;;; Functions you might like to call
153 ;;;---------------------------------------------------------------------------
154 ;;;
155 ;;; add-completion string &optional num-uses
156 ;;; Adds a new string to the database
157 ;;;
158 ;;; add-permanent-completion string
159 ;;; Adds a new string to the database with num-uses = T
160 ;;;
161
162 ;;; kill-completion string
163 ;;; Kills the completion from the database.
164 ;;;
165 ;;; clear-all-completions
166 ;;; Clears the database
167 ;;;
168 ;;; list-all-completions
169 ;;; Returns a list of all completions.
170 ;;;
171 ;;;
172 ;;; next-completion string &optional index
173 ;;; Returns a completion entry that starts with string.
174 ;;;
175 ;;; find-exact-completion string
176 ;;; Returns a completion entry that exactly matches string.
177 ;;;
178 ;;; complete
179 ;;; Inserts a completion at point
180 ;;;
181 ;;; initialize-completions
182 ;;; Loads the completions file and sets up so that exiting emacs will
183 ;;; save them.
184 ;;;
185 ;;; save-completions-to-file &optional filename
186 ;;; load-completions-from-file &optional filename
187 ;;;
188 ;;;-----------------------------------------------
189 ;;; Other functions
190 ;;;-----------------------------------------------
191 ;;;
192 ;;; get-completion-list string
193 ;;;
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
200 ;;;
201 ;;;
202 \f
203 ;;;-----------------------------------------------
204 ;;; To Do :: (anybody ?)
205 ;;;-----------------------------------------------
206 ;;;
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
212 ;;;
213 ;;;
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 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.
229 ;;;
230 ;;;-----------------------------------------------
231 ;;; Acknowledgements
232 ;;;-----------------------------------------------
233 ;;; Cliff Lasser (cal@think.com), Kevin Herbert (kph@cisco.com),
234 ;;; eero@media-lab, kgk@cs.brown.edu, jla@ai.mit.edu,
235 ;;;
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
244 ;;;
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)
248 ;;;
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)
254 ;;;
255 ;;; From Version 6 to 7
256 ;;; - Fixed bug with saving out .completion file the first time
257 ;;;
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
263 ;;;
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)
273 \f
274 ;;; Code:
275
276 ;;;---------------------------------------------------------------------------
277 ;;; User changeable parameters
278 ;;;---------------------------------------------------------------------------
279
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.")
283
284 (defvar save-completions-flag t
285 "*Non-nil means save most-used completions when exiting Emacs.
286 See also `saved-completions-retention-time'.")
287
288 (defvar save-completions-file-name "~/.completions"
289 "*The filename to save completions to.")
290
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.")
295
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.")
299
300 (defvar completions-file-versions-kept kept-new-versions
301 "*Number of versions to keep for the saved completions file.")
302
303 (defvar completion-prompt-speed-threshold 4800
304 "*Minimum output speed at which to display next potential completion.")
305
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.")
309
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.")
313
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.")
318
319 ;;;(defvar *record-cmpl-statistics-p* nil
320 ;;; "*If non-nil, record completion statistics.")
321
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.")
325
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.")
329
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.")
333
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.")
337
338 (defmacro eval-when-compile-load-eval (&rest body)
339 ;; eval everything before expanding
340 (mapcar 'eval body)
341 (cons 'progn body))
342
343 (eval-when-compile
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)))))
353
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
363 (list 'cdr temp)))))
364 (if (cdr (cdr spec))
365 (cons (list 'setq (car spec) nil) (cdr (cdr spec)))
366 '(nil)))))
367
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)))
374
375 (completion-eval-when)
376
377 ;;;---------------------------------------------------------------------------
378 ;;; Internal Variables
379 ;;;---------------------------------------------------------------------------
380
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.")
384
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.")
388
389 (defvar cmpl-preceding-syntax)
390 \f
391 ;;;---------------------------------------------------------------------------
392 ;;; Low level tools
393 ;;;---------------------------------------------------------------------------
394
395 ;;;-----------------------------------------------
396 ;;; Misc.
397 ;;;-----------------------------------------------
398
399 (defun minibuffer-window-selected-p ()
400 "True iff the current window is the minibuffer."
401 (window-minibuffer-p (selected-window)))
402
403 ;; This used to be `(eval form)'. Eval FORM at run time now.
404 (defmacro cmpl-read-time-eval (form)
405 form)
406
407 ;;;-----------------------------------------------
408 ;;; String case coercion
409 ;;;-----------------------------------------------
410
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)))
418 ':capitalized)
419 (t
420 ':mixed)))
421 (t ':down)))
422 (t
423 (cond ((string-match "[A-Z]" string)
424 ':up)
425 (t ':neither))))
426 ))
427
428 ;;; Tests -
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
434
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)))
441 string)
442 (t string)
443 ))
444
445 (defun cmpl-merge-string-cases (string-to-coerce given-string)
446 (let ((string-case-type (cmpl-string-case-type string-to-coerce))
447 )
448 (cond ((memq string-case-type '(:down :up :capitalized))
449 ;; Found string is in a standard case. Coerce to a type based on
450 ;; the given string
451 (cmpl-coerce-string-case string-to-coerce
452 (cmpl-string-case-type given-string))
453 )
454 (t
455 ;; If the found string is in some unusual case, just insert it
456 ;; as is
457 string-to-coerce)
458 )))
459
460 ;;; Tests -
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
465
466 \f
467 (defun cmpl-hours-since-origin ()
468 (let ((time (current-time)))
469 (truncate
470 (+ (* (/ (car time) 3600.0) (lsh 1 16))
471 (/ (nth 2 time) 3600.0)))))
472 \f
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 ::
480 ;;;
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
484 ;;;
485 ;;; Thus by judicious use of scan-sexps and forward-word, we can get
486 ;;; the word we want relatively fast and without consing.
487 ;;;
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.
495
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>
501
502 ;;; Mode specific differences and notes ::
503 ;;; LISP diffs ->
504 ;;; Symbol chars :: ! & ? = ^
505 ;;;
506 ;;; C diffs ->
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
511 ;;; concerned.
512 ;;;
513 ;;; FORTRAN diffs ->
514 ;;; Separator chars :: + - * / :
515 ;;;
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
520 ;;; like.
521
522 ;;;-----------------------------------------------
523 ;;; Table definitions
524 ;;;-----------------------------------------------
525
526 (defun cmpl-make-standard-completion-syntax-table ()
527 (let ((table (make-vector 256 0)) ;; default syntax is whitespace
528 i)
529 ;; alpha chars
530 (setq i 0)
531 (while (< i 26)
532 (modify-syntax-entry (+ ?a i) "_" table)
533 (modify-syntax-entry (+ ?A i) "_" table)
534 (setq i (1+ i)))
535 ;; digit chars.
536 (setq i 0)
537 (while (< i 10)
538 (modify-syntax-entry (+ ?0 i) "_" table)
539 (setq i (1+ i)))
540 ;; Other ones
541 (let ((symbol-chars '(?@ ?/ ?\\ ?* ?+ ?~ ?$ ?< ?> ?%))
542 (symbol-chars-ignore '(?_ ?- ?: ?.))
543 )
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)
548 )
549 )
550 table))
551
552 (defconst cmpl-standard-syntax-table (cmpl-make-standard-completion-syntax-table))
553
554 (defun cmpl-make-lisp-completion-syntax-table ()
555 (let ((table (copy-syntax-table cmpl-standard-syntax-table))
556 (symbol-chars '(?! ?& ?? ?= ?^))
557 )
558 (completion-dolist (char symbol-chars)
559 (modify-syntax-entry char "_" table))
560 table))
561
562 (defun cmpl-make-c-completion-syntax-table ()
563 (let ((table (copy-syntax-table cmpl-standard-syntax-table))
564 (separator-chars '(?+ ?* ?/ ?: ?%))
565 )
566 (completion-dolist (char separator-chars)
567 (modify-syntax-entry char " " table))
568 table))
569
570 (defun cmpl-make-fortran-completion-syntax-table ()
571 (let ((table (copy-syntax-table cmpl-standard-syntax-table))
572 (separator-chars '(?+ ?- ?* ?/ ?:))
573 )
574 (completion-dolist (char separator-chars)
575 (modify-syntax-entry char " " table))
576 table))
577
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))
581
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)
585
586 ;;;-----------------------------------------------
587 ;;; Installing the appropriate mode tables
588 ;;;-----------------------------------------------
589
590 (add-hook 'lisp-mode-hook
591 '(lambda ()
592 (setq cmpl-syntax-table cmpl-lisp-syntax-table)))
593
594 (add-hook 'c-mode-hook
595 '(lambda ()
596 (setq cmpl-syntax-table cmpl-c-syntax-table)))
597
598 (add-hook 'fortran-mode-hook
599 '(lambda ()
600 (setq cmpl-syntax-table cmpl-fortran-syntax-table)
601 (completion-setup-fortran-mode)))
602
603 ;;;-----------------------------------------------
604 ;;; Symbol functions
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)
614
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)
620 (cond
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)
629 (forward-word 1)
630 (setq cmpl-symbol-start (point))
631 (goto-char cmpl-saved-point)
632 ))
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)
636 (forward-word -1)
637 (setq cmpl-symbol-end (point))
638 (goto-char cmpl-saved-point)
639 ))
640 ;; restore state
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))
648 )
649 (t
650 ;; restore table if no symbol
651 (set-syntax-table cmpl-saved-syntax)
652 nil)
653 ))
654
655 ;;; tests for symbol-under-point
656 ;;; `^' indicates cursor pos. where value is returned
657 ;;; simple-word-test
658 ;;; ^^^^^^^^^^^^^^^^ --> simple-word-test
659 ;;; _harder_word_test_
660 ;;; ^^^^^^^^^^^^^^^^^^ --> harder_word_test
661 ;;; .___.______.
662 ;;; --> nil
663 ;;; /foo/bar/quux.hello
664 ;;; ^^^^^^^^^^^^^^^^^^^ --> /foo/bar/quux.hello
665 ;;;
666
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)
678 )
679 ;; remove chars to ignore at the start
680 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
681 (goto-char cmpl-symbol-start)
682 (forward-word 1)
683 (setq cmpl-symbol-start (point))
684 (goto-char cmpl-symbol-end)
685 ))
686 ;; restore state
687 (set-syntax-table cmpl-saved-syntax)
688 ;; return value if long enough
689 (if (>= cmpl-symbol-end
690 (+ cmpl-symbol-start
691 (cmpl-read-time-eval completion-min-length)))
692 (buffer-substring cmpl-symbol-start cmpl-symbol-end))
693 )
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
699 (forward-word -1)
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)
704 (forward-word 1)
705 (setq cmpl-symbol-start (point))
706 ))
707 ;; restore state
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))
716 )
717 (t
718 ;; restore table if no symbol
719 (set-syntax-table cmpl-saved-syntax)
720 nil)
721 ))
722
723 ;;; tests for symbol-before-point
724 ;;; `^' indicates cursor pos. where value is returned
725 ;;; simple-word-test
726 ;;; ^ --> nil
727 ;;; ^ --> nil
728 ;;; ^ --> simple-w
729 ;;; ^ --> simple-word-test
730 ;;; _harder_word_test_
731 ;;; ^ --> harder_word_test
732 ;;; ^ --> harder_word_test
733 ;;; ^ --> harder
734 ;;; .___....
735 ;;; --> nil
736
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))
747 (t
748 (set-syntax-table cmpl-saved-syntax)
749 (symbol-before-point))
750 ))
751
752
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
756 ;; end chars."
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)))
761 '(?_ ?w))
762 (setq cmpl-symbol-end (point)
763 cmpl-symbol-start (scan-sexps (1+ cmpl-symbol-end) -1)
764 )
765 ;; remove chars to ignore at the start
766 (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
767 (goto-char cmpl-symbol-start)
768 (forward-word 1)
769 (setq cmpl-symbol-start (point))
770 (goto-char cmpl-symbol-end)
771 ))
772 ;; restore state
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))
781 )
782 (t
783 ;; restore table if no symbol
784 (set-syntax-table cmpl-saved-syntax)
785 nil)
786 ))
787
788 ;;; tests for symbol-before-point-for-complete
789 ;;; `^' indicates cursor pos. where value is returned
790 ;;; simple-word-test
791 ;;; ^ --> nil
792 ;;; ^ --> nil
793 ;;; ^ --> simple-w
794 ;;; ^ --> simple-word-test
795 ;;; _harder_word_test_
796 ;;; ^ --> harder_word_test
797 ;;; ^ --> harder_word_test_
798 ;;; ^ --> harder_
799 ;;; .___....
800 ;;; --> nil
801
802
803 \f
804 ;;;---------------------------------------------------------------------------
805 ;;; Statistics Recording
806 ;;;---------------------------------------------------------------------------
807
808 ;;; Note that the guts of this has been turned off. The guts
809 ;;; are in completion-stats.el.
810
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."
817 ;;; (list 'cond
818 ;;; (list* '*record-cmpl-statistics-p* body)
819 ;;; ))
820
821 ;;;-----------------------------------------------
822 ;;; Completion Sources
823 ;;;-----------------------------------------------
824
825 ;; ID numbers
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)
835
836
837 \f
838 ;;;---------------------------------------------------------------------------
839 ;;; Completion Method #2: dabbrev-expand style
840 ;;;---------------------------------------------------------------------------
841 ;;;
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.
849 ;;;
850
851 (defvar cdabbrev-completions-tried nil)
852 ;;; "A list of all the cdabbrev completions since the last reset.")
853
854 (defvar cdabbrev-current-point 0)
855 ;;; "The current point position the cdabbrev search is at.")
856
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.")
860
861 (defvar cdabbrev-wrapped-p nil)
862 ;;; "T if the cdabbrev search has wrapped around the file.")
863
864 (defvar cdabbrev-abbrev-string "")
865 (defvar cdabbrev-start-point 0)
866 (defvar cdabbrev-stop-point)
867
868 ;;; Test strings for cdabbrev
869 ;;; cdat-upcase ;;same namestring
870 ;;; CDAT-UPCASE ;;ok
871 ;;; cdat2 ;;too short
872 ;;; cdat-1-2-3-4 ;;ok
873 ;;; a-cdat-1 ;;doesn't start correctly
874 ;;; cdat-simple ;;ok
875
876
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
880 during the search."
881 (setq cdabbrev-abbrev-string abbrev-string
882 cdabbrev-completions-tried
883 (cons (downcase abbrev-string) initial-completions-tried)
884 )
885 (reset-cdabbrev-window t)
886 )
887
888 (defun set-cdabbrev-buffer ()
889 ;; cdabbrev-current-window must not be NIL
890 (set-buffer (if (eq cdabbrev-current-window t)
891 (other-buffer)
892 (window-buffer cdabbrev-current-window)))
893 )
894
895
896 (defun reset-cdabbrev-window (&optional initializep)
897 "Resets the cdabbrev search to search for abbrev-string."
898 ;; Set the window
899 (cond (initializep
900 (setq cdabbrev-current-window (selected-window))
901 )
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)))
910 )
911 (if cdabbrev-current-window
912 (save-excursion
913 (set-cdabbrev-buffer)
914 (setq cdabbrev-current-point (point)
915 cdabbrev-start-point cdabbrev-current-point
916 cdabbrev-stop-point
917 (if completion-search-distance
918 (max (point-min)
919 (- cdabbrev-start-point completion-search-distance))
920 (point-min))
921 cdabbrev-wrapped-p nil)
922 )))
923
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
931 (let (saved-point
932 saved-syntax
933 (expansion nil)
934 downcase-expansion tried-list syntax saved-point-2)
935 (save-excursion
936 (unwind-protect
937 (progn
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
947 (while
948 ;; This code returns t if it should loop again
949 (cond
950 (;; search for the string
951 (search-backward cdabbrev-abbrev-string cdabbrev-stop-point t)
952 ;; return nil if the completion is valid
953 (not
954 (and
955 ;; does it start with a separator char ?
956 (or (= (setq syntax (char-syntax (preceding-char))) ? )
957 (and (= syntax ?w)
958 ;; symbol char to ignore at end. Are we at end ?
959 (progn
960 (setq saved-point-2 (point))
961 (forward-word -1)
962 (prog1
963 (= (char-syntax (preceding-char)) ? )
964 (goto-char saved-point-2)
965 ))))
966 ;; is the symbol long enough ?
967 (setq expansion (symbol-under-point))
968 ;; have we not tried this one before
969 (progn
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
975 (car tried-list))))
976 ;; Already tried, don't choose this one
977 (setq tried-list (cdr tried-list))
978 )
979 ;; at this point tried-list will be nil if this
980 ;; expansion has not yet been tried
981 (if tried-list
982 (setq expansion nil)
983 t)
984 ))))
985 ;; search failed
986 (cdabbrev-wrapped-p
987 ;; If already wrapped, then we've failed completely
988 nil)
989 (t
990 ;; need to wrap
991 (goto-char (setq cdabbrev-current-point
992 (if completion-search-distance
993 (min (point-max) (+ cdabbrev-start-point completion-search-distance))
994 (point-max))))
995
996 (setq cdabbrev-wrapped-p t))
997 ))
998 ;; end of while loop
999 (cond (expansion
1000 ;; successful
1001 (setq cdabbrev-completions-tried
1002 (cons downcase-expansion cdabbrev-completions-tried)
1003 cdabbrev-current-point (point))))
1004 )
1005 (set-syntax-table saved-syntax)
1006 (goto-char saved-point)
1007 ))
1008 ;; If no expansion, go to next window
1009 (cond (expansion)
1010 (t (reset-cdabbrev-window)
1011 (next-cdabbrev))))))
1012
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
1023
1024 ;;; _cdat_start_sym
1025 ;;; cdat-wrapping
1026
1027 \f
1028 ;;;---------------------------------------------------------------------------
1029 ;;; Completion Database
1030 ;;;---------------------------------------------------------------------------
1031
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
1039
1040 ;;; bad things may happen if this length is changed due to the way
1041 ;;; GNU implements obarrays
1042 (defconst cmpl-obarray-length 511)
1043
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.")
1047
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.")
1051
1052 ;;;-----------------------------------------------
1053 ;;; Completion Entry Structure Definition
1054 ;;;-----------------------------------------------
1055
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.
1060
1061 ;;; We chose lists because (car foo) is faster than (aref foo 0) and the
1062 ;;; creation time is about the same.
1063
1064 ;;; READER MACROS
1065
1066 (defmacro completion-string (completion-entry)
1067 (list 'car completion-entry))
1068
1069 (defmacro completion-num-uses (completion-entry)
1070 ;; "The number of times it has used. Used to decide whether to save
1071 ;; it."
1072 (list 'car (list 'cdr completion-entry)))
1073
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))
1078
1079 (defmacro completion-source (completion-entry)
1080 (list 'nth 3 completion-entry))
1081
1082 ;;; WRITER MACROS
1083 (defmacro set-completion-string (completion-entry string)
1084 (list 'setcar completion-entry string))
1085
1086 (defmacro set-completion-num-uses (completion-entry num-uses)
1087 (list 'setcar (list 'cdr completion-entry) num-uses))
1088
1089 (defmacro set-completion-last-use-time (completion-entry last-use-time)
1090 (list 'setcar (list 'cdr (list 'cdr completion-entry)) last-use-time))
1091
1092 ;;; CONSTRUCTOR
1093 (defun make-completion (string)
1094 "Returns a list of a completion entry."
1095 (list (list string 0 nil current-completion-source)))
1096
1097 ;; Obsolete
1098 ;;(defmacro cmpl-prefix-entry-symbol (completion-entry)
1099 ;; (list 'car (list 'cdr completion-entry)))
1100
1101
1102 \f
1103 ;;;-----------------------------------------------
1104 ;;; Prefix symbol entry definition
1105 ;;;-----------------------------------------------
1106 ;;; A cons of (head . tail)
1107
1108 ;;; READER Macros
1109
1110 (defmacro cmpl-prefix-entry-head (prefix-entry)
1111 (list 'car prefix-entry))
1112
1113 (defmacro cmpl-prefix-entry-tail (prefix-entry)
1114 (list 'cdr prefix-entry))
1115
1116 ;;; WRITER Macros
1117
1118 (defmacro set-cmpl-prefix-entry-head (prefix-entry new-head)
1119 (list 'setcar prefix-entry new-head))
1120
1121 (defmacro set-cmpl-prefix-entry-tail (prefix-entry new-tail)
1122 (list 'setcdr prefix-entry new-tail))
1123
1124 ;;; Constructor
1125
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))
1129
1130 ;;;-----------------------------------------------
1131 ;;; Completion Database - Utilities
1132 ;;;-----------------------------------------------
1133
1134 (defun clear-all-completions ()
1135 "Initializes the completion storage. All existing completions are lost."
1136 (interactive)
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))
1141 )
1142
1143 (defvar completions-list-return-value)
1144
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))
1150
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))))
1156
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))
1162
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))))
1168
1169 \f
1170 ;;;-----------------------------------------------
1171 ;;; Updating the database
1172 ;;;-----------------------------------------------
1173 ;;;
1174 ;;; These are the internal functions used to update the datebase
1175 ;;;
1176 ;;;
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
1180
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.")
1191
1192 ;;; READS
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))
1198 cmpl-obarray)))
1199 (symbol-value cmpl-db-symbol)
1200 ))
1201
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)))
1210
1211 (defvar inside-locate-completion-entry nil)
1212 ;; used to trap lossage in silent error correction
1213
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))
1220 next-prefix-list
1221 )
1222 (cond
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)))
1228 )))
1229 (setq prefix-list next-prefix-list))
1230 (cond (;; found
1231 prefix-list)
1232 ;; Didn't find it. Database is messed up.
1233 (cmpl-db-debug-p
1234 ;; not found, error if debug mode
1235 (error "Completion entry exists but not on prefix list - %s"
1236 completion-string))
1237 (inside-locate-completion-entry
1238 ;; recursive error: really scrod
1239 (locate-completion-db-error))
1240 (t
1241 ;; Patch out
1242 (set cmpl-db-symbol nil)
1243 ;; Retry
1244 (locate-completion-entry-retry completion-entry)
1245 ))))))
1246
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)))
1253 (pref-entry
1254 (if cmpl-entry
1255 (find-cmpl-prefix-entry
1256 (substring cmpl-db-downcase-string
1257 0 completion-prefix-min-length))))
1258 )
1259 (if (and cmpl-entry pref-entry)
1260 ;; try again
1261 (locate-completion-entry cmpl-entry pref-entry)
1262 ;; still losing
1263 (locate-completion-db-error))
1264 )))
1265
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.")
1269 )
1270
1271 ;;; WRITES
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)
1280 ;; not there
1281 (let (;; create an entry
1282 (entry (make-completion string))
1283 ;; setup the prefix
1284 (prefix-entry (find-cmpl-prefix-entry
1285 (substring cmpl-db-downcase-string 0
1286 (cmpl-read-time-eval
1287 completion-prefix-min-length))))
1288 )
1289 ;; The next two forms should happen as a unit (atomically) but
1290 ;; no fatal errors should result if that is not the case.
1291 (cond (prefix-entry
1292 ;; These two should be atomic, but nothing fatal will happen
1293 ;; if they're not.
1294 (setcdr (cmpl-prefix-entry-tail prefix-entry) entry)
1295 (set-cmpl-prefix-entry-tail prefix-entry entry))
1296 (t
1297 (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))
1298 ))
1299 ;; statistics
1300 (cmpl-statistics-block
1301 (note-added-completion))
1302 ;; set symbol
1303 (set cmpl-db-symbol (car entry))
1304 )))
1305
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))
1318 ;; found
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))
1325 )
1326 ;; update entry
1327 (set-completion-string cmpl-db-entry completion-string)
1328 ;; move to head (if necessary)
1329 (cond (splice-ptr
1330 ;; These should all execute atomically but it is not fatal if
1331 ;; they don't.
1332 ;; splice it out
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)
1339 ))
1340 cmpl-db-entry)
1341 ;; not there
1342 (let (;; create an entry
1343 (entry (make-completion completion-string))
1344 ;; setup the prefix
1345 (prefix-entry (find-cmpl-prefix-entry
1346 (substring cmpl-db-downcase-string 0
1347 (cmpl-read-time-eval
1348 completion-prefix-min-length))))
1349 )
1350 (cond (prefix-entry
1351 ;; Splice in at head
1352 (setcdr entry (cmpl-prefix-entry-head prefix-entry))
1353 (set-cmpl-prefix-entry-head prefix-entry entry))
1354 (t
1355 ;; Start new prefix entry
1356 (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))
1357 ))
1358 ;; statistics
1359 (cmpl-statistics-block
1360 (note-added-completion))
1361 ;; Add it to the symbol
1362 (set cmpl-db-symbol (car entry))
1363 )))
1364
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))
1371 ;; found
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))
1377 )
1378 ;; delete symbol reference
1379 (set cmpl-db-symbol nil)
1380 ;; remove from prefix list
1381 (cond (splice-ptr
1382 ;; not at head
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))
1386 )
1387 (t
1388 ;; at head
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))
1393 ))
1394 (cmpl-statistics-block
1395 (note-completion-deleted))
1396 )
1397 (error "Unknown completion `%s'" completion-string)
1398 ))
1399
1400 ;;; Tests --
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" ...))
1414 ;;;
1415 ;;; - Deleting -
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
1429 ;;;
1430 ;;; - Tail -
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" ...))
1437 ;;;
1438
1439 \f
1440 ;;;---------------------------------------------------------------------------
1441 ;;; Database Update :: Interface level routines
1442 ;;;---------------------------------------------------------------------------
1443 ;;;
1444 ;;; These lie on top of the database ref. functions but below the standard
1445 ;;; user interface level
1446
1447
1448 (defun interactive-completion-string-reader (prompt)
1449 (let* ((default (symbol-under-or-before-point))
1450 (new-prompt
1451 (if default
1452 (format "%s: (default: %s) " prompt default)
1453 (format "%s: " prompt))
1454 )
1455 (read (completing-read new-prompt cmpl-obarray))
1456 )
1457 (if (zerop (length read)) (setq read (or default "")))
1458 (list read)
1459 ))
1460
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"
1464 string)
1465 (list string)))
1466
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
1470 specified."
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)))
1477
1478 (if num-uses (set-completion-num-uses entry num-uses))
1479 (if last-use-time
1480 (set-completion-last-use-time entry last-use-time))
1481 ))
1482
1483 (defun add-permanent-completion (string)
1484 "Add STRING if it isn't already listed, and mark it permanent."
1485 (interactive
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))
1490 )
1491 (add-completion string nil t)
1492 ))
1493
1494 (defun kill-completion (string)
1495 (interactive (interactive-completion-string-reader "Completion to kill"))
1496 (check-completion-length string)
1497 (delete-completion string)
1498 )
1499
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)
1507 entry
1508 )
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)
1513 ))
1514
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))))
1520
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))))
1526
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))))
1532
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)
1539 entry)
1540 (cmpl-statistics-block
1541 (note-separator-character string)
1542 )
1543 (cond (string
1544 (setq entry (add-completion-to-head string))
1545 (if (and completion-on-separator-character
1546 (zerop (completion-num-uses entry)))
1547 (progn
1548 (set-completion-num-uses entry 1)
1549 (setq cmpl-completions-accepted-p t)))))
1550 ))
1551
1552 ;;; Tests --
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" ...))
1560 ;;;
1561 ;;; - Accepting -
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 ...))
1570 ;;;
1571 ;;; - Deleting -
1572 ;;; (kill-completion "banish")
1573 ;;; (car (find-cmpl-prefix-entry "ban")) --> (("banner" ...) ("banana" ...))
1574
1575 \f
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
1581 ;;;
1582
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."
1603
1604
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)
1616 )
1617
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
1622 cmpl-last-index -1
1623 cmpl-tried-list nil
1624 ))
1625
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."
1630 (cond
1631 ((= index (setq cmpl-last-index (1+ cmpl-last-index)))
1632 (completion-search-peek t))
1633 ((< index 0)
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)
1642 )
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))
1649 (t
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))
1655 )))
1656 (t
1657 ;; non-negative index, reset and search
1658 ;;(prin1 'reset)
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)
1664 ))
1665 )
1666 (prog1
1667 cmpl-next-possibility
1668 (setq cmpl-next-possibility nil)
1669 ))
1670
1671
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."
1677 (cond
1678 ;; return the cached value if we have it
1679 (cmpl-next-possibility)
1680 ((and cmpl-next-possibilities
1681 ;; still a few possibilities left
1682 (progn
1683 (while
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))
1687 ))
1688 cmpl-next-possibilities
1689 ))
1690 ;; successful match
1691 (setq cmpl-next-possibility (car cmpl-next-possibilities)
1692 cmpl-tried-list (cons (downcase (completion-string cmpl-next-possibility))
1693 cmpl-tried-list)
1694 cmpl-next-possibilities (cdr cmpl-next-possibilities)
1695 )
1696 cmpl-next-possibility)
1697 (use-cdabbrev
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)
1702 ))
1703 (setq cmpl-next-possibility (next-cdabbrev))
1704 )
1705 ;; Completely unsuccessful, return nil
1706 ))
1707
1708 ;;; Tests --
1709 ;;; - Add and Find -
1710 ;;; (add-completion "banana")
1711 ;;; (completion-search-reset "ban")
1712 ;;; (completion-search-next 0) --> "banana"
1713 ;;;
1714 ;;; - Discrimination -
1715 ;;; (add-completion "cumberland")
1716 ;;; (add-completion "cumberbund")
1717 ;;; cumbering
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}
1728 ;;;
1729 ;;; - Accepting -
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"
1735 ;;;
1736 ;;; - Deleting -
1737 ;;; (kill-completion "cumberland")
1738 ;;; cummings
1739 ;;; (completion-search-reset "cum")
1740 ;;; (completion-search-next 0) --> "cumberbund"
1741 ;;; (completion-search-next 1) --> "cummings"
1742 ;;;
1743 ;;; - Ignoring Capitalization -
1744 ;;; (completion-search-reset "CuMb")
1745 ;;; (completion-search-next 0) --> "cumberbund"
1746
1747
1748 \f
1749 ;;;-----------------------------------------------
1750 ;;; COMPLETE
1751 ;;;-----------------------------------------------
1752
1753 (defun completion-mode ()
1754 "Toggles whether or not to add new words to the completion database."
1755 (interactive)
1756 (setq enable-completion (not enable-completion))
1757 (message "Completion mode is now %s." (if enable-completion "ON" "OFF"))
1758 )
1759
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)
1764
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.
1768 Prefix args ::
1769 control-u :: leave the point at the beginning of the completion rather
1770 than at the end.
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.}"
1774 (interactive "*p")
1775 ;;; Set up variables
1776 (cond ((eq last-command this-command)
1777 ;; Undo last one
1778 (delete-region cmpl-last-insert-location (point))
1779 ;; get next completion
1780 (setq cmpl-current-index (+ cmpl-current-index (or arg 1)))
1781 )
1782 (t
1783 (if (not cmpl-initialized-p)
1784 (initialize-completions)) ;; make sure everything's loaded
1785 (cond ((consp current-prefix-arg) ;; control-u
1786 (setq arg 0)
1787 (setq cmpl-leave-point-at-start t)
1788 )
1789 (t
1790 (setq cmpl-leave-point-at-start nil)
1791 ))
1792 ;; get string
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)))
1798 ;; get index
1799 (setq cmpl-current-index (if current-prefix-arg arg 0))
1800 ;; statistics
1801 (cmpl-statistics-block
1802 (note-complete-entered-afresh cmpl-original-string))
1803 ;; reset database
1804 (completion-search-reset cmpl-original-string)
1805 ;; erase what we've got
1806 (delete-region cmpl-symbol-start cmpl-symbol-end)
1807 ))
1808
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))
1816 string
1817 )
1818 ;; entry is either a completion entry or a string (if cdabbrev)
1819
1820 ;; If found, insert
1821 (cond (entry
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))
1827 ;; insert
1828 (insert string)
1829 ;; accept it
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))
1835 (t;; point at end,
1836 (setq cmpl-last-insert-location insert-point))
1837 )
1838 ;; statistics
1839 (cmpl-statistics-block
1840 (note-complete-inserted entry cmpl-current-index))
1841 ;; Done ! cmpl-stat-complete-successful
1842 ;;display the next completion
1843 (cond
1844 ((and print-status-p
1845 ;; This updates the display and only prints if there
1846 ;; is no typeahead
1847 (sit-for 0)
1848 (setq entry
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)
1856 ))
1857 )
1858 (t;; none found, insert old
1859 (insert cmpl-original-string)
1860 ;; Don't accept completions
1861 (setq completion-to-accept nil)
1862 ;; print message
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 " "")))
1868 ;; statistics
1869 (cmpl-statistics-block
1870 (record-complete-failed cmpl-current-index))
1871 ;; Pretend that we were never here
1872 (setq this-command 'failed-complete)
1873 ))))
1874
1875 ;;;-----------------------------------------------
1876 ;;; "Complete" Key Keybindings
1877 ;;;-----------------------------------------------
1878
1879 (global-set-key "\M-\r" 'complete)
1880 (global-set-key [?\C-\r] 'complete)
1881 (define-key function-key-map [C-return] [?\C-\r])
1882
1883 ;;; Tests -
1884 ;;; (add-completion "cumberland")
1885 ;;; (add-completion "cumberbund")
1886 ;;; cum
1887 ;;; Cumber
1888 ;;; cumbering
1889 ;;; cumb
1890
1891 \f
1892 ;;;---------------------------------------------------------------------------
1893 ;;; Parsing definitions from files into the database
1894 ;;;---------------------------------------------------------------------------
1895
1896 ;;;-----------------------------------------------
1897 ;;; Top Level functions ::
1898 ;;;-----------------------------------------------
1899
1900 ;;; User interface
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)
1907 )
1908 (if (not buffer-already-there-p)
1909 (let ((completions-merging-modes nil))
1910 (setq buffer (find-file-noselect file))))
1911 (unwind-protect
1912 (save-excursion
1913 (set-buffer buffer)
1914 (add-completions-from-buffer)
1915 )
1916 (if (not buffer-already-there-p)
1917 (kill-buffer buffer)))))
1918
1919 (defun add-completions-from-buffer ()
1920 (interactive)
1921 (let ((current-completion-source cmpl-source-file-parsing)
1922 (start-num
1923 (cmpl-statistics-block
1924 (aref completion-add-count-vector cmpl-source-file-parsing)))
1925 mode
1926 )
1927 (cond ((memq major-mode '(emacs-lisp-mode lisp-mode))
1928 (add-completions-from-lisp-buffer)
1929 (setq mode 'lisp)
1930 )
1931 ((memq major-mode '(c-mode))
1932 (add-completions-from-c-buffer)
1933 (setq mode 'c)
1934 )
1935 (t
1936 (error "Cannot parse completions in %s buffers"
1937 major-mode)
1938 ))
1939 (cmpl-statistics-block
1940 (record-cmpl-parse-file
1941 mode (point-max)
1942 (- (aref completion-add-count-vector cmpl-source-file-parsing)
1943 start-num)))
1944 ))
1945
1946 ;;; Find file hook
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)
1951 )
1952 (add-completions-from-buffer))
1953 ((and (memq major-mode '(c-mode))
1954 (memq 'c completions-merging-modes)
1955 )
1956 (add-completions-from-buffer)
1957 )))
1958 ))
1959
1960 (add-hook 'find-file-hooks 'cmpl-find-file-hook)
1961
1962 ;;;-----------------------------------------------
1963 ;;; Tags Table Completions
1964 ;;;-----------------------------------------------
1965
1966 (defun add-completions-from-tags-table ()
1967 ;; Inspired by eero@media-lab.media.mit.edu
1968 "Add completions from the current tags table."
1969 (interactive)
1970 (visit-tags-table-buffer) ;this will prompt if no tags-table
1971 (save-excursion
1972 (goto-char (point-min))
1973 (let (string)
1974 (condition-case e
1975 (while t
1976 (search-forward "\177")
1977 (backward-char 3)
1978 (and (setq string (symbol-under-point))
1979 (add-completion-to-tail-if-new string))
1980 (forward-char 3)
1981 )
1982 (search-failed)
1983 ))))
1984
1985 \f
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.
1991 ;;;
1992 ;;; We tried using forward-lines and explicit searches but the regexp technique
1993 ;;; was faster. (About 100K characters per second)
1994 ;;;
1995 (defconst *lisp-def-regexp*
1996 "\n(\\(\\w*:\\)?def\\(\\w\\|\\s_\\)*\\s +(*"
1997 "A regexp that searches for lisp definition form."
1998 )
1999
2000 ;;; Tests -
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
2005
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 ()
2009 ;;; Benchmarks
2010 ;;; Sun-3/280 - 1500 to 3000 lines of lisp code per second
2011 (let (string)
2012 (save-excursion
2013 (goto-char (point-min))
2014 (condition-case e
2015 (while t
2016 (re-search-forward *lisp-def-regexp*)
2017 (and (setq string (symbol-under-point))
2018 (add-completion-to-tail-if-new string))
2019 )
2020 (search-failed)
2021 ))))
2022
2023 \f
2024 ;;;-----------------------------------------------
2025 ;;; C file completion parsing
2026 ;;;-----------------------------------------------
2027 ;;; C :
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.
2031 ;;;
2032 ;;; As you might suspect by now, we use some symbol table hackery
2033 ;;;
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
2040
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 '(?, ?* ?= ?\( ?\;
2046 ))
2047 i)
2048 ;; default syntax is whitespace
2049 (setq i 0)
2050 (while (< i 256)
2051 (modify-syntax-entry i "w" table)
2052 (setq i (1+ i)))
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)
2061 table))
2062
2063 (defconst cmpl-c-def-syntax-table (cmpl-make-c-def-completion-syntax-table))
2064
2065 ;;; Regexps
2066 (defconst *c-def-regexp*
2067 ;; This stops on lines with possible definitions
2068 "\n[_a-zA-Z#]"
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."
2076 )
2077 ;
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.")
2081 ;
2082 ;(defconst *c-struct-regexp*
2083 ; "\\(*\\|\\s \\)*\\b"
2084 ; "This regexp should be used to test whether a symbol follows a structure definition.")
2085
2086 ;(defun test-c-def-regexp (regexp string)
2087 ; (and (eq 0 (string-match regexp string)) (match-end 0))
2088 ; )
2089
2090 ;;; Tests -
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
2102
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 ()
2106 ;; Benchmark --
2107 ;; Sun 3/280-- 1250 lines/sec.
2108
2109 (let (string next-point char
2110 (saved-syntax (syntax-table))
2111 )
2112 (save-excursion
2113 (goto-char (point-min))
2114 (catch 'finish-add-completions
2115 (unwind-protect
2116 (while t
2117 ;; we loop here only when scan-sexps fails
2118 ;; (i.e. unbalance exps.)
2119 (set-syntax-table cmpl-c-def-syntax-table)
2120 (condition-case e
2121 (while t
2122 (re-search-forward *c-def-regexp*)
2123 (cond
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 ")
2129 )
2130 ;; skip forward over definition symbol
2131 ;; and add it to database
2132 (and (forward-word 2)
2133 (setq string (symbol-before-point))
2134 ;;(push string foo)
2135 (add-completion-to-tail-if-new string)
2136 ))))
2137 (t
2138 ;; C definition
2139 (setq next-point (point))
2140 (while (and
2141 next-point
2142 ;; scan to next separator char.
2143 (setq next-point (scan-sexps next-point 1))
2144 )
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.
2150 (goto-char
2151 (setq next-point (scan-sexps (point) 1)))
2152 )
2153 (forward-word -1)
2154 ;; add to database
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"
2160 (progn
2161 (forward-word -1)
2162 (setq string
2163 (symbol-under-point))
2164 ))
2165 (add-completion-to-tail-if-new string)
2166 )
2167 )
2168 ;; go to next
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))
2176 )
2177 (or (= char ?,)
2178 ;; Current char is an end char.
2179 (setq next-point nil)
2180 ))
2181 ))))
2182 (search-failed ;;done
2183 (throw 'finish-add-completions t)
2184 )
2185 (error
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
2191 ;;(ding)
2192 (forward-line 1)
2193 (message "Error parsing C buffer for completions--please send bug report")
2194 (throw 'finish-add-completions t)
2195 ))
2196 ))
2197 (set-syntax-table saved-syntax)
2198 )))))
2199
2200 \f
2201 ;;;---------------------------------------------------------------------------
2202 ;;; Init files
2203 ;;;---------------------------------------------------------------------------
2204
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)
2208 (cond
2209 ((not cmpl-completions-accepted-p)
2210 (message "Completions database has not changed - not writing."))
2211 (t
2212 (save-completions-to-file)))))
2213
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")
2218
2219 (defconst saved-cmpl-file-header
2220 ";;; Completion Initialization file.
2221 ;;; Version = %s
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.
2227 \n")
2228
2229 (defun completion-backup-filename (filename)
2230 (concat filename ".BAK"))
2231
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'."
2235 (interactive)
2236 (setq filename (expand-file-name (or filename save-completions-file-name)))
2237 (if (file-writable-p filename)
2238 (progn
2239 (if (not cmpl-initialized-p)
2240 (initialize-completions));; make sure everything's loaded
2241 (message "Saving completions to file %s" filename)
2242
2243 (let* ((delete-old-versions t)
2244 (kept-old-versions 0)
2245 (kept-new-versions completions-file-versions-kept)
2246 last-use-time
2247 (current-time (cmpl-hours-since-origin))
2248 (total-in-db 0)
2249 (total-perm 0)
2250 (total-saved 0)
2251 (backup-filename (completion-backup-filename filename))
2252 )
2253
2254 (save-excursion
2255 (get-buffer-create " *completion-save-buffer*")
2256 (set-buffer " *completion-save-buffer*")
2257 (setq buffer-file-name filename)
2258
2259 (if (not (verify-visited-file-modtime (current-buffer)))
2260 (progn
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)))
2265
2266 ;; prepare the buffer to be modified
2267 (clear-visited-file-modtime)
2268 (erase-buffer)
2269 ;; (/ 1 0)
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
2276 ;; permanent
2277 (and (eq last-use-time t)
2278 (setq total-perm (1+ total-perm)))
2279 ;; or if
2280 (if (> (completion-num-uses completion) 0)
2281 ;; it's been used
2282 (setq last-use-time current-time)
2283 ;; or it was saved before and
2284 (and last-use-time
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))
2290 )))
2291 ;; write to file
2292 (setq total-saved (1+ total-saved))
2293 (insert (prin1-to-string (cons (completion-string completion)
2294 last-use-time)) "\n")
2295 )))
2296
2297 ;; write the buffer
2298 (condition-case e
2299 (let ((file-exists-p (file-exists-p filename)))
2300 (if file-exists-p
2301 (progn
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!)
2305
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)))
2313 ;; Save it
2314 (save-buffer)
2315 (if file-exists-p
2316 ;; If successful, remove backup
2317 (delete-file backup-filename)))
2318 (error
2319 (set-buffer-modified-p nil)
2320 (message "Couldn't save completion file `%s'" filename)
2321 ))
2322 ;; Reset accepted-p flag
2323 (setq cmpl-completions-accepted-p nil)
2324 )
2325 (cmpl-statistics-block
2326 (record-save-completions total-in-db total-perm total-saved))
2327 ))))
2328
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)))
2335
2336 ;;;(add-hook 'cmpl-emacs-idle-time-hooks 'autosave-completions)
2337
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'."
2341 (interactive)
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))
2345 )
2346 (if backup-readable-p (setq filename backup-filename))
2347 (if (file-readable-p filename)
2348 (progn
2349 (if (not no-message-p)
2350 (message "Loading completions from %sfile %s . . ."
2351 (if backup-readable-p "backup " "") filename))
2352 (save-excursion
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)
2358 (erase-buffer)
2359
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)
2366 (start-num
2367 (cmpl-statistics-block
2368 (aref completion-add-count-vector cmpl-source-file-parsing)))
2369 (total-in-file 0) (total-perm 0)
2370 )
2371 ;; insert the file into a buffer
2372 (condition-case e
2373 (progn (insert-file-contents filename t)
2374 (setq insert-okay-p t))
2375
2376 (file-error
2377 (message "File error trying to load completion file %s."
2378 filename)))
2379 ;; parse it
2380 (if insert-okay-p
2381 (progn
2382 (goto-char (point-min))
2383
2384 (condition-case e
2385 (while t
2386 (setq entry (read buffer))
2387 (setq total-in-file (1+ total-in-file))
2388 (cond
2389 ((and (consp entry)
2390 (stringp (setq string (car entry)))
2391 (cond
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))
2399 ))
2400 ;; Valid entry
2401 ;; add it in
2402 (setq cmpl-last-use-time
2403 (completion-last-use-time
2404 (setq cmpl-entry
2405 (add-completion-to-tail-if-new string))
2406 ))
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)
2411 ;; more recent
2412 (> last-use-time cmpl-last-use-time))
2413 ))
2414 ;; update last-use-time
2415 (set-completion-last-use-time cmpl-entry last-use-time)
2416 ))
2417 (t
2418 ;; Bad format
2419 (message "Error: invalid saved completion - %s"
2420 (prin1-to-string entry))
2421 ;; try to get back in sync
2422 (search-forward "\n(")
2423 )))
2424 (search-failed
2425 (message "End of file while reading completions.")
2426 )
2427 (end-of-file
2428 (if (= (point) (point-max))
2429 (if (not no-message-p)
2430 (message "Loading completions from file %s . . . Done."
2431 filename))
2432 (message "End of file while reading completions.")
2433 ))
2434 )))
2435
2436 (cmpl-statistics-block
2437 (record-load-completions
2438 total-in-file total-perm
2439 (- (aref completion-add-count-vector cmpl-source-init-file)
2440 start-num)))
2441
2442 ))))))
2443
2444 (defun initialize-completions ()
2445 "Load the default completions file.
2446 Also sets up so that exiting emacs will automatically save the file."
2447 (interactive)
2448 (cond ((not cmpl-initialized-p)
2449 (load-completions-from-file)
2450 ))
2451 (setq cmpl-initialized-p t)
2452 )
2453
2454
2455 ;;;-----------------------------------------------
2456 ;;; Kill EMACS patch
2457 ;;;-----------------------------------------------
2458
2459 (add-hook 'kill-emacs-hook
2460 '(lambda ()
2461 (kill-emacs-save-completions)
2462 (cmpl-statistics-block
2463 (record-cmpl-kill-emacs))))
2464 \f
2465 ;;;-----------------------------------------------
2466 ;;; Kill region patch
2467 ;;;-----------------------------------------------
2468
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].)
2474
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
2477 to be killed.
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."
2483 (interactive "r")
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)))
2490 (t
2491 (kill-region beg end))))
2492
2493 (global-set-key "\C-w" 'completion-kill-region)
2494 \f
2495 ;;;-----------------------------------------------
2496 ;;; Patches to self-insert-command.
2497 ;;;-----------------------------------------------
2498
2499 ;;; Need 2 versions: generic separator chars. and space (to get auto fill
2500 ;;; to work)
2501
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).
2507
2508 (defun completion-separator-self-insert-command (arg)
2509 (interactive "p")
2510 (use-completion-before-separator)
2511 (self-insert-command arg)
2512 )
2513
2514 (defun completion-separator-self-insert-autofilling (arg)
2515 (interactive "p")
2516 (use-completion-before-separator)
2517 (self-insert-command arg)
2518 (and auto-fill-function
2519 (funcall auto-fill-function))
2520 )
2521
2522 ;;;-----------------------------------------------
2523 ;;; Wrapping Macro
2524 ;;;-----------------------------------------------
2525
2526 ;;; Note that because of the way byte compiling works, none of
2527 ;;; the functions defined with this macro get byte compiled.
2528
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))
2535 ((eq type ':before)
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))
2544 ((eq type ':under)
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))))
2553
2554 (defun use-completion-minibuffer-separator ()
2555 (let ((cmpl-syntax-table cmpl-standard-syntax-table))
2556 (use-completion-before-separator)))
2557
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))))
2563
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))))
2568
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)
2574
2575
2576 ;;;---------------------------------------------------------------------------
2577 ;;; Patches to standard keymaps insert completions
2578 ;;;---------------------------------------------------------------------------
2579
2580 ;;;-----------------------------------------------
2581 ;;; Separators
2582 ;;;-----------------------------------------------
2583 ;;; We've used the completion syntax table given as a guide.
2584 ;;;
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)
2608
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)
2615
2616 ;;; Lisp Mode diffs
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)
2623
2624 ;;; C mode diffs.
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)
2629
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)
2636 )
2637
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)
2648
2649 ;;;-----------------------------------------------
2650 ;;; Cursor movement
2651 ;;;-----------------------------------------------
2652
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)
2665
2666 (def-completion-wrapper delete-backward-char :backward)
2667 (def-completion-wrapper delete-backward-char-untabify :backward)
2668
2669 ;;; Tests --
2670 ;;; foobarbiz
2671 ;;; foobar
2672 ;;; fooquux
2673 ;;; fooper
2674
2675 (cmpl-statistics-block
2676 (record-completion-file-loaded))
2677
2678 ;;; completion.el ends here