completion.el 90.9 KB
Newer Older
Eric S. Raymond's avatar
Eric S. Raymond committed
1
;;; completion.el --- dynamic word-completion code
Erik Naggum's avatar
Erik Naggum committed
2

3 4
;; Copyright (C) 1990, 1993, 1995, 1997, 2002, 2003, 2004,
;;   2005 Free Software Foundation, Inc.
Eric S. Raymond's avatar
Eric S. Raymond committed
5

Richard M. Stallman's avatar
Richard M. Stallman committed
6
;; Maintainer: FSF
Dan Nicolaescu's avatar
Dan Nicolaescu committed
7
;; Keywords: abbrev convenience
8
;; Author: Jim Salem <alem@bbnplanet.com> of Thinking Machines Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
9
;;  (ideas suggested by Brewster Kahle)
Eric S. Raymond's avatar
Eric S. Raymond committed
10

11
;; This file is part of GNU Emacs.
Eric S. Raymond's avatar
Eric S. Raymond committed
12

13 14 15 16 17 18 19 20 21 22 23
;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
Erik Naggum's avatar
Erik Naggum committed
24
;; along with GNU Emacs; see the file COPYING.  If not, write to the
Lute Kamstra's avatar
Lute Kamstra committed
25 26
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
27 28

;;; Commentary:
Erik Naggum's avatar
Erik Naggum committed
29 30 31

;; What to put in .emacs
;;-----------------------
32
;; (dynamic-completion-mode)
Richard M. Stallman's avatar
Richard M. Stallman committed
33

Erik Naggum's avatar
Erik Naggum committed
34 35 36 37 38 39 40
;;---------------------------------------------------------------------------
;; Documentation [Slightly out of date]
;;---------------------------------------------------------------------------
;;  (also check the documentation string of the functions)
;;
;; Introduction
;;---------------
41
;;
Erik Naggum's avatar
Erik Naggum committed
42
;;     After you type a few characters, pressing the "complete" key inserts
43
;; the rest of the word you are likely to type.
Erik Naggum's avatar
Erik Naggum committed
44
;;
45
;; This watches all the words that you type and remembers them.  When
Erik Naggum's avatar
Erik Naggum committed
46
;; typing a new word, pressing "complete" (meta-return) "completes" the
47
;; word by inserting the most recently used word that begins with the
Erik Naggum's avatar
Erik Naggum committed
48 49 50 51
;; same characters.  If you press meta-return repeatedly, it cycles
;; through all the words it knows about.
;;
;;  If you like the completion then just continue typing, it is as if you
52
;; entered the text by hand.  If you want the inserted extra characters
Erik Naggum's avatar
Erik Naggum committed
53 54 55
;; to go away, type control-w or delete.  More options are described below.
;;
;;  The guesses are made in the order of the most recently "used".  Typing
56 57
;; in a word and then typing a separator character (such as a space) "uses"
;; the word.  So does moving a cursor over the word.  If no words are found,
Erik Naggum's avatar
Erik Naggum committed
58 59
;; it uses an extended version of the dabbrev style completion.
;;
60 61
;;   You automatically save the completions you use to a file between
;; sessions.
Erik Naggum's avatar
Erik Naggum committed
62
;;
63
;;   Completion enables programmers to enter longer, more descriptive
Erik Naggum's avatar
Erik Naggum committed
64 65 66 67 68 69
;; variable names while typing fewer keystrokes than they normally would.
;;
;;
;; Full documentation
;;---------------------
;;
70
;;   A "word" is any string containing characters with either word or symbol
Erik Naggum's avatar
Erik Naggum committed
71 72 73 74 75 76 77 78
;; syntax.  [E.G. Any alphanumeric string with hyphens, underscores, etc.]
;; Unless you change the constants, you must type at least three characters
;; for the word to be recognized.  Only words longer than 6 characters are
;; saved.
;;
;;   When you load this file, completion will be on.  I suggest you use the
;; compiled version (because it is noticeably faster).
;;
79
;;  M-x completion-mode toggles whether or not new words are added to the
Erik Naggum's avatar
Erik Naggum committed
80 81 82 83 84 85
;; database by changing the value of enable-completion.
;;
;;  SAVING/LOADING COMPLETIONS
;;   Completions are automatically saved from one session to another
;; (unless save-completions-flag or enable-completion is nil).
;; Loading this file (or calling initialize-completions) causes EMACS
86
;; to load a completions database for a saved completions file
Erik Naggum's avatar
Erik Naggum committed
87
;; (default: ~/.completions).  When you exit, EMACS saves a copy of the
88
;; completions that you
Erik Naggum's avatar
Erik Naggum committed
89 90
;; often use.  When you next start, EMACS loads in the saved completion file.
;;
91 92
;;   The number of completions saved depends loosely on
;; *saved-completions-decay-factor*.  Completions that have never been
Erik Naggum's avatar
Erik Naggum committed
93 94 95
;; inserted via "complete" are not saved.  You are encouraged to experiment
;; with different functions (see compute-completion-min-num-uses).
;;
96 97
;;   Some completions are permanent and are always saved out.  These
;; completions have their num-uses slot set to T.  Use
Erik Naggum's avatar
Erik Naggum committed
98 99 100
;; add-permanent-completion to do this
;;
;;   Completions are saved only if enable-completion is T.  The number of old
101
;; versions kept of the saved completions file is controlled by
Erik Naggum's avatar
Erik Naggum committed
102 103 104
;; completions-file-versions-kept.
;;
;; COMPLETE KEY OPTIONS
105 106
;;   The complete function takes a numeric arguments.
;;  control-u :: leave the point at the beginning of the completion rather
Erik Naggum's avatar
Erik Naggum committed
107 108 109 110 111 112 113 114
;;               than the middle.
;;  a number  :: rotate through the possible completions by that amount
;;  `-'       :: same as -1 (insert previous completion)
;;
;; HOW THE DATABASE IS MAINTAINED
;;  <write>
;;
;; UPDATING THE DATABASE MANUALLY
115
;;   m-x kill-completion
Erik Naggum's avatar
Erik Naggum committed
116 117 118
;;     kills the completion at point.
;;   m-x add-completion
;;   m-x add-permanent-completion
119
;;
Erik Naggum's avatar
Erik Naggum committed
120 121 122 123 124
;; UPDATING THE DATABASE FROM A SOURCE CODE FILE
;;   m-x add-completions-from-buffer
;;     Parses all the definition names from a C or LISP mode buffer and
;;     adds them to the completion database.
;;
125
;;   m-x add-completions-from-lisp-file
Erik Naggum's avatar
Erik Naggum committed
126 127 128 129 130 131 132 133 134 135 136
;;     Parses all the definition names from a C or Lisp mode file and
;;     adds them to the completion database.
;;
;; UPDATING THE DATABASE FROM A TAGS TABLE
;;   m-x add-completions-from-tags-table
;;     Adds completions from the current tags-table-buffer.
;;
;; HOW A COMPLETION IS FOUND
;;  <write>
;;
;; STRING CASING
137
;;   Completion is string case independent if case-fold-search has its
Erik Naggum's avatar
Erik Naggum committed
138
;;  normal default of T.  Also when the completion is inserted the case of the
139 140
;;  entry is coerced appropriately.
;;  [E.G.  APP --> APPROPRIATELY     app --> appropriately
Erik Naggum's avatar
Erik Naggum committed
141 142 143
;;         App --> Appropriately]
;;
;; INITIALIZATION
144 145 146
;;  The form `(initialize-completions)' initializes the completion system by
;; trying to load in the user's completions.  After the first cal, further
;; calls have no effect so one should be careful not to put the form in a
Erik Naggum's avatar
Erik Naggum committed
147 148 149 150 151
;; site's standard site-init file.
;;
;;---------------------------------------------------------------------------
;;
;;
Richard M. Stallman's avatar
Richard M. Stallman committed
152

Erik Naggum's avatar
Erik Naggum committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
;;---------------------------------------------------------------------------
;; Functions you might like to call
;;---------------------------------------------------------------------------
;;
;;  add-completion  string &optional num-uses
;;    Adds a new string to the database
;;
;;  add-permanent-completion  string
;;    Adds a new string to the database with num-uses = T
;;

;;  kill-completion string
;;    Kills the completion from the database.
;;
;;  clear-all-completions
;;    Clears the database
;;
;;  list-all-completions
;;    Returns a list of all completions.
;;
;;
;;  next-completion string &optional index
;;    Returns a completion entry that starts with string.
;;
;;  find-exact-completion string
;;    Returns a completion entry that exactly matches string.
;;
;;  complete
;;    Inserts a completion at point
;;
;;  initialize-completions
184
;;    Loads the completions file and sets up so that exiting emacs will
Erik Naggum's avatar
Erik Naggum committed
185 186
;;  save them.
;;
187
;;  save-completions-to-file &optional filename
Erik Naggum's avatar
Erik Naggum committed
188 189 190 191 192 193 194 195 196 197
;;  load-completions-from-file &optional filename
;;
;;-----------------------------------------------
;; Other functions
;;-----------------------------------------------
;;
;;  get-completion-list string
;;
;; These things are for manipulating the structure
;;  make-completion string num-uses
198
;;  completion-num-uses completion
Erik Naggum's avatar
Erik Naggum committed
199 200 201
;;  completion-string completion
;;  set-completion-num-uses completion num-uses
;;  set-completion-string completion string
202
;;
Erik Naggum's avatar
Erik Naggum committed
203
;;
Richard M. Stallman's avatar
Richard M. Stallman committed
204

Erik Naggum's avatar
Erik Naggum committed
205 206 207 208 209 210 211 212 213 214 215 216
;;-----------------------------------------------
;; To Do :: (anybody ?)
;;-----------------------------------------------
;;
;;   Implement Lookup and keyboard interface in C
;;   Add package prefix smarts (for Common Lisp)
;;   Add autoprompting of possible completions after every keystroke (fast
;;      terminals only !)
;;   Add doc. to texinfo
;;
;;
;;-----------------------------------------------
Erik Naggum's avatar
Erik Naggum committed
217
;;; Change Log:
Erik Naggum's avatar
Erik Naggum committed
218
;;-----------------------------------------------
219
;;    Sometime in '84 Brewster implemented a somewhat buggy version for
Erik Naggum's avatar
Erik Naggum committed
220
;; Symbolics LISPMs.
221
;;    Jan. '85 Jim became enamored of the idea and implemented a faster,
Erik Naggum's avatar
Erik Naggum committed
222 223
;; more robust version.
;;    With input from many users at TMC, (rose, craig, and gls come to mind),
224 225 226 227 228
;; the current style of interface was developed.
;;    9/87, Jim and Brewster took terminals home.  Yuck.  After
;; complaining for a while Brewster implemented a subset of the current
;; LISPM version for GNU Emacs.
;;    8/88  After complaining for a while (and with sufficient
Erik Naggum's avatar
Erik Naggum committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
;; promised rewards), Jim reimplemented a version of GNU completion
;; superior to that of the LISPM version.
;;
;;-----------------------------------------------
;; Acknowledgements
;;-----------------------------------------------
;;  Cliff Lasser (cal@think.com), Kevin Herbert (kph@cisco.com),
;;  eero@media-lab, kgk@cs.brown.edu, jla@ai.mit.edu,
;;
;;-----------------------------------------------
;; Change Log
;;-----------------------------------------------
;; From version 9 to 10
;;  - Allowance for non-integral *completion-version* nos.
;;  - Fix cmpl-apply-as-top-level for keyboard macros
;;  - Fix broken completion merging (in save-completions-to-file)
;;  - More misc. fixes for version 19.0 of emacs
;;
;; From Version 8 to 9
;;  - Ported to version 19.0 of emacs (backcompatible with version 18)
;;  - Added add-completions-from-tags-table (with thanks to eero@media-lab)
;;
;; From Version 7 to 8
;;  - Misc. changes to comments
;;  - new completion key bindings: c-x o, M->, M-<, c-a, c-e
;;  - cdabbrev now checks all the visible window buffers and the "other buffer"
;;  - `%' is now a symbol character rather than a separator (except in C mode)
;;
;; From Version 6 to 7
;;  - Fixed bug with saving out .completion file the first time
;;
;; From Version 5 to 6
;;  - removed statistics recording
;;  - reworked advise to handle autoloads
;;  - Fixed fortran mode support
;;  - Added new cursor motion triggers
;;
;; From Version 4 to 5
;;  - doesn't bother saving if nothing has changed
;;  - auto-save if haven't used for a 1/2 hour
;;  - save period extended to two weeks
;;  - minor fix to capitalization code
;;  - added *completion-auto-save-period* to variables recorded.
;;  - added reenter protection to cmpl-record-statistics-filter
273
;;  - added backup protection to save-completions-to-file (prevents
Erik Naggum's avatar
Erik Naggum committed
274
;;    problems with disk full errors)
Richard M. Stallman's avatar
Richard M. Stallman committed
275

Eric S. Raymond's avatar
Eric S. Raymond committed
276 277
;;; Code:

Erik Naggum's avatar
Erik Naggum committed
278 279 280
;;---------------------------------------------------------------------------
;; User changeable parameters
;;---------------------------------------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
281

282 283
(defgroup completion nil
  "Dynamic word-completion code."
Dan Nicolaescu's avatar
Dan Nicolaescu committed
284 285
  :group 'matching
  :group 'convenience)
286 287 288


(defcustom enable-completion t
289
  "*Non-nil means enable recording and saving of completions.
290
If nil, no new words are added to the database or saved to the init file."
291 292
  :type 'boolean
  :group 'completion)
Richard M. Stallman's avatar
Richard M. Stallman committed
293

294
(defcustom save-completions-flag t
295
  "*Non-nil means save most-used completions when exiting Emacs.
296
See also `save-completions-retention-time'."
297 298
  :type 'boolean
  :group 'completion)
Richard M. Stallman's avatar
Richard M. Stallman committed
299

300 301 302 303
(defcustom save-completions-file-name (convert-standard-filename "~/.completions")
  "*The filename to save completions to."
  :type 'file
  :group 'completion)
Richard M. Stallman's avatar
Richard M. Stallman committed
304

305
(defcustom save-completions-retention-time 336
306 307
  "*Discard a completion if unused for this many hours.
\(1 day = 24, 1 week = 168).  If this is 0, non-permanent completions
308 309 310
will not be saved unless these are used.  Default is two weeks."
  :type 'integer
  :group 'completion)
Richard M. Stallman's avatar
Richard M. Stallman committed
311

312
(defcustom completion-on-separator-character nil
313
  "*Non-nil means separator characters mark previous word as used.
314 315 316
This means the word will be saved as a completion."
  :type 'boolean
  :group 'completion)
Richard M. Stallman's avatar
Richard M. Stallman committed
317

318 319 320 321
(defcustom completions-file-versions-kept kept-new-versions
  "*Number of versions to keep for the saved completions file."
  :type 'integer
  :group 'completion)
Richard M. Stallman's avatar
Richard M. Stallman committed
322

323 324 325 326
(defcustom completion-prompt-speed-threshold 4800
  "*Minimum output speed at which to display next potential completion."
  :type 'integer
  :group 'completion)
Richard M. Stallman's avatar
Richard M. Stallman committed
327

328
(defcustom completion-cdabbrev-prompt-flag nil
329
  "*If non-nil, the next completion prompt does a cdabbrev search.
330 331 332
This can be time consuming."
  :type 'boolean
  :group 'completion)
Richard M. Stallman's avatar
Richard M. Stallman committed
333

334
(defcustom completion-search-distance 15000
335
  "*How far to search in the buffer when looking for completions.
336 337 338
In number of characters.  If nil, search the whole buffer."
  :type 'integer
  :group 'completion)
Richard M. Stallman's avatar
Richard M. Stallman committed
339

340
(defcustom completions-merging-modes '(lisp c)
341 342
  "*List of modes {`c' or `lisp'} for automatic completions merging.
Definitions from visited files which have these modes
343 344 345
are automatically added to the completion database."
  :type '(set (const lisp) (const c))
  :group 'completion)
Richard M. Stallman's avatar
Richard M. Stallman committed
346

Erik Naggum's avatar
Erik Naggum committed
347 348
;;(defvar *record-cmpl-statistics-p* nil
;;  "*If non-nil, record completion statistics.")
Richard M. Stallman's avatar
Richard M. Stallman committed
349

Erik Naggum's avatar
Erik Naggum committed
350 351 352
;;(defvar *completion-auto-save-period* 1800
;;  "*The period in seconds to wait for emacs to be idle before autosaving
;;the completions.  Default is a 1/2 hour.")
Richard M. Stallman's avatar
Richard M. Stallman committed
353

354
(defvar completion-min-length 6
Richard M. Stallman's avatar
Richard M. Stallman committed
355 356 357
  "*The minimum length of a stored completion.
DON'T CHANGE WITHOUT RECOMPILING !  This is used by macros.")

358
(defvar completion-max-length 200
Richard M. Stallman's avatar
Richard M. Stallman committed
359 360 361
  "*The maximum length of a stored completion.
DON'T CHANGE WITHOUT RECOMPILING !  This is used by macros.")

362
(defvar completion-prefix-min-length 3
Richard M. Stallman's avatar
Richard M. Stallman committed
363 364 365
  "The minimum length of a completion search string.
DON'T CHANGE WITHOUT RECOMPILING !  This is used by macros.")

Erik Naggum's avatar
Erik Naggum committed
366 367 368
;;---------------------------------------------------------------------------
;; Internal Variables
;;---------------------------------------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
369 370

(defvar cmpl-initialized-p nil
371 372
  "Set to t when the completion system is initialized.
Indicates that the old completion file has been read in.")
Richard M. Stallman's avatar
Richard M. Stallman committed
373 374

(defvar cmpl-completions-accepted-p nil
375 376
  "Set to t as soon as the first completion has been accepted.
Used to decide whether to save completions.")
Richard M. Stallman's avatar
Richard M. Stallman committed
377

378
(defvar cmpl-preceding-syntax)
379 380

(defvar completion-string)
Richard M. Stallman's avatar
Richard M. Stallman committed
381

Erik Naggum's avatar
Erik Naggum committed
382 383 384
;;---------------------------------------------------------------------------
;; Low level tools
;;---------------------------------------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
385

Erik Naggum's avatar
Erik Naggum committed
386 387 388
;;-----------------------------------------------
;; String case coercion
;;-----------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
389 390

(defun cmpl-string-case-type (string)
391
  "Return :capitalized, :up, :down, :mixed, or :neither for case of STRING."
Richard M. Stallman's avatar
Richard M. Stallman committed
392
  (let ((case-fold-search nil))
393 394
    (cond ((string-match "[[:lower:]]" string)
	   (cond ((string-match "[[:upper:]]" string)
Richard M. Stallman's avatar
Richard M. Stallman committed
395
		  (cond ((and (> (length string) 1)
396 397
			      (null (string-match "[[:upper:]]" string 1)))
			 :capitalized)
Richard M. Stallman's avatar
Richard M. Stallman committed
398
			(t
399 400
			 :mixed)))
		 (t :down)))
Richard M. Stallman's avatar
Richard M. Stallman committed
401
	  (t
402 403 404
	   (cond ((string-match "[[:upper:]]" string)
		  :up)
		 (t :neither))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
405

Erik Naggum's avatar
Erik Naggum committed
406 407 408 409 410 411
;; Tests -
;; (cmpl-string-case-type "123ABCDEF456") --> :up
;; (cmpl-string-case-type "123abcdef456") --> :down
;; (cmpl-string-case-type "123aBcDeF456") --> :mixed
;; (cmpl-string-case-type "123456")       --> :neither
;; (cmpl-string-case-type "Abcde123")     --> :capitalized
Richard M. Stallman's avatar
Richard M. Stallman committed
412 413

(defun cmpl-coerce-string-case (string case-type)
414 415 416
  (cond ((eq case-type :down) (downcase string))
	((eq case-type :up) (upcase string))
	((eq case-type :capitalized)
Richard M. Stallman's avatar
Richard M. Stallman committed
417 418 419
	 (setq string (downcase string))
	 (aset string 0 (logand ?\337 (aref string 0)))
	 string)
420
	(t string)))
Richard M. Stallman's avatar
Richard M. Stallman committed
421 422

(defun cmpl-merge-string-cases (string-to-coerce given-string)
423
  (let ((string-case-type (cmpl-string-case-type string-to-coerce)))
Richard M. Stallman's avatar
Richard M. Stallman committed
424 425 426 427
    (cond ((memq string-case-type '(:down :up :capitalized))
	   ;; Found string is in a standard case.  Coerce to a type based on
	   ;; the given string
	   (cmpl-coerce-string-case string-to-coerce
428
			       (cmpl-string-case-type given-string)))
Richard M. Stallman's avatar
Richard M. Stallman committed
429 430 431
	  (t
	   ;; If the found string is in some unusual case, just insert it
	   ;; as is
432
	   string-to-coerce))))
Richard M. Stallman's avatar
Richard M. Stallman committed
433

Erik Naggum's avatar
Erik Naggum committed
434 435 436 437 438
;; Tests -
;; (cmpl-merge-string-cases "AbCdEf456" "abc")     --> AbCdEf456
;; (cmpl-merge-string-cases "abcdef456" "ABC")     --> ABCDEF456
;; (cmpl-merge-string-cases "ABCDEF456" "Abc")     --> Abcdef456
;; (cmpl-merge-string-cases "ABCDEF456" "abc")     --> abcdef456
Richard M. Stallman's avatar
Richard M. Stallman committed
439 440


441 442
(defun cmpl-hours-since-origin ()
  (let ((time (current-time)))
443
    (floor (+ (* 65536.0 (nth 0 time)) (nth 1 time)) 3600)))
Richard M. Stallman's avatar
Richard M. Stallman committed
444

Erik Naggum's avatar
Erik Naggum committed
445 446 447 448 449 450 451 452 453
;;---------------------------------------------------------------------------
;; "Symbol" parsing functions
;;---------------------------------------------------------------------------
;; The functions symbol-before-point, symbol-under-point, etc. quickly return
;; an appropriate symbol string.  The strategy is to temporarily change
;; the syntax table to enable fast symbol searching.  There are three classes
;; of syntax in these "symbol" syntax tables ::
;;
;; syntax (?_) - "symbol" chars (e.g. alphanumerics)
454
;; syntax (?w) - symbol chars to ignore at end of words (e.g. period).
Erik Naggum's avatar
Erik Naggum committed
455 456 457
;; syntax (? ) - everything else
;;
;; Thus by judicious use of scan-sexps and forward-word, we can get
458
;; the word we want relatively fast and without consing.
Erik Naggum's avatar
Erik Naggum committed
459 460
;;
;; Why do we need a separate category for "symbol chars to ignore at ends" ?
461
;; For example, in LISP we want starting :'s trimmed
Erik Naggum's avatar
Erik Naggum committed
462 463
;; so keyword argument specifiers also define the keyword completion.  And,
;; for example, in C we want `.' appearing in a structure ref. to
464
;; be kept intact in order to store the whole structure ref.; however, if
Erik Naggum's avatar
Erik Naggum committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
;; it appears at the end of a symbol it should be discarded because it is
;; probably used as a period.

;; Here is the default completion syntax ::
;; Symbol chars :: A-Z a-z 0-9 @ / \ * + ~ $ < > %
;; Symbol chars to ignore at ends :: _ : . -
;; Separator chars. :: <tab> <space> ! ^ & ( ) = ` | { } [ ] ; " ' #
;;                     , ? <Everything else>

;; Mode specific differences and notes ::
;;  LISP diffs ->
;;    Symbol chars :: ! & ? = ^
;;
;; C diffs ->
;;   Separator chars :: + * / : %
;;  A note on the hyphen (`-').  Perhaps the hyphen should also be a separator
481
;; char., however, we wanted to have completion symbols include pointer
Erik Naggum's avatar
Erik Naggum committed
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
;; references.  For example, "foo->bar" is a symbol as far as completion is
;; concerned.
;;
;; FORTRAN diffs ->
;;   Separator chars :: + - * / :
;;
;; Pathname diffs ->
;;   Symbol chars :: .
;;  Of course there is no pathname "mode" and in fact we have not implemented
;; this table.  However, if there was such a mode, this is what it would look
;; like.

;;-----------------------------------------------
;; Table definitions
;;-----------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
497

498
(defun cmpl-make-standard-completion-syntax-table ()
Richard M. Stallman's avatar
Richard M. Stallman committed
499
  (let ((table (make-syntax-table))
500
	i)
Richard M. Stallman's avatar
Richard M. Stallman committed
501 502 503 504 505
    ;; Default syntax is whitespace.
    (setq i 0)
    (while (< i 256)
      (modify-syntax-entry i " " table)
      (setq i (1+ i)))
Richard M. Stallman's avatar
Richard M. Stallman committed
506
    ;; alpha chars
507 508
    (setq i 0)
    (while (< i 26)
Richard M. Stallman's avatar
Richard M. Stallman committed
509
      (modify-syntax-entry (+ ?a i) "_" table)
510 511
      (modify-syntax-entry (+ ?A i) "_" table)
      (setq i (1+ i)))
Richard M. Stallman's avatar
Richard M. Stallman committed
512
    ;; digit chars.
513 514 515 516
    (setq i 0)
    (while (< i 10)
      (modify-syntax-entry (+ ?0 i) "_" table)
      (setq i (1+ i)))
Richard M. Stallman's avatar
Richard M. Stallman committed
517 518
    ;; Other ones
    (let ((symbol-chars '(?@ ?/ ?\\ ?* ?+ ?~ ?$ ?< ?> ?%))
519
	  (symbol-chars-ignore '(?_ ?- ?: ?.)))
520
      (dolist (char symbol-chars)
Richard M. Stallman's avatar
Richard M. Stallman committed
521
	(modify-syntax-entry char "_" table))
522
      (dolist (char symbol-chars-ignore)
523
	(modify-syntax-entry char "w" table)))
Richard M. Stallman's avatar
Richard M. Stallman committed
524 525
    table))

526
(defconst cmpl-standard-syntax-table (cmpl-make-standard-completion-syntax-table))
Richard M. Stallman's avatar
Richard M. Stallman committed
527

528
(defun cmpl-make-lisp-completion-syntax-table ()
Richard M. Stallman's avatar
Richard M. Stallman committed
529
  (let ((table (copy-syntax-table cmpl-standard-syntax-table))
530
	(symbol-chars '(?! ?& ?? ?= ?^)))
531
    (dolist (char symbol-chars)
Richard M. Stallman's avatar
Richard M. Stallman committed
532 533
      (modify-syntax-entry char "_" table))
    table))
534

535
(defun cmpl-make-c-completion-syntax-table ()
Richard M. Stallman's avatar
Richard M. Stallman committed
536
  (let ((table (copy-syntax-table cmpl-standard-syntax-table))
537
	(separator-chars '(?+ ?* ?/ ?: ?%)))
538
    (dolist (char separator-chars)
Richard M. Stallman's avatar
Richard M. Stallman committed
539 540 541
      (modify-syntax-entry char " " table))
    table))

542
(defun cmpl-make-fortran-completion-syntax-table ()
Richard M. Stallman's avatar
Richard M. Stallman committed
543
  (let ((table (copy-syntax-table cmpl-standard-syntax-table))
544
	(separator-chars '(?+ ?- ?* ?/ ?:)))
545
    (dolist (char separator-chars)
Richard M. Stallman's avatar
Richard M. Stallman committed
546 547 548
      (modify-syntax-entry char " " table))
    table))

549 550 551
(defconst cmpl-lisp-syntax-table       (cmpl-make-lisp-completion-syntax-table))
(defconst cmpl-c-syntax-table          (cmpl-make-c-completion-syntax-table))
(defconst cmpl-fortran-syntax-table    (cmpl-make-fortran-completion-syntax-table))
Richard M. Stallman's avatar
Richard M. Stallman committed
552 553 554 555 556

(defvar cmpl-syntax-table cmpl-standard-syntax-table
  "This variable holds the current completion syntax table.")
(make-variable-buffer-local 'cmpl-syntax-table)

Erik Naggum's avatar
Erik Naggum committed
557 558 559
;;-----------------------------------------------
;; Symbol functions
;;-----------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
560
(defvar cmpl-symbol-start nil
561
  "Holds first character of symbol, after any completion symbol function.")
Richard M. Stallman's avatar
Richard M. Stallman committed
562
(defvar cmpl-symbol-end nil
563
  "Holds last character of symbol, after any completion symbol function.")
Erik Naggum's avatar
Erik Naggum committed
564 565
;; These are temp. vars. we use to avoid using let.
;;   Why ?  Small speed improvement.
Richard M. Stallman's avatar
Richard M. Stallman committed
566 567 568 569
(defvar cmpl-saved-syntax nil)
(defvar cmpl-saved-point nil)

(defun symbol-under-point ()
570
  "Return the symbol that the point is currently on.
571
But only if it is longer than `completion-min-length'."
Richard M. Stallman's avatar
Richard M. Stallman committed
572
  (setq cmpl-saved-syntax (syntax-table))
573 574 575
  (unwind-protect
      (progn
	(set-syntax-table cmpl-syntax-table)
576
	(cond
577
	;; Cursor is on following-char and after preceding-char
578
	  ((memq (char-syntax (following-char)) '(?w ?_))
579 580 581 582 583 584 585 586
	   (setq cmpl-saved-point (point)
		 cmpl-symbol-start (scan-sexps (1+ cmpl-saved-point) -1)
		 cmpl-symbol-end (scan-sexps cmpl-saved-point 1))
	   ;; Remove chars to ignore at the start.
	   (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
		  (goto-char cmpl-symbol-start)
		  (forward-word 1)
		  (setq cmpl-symbol-start (point))
587
		  (goto-char cmpl-saved-point)))
588 589 590 591 592
	   ;; Remove chars to ignore at the end.
	   (cond ((= (char-syntax (char-after (1- cmpl-symbol-end))) ?w)
		  (goto-char cmpl-symbol-end)
		  (forward-word -1)
		  (setq cmpl-symbol-end (point))
593
		  (goto-char cmpl-saved-point)))
594
	   ;; Return completion if the length is reasonable.
595
	   (if (and (<= completion-min-length
596 597
			(- cmpl-symbol-end cmpl-symbol-start))
		    (<= (- cmpl-symbol-end cmpl-symbol-start)
598
			completion-max-length))
599 600
	       (buffer-substring cmpl-symbol-start cmpl-symbol-end)))))
    (set-syntax-table cmpl-saved-syntax)))
Richard M. Stallman's avatar
Richard M. Stallman committed
601

Erik Naggum's avatar
Erik Naggum committed
602 603 604 605 606 607 608 609 610 611 612
;; tests for symbol-under-point
;;  `^' indicates cursor pos. where value is returned
;;  simple-word-test
;;  ^^^^^^^^^^^^^^^^  --> simple-word-test
;;  _harder_word_test_
;;  ^^^^^^^^^^^^^^^^^^ --> harder_word_test
;;  .___.______.
;;  --> nil
;;  /foo/bar/quux.hello
;;  ^^^^^^^^^^^^^^^^^^^ --> /foo/bar/quux.hello
;;
Richard M. Stallman's avatar
Richard M. Stallman committed
613 614

(defun symbol-before-point ()
615
  "Return a string of the symbol immediately before point.
616
Returns nil if there isn't one longer than `completion-min-length'."
Richard M. Stallman's avatar
Richard M. Stallman committed
617 618
  ;; This is called when a word separator is typed so it must be FAST !
  (setq cmpl-saved-syntax (syntax-table))
619 620 621 622 623 624 625
  (unwind-protect
      (progn
	(set-syntax-table cmpl-syntax-table)
	;; Cursor is on following-char and after preceding-char
	(cond ((= (setq cmpl-preceding-syntax (char-syntax (preceding-char))) ?_)
	       ;; Number of chars to ignore at end.
	       (setq cmpl-symbol-end (point)
626
		     cmpl-symbol-start (scan-sexps cmpl-symbol-end -1))
627 628 629 630 631
	       ;; Remove chars to ignore at the start.
	       (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
		      (goto-char cmpl-symbol-start)
		      (forward-word 1)
		      (setq cmpl-symbol-start (point))
632
		      (goto-char cmpl-symbol-end)))
633 634
	       ;; Return value if long enough.
	       (if (>= cmpl-symbol-end
635
		       (+ cmpl-symbol-start completion-min-length))
636
		   (buffer-substring cmpl-symbol-start cmpl-symbol-end)))
637 638 639 640 641 642 643 644 645 646 647
	      ((= cmpl-preceding-syntax ?w)
	       ;; chars to ignore at end
	       (setq cmpl-saved-point (point)
		     cmpl-symbol-start (scan-sexps cmpl-saved-point -1))
	       ;; take off chars. from end
	       (forward-word -1)
	       (setq cmpl-symbol-end (point))
	       ;; remove chars to ignore at the start
	       (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
		      (goto-char cmpl-symbol-start)
		      (forward-word 1)
648
		      (setq cmpl-symbol-start (point))))
649 650 651
	       ;; Restore state.
	       (goto-char cmpl-saved-point)
	       ;; Return completion if the length is reasonable
652
	       (if (and (<= completion-min-length
653 654
			    (- cmpl-symbol-end cmpl-symbol-start))
			(<= (- cmpl-symbol-end cmpl-symbol-start)
655
			    completion-max-length))
656 657
		   (buffer-substring cmpl-symbol-start cmpl-symbol-end)))))
    (set-syntax-table cmpl-saved-syntax)))
Richard M. Stallman's avatar
Richard M. Stallman committed
658

Erik Naggum's avatar
Erik Naggum committed
659 660 661 662 663 664 665 666 667 668 669 670 671
;; tests for symbol-before-point
;;  `^' indicates cursor pos. where value is returned
;;  simple-word-test
;;  ^ --> nil
;;   ^ --> nil
;;          ^  --> simple-w
;;                  ^ --> simple-word-test
;;  _harder_word_test_
;;                   ^  --> harder_word_test
;;                    ^  --> harder_word_test
;;          ^ --> harder
;;  .___....
;;  --> nil
Richard M. Stallman's avatar
Richard M. Stallman committed
672 673

(defun symbol-under-or-before-point ()
Erik Naggum's avatar
Erik Naggum committed
674 675 676 677
  ;; This could be made slightly faster but it is better to avoid
  ;; copying all the code.
  ;; However, it is only used by the completion string prompter.
  ;; If it comes into common use, it could be rewritten.
678 679 680 681 682 683 684 685
  (cond ((memq (progn
		 (setq cmpl-saved-syntax (syntax-table))
		 (unwind-protect
		     (progn
		       (set-syntax-table cmpl-syntax-table)
		       (char-syntax (following-char)))
		   (set-syntax-table cmpl-saved-syntax)))
	       '(?w ?_))
Richard M. Stallman's avatar
Richard M. Stallman committed
686 687
	 (symbol-under-point))
	(t
688
	 (symbol-before-point))))
Richard M. Stallman's avatar
Richard M. Stallman committed
689 690 691 692 693 694 695 696


(defun symbol-before-point-for-complete ()
  ;; "Returns a string of the symbol immediately before point
  ;; or nil if there isn't one.  Like symbol-before-point but doesn't trim the
  ;; end chars."
  ;; Cursor is on following-char and after preceding-char
  (setq cmpl-saved-syntax (syntax-table))
697 698 699 700 701 702
  (unwind-protect
      (progn
	(set-syntax-table cmpl-syntax-table)
	(cond ((memq (setq cmpl-preceding-syntax (char-syntax (preceding-char)))
		     '(?_ ?w))
	       (setq cmpl-symbol-end (point)
703
		     cmpl-symbol-start (scan-sexps cmpl-symbol-end -1))
704 705 706 707 708
	       ;; Remove chars to ignore at the start.
	       (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
		      (goto-char cmpl-symbol-start)
		      (forward-word 1)
		      (setq cmpl-symbol-start (point))
709
		      (goto-char cmpl-symbol-end)))
710
	       ;; Return completion if the length is reasonable.
711
	       (if (and (<= completion-prefix-min-length
712 713
			    (- cmpl-symbol-end cmpl-symbol-start))
			(<= (- cmpl-symbol-end cmpl-symbol-start)
714
			    completion-max-length))
715 716 717
		   (buffer-substring cmpl-symbol-start cmpl-symbol-end)))))
    ;; Restore syntax table.
    (set-syntax-table cmpl-saved-syntax)))
Richard M. Stallman's avatar
Richard M. Stallman committed
718

Erik Naggum's avatar
Erik Naggum committed
719 720 721 722 723 724 725 726 727 728 729 730 731
;; tests for symbol-before-point-for-complete
;;  `^' indicates cursor pos. where value is returned
;;  simple-word-test
;;  ^ --> nil
;;   ^ --> nil
;;          ^  --> simple-w
;;                  ^ --> simple-word-test
;;  _harder_word_test_
;;                   ^  --> harder_word_test
;;                    ^  --> harder_word_test_
;;          ^ --> harder_
;;  .___....
;;  --> nil
Richard M. Stallman's avatar
Richard M. Stallman committed
732 733 734



Erik Naggum's avatar
Erik Naggum committed
735 736 737
;;---------------------------------------------------------------------------
;; Statistics Recording
;;---------------------------------------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
738

Erik Naggum's avatar
Erik Naggum committed
739 740
;; Note that the guts of this has been turned off.  The guts
;; are in completion-stats.el.
Richard M. Stallman's avatar
Richard M. Stallman committed
741

Erik Naggum's avatar
Erik Naggum committed
742 743 744 745
;;-----------------------------------------------
;; Conditionalizing code on *record-cmpl-statistics-p*
;;-----------------------------------------------
;; All statistics code outside this block should use this
746
(defmacro cmpl-statistics-block (&rest body))
Erik Naggum's avatar
Erik Naggum committed
747 748 749
;;  "Only executes body if we are recording statistics."
;;  (list 'cond
;;	(list* '*record-cmpl-statistics-p* body)
750
;;	))
Richard M. Stallman's avatar
Richard M. Stallman committed
751

Erik Naggum's avatar
Erik Naggum committed
752 753 754
;;-----------------------------------------------
;; Completion Sources
;;-----------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
755 756 757 758 759 760 761 762 763 764 765 766 767 768

;; ID numbers
(defconst cmpl-source-unknown 0)
(defconst cmpl-source-init-file 1)
(defconst cmpl-source-file-parsing 2)
(defconst cmpl-source-separator 3)
(defconst cmpl-source-cursor-moves 4)
(defconst cmpl-source-interactive 5)
(defconst cmpl-source-cdabbrev 6)
(defconst num-cmpl-sources 7)
(defvar current-completion-source cmpl-source-unknown)



Erik Naggum's avatar
Erik Naggum committed
769 770 771 772
;;---------------------------------------------------------------------------
;; Completion Method #2: dabbrev-expand style
;;---------------------------------------------------------------------------
;;
773
;;   This method is used if there are no useful stored completions.  It is
Erik Naggum's avatar
Erik Naggum committed
774 775 776 777 778 779 780
;; based on dabbrev-expand with these differences :
;;   1) Faster (we don't use regexps)
;;   2) case coercion handled correctly
;; This is called cdabbrev to differentiate it.
;;   We simply search backwards through the file looking for words which
;; start with the same letters we are trying to complete.
;;
Richard M. Stallman's avatar
Richard M. Stallman committed
781 782

(defvar cdabbrev-completions-tried nil)
Erik Naggum's avatar
Erik Naggum committed
783
;;  "A list of all the cdabbrev completions since the last reset.")
Richard M. Stallman's avatar
Richard M. Stallman committed
784 785

(defvar cdabbrev-current-point 0)
Erik Naggum's avatar
Erik Naggum committed
786
;;  "The current point position the cdabbrev search is at.")
Richard M. Stallman's avatar
Richard M. Stallman committed
787 788

(defvar cdabbrev-current-window nil)
789 790
;;  "The current window we are looking for cdabbrevs in.
;; Return t if looking in (other-buffer), nil if no more  cdabbrevs.")
Richard M. Stallman's avatar
Richard M. Stallman committed
791 792

(defvar cdabbrev-wrapped-p nil)
793
;;  "Return t if the cdabbrev search has wrapped around the file.")
Richard M. Stallman's avatar
Richard M. Stallman committed
794 795 796

(defvar cdabbrev-abbrev-string "")
(defvar cdabbrev-start-point 0)
797
(defvar cdabbrev-stop-point)
Richard M. Stallman's avatar
Richard M. Stallman committed
798

Erik Naggum's avatar
Erik Naggum committed
799 800 801 802 803 804 805
;; Test strings for cdabbrev
;; cdat-upcase   ;;same namestring
;; CDAT-UPCASE   ;;ok
;; cdat2         ;;too short
;; cdat-1-2-3-4  ;;ok
;; a-cdat-1      ;;doesn't start correctly
;; cdat-simple   ;;ok
Richard M. Stallman's avatar
Richard M. Stallman committed
806 807 808


(defun reset-cdabbrev (abbrev-string &optional initial-completions-tried)
809
  "Reset the cdabbrev search to search for ABBREV-STRING.
810
INITIAL-COMPLETIONS-TRIED is a list of downcased strings to ignore
Richard M. Stallman's avatar
Richard M. Stallman committed
811 812 813
during the search."
  (setq cdabbrev-abbrev-string abbrev-string
	cdabbrev-completions-tried
814 815
	(cons (downcase abbrev-string) initial-completions-tried))
  (reset-cdabbrev-window t))
Richard M. Stallman's avatar
Richard M. Stallman committed
816 817

(defun set-cdabbrev-buffer ()
Pavel Janík's avatar
Pavel Janík committed
818
  ;; cdabbrev-current-window must not be nil
Richard M. Stallman's avatar
Richard M. Stallman committed
819 820
  (set-buffer (if (eq cdabbrev-current-window t)
		  (other-buffer)
821
		  (window-buffer cdabbrev-current-window))))
Richard M. Stallman's avatar
Richard M. Stallman committed
822 823 824


(defun reset-cdabbrev-window (&optional initializep)
825
  "Reset the cdabbrev search to search for abbrev-string."
Richard M. Stallman's avatar
Richard M. Stallman committed
826 827
  ;; Set the window
  (cond (initializep
828
	 (setq cdabbrev-current-window (selected-window)))
Richard M. Stallman's avatar
Richard M. Stallman committed
829 830 831 832 833 834 835
	((eq cdabbrev-current-window t)
	 ;; Everything has failed
	 (setq cdabbrev-current-window nil))
	(cdabbrev-current-window
	 (setq cdabbrev-current-window (next-window cdabbrev-current-window))
	 (if (eq cdabbrev-current-window (selected-window))
	     ;; No more windows, try other buffer.
836
	     (setq cdabbrev-current-window t))))
837 838 839 840 841 842 843 844 845 846
  (if cdabbrev-current-window
      (save-excursion
	(set-cdabbrev-buffer)
	(setq cdabbrev-current-point (point)
	      cdabbrev-start-point cdabbrev-current-point
	      cdabbrev-stop-point
	      (if completion-search-distance
		  (max (point-min)
		       (- cdabbrev-start-point completion-search-distance))
		  (point-min))
847
	      cdabbrev-wrapped-p nil))))
Richard M. Stallman's avatar
Richard M. Stallman committed
848 849 850

(defun next-cdabbrev ()
  "Return the next possible cdabbrev expansion or nil if there isn't one.
851 852
`reset-cdabbrev' must've been called already.
This is sensitive to `case-fold-search'."
Richard M. Stallman's avatar
Richard M. Stallman committed
853 854
  ;; note that case-fold-search affects the behavior of this function
  ;; Bug: won't pick up an expansion that starts at the top of buffer
855
  (if cdabbrev-current-window
856
      (let (saved-point
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
	    saved-syntax
	    (expansion nil)
	    downcase-expansion tried-list syntax saved-point-2)
	(save-excursion
	  (unwind-protect
	      (progn
		;; Switch to current completion buffer
		(set-cdabbrev-buffer)
		;; Save current buffer state
		(setq saved-point  (point)
		      saved-syntax (syntax-table))
		;; Restore completion state
		(set-syntax-table cmpl-syntax-table)
		(goto-char cdabbrev-current-point)
		;; Loop looking for completions
		(while
		    ;; This code returns t if it should loop again
		    (cond
		      (;; search for the string
		       (search-backward cdabbrev-abbrev-string cdabbrev-stop-point t)
		       ;; return nil if the completion is valid
		       (not
			(and
			 ;; does it start with a separator char ?
			 (or (= (setq syntax (char-syntax (preceding-char))) ? )
			     (and (= syntax ?w)
				  ;; symbol char to ignore at end.  Are we at end ?
				  (progn
				    (setq saved-point-2 (point))
				    (forward-word -1)
				    (prog1
				      (= (char-syntax (preceding-char)) ? )
889
				      (goto-char saved-point-2)))))
890 891 892 893 894 895 896 897 898 899 900
			 ;; is the symbol long enough ?
			 (setq expansion (symbol-under-point))
			 ;; have we not tried this one before
			 (progn
			   ;; See if we've already used it
			   (setq tried-list cdabbrev-completions-tried
				 downcase-expansion (downcase expansion))
			   (while (and tried-list
				       (not (string-equal downcase-expansion
							  (car tried-list))))
			     ;; Already tried, don't choose this one
901
			     (setq tried-list (cdr tried-list)))
902 903 904 905
			   ;; at this point tried-list will be nil if this
			   ;; expansion has not yet been tried
			   (if tried-list
			       (setq expansion nil)
906
			       t)))))
907 908 909 910 911 912 913 914 915 916 917
		      ;; search failed
		      (cdabbrev-wrapped-p
		       ;; If already wrapped, then we've failed completely
		       nil)
		      (t
		       ;; need to wrap
		       (goto-char (setq cdabbrev-current-point
					(if completion-search-distance
					    (min (point-max) (+ cdabbrev-start-point completion-search-distance))
					    (point-max))))

918
		       (setq cdabbrev-wrapped-p t))))
919 920 921 922 923
		;; end of while loop
		(cond (expansion
		       ;; successful
		       (setq cdabbrev-completions-tried
			     (cons downcase-expansion cdabbrev-completions-tried)
924
			     cdabbrev-current-point (point)))))
925
	    (set-syntax-table saved-syntax)
926
	    (goto-char saved-point)))
927 928 929 930
	;; If no expansion, go to next window
	(cond (expansion)
	      (t (reset-cdabbrev-window)
		 (next-cdabbrev))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
931

Erik Naggum's avatar
Erik Naggum committed
932 933 934 935 936 937 938 939 940 941
;; The following must be eval'd in the minibuffer ::
;; (reset-cdabbrev "cdat")
;; (next-cdabbrev)  --> "cdat-simple"
;; (next-cdabbrev)  --> "cdat-1-2-3-4"
;; (next-cdabbrev)  --> "CDAT-UPCASE"
;; (next-cdabbrev)  --> "cdat-wrapping"
;; (next-cdabbrev)  --> "cdat_start_sym"
;; (next-cdabbrev)  --> nil
;; (next-cdabbrev)  --> nil
;; (next-cdabbrev)  --> nil
Richard M. Stallman's avatar
Richard M. Stallman committed
942

Erik Naggum's avatar
Erik Naggum committed
943 944
;; _cdat_start_sym
;; cdat-wrapping
Richard M. Stallman's avatar
Richard M. Stallman committed
945 946


Erik Naggum's avatar
Erik Naggum committed
947 948 949 950 951 952 953 954 955 956 957 958 959 960
;;---------------------------------------------------------------------------
;; Completion Database
;;---------------------------------------------------------------------------

;; We use two storage modes for the two search types ::
;;  1) Prefix {cmpl-prefix-obarray} for looking up possible completions
;;      Used by search-completion-next
;;      the value of the symbol is nil or a cons of head and tail pointers
;;  2) Interning {cmpl-obarray} to see if it's in the database
;;      Used by find-exact-completion, completion-in-database-p
;;      The value of the symbol is the completion entry

;; bad things may happen if this length is changed due to the way
;; GNU implements obarrays
Richard M. Stallman's avatar
Richard M. Stallman committed
961 962 963
(defconst cmpl-obarray-length 511)

(defvar cmpl-prefix-obarray (make-vector cmpl-obarray-length 0)
964
  "An obarray used to store the downcased completion prefixes.
Richard M. Stallman's avatar
Richard M. Stallman committed
965 966 967 968 969 970
Each symbol is bound to a list of completion entries.")

(defvar cmpl-obarray (make-vector cmpl-obarray-length 0)
  "An obarray used to store the downcased completions.
Each symbol is bound to a single completion entry.")

Erik Naggum's avatar
Erik Naggum committed
971 972 973
;;-----------------------------------------------
;; Completion Entry Structure Definition
;;-----------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
974

Erik Naggum's avatar
Erik Naggum committed
975 976
;; A completion entry is a LIST of string, prefix-symbol num-uses, and
;; last-use-time (the time the completion was last used)
Pavel Janík's avatar
Pavel Janík committed
977
;; last-use-time is t if the string should be kept permanently
Erik Naggum's avatar
Erik Naggum committed
978
;; num-uses is incremented every time the completion is used.
Richard M. Stallman's avatar
Richard M. Stallman committed
979

980
;; We chose lists because (car foo) is faster than (aref foo 0) and the
Erik Naggum's avatar
Erik Naggum committed
981
;; creation time is about the same.
Richard M. Stallman's avatar
Richard M. Stallman committed
982

Erik Naggum's avatar
Erik Naggum committed
983
;; READER MACROS
Richard M. Stallman's avatar
Richard M. Stallman committed
984 985 986 987 988

(defmacro completion-string (completion-entry)
  (list 'car completion-entry))

(defmacro completion-num-uses (completion-entry)
989
  ;;  "The number of times it has used.  Used to decide whether to save
Richard M. Stallman's avatar
Richard M. Stallman committed
990 991 992 993
  ;; it."
  (list 'car (list 'cdr completion-entry)))

(defmacro completion-last-use-time (completion-entry)
994
  ;;  "The time it was last used.  In hours since origin.  Used to decide
Pavel Janík's avatar
Pavel Janík committed
995
  ;; whether to save it.  t if one should always save it."
Richard M. Stallman's avatar
Richard M. Stallman committed
996 997 998 999 1000
  (list 'nth 2 completion-entry))

(defmacro completion-source (completion-entry)
  (list 'nth 3 completion-entry))

Erik Naggum's avatar
Erik Naggum committed
1001
;; WRITER MACROS
Richard M. Stallman's avatar
Richard M. Stallman committed
1002 1003 1004 1005 1006 1007 1008 1009 1010
(defmacro set-completion-string (completion-entry string)
  (list 'setcar completion-entry string))

(defmacro set-completion-num-uses (completion-entry num-uses)
  (list 'setcar (list 'cdr completion-entry) num-uses))

(defmacro set-completion-last-use-time (completion-entry last-use-time)
  (list 'setcar (list 'cdr (list 'cdr completion-entry)) last-use-time))

Erik Naggum's avatar
Erik Naggum committed
1011
;; CONSTRUCTOR
Richard M. Stallman's avatar
Richard M. Stallman committed
1012
(defun make-completion (string)
1013
  "Return a list of a completion entry."
Richard M. Stallman's avatar
Richard M. Stallman committed
1014 1015 1016 1017 1018 1019 1020 1021
  (list (list string 0 nil current-completion-source)))

;; Obsolete
;;(defmacro cmpl-prefix-entry-symbol (completion-entry)
;;  (list 'car (list 'cdr completion-entry)))



Erik Naggum's avatar
Erik Naggum committed
1022 1023 1024 1025
;;-----------------------------------------------
;; Prefix symbol entry definition
;;-----------------------------------------------
;; A cons of (head . tail)
Richard M. Stallman's avatar
Richard M. Stallman committed
1026

Erik Naggum's avatar
Erik Naggum committed
1027
;; READER Macros
Richard M. Stallman's avatar
Richard M. Stallman committed
1028 1029 1030 1031 1032 1033 1034

(defmacro cmpl-prefix-entry-head (prefix-entry)
  (list 'car prefix-entry))

(defmacro cmpl-prefix-entry-tail (prefix-entry)
  (list 'cdr prefix-entry))

Erik Naggum's avatar
Erik Naggum committed
1035
;; WRITER Macros
Richard M. Stallman's avatar
Richard M. Stallman committed
1036 1037 1038 1039 1040 1041 1042

(defmacro set-cmpl-prefix-entry-head (prefix-entry new-head)
  (list 'setcar prefix-entry new-head))

(defmacro set-cmpl-prefix-entry-tail (prefix-entry new-tail)
  (list 'setcdr prefix-entry new-tail))

Erik Naggum's avatar
Erik Naggum committed
1043
;; Constructor
Richard M. Stallman's avatar
Richard M. Stallman committed
1044 1045

(defun make-cmpl-prefix-entry (completion-entry-list)
1046
  "Make a new prefix entry containing only completion-entry."
Richard M. Stallman's avatar
Richard M. Stallman committed
1047 1048
  (cons completion-entry-list completion-entry-list))

Erik Naggum's avatar
Erik Naggum committed
1049 1050 1051
;;-----------------------------------------------
;; Completion Database - Utilities
;;-----------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
1052 1053

(defun clear-all-completions ()
1054
  "Initialize the completion storage.  All existing completions are lost."
Richard M. Stallman's avatar
Richard M. Stallman committed
1055 1056 1057 1058
  (interactive)
  (setq cmpl-prefix-obarray (make-vector cmpl-obarray-length 0))
  (setq cmpl-obarray (make-vector cmpl-obarray-length 0))
  (cmpl-statistics-block
1059
    (record-clear-all-completions)))
Richard M. Stallman's avatar
Richard M. Stallman committed
1060

1061 1062
(defvar completions-list-return-value)

Richard M. Stallman's avatar
Richard M. Stallman committed
1063
(defun list-all-completions ()
1064
  "Return a list of all the known completion entries."
1065
  (let ((completions-list-return-value nil))
Richard M. Stallman's avatar
Richard M. Stallman committed
1066
    (mapatoms 'list-all-completions-1 cmpl-prefix-obarray)
1067
    completions-list-return-value))
Richard M. Stallman's avatar
Richard M. Stallman committed
1068 1069 1070

(defun list-all-completions-1 (prefix-symbol)
  (if (boundp prefix-symbol)
1071
      (setq completions-list-return-value
Richard M. Stallman's avatar
Richard M. Stallman committed
1072
	    (append (cmpl-prefix-entry-head (symbol-value prefix-symbol))
1073
		    completions-list-return-value))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1074 1075

(defun list-all-completions-by-hash-bucket ()
1076
  "Return list of lists of known completion entries, organized by hash bucket."
1077
  (let ((completions-list-return-value nil))
Richard M. Stallman's avatar
Richard M. Stallman committed
1078
    (mapatoms 'list-all-completions-by-hash-bucket-1 cmpl-prefix-obarray)