completion.el 88.2 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

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1990, 1993, 1995, 1997, 2001-2018 Free Software
4
;; Foundation, Inc.
Eric S. Raymond's avatar
Eric S. Raymond committed
5

6
;; Maintainer: emacs-devel@gnu.org
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
;; GNU Emacs is free software: you can redistribute it and/or modify
14
;; it under the terms of the GNU General Public License as published by
15 16
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
17 18 19 20 21 22 23

;; 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
24
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
25 26

;;; Commentary:
Erik Naggum's avatar
Erik Naggum committed
27 28 29

;; What to put in .emacs
;;-----------------------
30
;; (dynamic-completion-mode)
Richard M. Stallman's avatar
Richard M. Stallman committed
31

Erik Naggum's avatar
Erik Naggum committed
32 33 34 35 36 37 38
;;---------------------------------------------------------------------------
;; Documentation [Slightly out of date]
;;---------------------------------------------------------------------------
;;  (also check the documentation string of the functions)
;;
;; Introduction
;;---------------
39
;;
Erik Naggum's avatar
Erik Naggum committed
40
;;     After you type a few characters, pressing the "complete" key inserts
41
;; the rest of the word you are likely to type.
Erik Naggum's avatar
Erik Naggum committed
42
;;
43
;; This watches all the words that you type and remembers them.  When
Erik Naggum's avatar
Erik Naggum committed
44
;; typing a new word, pressing "complete" (meta-return) "completes" the
45
;; word by inserting the most recently used word that begins with the
Erik Naggum's avatar
Erik Naggum committed
46 47 48 49
;; 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
50
;; entered the text by hand.  If you want the inserted extra characters
Erik Naggum's avatar
Erik Naggum committed
51 52 53
;; 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
54 55
;; 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
56 57
;; it uses an extended version of the dabbrev style completion.
;;
58 59
;;   You automatically save the completions you use to a file between
;; sessions.
Erik Naggum's avatar
Erik Naggum committed
60
;;
61
;;   Completion enables programmers to enter longer, more descriptive
Erik Naggum's avatar
Erik Naggum committed
62 63 64 65 66 67
;; variable names while typing fewer keystrokes than they normally would.
;;
;;
;; Full documentation
;;---------------------
;;
68
;;   A "word" is any string containing characters with either word or symbol
Erik Naggum's avatar
Erik Naggum committed
69 70 71 72 73 74 75 76
;; 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).
;;
77
;;  M-x completion-mode toggles whether or not new words are added to the
Erik Naggum's avatar
Erik Naggum committed
78 79 80 81 82
;; 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).
83 84
;; Activating this minor-mode (calling completion-initialize) loads
;; a completions database for a saved completions file
85
;; (default: ~/.completions).  When you exit, Emacs saves a copy of the
86 87
;; completions that you often use.  When you next start, Emacs loads in
;; the saved completion file.
Erik Naggum's avatar
Erik Naggum committed
88
;;
89 90
;;   The number of completions saved depends loosely on
;; *saved-completions-decay-factor*.  Completions that have never been
Erik Naggum's avatar
Erik Naggum committed
91 92 93
;; inserted via "complete" are not saved.  You are encouraged to experiment
;; with different functions (see compute-completion-min-num-uses).
;;
94 95
;;   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
96 97 98
;; add-permanent-completion to do this
;;
;;   Completions are saved only if enable-completion is T.  The number of old
99
;; versions kept of the saved completions file is controlled by
Erik Naggum's avatar
Erik Naggum committed
100 101 102
;; completions-file-versions-kept.
;;
;; COMPLETE KEY OPTIONS
103 104
;;   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
105 106 107 108 109 110 111 112
;;               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
113
;;   m-x kill-completion
Erik Naggum's avatar
Erik Naggum committed
114 115 116
;;     kills the completion at point.
;;   m-x add-completion
;;   m-x add-permanent-completion
117
;;
Erik Naggum's avatar
Erik Naggum committed
118 119 120 121 122
;; 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.
;;
123
;;   m-x add-completions-from-lisp-file
Erik Naggum's avatar
Erik Naggum committed
124 125 126 127 128 129 130 131 132 133 134
;;     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
135
;;   Completion is string case independent if case-fold-search has its
Erik Naggum's avatar
Erik Naggum committed
136
;;  normal default of T.  Also when the completion is inserted the case of the
137 138
;;  entry is coerced appropriately.
;;  [E.G.  APP --> APPROPRIATELY     app --> appropriately
Erik Naggum's avatar
Erik Naggum committed
139 140 141
;;         App --> Appropriately]
;;
;; INITIALIZATION
142 143
;;  The form `(completion-initialize)' initializes the completion system by
;; trying to load in the user's completions.  After the first call, further
144
;; calls have no effect so one should be careful not to put the form in a
Erik Naggum's avatar
Erik Naggum committed
145 146 147 148 149
;; site's standard site-init file.
;;
;;---------------------------------------------------------------------------
;;
;;
Richard M. Stallman's avatar
Richard M. Stallman committed
150

Erik Naggum's avatar
Erik Naggum committed
151 152 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
;;---------------------------------------------------------------------------
;; 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
;;
181
;;  completion-initialize
182
;;    Loads the completions file and sets up so that exiting emacs will
Erik Naggum's avatar
Erik Naggum committed
183 184
;;  save them.
;;
185
;;  save-completions-to-file &optional filename
Erik Naggum's avatar
Erik Naggum committed
186 187 188 189 190 191 192 193 194 195
;;  load-completions-from-file &optional filename
;;
;;-----------------------------------------------
;; Other functions
;;-----------------------------------------------
;;
;;  get-completion-list string
;;
;; These things are for manipulating the structure
;;  make-completion string num-uses
196
;;  completion-num-uses completion
Erik Naggum's avatar
Erik Naggum committed
197 198 199
;;  completion-string completion
;;  set-completion-num-uses completion num-uses
;;  set-completion-string completion string
200
;;
Erik Naggum's avatar
Erik Naggum committed
201
;;
Richard M. Stallman's avatar
Richard M. Stallman committed
202

Erik Naggum's avatar
Erik Naggum committed
203 204 205 206 207 208 209 210 211 212 213 214
;;-----------------------------------------------
;; 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
215
;;; Change Log:
Erik Naggum's avatar
Erik Naggum committed
216
;;-----------------------------------------------
217
;;    Sometime in '84 Brewster implemented a somewhat buggy version for
Erik Naggum's avatar
Erik Naggum committed
218
;; Symbolics LISPMs.
219
;;    Jan. '85 Jim became enamored of the idea and implemented a faster,
Erik Naggum's avatar
Erik Naggum committed
220 221
;; more robust version.
;;    With input from many users at TMC, (rose, craig, and gls come to mind),
222 223 224 225 226
;; 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
227 228 229 230
;; promised rewards), Jim reimplemented a version of GNU completion
;; superior to that of the LISPM version.
;;
;;-----------------------------------------------
231
;; Acknowledgments
Erik Naggum's avatar
Erik Naggum committed
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
;;-----------------------------------------------
;;  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
271
;;  - added backup protection to save-completions-to-file (prevents
Erik Naggum's avatar
Erik Naggum committed
272
;;    problems with disk full errors)
Richard M. Stallman's avatar
Richard M. Stallman committed
273

Eric S. Raymond's avatar
Eric S. Raymond committed
274 275
;;; Code:

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

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


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

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

298
(defcustom save-completions-file-name
299
  (locate-user-emacs-file "completions" ".completions")
300
  "The filename to save completions to."
301 302
  :type 'file
  :group 'completion)
Richard M. Stallman's avatar
Richard M. Stallman committed
303

304
(defcustom save-completions-retention-time 336
305
  "Discard a completion if unused for this many hours.
306
\(1 day = 24, 1 week = 168).  If this is 0, non-permanent completions
307 308 309
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
310

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

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

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

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

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

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

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

350
(defvar completion-min-length 6
351
  "The minimum length of a stored completion.
Richard M. Stallman's avatar
Richard M. Stallman committed
352 353
DON'T CHANGE WITHOUT RECOMPILING !  This is used by macros.")

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

358
(defvar completion-prefix-min-length 3
Richard M. Stallman's avatar
Richard M. Stallman committed
359 360 361
  "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
362 363 364
;;---------------------------------------------------------------------------
;; Internal Variables
;;---------------------------------------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
365 366

(defvar cmpl-initialized-p nil
367 368
  "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
369 370

(defvar cmpl-completions-accepted-p nil
371 372
  "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
373

374
(defvar cmpl-preceding-syntax)
375

376
(defvar cmpl--completion-string)
Richard M. Stallman's avatar
Richard M. Stallman committed
377

Erik Naggum's avatar
Erik Naggum committed
378 379 380
;;---------------------------------------------------------------------------
;; Low level tools
;;---------------------------------------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
381

Erik Naggum's avatar
Erik Naggum committed
382 383 384
;;-----------------------------------------------
;; String case coercion
;;-----------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
385 386

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

Erik Naggum's avatar
Erik Naggum committed
402 403 404 405 406 407
;; 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
408 409

(defun cmpl-coerce-string-case (string case-type)
410 411 412
  (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
413 414 415
	 (setq string (downcase string))
	 (aset string 0 (logand ?\337 (aref string 0)))
	 string)
416
	(t string)))
Richard M. Stallman's avatar
Richard M. Stallman committed
417 418

(defun cmpl-merge-string-cases (string-to-coerce given-string)
419
  (let ((string-case-type (cmpl-string-case-type string-to-coerce)))
Richard M. Stallman's avatar
Richard M. Stallman committed
420 421 422 423
    (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
424
			       (cmpl-string-case-type given-string)))
Richard M. Stallman's avatar
Richard M. Stallman committed
425 426 427
	  (t
	   ;; If the found string is in some unusual case, just insert it
	   ;; as is
428
	   string-to-coerce))))
Richard M. Stallman's avatar
Richard M. Stallman committed
429

Erik Naggum's avatar
Erik Naggum committed
430 431 432 433 434
;; 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
435 436


437
(defun cmpl-hours-since-origin ()
438
  (floor (float-time) 3600))
Richard M. Stallman's avatar
Richard M. Stallman committed
439

Erik Naggum's avatar
Erik Naggum committed
440 441 442 443 444 445 446 447 448
;;---------------------------------------------------------------------------
;; "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)
449
;; syntax (?w) - symbol chars to ignore at end of words (e.g. period).
Erik Naggum's avatar
Erik Naggum committed
450 451 452
;; syntax (? ) - everything else
;;
;; Thus by judicious use of scan-sexps and forward-word, we can get
453
;; the word we want relatively fast and without consing.
Erik Naggum's avatar
Erik Naggum committed
454 455
;;
;; Why do we need a separate category for "symbol chars to ignore at ends" ?
456
;; For example, in LISP we want starting :'s trimmed
Erik Naggum's avatar
Erik Naggum committed
457 458
;; so keyword argument specifiers also define the keyword completion.  And,
;; for example, in C we want `.' appearing in a structure ref. to
459
;; be kept intact in order to store the whole structure ref.; however, if
Erik Naggum's avatar
Erik Naggum committed
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
;; 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
476
;; char., however, we wanted to have completion symbols include pointer
Erik Naggum's avatar
Erik Naggum committed
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
;; 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
492

493
(defconst completion-standard-syntax-table
Richard M. Stallman's avatar
Richard M. Stallman committed
494
  (let ((table (make-syntax-table))
495
	i)
Richard M. Stallman's avatar
Richard M. Stallman committed
496 497 498 499 500
    ;; 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
501
    ;; alpha chars
502 503
    (setq i 0)
    (while (< i 26)
Richard M. Stallman's avatar
Richard M. Stallman committed
504
      (modify-syntax-entry (+ ?a i) "_" table)
505 506
      (modify-syntax-entry (+ ?A i) "_" table)
      (setq i (1+ i)))
Richard M. Stallman's avatar
Richard M. Stallman committed
507
    ;; digit chars.
508 509 510 511
    (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
512 513
    ;; Other ones
    (let ((symbol-chars '(?@ ?/ ?\\ ?* ?+ ?~ ?$ ?< ?> ?%))
514
	  (symbol-chars-ignore '(?_ ?- ?: ?.)))
515
      (dolist (char symbol-chars)
Richard M. Stallman's avatar
Richard M. Stallman committed
516
	(modify-syntax-entry char "_" table))
517
      (dolist (char symbol-chars-ignore)
518
	(modify-syntax-entry char "w" table)))
Richard M. Stallman's avatar
Richard M. Stallman committed
519 520
    table))

521
(defvar completion-syntax-table completion-standard-syntax-table
Richard M. Stallman's avatar
Richard M. Stallman committed
522
  "This variable holds the current completion syntax table.")
523
(make-variable-buffer-local 'completion-syntax-table)
Richard M. Stallman's avatar
Richard M. Stallman committed
524

Erik Naggum's avatar
Erik Naggum committed
525 526 527
;;-----------------------------------------------
;; Symbol functions
;;-----------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
528
(defvar cmpl-symbol-start nil
529
  "Holds first character of symbol, after any completion symbol function.")
Richard M. Stallman's avatar
Richard M. Stallman committed
530
(defvar cmpl-symbol-end nil
531
  "Holds last character of symbol, after any completion symbol function.")
Richard M. Stallman's avatar
Richard M. Stallman committed
532 533

(defun symbol-under-point ()
534
  "Return the symbol that the point is currently on.
535
But only if it is longer than `completion-min-length'."
536 537 538 539 540 541 542 543 544
  (with-syntax-table completion-syntax-table
    (when (memq (char-syntax (following-char)) '(?w ?_))
      ;; Cursor is on following-char and after preceding-char
      (let ((saved-point (point)))
        (setq cmpl-symbol-start (scan-sexps (1+ saved-point) -1)
              cmpl-symbol-end (scan-sexps saved-point 1))
        ;; Remove chars to ignore at the start.
        (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
               (goto-char cmpl-symbol-start)
545
               (forward-word-strictly 1)
546 547 548 549 550
               (setq cmpl-symbol-start (point))
               (goto-char saved-point)))
        ;; Remove chars to ignore at the end.
        (cond ((= (char-syntax (char-after (1- cmpl-symbol-end))) ?w)
               (goto-char cmpl-symbol-end)
551
               (forward-word-strictly -1)
552 553 554 555 556 557 558
               (setq cmpl-symbol-end (point))
               (goto-char saved-point)))
        ;; Return completion if the length is reasonable.
        (if (and (<= completion-min-length
                     (- cmpl-symbol-end cmpl-symbol-start))
                 (<= (- cmpl-symbol-end cmpl-symbol-start)
                     completion-max-length))
559 560
            (buffer-substring-no-properties
             cmpl-symbol-start cmpl-symbol-end))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
561

Erik Naggum's avatar
Erik Naggum committed
562 563 564 565 566 567 568 569 570 571 572
;; 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
573 574

(defun symbol-before-point ()
575
  "Return a string of the symbol immediately before point.
576
Returns nil if there isn't one longer than `completion-min-length'."
Richard M. Stallman's avatar
Richard M. Stallman committed
577
  ;; This is called when a word separator is typed so it must be FAST !
578 579 580 581 582 583 584 585 586
  (with-syntax-table completion-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)
                 cmpl-symbol-start (scan-sexps cmpl-symbol-end -1))
           ;; Remove chars to ignore at the start.
           (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
                  (goto-char cmpl-symbol-start)
587
                  (forward-word-strictly 1)
588 589 590 591 592
                  (setq cmpl-symbol-start (point))
                  (goto-char cmpl-symbol-end)))
           ;; Return value if long enough.
           (if (>= cmpl-symbol-end
                   (+ cmpl-symbol-start completion-min-length))
593 594
               (buffer-substring-no-properties
                cmpl-symbol-start cmpl-symbol-end)))
595 596 597 598 599
          ((= cmpl-preceding-syntax ?w)
           ;; chars to ignore at end
           (let ((saved-point (point)))
             (setq cmpl-symbol-start (scan-sexps saved-point -1))
             ;; take off chars. from end
600
             (forward-word-strictly -1)
601 602 603 604
             (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)
605
                    (forward-word-strictly 1)
606 607 608 609 610 611 612 613
                    (setq cmpl-symbol-start (point))))
             ;; Restore state.
             (goto-char saved-point)
             ;; Return completion if the length is reasonable
             (if (and (<= completion-min-length
                          (- cmpl-symbol-end cmpl-symbol-start))
                      (<= (- cmpl-symbol-end cmpl-symbol-start)
                          completion-max-length))
614 615
                 (buffer-substring-no-properties
                  cmpl-symbol-start cmpl-symbol-end)))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
616

Erik Naggum's avatar
Erik Naggum committed
617 618 619 620 621 622 623 624 625 626 627 628 629
;; 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
630 631

(defun symbol-under-or-before-point ()
Erik Naggum's avatar
Erik Naggum committed
632 633 634 635
  ;; 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.
636 637 638 639 640
  (if (memq (with-syntax-table completion-syntax-table
              (char-syntax (following-char)))
            '(?w ?_))
      (symbol-under-point)
    (symbol-before-point)))
Richard M. Stallman's avatar
Richard M. Stallman committed
641 642 643 644 645 646 647


(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
648 649 650 651 652 653 654 655
  (with-syntax-table completion-syntax-table
    (cond ((memq (setq cmpl-preceding-syntax (char-syntax (preceding-char)))
                 '(?_ ?w))
           (setq cmpl-symbol-end (point)
                 cmpl-symbol-start (scan-sexps cmpl-symbol-end -1))
           ;; Remove chars to ignore at the start.
           (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
                  (goto-char cmpl-symbol-start)
656
                  (forward-word-strictly 1)
657 658 659 660 661 662 663
                  (setq cmpl-symbol-start (point))
                  (goto-char cmpl-symbol-end)))
           ;; Return completion if the length is reasonable.
           (if (and (<= completion-prefix-min-length
                        (- cmpl-symbol-end cmpl-symbol-start))
                    (<= (- cmpl-symbol-end cmpl-symbol-start)
                        completion-max-length))
664 665
               (buffer-substring-no-properties
                cmpl-symbol-start cmpl-symbol-end))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
666

Erik Naggum's avatar
Erik Naggum committed
667 668 669 670 671 672 673 674 675 676 677 678 679
;; 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
680 681 682



Erik Naggum's avatar
Erik Naggum committed
683 684 685
;;---------------------------------------------------------------------------
;; Statistics Recording
;;---------------------------------------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
686

Erik Naggum's avatar
Erik Naggum committed
687 688
;; 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
689

Erik Naggum's avatar
Erik Naggum committed
690 691 692
;;-----------------------------------------------
;; Completion Sources
;;-----------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
693 694 695 696 697 698 699 700 701 702 703 704 705 706

;; 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
707 708 709 710
;;---------------------------------------------------------------------------
;; Completion Method #2: dabbrev-expand style
;;---------------------------------------------------------------------------
;;
711
;;   This method is used if there are no useful stored completions.  It is
Erik Naggum's avatar
Erik Naggum committed
712 713 714 715 716 717 718
;; 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
719 720

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

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

(defvar cdabbrev-current-window nil)
727 728
;;  "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
729 730

(defvar cdabbrev-wrapped-p nil)
731
;;  "Return t if the cdabbrev search has wrapped around the file.")
Richard M. Stallman's avatar
Richard M. Stallman committed
732 733 734

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

Erik Naggum's avatar
Erik Naggum committed
737 738 739 740 741 742 743
;; 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
744 745 746


(defun reset-cdabbrev (abbrev-string &optional initial-completions-tried)
747
  "Reset the cdabbrev search to search for ABBREV-STRING.
748
INITIAL-COMPLETIONS-TRIED is a list of downcased strings to ignore
Richard M. Stallman's avatar
Richard M. Stallman committed
749 750 751
during the search."
  (setq cdabbrev-abbrev-string abbrev-string
	cdabbrev-completions-tried
752 753
	(cons (downcase abbrev-string) initial-completions-tried))
  (reset-cdabbrev-window t))
Richard M. Stallman's avatar
Richard M. Stallman committed
754 755

(defun set-cdabbrev-buffer ()
Pavel Janík's avatar
Pavel Janík committed
756
  ;; cdabbrev-current-window must not be nil
Richard M. Stallman's avatar
Richard M. Stallman committed
757 758
  (set-buffer (if (eq cdabbrev-current-window t)
		  (other-buffer)
759
		  (window-buffer cdabbrev-current-window))))
Richard M. Stallman's avatar
Richard M. Stallman committed
760 761 762


(defun reset-cdabbrev-window (&optional initializep)
763
  "Reset the cdabbrev search to search for abbrev-string."
Richard M. Stallman's avatar
Richard M. Stallman committed
764 765
  ;; Set the window
  (cond (initializep
766
	 (setq cdabbrev-current-window (selected-window)))
Richard M. Stallman's avatar
Richard M. Stallman committed
767 768 769 770 771 772 773
	((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.
774
	     (setq cdabbrev-current-window t))))
775 776 777 778 779 780 781 782 783 784
  (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))
785
	      cdabbrev-wrapped-p nil))))
Richard M. Stallman's avatar
Richard M. Stallman committed
786 787 788

(defun next-cdabbrev ()
  "Return the next possible cdabbrev expansion or nil if there isn't one.
789 790
`reset-cdabbrev' must've been called already.
This is sensitive to `case-fold-search'."
Richard M. Stallman's avatar
Richard M. Stallman committed
791 792
  ;; 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
793
  (if cdabbrev-current-window
794
      (let (saved-point
795 796 797 798 799 800 801 802 803 804 805 806
	    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
807
		(set-syntax-table completion-syntax-table)
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
		(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))
824
				    (forward-word-strictly -1)
825 826
				    (prog1
				      (= (char-syntax (preceding-char)) ? )
827
				      (goto-char saved-point-2)))))
828 829 830 831 832 833 834 835 836 837 838
			 ;; 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
839
			     (setq tried-list (cdr tried-list)))
840 841 842 843
			   ;; at this point tried-list will be nil if this
			   ;; expansion has not yet been tried
			   (if tried-list
			       (setq expansion nil)
844
			       t)))))
845 846 847 848 849 850 851 852 853 854 855
		      ;; 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))))

856
		       (setq cdabbrev-wrapped-p t))))
857 858 859 860 861
		;; end of while loop
		(cond (expansion
		       ;; successful
		       (setq cdabbrev-completions-tried
			     (cons downcase-expansion cdabbrev-completions-tried)
862
			     cdabbrev-current-point (point)))))
863
	    (set-syntax-table saved-syntax)
864
	    (goto-char saved-point)))
865 866 867 868
	;; If no expansion, go to next window
	(cond (expansion)
	      (t (reset-cdabbrev-window)
		 (next-cdabbrev))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
869

Erik Naggum's avatar
Erik Naggum committed
870 871 872 873 874 875 876 877 878 879
;; 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
880

Erik Naggum's avatar
Erik Naggum committed
881 882
;; _cdat_start_sym
;; cdat-wrapping
Richard M. Stallman's avatar
Richard M. Stallman committed
883 884


Erik Naggum's avatar
Erik Naggum committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898
;;---------------------------------------------------------------------------
;; 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
899 900 901
(defconst cmpl-obarray-length 511)

(defvar cmpl-prefix-obarray (make-vector cmpl-obarray-length 0)
902
  "An obarray used to store the downcased completion prefixes.
Richard M. Stallman's avatar
Richard M. Stallman committed
903 904 905 906 907 908
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
909 910 911
;;-----------------------------------------------
;; Completion Entry Structure Definition
;;-----------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
912

Erik Naggum's avatar
Erik Naggum committed
913 914
;; 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
915
;; last-use-time is t if the string should be kept permanently
Erik Naggum's avatar
Erik Naggum committed
916
;; num-uses is incremented every time the completion is used.
Richard M. Stallman's avatar
Richard M. Stallman committed
917

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

Erik Naggum's avatar
Erik Naggum committed
921
;; READER MACROS
Richard M. Stallman's avatar
Richard M. Stallman committed
922 923 924 925 926

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

(defmacro completion-num-uses (completion-entry)
927
  ;;  "The number of times it has used.  Used to decide whether to save
Richard M. Stallman's avatar
Richard M. Stallman committed
928 929 930 931
  ;; it."
  (list 'car (list 'cdr completion-entry)))

(defmacro completion-last-use-time (completion-entry)
932
  ;;  "The time it was last used.  In hours since origin.  Used to decide
Pavel Janík's avatar
Pavel Janík committed
933
  ;; whether to save it.  t if one should always save it."
Richard M. Stallman's avatar
Richard M. Stallman committed
934 935 936 937 938
  (list 'nth 2 completion-entry))

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

Erik Naggum's avatar
Erik Naggum committed
939
;; WRITER MACROS
Richard M. Stallman's avatar
Richard M. Stallman committed
940 941 942 943 944 945 946 947 948
(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
949
;; CONSTRUCTOR
Richard M. Stallman's avatar
Richard M. Stallman committed
950
(defun make-completion (string)
951 952
  "Return a completion entry."
  (list string 0 nil current-completion-source))
Richard M. Stallman's avatar
Richard M. Stallman committed
953 954 955 956 957 958 959

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



Erik Naggum's avatar
Erik Naggum committed
960 961 962 963
;;-----------------------------------------------
;; Prefix symbol entry definition
;;-----------------------------------------------
;; A cons of (head . tail)
Richard M. Stallman's avatar
Richard M. Stallman committed
964

Erik Naggum's avatar
Erik Naggum committed
965
;; READER Macros
Richard M. Stallman's avatar
Richard M. Stallman committed
966

967
(defalias 'cmpl-prefix-entry-head 'car)
Richard M. Stallman's avatar
Richard M. Stallman committed
968

969
(defalias 'cmpl-prefix-entry-tail 'cdr)
Richard M. Stallman's avatar
Richard M. Stallman committed
970

Erik Naggum's avatar
Erik Naggum committed
971
;; WRITER Macros
Richard M. Stallman's avatar
Richard M. Stallman committed
972 973 974 975 976 977 978

(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
979
;; Constructor
Richard M. Stallman's avatar
Richard M. Stallman committed
980 981

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

Erik Naggum's avatar
Erik Naggum committed
985 986 987
;;-----------------------------------------------
;; Completion Database - Utilities
;;-----------------------------------------------
Richard M. Stallman's avatar
Richard M. Stallman committed
988 989

(defun clear-all-completions ()
990
  "Initialize the completion storage.  All existing completions are lost."
Richard M. Stallman's avatar
Richard M. Stallman committed
991 992
  (interactive)
  (setq cmpl-prefix-obarray (make-vector cmpl-obarray-length 0))
993
  (setq cmpl-obarray (make-vector cmpl-obarray-length 0)))
Richard M. Stallman's avatar
Richard M. Stallman committed
994

995 996
(defvar completions-list-return-value)

Richard M. Stallman's avatar
Richard M. Stallman committed
997
(defun list-all-completions ()
998
  "Return a list of all the known completion entries."
999
  (let ((completions-list-return-value nil))
Richard M. Stallman's avatar
Richard M. Stallman committed
1000
    (mapatoms 'list-all-completions-1 cmpl-prefix-obarray)
1001
    completions-list-return-value))
Richard M. Stallman's avatar
Richard M. Stallman committed
1002 1003 1004

(defun list-all-completions-1 (prefix-symbol)
  (if (boundp prefix-symbol)
1005
      (setq completions-list-return-value
Richard M. Stallman's avatar
Richard M. Stallman committed
1006
	    (append (cmpl-prefix-entry-head (symbol-value prefix-symbol))
1007
		    completions-list-return-value))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1008 1009

(defun list-all-completions-by-hash-bucket ()
1010
  "Return list of lists of known completion entries, organized by hash bucket."
1011
  (let ((completions-list-return-value nil))
Richard M. Stallman's avatar
Richard M. Stallman committed
1012
    (mapatoms 'list-all-completions-by-hash-bucket-1 cmpl-prefix-obarray)
1013
    completions-list-return-value))
Richard M. Stallman's avatar
Richard M. Stallman committed
1014 1015 1016

(defun list-all-completions-by-hash-bucket-1 (prefix-symbol)
  (if (boundp prefix-symbol)
1017
      (setq completions-list-return-value
Richard M. Stallman's avatar
Richard M. Stallman committed
1018
	    (cons (cmpl-prefix-entry-head (symbol-value prefix-symbol))
1019
		  completions-list-return-value))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1020 1021


Erik Naggum's avatar
Erik Naggum committed
1022 1023 1024 1025 1026 1027 1028
;;-----------------------------------------------
;; Updating the database
;;-----------------------------------------------
;;
;;   These are the internal functions used to update the datebase
;;
;;
1029 1030
(defvar completion-to-accept nil
  "Set to a string that is pending its acceptance.")
Richard M. Stallman's avatar
Richard M. Stallman committed
1031 1032
  ;; this checked by the top level reading functions

1033 1034 1035 1036 1037 1038 1039
(defvar cmpl-db-downcase-string nil
  "Setup by `find-exact-completion', etc.  The given string, downcased.")
(defvar cmpl-db-symbol nil
  "The interned symbol corresponding to `cmpl-db-downcase-string'.
Set up by `cmpl-db-symbol'.")
(defvar cmpl-db-prefix-symbol nil
  "The interned prefix symbol corresponding to `cmpl-db-downcase-string'.")
Richard M. Stallman's avatar
Richard M. Stallman committed
1040 1041
(defvar cmpl-db-entry nil)
(defvar cmpl-db-debug-p nil
Pavel Janík's avatar
Pavel Janík committed
1042
  "Set to t if you want to debug the database.")
Richard M. Stallman's avatar
Richard M. Stallman committed
1043

Erik Naggum's avatar
Erik Naggum committed
1044
;; READS
Richard M. Stallman's avatar
Richard M. Stallman committed
1045
(defun find-exact-completion (string)
1046
  "Return the completion entry for STRING or nil.
1047
Sets up `cmpl-db-downcase-string' and `cmpl-db-symbol'."
Richard M. Stallman's avatar
Richard M. Stallman committed
1048 1049 1050
  (and (boundp (setq cmpl-db-symbol
		     (intern (setq cmpl-db-downcase-string (downcase string))
			     cmpl-obarray)))
1051
       (symbol-value cmpl-db-symbol)))
Richard M. Stallman's avatar
Richard M. Stallman committed
1052 1053

(defun find-cmpl-prefix-entry (prefix-string)
1054
  "Return the prefix entry for string.
1055 1056 1057
Sets `cmpl-db-prefix-symbol'.
Prefix-string must be exactly `completion-prefix-min-length' long
and downcased.  Sets up `cmpl-db-prefix-symbol'."
Richard M. Stallman's avatar
Richard M. Stallman committed
1058 1059 1060 1061 1062 1063 1064 1065
  (and (boundp (setq cmpl-db-prefix-symbol
		     (intern prefix-string cmpl-prefix-obarray)))
       (symbol-value cmpl-db-prefix-symbol)))

(defvar inside-locate-completion-entry nil)
;; used to trap lossage in silent error correction

(defun locate-completion-entry (completion-entry prefix-entry)
1066
  "Locate the completion entry.
Christopher Zaborsky's avatar
Christopher Zaborsky committed
1067 1068
Returns a pointer to the element before the completion entry or nil if
the completion entry is at the head.
1069
Must be called after `find-exact-completion'."
Richard M. Stallman's avatar
Richard M. Stallman committed
1070
  (let ((prefix-list (cmpl-prefix-entry-head prefix-entry))
1071
	 next-prefix-list)
Richard M. Stallman's avatar
Richard M. Stallman committed
1072 1073 1074 1075 1076
    (cond
      ((not (eq (car prefix-list) completion-entry))
       ;; not already at head
       (while (and prefix-list
		   (not (eq completion-entry
1077
			    (car (setq next-prefix-list (cdr prefix-list))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1078 1079 1080 1081 1082 1083 1084
	 (setq prefix-list next-prefix-list))
       (cond (;; found
	      prefix-list)
	     ;; Didn't find it.  Database is messed up.
	     (cmpl-db-debug-p
	      ;; not found, error if debug mode
	      (error "Completion entry exists but not on prefix list - %s"
1085
		     cmpl--completion-string))
Richard M. Stallman's avatar
Richard M. Stallman committed
1086 1087 1088 1089 1090 1091 1092
	     (inside-locate-completion-entry
	      ;; recursive error: really scrod
	      (locate-completion-db-error))
	     (t
	       ;; Patch out
	       (set cmpl-db-symbol nil)
	       ;; Retry
1093
	       (locate-completion-entry-retry completion-entry)))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1094 1095 1096 1097 1098 1099

(defun locate-completion-entry-retry (old-entry)
  (let ((inside-locate-completion-entry t))
    (add-completion (completion-string old-entry)
		    (completion-num-uses old-entry)
		    (completion-last-use-time old-entry))
1100 1101 1102 1103 1104
    (let* ((cmpl-entry (find-exact-completion (completion-string old-entry)))
	   (pref-entry
	    (if cmpl-entry
		(find-cmpl-prefix-entry
		  (substring cmpl-db-downcase-string
1105
			     0 completion-prefix-min-length)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1106 1107 1108 1109
      (if (and cmpl-entry pref-entry)
	  ;; try again
	  (locate-completion-entry cmpl-entry pref-entry)
	  ;; still losing
1110
	  (locate-completion-db-error)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1111 1112 1113

(defun locate-completion-db-error ()
  ;; recursive error: really scrod
1114
  (error "Completion database corrupted.  Try M-x clear-all-completions.  Send bug report"))
Richard M. Stallman's avatar
Richard M. Stallman committed
1115

Erik Naggum's avatar
Erik Naggum committed
1116
;; WRITES
Richard M. Stallman's avatar
Richard M. Stallman committed
1117
(defun add-completion-to-tail-if-new (string)
Christopher Zaborsky's avatar
Christopher Zaborsky committed
1118
  "If STRING is not in the database add it to appropriate prefix list.
1119
STRING is added to the end of the appropriate prefix list with
Christopher Zaborsky's avatar
Christopher Zaborsky committed
1120
num-uses = 0.  The database is unchanged if it is there.  STRING must be
1121
longer than `completion-prefix-min-length'.
Richard M. Stallman's avatar
Richard M. Stallman committed
1122 1123 1124 1125 1126
This must be very fast.
Returns the completion entry."
  (or (find-exact-completion string)
      ;; not there
      (let (;; create an entry
1127
	    (entry (list (make-completion string)))
Richard M. Stallman's avatar
Richard M. Stallman committed
1128 1129 1130
	    ;; setup the prefix
	    (prefix-entry (find-cmpl-prefix-entry
			    (substring cmpl-db-downcase-string 0
1131
				       completion-prefix-min-length))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1132 1133 1134 1135 1136 1137 1138 1139
	;; The next two forms should happen as a unit (atomically) but
	;; no fatal errors should result if that is not the case.
	(cond (prefix-entry
	       ;; These two should be atomic, but nothing fatal will happen
	       ;; if they're not.
	       (setcdr (cmpl-prefix-entry-tail prefix-entry) entry)
	       (set-cmpl-prefix-entry-tail prefix-entry entry))
	      (t
1140
	       (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1141
	;; set symbol
1142
	(set cmpl-db-symbol (car entry)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1143

1144 1145 1146
(defun add-completion-to-head (completion-string)
  "If COMPLETION-STRING is not in the database, add it to prefix list.
We add COMPLETION-STRING to the head of the appropriate prefix list,
1147
or to the head of the list.
1148
COMPLETION-STRING must be longer than `completion-prefix-min-length'.
Richard M. Stallman's avatar
Richard M. Stallman committed
1149 1150 1151
Updates the saved string with the supplied string.
This must be very fast.
Returns the completion entry."
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
  (let ((cmpl--completion-string completion-string))
    ;; Handle pending acceptance
    (if completion-to-accept (accept-completion))
    ;; test if already in database
    (if (setq cmpl-db-entry (find-exact-completion completion-string))
        ;; found
        (let* ((prefix-entry (find-cmpl-prefix-entry
                              (substring cmpl-db-downcase-string 0
                                         completion-prefix-min-length)))
               (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry))
               (cmpl-ptr (cdr splice-ptr)))
          ;; update entry
          (set-completion-string cmpl-db-entry completion-string)
          ;; move to head (if necessary)
          (cond (splice-ptr
                 ;; These should all execute atomically but it is not fatal if
                 ;; they don't.
                 ;; splice it out
                 (or (setcdr splice-ptr (cdr cmpl-ptr))
                     ;; fix up tail if necessary
                     (set-cmpl-prefix-entry-tail prefix-entry splice-ptr))
                 ;; splice in at head
                 (setcdr cmpl-ptr (cmpl-prefix-entry-head prefix-entry))
                 (set-cmpl-prefix-entry-head prefix-entry cmpl-ptr)))
          cmpl-db-entry)
      ;; not there
      (let ( ;; create an entry
            (entry (list (make-completion completion-string)))
            ;; setup the prefix
            (prefix-entry (find-cmpl-prefix-entry
                           (substring cmpl-db-downcase-string 0
                                      completion-prefix-min-length))))
        (cond (prefix-entry
               ;; Splice in at head
               (setcdr entry (cmpl-prefix-entry-head prefix-entry))
               (set-cmpl-prefix-entry-head prefix-entry entry))
              (t
               ;; Start new prefix entry
               (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))))
        ;; Add it to the symbol
        (set cmpl-db-symbol (car entry))))))
1193

1194
(defun delete-completion (completion-string)
1195
  "Delete the completion from the database.
1196
String must be longer than `completion-prefix-min-length'."
Richard M. Stallman's avatar
Richard M. Stallman committed
1197
  ;; Handle pending acceptance
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210