home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / languages / elisp / interfaces / Emacs-cl-shell / completion.el < prev    next >
Encoding:
Text File  |  1990-10-15  |  105.6 KB  |  3,063 lines

  1. ;;; This is a Completion system for GNU Emacs
  2. ;;;    Version 8 with Patch 1 (fixes kbd macro playback problem)
  3. ;;;
  4. ;;;  E-Mail: 
  5. ;;;   Internet: completion@think.com, bug-completion@think.com
  6. ;;;   UUCP: {rutgers,harvard,mit-eddie}!think!completion
  7. ;;;
  8. ;;;    If you are a new user, we'd appreciate knowing your site name and
  9. ;;; any comments you have.
  10. ;;;
  11. ;;;
  12. ;;;                NO WARRANTY
  13. ;;;
  14. ;;; This software is distributed free of charge and is in the public domain.
  15. ;;; Anyone may use, duplicate or modify this program.  Thinking Machines
  16. ;;; Corporation does not restrict in any way the use of this software by
  17. ;;; anyone.
  18. ;;; 
  19. ;;; Thinking Machines Corporation provides absolutely no warranty of any kind.
  20. ;;; The entire risk as to the quality and performance of this program is with
  21. ;;; you.  In no event will Thinking Machines Corporation be liable to you for
  22. ;;; damages, including any lost profits, lost monies, or other special,
  23. ;;; incidental or consequential damages arising out of the use of this program.
  24. ;;;
  25. ;;; You must not restrict the distribution of this software.
  26. ;;;
  27. ;;; Please keep this notice and author information in any copies you make.
  28. ;;;
  29. ;;; 12/89
  30. ;;;
  31. ;;;
  32. ;;; Advertisement
  33. ;;;---------------
  34. ;;;  Try using this.  If you are like most you will be happy you did.
  35. ;;; 
  36. ;;; What to put in .emacs
  37. ;;;-----------------------
  38. ;;; (load "completion") ;; If it's not part of the standard band.
  39. ;;; (initialize-completions)
  40. ;;; 
  41. ;;; For best results, be sure to byte-compile the file first.
  42. ;;;
  43.  
  44. ;;; Authors 
  45. ;;;---------
  46. ;;;     Jim Salem      {salem@think.com}
  47. ;;;     Brewster Kahle {brewster@think.com}
  48. ;;;  Thinking Machines Corporation
  49. ;;;  245 First St., Cambridge MA 02142 (617) 876-1111
  50. ;;;
  51. ;;; Mailing Lists
  52. ;;;---------------
  53. ;;;
  54. ;;; Bugs to bug-completion@think.com
  55. ;;; Comments to completion@think.com
  56. ;;; Requests to be added completion-request@think.com
  57. ;;;
  58. ;;; Availability
  59. ;;;--------------
  60. ;;; Anonymous FTP from think.com
  61. ;;;
  62.  
  63. ;;;---------------------------------------------------------------------------
  64. ;;; Documentation [Slightly out of date]
  65. ;;;---------------------------------------------------------------------------
  66. ;;;  (also check the documentation string of the functions)
  67. ;;;
  68. ;;; Introduction
  69. ;;;---------------
  70. ;;;  
  71. ;;;     After you type a few characters, pressing the "complete" key inserts
  72. ;;; the rest of the word you are likely to type.  
  73. ;;;
  74. ;;; This watches all the words that you type and remembers them.  When 
  75. ;;; typing a new word, pressing "complete" (meta-return) "completes" the
  76. ;;; word by inserting the most recently used word that begins with the 
  77. ;;; same characters.  If you press meta-return repeatedly, it cycles
  78. ;;; through all the words it knows about.
  79. ;;;
  80. ;;;  If you like the completion then just continue typing, it is as if you
  81. ;;; entered the text by hand.  If you want the inserted extra characters 
  82. ;;; to go away, type control-w or delete.  More options are described below.
  83. ;;;
  84. ;;;  The guesses are made in the order of the most recently "used".  Typing
  85. ;;; in a word and then typing a separator character (such as a space) "uses" 
  86. ;;; the word.  So does moving a cursor over the word.
  87. ;;;
  88. ;;;   You automatically save the completions you use to a file between 
  89. ;;; sessions.  
  90. ;;;
  91. ;;;   Completion enables programmers to enter longer, more descriptive 
  92. ;;; variable names while typing fewer keystrokes than they normally would.
  93. ;;;
  94. ;;;
  95. ;;; Full documentation
  96. ;;;---------------------
  97. ;;;
  98. ;;;   A "word" is any string containing characters with either word or symbol 
  99. ;;; syntax.  [E.G. Any alphanumeric string with hypens, underscores, etc.]
  100. ;;; Unless you change the constants, you must type at least three characters
  101. ;;; for the word to be recognized.  Only words longer than 6 characters are
  102. ;;; saved.
  103. ;;;
  104. ;;;   When you load this file, completion will be on.  I suggest you use the
  105. ;;; compiled version (because it is noticibly faster).
  106. ;;;
  107. ;;;  M-X completion-mode toggles whether or not new words are added to the
  108. ;;; database by changing the value of *completep*.
  109. ;;;
  110. ;;;  SAVING/LOADING COMPLETIONS
  111. ;;;   Completions are automatically saved from one session to another
  112. ;;; (unless *save-completions-p* or *completep* is nil).
  113. ;;; Loading this file (or calling initialize-completions) causes EMACS
  114. ;;; to load a completions database for a saved completions file 
  115. ;;; (default: ~/.completions).  When you exit, EMACS saves a copy of the
  116. ;;; completions that you 
  117. ;;; often use.  When you next start, EMACS loads in the saved completion file.
  118. ;;;
  119. ;;;   The number of completions saved depends loosely on 
  120. ;;; *saved-completions-decay-factor*.  Completions that have never been 
  121. ;;; inserted via "complete" are not saved.  You are encouraged to experiment
  122. ;;; with different functions (see compute-completion-min-num-uses).
  123. ;;;
  124. ;;;   Some completions are permanent and are always saved out.  These 
  125. ;;; completions have their num-uses slot set to T.  Use 
  126. ;;; add-permanent-completion to do this
  127. ;;;
  128. ;;;   Completions are saved only if *completep* is T.  The number of old
  129. ;;; versions kept of the saved completions file is controlled by 
  130. ;;; *completion-file-versions-kept*.
  131. ;;;
  132. ;;; COMPLETE KEY OPTIONS
  133. ;;;   The complete function takes a numeric arguments.  
  134. ;;;  control-u :: leave the point at the beginning of the completion rather 
  135. ;;;               than the middle.
  136. ;;;  a number  :: rotate through the possible completions by that amount
  137. ;;;  `-'       :: same as -1 (insert previous completion)
  138. ;;;
  139. ;;; HOW THE DATABASE IS MAINTAINED
  140. ;;;  <write>
  141. ;;;
  142. ;;; UPDATING THE DATABASE MANUALLY
  143. ;;;   m-x kill-completion 
  144. ;;;     kills the completion at point.
  145. ;;;   m-x add-completion
  146. ;;;   m-x add-permanent-completion
  147. ;;;   
  148. ;;; UPDATING THE DATABASE FROM A SOURCE CODE FILE
  149. ;;;   m-x add-completions-from-buffer
  150. ;;;     Parses all the definition names from a C or LISP mode buffer and
  151. ;;;     adds them to the completion database.
  152. ;;;
  153. ;;;   m-x add-completions-from-lisp-file 
  154. ;;;     Parses all the definition names from a C or Lisp mode file and
  155. ;;;     adds them to the completion database.
  156. ;;;
  157. ;;; HOW A COMPLETION IS FOUND
  158. ;;;  <write>
  159. ;;;
  160. ;;; STRING CASING
  161. ;;;   Completion is string case independent if case-fold-search has its 
  162. ;;;  normal default of T.  Also when the completion is inserted the case of the
  163. ;;;  entry is coerced appropriately.  
  164. ;;;  [E.G.  APP --> APPROPRIATELY     app --> appropriately  
  165. ;;;         App --> Appropriately]
  166. ;;;
  167. ;;; INITIALIZATION
  168. ;;;  The form `(initialize-completions)' initializes the completion system by 
  169. ;;; trying to load in the user's completions.  After the first cal, further 
  170. ;;; calls have no effect so one should be careful not to put the form in a 
  171. ;;; site's standard site-init file.
  172. ;;;
  173. ;;;---------------------------------------------------------------------------
  174. ;;;
  175. ;;;
  176.  
  177. ;;;-----------------------------------------------
  178. ;;; Porting Notes
  179. ;;;-----------------------------------------------
  180. ;;;
  181. ;;;  Based on 18.49.20
  182. ;;;  Tested on vanilla version.
  183. ;;;  This requires the standard cl.el file.  It could easily rewritten to not 
  184. ;;; require it.  It defines remove which is not in cl.el.
  185. ;;;
  186. ;;;  FUNCTIONS BASHED
  187. ;;; The following functions are bashed but it is done carefully and should not
  188. ;;; cause problems ::
  189. ;;;   kill-region, next-line, previous-line, newline, newline-and-indent,
  190. ;;;   kill-emacs
  191. ;;;
  192. ;;;
  193. ;;;---------------------------------------------------------------------------
  194. ;;; Functions you might like to call
  195. ;;;---------------------------------------------------------------------------
  196. ;;;
  197. ;;;  add-completion  string &optional num-uses
  198. ;;;    Adds a new string to the database
  199. ;;;
  200. ;;;  add-permanent-completion  string
  201. ;;;    Adds a new string to the database with num-uses = T
  202. ;;;
  203.  
  204. ;;;  kill-completion string
  205. ;;;    Kills the completion from the database.
  206. ;;;
  207. ;;;  clear-all-completions
  208. ;;;    Clears the database
  209. ;;;
  210. ;;;  list-all-completions
  211. ;;;    Returns a list of all completions.
  212. ;;;
  213. ;;;
  214. ;;;  next-completion string &optional index
  215. ;;;    Returns a completion entry that starts with string.
  216. ;;;
  217. ;;;  find-exact-completion string
  218. ;;;    Returns a completion entry that exactly matches string.
  219. ;;;
  220. ;;;  complete
  221. ;;;    Inserts a completion at point
  222. ;;;
  223. ;;;  initialize-completions
  224. ;;;    Loads the completions file and sets up so that exiting emacs will 
  225. ;;;  save them.
  226. ;;;
  227. ;;;  save-completions-to-file &optional filename  
  228. ;;;  load-completions-from-file &optional filename
  229. ;;;
  230. ;;;-----------------------------------------------
  231. ;;; Other functions
  232. ;;;-----------------------------------------------
  233. ;;;
  234. ;;;  get-completion-list string
  235. ;;;
  236. ;;; These things are for manipulating the structure
  237. ;;;  make-completion string num-uses
  238. ;;;  completion-num-uses completion 
  239. ;;;  completion-string completion
  240. ;;;  set-completion-num-uses completion num-uses
  241. ;;;  set-completion-string completion string
  242. ;;;  
  243. ;;;
  244.  
  245. ;;;-----------------------------------------------
  246. ;;; To Do :: (anybody ?)
  247. ;;;-----------------------------------------------
  248. ;;;
  249. ;;;   Fix saved completion (it's not saving enough)
  250. ;;;
  251. ;;;   Implement Lookup and keyboard interface in C
  252. ;;;   Add package prefix smarts (for Common Lisp)
  253. ;;;   Add autoprompting of possible completions after every keystroke (fast
  254. ;;;      terminals only !)
  255. ;;;   Add doc. to texinfo
  256. ;;;
  257. ;;;
  258. ;;;-----------------------------------------------
  259. ;;; History ::
  260. ;;;-----------------------------------------------
  261. ;;;    Sometime in '84 Brewster implemented a somewhat buggy version for 
  262. ;;; Symbolics LISPMs.
  263. ;;;    Jan. '85 Jim became enamored of the idea and implemented a faster, 
  264. ;;; more robust version.
  265. ;;;    With input from many users at TMC, (rose, craig, and gls come to mind),
  266. ;;; the current style of interface was developed. 
  267. ;;;    9/87, Jim and Brewster took terminals home.  Yuck.  After 
  268. ;;; complaining for a while Brewester implemented a subset of the current 
  269. ;;; LISPM version for GNU Emacs.  
  270. ;;;    8/88  After complaining for a while (and with sufficient 
  271. ;;; promised rewards), Jim reimplemented a version of GNU completion
  272. ;;; superior to that of the LISPM version.
  273. ;;;
  274.  
  275. ;;;-----------------------------------------------
  276. ;;; Change Log
  277. ;;;-----------------------------------------------
  278. ;;; From Version 7 to 8
  279. ;;;  - Misc. changes to comments
  280. ;;;  - new completion key bindings: c-x o, M->, M-<, c-a, c-e
  281. ;;;  - cdabbrev now checks all the visible window buffers and the "other buffer"
  282. ;;;  - `%' is now a symbol character rather than a separator (except in C mode)
  283. ;;;
  284. ;;; From Version 6 to 7
  285. ;;;  - Fixed bug with saving out .completion file the first time
  286. ;;;
  287. ;;; From Version 5 to 6
  288. ;;;  - removed statistics recording
  289. ;;;  - reworked advise to handle autoloads
  290. ;;;  - Fixed fortran mode support
  291. ;;;  - Added new cursor motion triggers
  292. ;;;
  293. ;;; From Version 4 to 5
  294. ;;;  - doesn't bother saving if nothing has changed
  295. ;;;  - auto-save if haven't used for a 1/2 hour
  296. ;;;  - save period extended to two weeks
  297. ;;;  - minor fix to capitalization code
  298. ;;;  - added *completion-auto-save-period* to variables recorded.
  299. ;;;  - added reenter protection to cmpl-record-statistics-filter
  300. ;;;  - added backup protection to save-completions-to-file (prevents 
  301. ;;;    problems with disk full errors)
  302.  
  303. ;;;-----------------------------------------------
  304. ;;; Requires
  305. ;;; Version
  306. ;;;-----------------------------------------------
  307.  
  308. (require 'cl) ;; DOTIMES, etc.
  309.  
  310. (defconst *completion-version*  8
  311.   "For EMACS version 18.52 (seems to work on 18.51 and 18.49 too)")
  312.  
  313. ;;;---------------------------------------------------------------------------
  314. ;;; User changeable parameters
  315. ;;;---------------------------------------------------------------------------
  316.  
  317. (defvar *completep* t
  318.   "*Set to nil to turn off the completion hooks.
  319. (No new words added to the database or saved to the init file)."
  320.   )
  321.  
  322. (defvar *save-completions-p* t
  323.   "*If non-nil, the most useful completions are saved to disk when
  324. exiting EMACS.  See *saved-completions-decay-factor*.")
  325.  
  326. (defvar *saved-completions-filename* "~/.completions"
  327.   "*The filename to save completions to.")
  328.  
  329. (defvar *saved-completion-retention-time* 336
  330.   "*The maximum amout of time to save a completion for if it has not been used.
  331. In hours.  (1 day = 24, 1 week = 168).  If this is 0, non-permanent completions
  332. will not be saved unless these are used.  Default is two weeks."
  333.   )
  334.  
  335. (defvar *separator-character-uses-completion-p* nil
  336.   "*If non-nil, typing a separator character after a completion symbol that
  337. is not part of the database marks it as used (so it will be saved).")
  338.  
  339. (defvar *completion-file-versions-kept* kept-new-versions
  340.   "*Set this to the number of versions you want save-completions-to-file
  341. to keep.")
  342.  
  343. (defvar *print-next-completion-speed-threshold* 4800
  344.   "*The baud rate at or above which to print the next potential completion
  345. after inserting the current one."
  346.   )
  347.  
  348. (defvar *print-next-completion-does-cdabbrev-search-p* nil
  349.   "*If non-NIL, the next completion prompt will also do a cdabbrev search.
  350. This can be time consuming.")
  351.  
  352. (defvar *cdabbrev-radius* 15000
  353.   "*How far to search for cdabbrevs.  In number of characters.  If nil, the 
  354. whole buffer is searched.")
  355.  
  356. (defvar *modes-for-completion-find-file-hook* '(lisp c)
  357.   "*A list of modes {either c or lisp}.  Definitions from visited files
  358. of those types are automatically added to the completion database.")
  359.  
  360. (defvar *record-cmpl-statistics-p* nil
  361.   "*If non-nil, statistics are automatically recorded.")
  362.  
  363. (defvar *completion-auto-save-period* 1800
  364.   "*The period in seconds to wait for emacs to be idle before autosaving
  365. the completions.  Default is a 1/2 hour.")
  366.  
  367. (defconst *completion-min-length* nil ;; defined below in eval-when
  368.   "*The minimum length of a stored completion.
  369. DON'T CHANGE WITHOUT RECOMPILING !  This is used by macros.")
  370.  
  371. (defconst *completion-max-length* nil ;; defined below in eval-when
  372.   "*The maximum length of a stored completion.
  373. DON'T CHANGE WITHOUT RECOMPILING !  This is used by macros.")
  374.  
  375. (defconst *completion-prefix-min-length* nil ;; defined below in eval-when
  376.   "The minimum length of a completion search string.
  377. DON'T CHANGE WITHOUT RECOMPILING !  This is used by macros.")
  378.  
  379. (defmacro eval-when-compile-load-eval (&rest body)
  380.   (dolist (form body)
  381.     (eval form)
  382.     )
  383.   (cons 'progn body)
  384.   )
  385.  
  386. (defun completion-eval-when ()
  387.   (eval-when-compile-load-eval
  388.    ;; These vars. are defined at both compile and load time.
  389.    (setq *completion-min-length* 6)
  390.    (setq *completion-max-length* 200)
  391.    (setq *completion-prefix-min-length* 3)
  392.    )) ;; eval-when
  393.  
  394. (completion-eval-when)
  395.  
  396. ;;;---------------------------------------------------------------------------
  397. ;;; Internal Variables
  398. ;;;---------------------------------------------------------------------------
  399.  
  400. (defvar cmpl-initialized-p nil
  401.   "Set to t when the completion system is initialized.  Indicates that the old 
  402. completion file has been read in.")
  403.  
  404. (defvar cmpl-completions-accepted-p nil
  405.   "Set to T as soon as the first completion has been accepted.  Used to
  406. decide whether to save completions.")
  407.  
  408.  
  409. ;;;---------------------------------------------------------------------------
  410. ;;; Low level tools
  411. ;;;---------------------------------------------------------------------------
  412.  
  413. ;;;-----------------------------------------------
  414. ;;; Misc.
  415. ;;;-----------------------------------------------
  416.  
  417. (defun remove (item list)
  418.   (setq list (copy-sequence list))
  419.   (delq item list)
  420.   )
  421.  
  422. ;;; inspired by sun-mouse.el
  423. (defun minibuffer-window-selected-p ()
  424.   "True iff the current window is the minibuffer."
  425.   (= (screen-height)
  426.      (nth 3 (window-edges (selected-window)))    ; The bottom edge.
  427.      ))
  428.  
  429. (defun function-needs-autoloading-p (symbol)
  430.   ;; True iff symbol is represents an autoloaded function and has not yet been
  431.   ;; autoloaded.
  432.   (and (listp (symbol-function symbol))
  433.        (eq 'autoload (car (symbol-function symbol)))
  434.        ))
  435.  
  436. (defun function-defined-and-loaded (symbol)
  437.   ;; True iff symbol is bound to a loaded function.
  438.   (and (fboundp symbol) (not (function-needs-autoloading-p symbol)))
  439.   )
  440.  
  441. (defmacro read-time-eval (form)
  442.   ;; Like the #. reader macro
  443.   (eval form)
  444.   )
  445.  
  446. ;;;-----------------------------------------------
  447. ;;; Advise
  448. ;;;-----------------------------------------------
  449.  
  450. (defmacro completion-advise (function-name where &rest body)
  451.   "Adds the body code before calling function.  This advise is not compiled.
  452. WHERE is either :BEFORE or :AFTER."
  453.   (completion-advise-1 function-name where body)
  454.   )
  455.  
  456. (defmacro cmpl-apply-as-top-level (function arglist)
  457.   "Calls function-name interactively if INTERACTIVE-P is true."
  458.   (list 'if (list 'and '(let ((executing-macro nil)) (interactive-p))
  459.           (list 'commandp function))
  460.     (list 'call-interactively function)
  461.     (list 'apply function arglist)
  462.     ))
  463.  
  464. (defun cmpl-defun-preamble (function-name)
  465.   (let ((doc-string
  466.      (condition-case e
  467.           ;; This condition-case is here to stave
  468.           ;; off bizarre load time errors 18.52 gets
  469.           ;; on the function c-mode
  470.           (documentation function-name)
  471.         (error nil)))
  472.     (interactivep (commandp function-name))
  473.     )
  474.     (append
  475.      (if doc-string (list doc-string))
  476.      (if interactivep '((interactive)))
  477.      )))
  478.  
  479. (defun completion-advise-1 (function-name where body &optional new-name)
  480.   (unless new-name (setq new-name function-name))
  481.   (let ((quoted-name (list 'quote function-name))
  482.     (quoted-new-name (list 'quote new-name))
  483.     )
  484.  
  485.   (cond ((function-needs-autoloading-p function-name)
  486.      (list* 'defun function-name '(&rest arglist)
  487.         (append
  488.          (cmpl-defun-preamble function-name)
  489.          (list (list 'load (second (symbol-function function-name)))
  490.                (list 'eval
  491.                  (list 'completion-advise-1 quoted-name
  492.                    (list 'quote where) (list 'quote body)
  493.                    quoted-new-name))
  494.                (list 'cmpl-apply-as-top-level quoted-new-name 'arglist)
  495.                )))
  496.      )
  497.     (t
  498.      (let ((old-def-name
  499.         (intern (concat "$$$cmpl-" (symbol-name function-name))))
  500.            )
  501.     
  502.        (list 'progn
  503.          (list 'defvar old-def-name
  504.                (list 'symbol-function quoted-name))
  505.          (list* 'defun new-name '(&rest arglist)
  506.             (append
  507.              (cmpl-defun-preamble function-name)
  508.              (ecase where
  509.                (:before
  510.                 (list (cons 'progn body)
  511.                   (list 'cmpl-apply-as-top-level
  512.                     old-def-name 'arglist)))
  513.                (:after
  514.                 (list* (list 'cmpl-apply-as-top-level
  515.                      old-def-name 'arglist)
  516.                    body)
  517.                 )))
  518.             )))
  519.      ))))             
  520.  
  521. ;;;-----------------------------------------------
  522. ;;; String case coercion
  523. ;;;-----------------------------------------------
  524.  
  525. (defun cmpl-string-case-type (string)
  526.   "Returns :capitalized, :up, :down, :mixed, or :neither."
  527.   (let ((case-fold-search nil))
  528.     (cond ((string-match "[a-z]" string)
  529.        (cond ((string-match "[A-Z]" string)
  530.           (cond ((and (> (length string) 1)
  531.                   (null (string-match "[A-Z]" string 1)))
  532.              ':capitalized)
  533.             (t
  534.              ':mixed)))
  535.          (t ':down)))
  536.       (t
  537.        (cond ((string-match "[A-Z]" string)
  538.           ':up)
  539.          (t ':neither))))
  540.     ))
  541.  
  542. ;;; Tests -
  543. ;;; (cmpl-string-case-type "123ABCDEF456") --> :up
  544. ;;; (cmpl-string-case-type "123abcdef456") --> :down
  545. ;;; (cmpl-string-case-type "123aBcDeF456") --> :mixed
  546. ;;; (cmpl-string-case-type "123456")       --> :neither
  547. ;;; (cmpl-string-case-type "Abcde123")     --> :capitalized
  548.  
  549. (defun cmpl-coerce-string-case (string case-type)
  550.   (cond ((eq case-type ':down) (downcase string))
  551.     ((eq case-type ':up) (upcase string))
  552.     ((eq case-type ':capitalized)
  553.      (setq string (downcase string))
  554.      (aset string 0 (logand ?\337 (aref string 0)))
  555.      string)
  556.     (t string)
  557.     ))
  558.  
  559. (defun cmpl-merge-string-cases (string-to-coerce given-string)
  560.   (let ((string-case-type (cmpl-string-case-type string-to-coerce))
  561.     )
  562.     (cond ((memq string-case-type '(:down :up :capitalized))
  563.        ;; Found string is in a standard case.  Coerce to a type based on
  564.        ;; the given string
  565.        (cmpl-coerce-string-case string-to-coerce
  566.                    (cmpl-string-case-type given-string))
  567.        )
  568.       (t
  569.        ;; If the found string is in some unusual case, just insert it
  570.        ;; as is
  571.        string-to-coerce)
  572.       )))
  573.  
  574. ;;; Tests -
  575. ;;; (cmpl-merge-string-cases "AbCdEf456" "abc")     --> AbCdEf456
  576. ;;; (cmpl-merge-string-cases "abcdef456" "ABC")     --> ABCDEF456
  577. ;;; (cmpl-merge-string-cases "ABCDEF456" "Abc")     --> Abcdef456
  578. ;;; (cmpl-merge-string-cases "ABCDEF456" "abc")     --> abcdef456
  579.  
  580.  
  581. ;;;-----------------------------------------------
  582. ;;; Emacs Idle Time hooks
  583. ;;;-----------------------------------------------
  584.  
  585. (defvar cmpl-emacs-idle-process nil)
  586.  
  587. (defvar cmpl-emacs-idle-interval 150
  588.   "Seconds between possible updates the record statistics process.")
  589.  
  590. (defun init-cmpl-emacs-idle-process ()
  591.   "Initialize the completion record statistics process."
  592.   (let ((live (and cmpl-emacs-idle-process
  593.            (eq (process-status cmpl-emacs-idle-process) 'run)))
  594.     ;; do not allocate a pty
  595.     (process-connection-type nil))
  596.     (if live
  597.     (kill-process cmpl-emacs-idle-process))
  598.     (if cmpl-emacs-idle-process
  599.     (delete-process cmpl-emacs-idle-process))
  600.     (setq cmpl-emacs-idle-process
  601.       (start-process "cmpl-emacs-idle" nil
  602.              "loadst" 
  603.              "-n" (int-to-string cmpl-emacs-idle-interval)))
  604.     (process-kill-without-query cmpl-emacs-idle-process)
  605.     (set-process-filter cmpl-emacs-idle-process 'cmpl-emacs-idle-filter)
  606.     ))
  607.  
  608. (defvar cmpl-emacs-buffer nil)
  609. (defvar cmpl-emacs-point 0)
  610. (defvar cmpl-emacs-last-command nil)
  611. (defvar cmpl-emacs-last-command-char nil)
  612. (defun cmpl-emacs-idle-p ()
  613.   ;; returns T if emacs has been idle
  614.   (if (and (eq cmpl-emacs-buffer (current-buffer))
  615.        (= cmpl-emacs-point (point))
  616.        (eq cmpl-emacs-last-command last-command)
  617.        (eq last-command-char last-command-char)
  618.        )
  619.       t ;; idle
  620.       ;; otherwise, update count
  621.       (setq cmpl-emacs-buffer (current-buffer))
  622.       (setq cmpl-emacs-point (point))
  623.       (setq cmpl-emacs-last-command last-command)
  624.       (setq last-command-char last-command-char)
  625.       nil
  626.       ))
  627.        
  628. (defvar cmpl-emacs-idle-time 0
  629.   "The idle time of emacs in seconds.")
  630.  
  631. (defvar inside-cmpl-emacs-idle-filter nil)
  632. (defvar cmpl-emacs-idle-time-hooks nil)
  633.  
  634. (defun cmpl-emacs-idle-filter (proc string)
  635.   ;; This gets called every cmpl-emacs-idle-interval seconds
  636.   ;; Update idle time clock
  637.   (if (cmpl-emacs-idle-p)
  638.       (incf cmpl-emacs-idle-time cmpl-emacs-idle-interval)
  639.       (setq cmpl-emacs-idle-time 0))
  640.  
  641.   (unless inside-cmpl-emacs-idle-filter
  642.     ;; Don't reenter if we are hung
  643.  
  644.     (setq inside-cmpl-emacs-idle-filter t)
  645.   
  646.     (dolist (function cmpl-emacs-idle-time-hooks)
  647.       (condition-case e
  648.        (funcall function)
  649.      (error nil)
  650.      ))
  651.     (setq inside-cmpl-emacs-idle-filter nil)
  652.     ))
  653.  
  654.  
  655. ;;;-----------------------------------------------
  656. ;;; Time 
  657. ;;;-----------------------------------------------
  658. ;;; What a backwards way to get the time ! Unfortunately, GNU Emacs
  659. ;;; doesn't have an accessible time function.
  660.  
  661. (defconst cmpl-hours-per-day  24)
  662. (defconst cmpl-hours-per-year  (* 365 cmpl-hours-per-day))
  663. (defconst cmpl-hours-per-4-years  (+ (* 4 cmpl-hours-per-year)
  664.                     cmpl-hours-per-day))
  665. (defconst cmpl-days-since-start-of-year
  666.     '(0 31 59 90 120 151 181 212 243 273 304 334))
  667. (defconst cmpl-days-since-start-of-leap-year
  668.     '(0 31 60 91 121 152 182 213 244 274 305 335))
  669. (defconst cmpl-months
  670.     '("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec")
  671.   )
  672.  
  673. (defun cmpl-hours-since-1900-internal (month day year hours)
  674.   "Month is an integer from 1 to 12.  Year is a two digit integer (19XX)"
  675.   (+ ;; Year
  676.     (* (/ (1- year) 4) cmpl-hours-per-4-years)
  677.     (* (1+ (mod (1- year) 4)) cmpl-hours-per-year)
  678.     ;; minus two to account for  1968 rather than 1900
  679.     ;; month
  680.     (* cmpl-hours-per-day
  681.        (nth (1- month) (if (zerop (mod year 4))
  682.                cmpl-days-since-start-of-leap-year
  683.                cmpl-days-since-start-of-year)))
  684.     (* (1- day) cmpl-hours-per-day)
  685.     hours
  686.     ))
  687.  
  688. (defun cmpl-month-from-string (month-string)
  689.   "Month string is a three char. month string"
  690.   (let ((count 1))
  691.     (do ((list cmpl-months (cdr list))
  692.      )
  693.     ((or (null list) (string-equal month-string (car list))))
  694.       (setq count (1+ count)))
  695.     (if (> count 12)
  696.     (error "Unknown month - %s" month-string))
  697.     count))
  698.  
  699. (defun cmpl-hours-since-1900 (&optional time-string)
  700.   "String is a string in the format of current-time-string (the default)."
  701.   (let* ((string (or time-string (current-time-string)))
  702.      (month (cmpl-month-from-string (substring string 4 7)))
  703.      (day (string-to-int (substring string 8 10)))
  704.      (year (string-to-int (substring string 22 24)))
  705.      (hour (string-to-int (substring string 11 13)))
  706.      )
  707.     (cmpl-hours-since-1900-internal month day year hour)
  708.     ))
  709.  
  710. ;;; Tests -
  711. ;;;(cmpl-hours-since-1900 "Wed Jan  1 00:00:28 1900") --> 0
  712. ;;;(cmpl-hours-since-1900 "Wed Nov  2 23:00:28 1988") --> 778751
  713. ;;;(cmpl-hours-since-1900 "Wed Jan 23 14:34:28 1988") --> 771926
  714. ;;;(cmpl-hours-since-1900 "Wed Feb 23 14:34:28 1988") --> 772670
  715. ;;;(cmpl-hours-since-1900 "Wed Mar 23 14:34:28 1988") --> 773366
  716. ;;;(cmpl-hours-since-1900 "Wed Apr 23 14:34:28 1988") --> 774110
  717. ;;;(cmpl-hours-since-1900 "Wed May 23 14:34:28 1988") --> 774830
  718. ;;;(cmpl-hours-since-1900 "Wed Jun 23 14:34:28 1988") --> 775574
  719. ;;;(cmpl-hours-since-1900 "Wed Jul 23 14:34:28 1988") --> 776294
  720. ;;;(cmpl-hours-since-1900 "Wed Aug 23 14:34:28 1988") --> 777038
  721. ;;;(cmpl-hours-since-1900 "Wed Sep 23 14:34:28 1988") --> 777782
  722. ;;;(cmpl-hours-since-1900 "Wed Oct 23 14:34:28 1988") --> 778502
  723. ;;;(cmpl-hours-since-1900 "Wed Nov 23 14:34:28 1988") --> 779246
  724. ;;;(cmpl-hours-since-1900 "Wed Dec 23 14:34:28 1988") --> 779966
  725. ;;;(cmpl-hours-since-1900 "Wed Jan 23 14:34:28 1957") --> 500198
  726. ;;;(cmpl-hours-since-1900 "Wed Feb 23 14:34:28 1957") --> 500942
  727. ;;;(cmpl-hours-since-1900 "Wed Mar 23 14:34:28 1957") --> 501614
  728. ;;;(cmpl-hours-since-1900 "Wed Apr 23 14:34:28 1957") --> 502358
  729. ;;;(cmpl-hours-since-1900 "Wed May 23 14:34:28 1957") --> 503078
  730. ;;;(cmpl-hours-since-1900 "Wed Jun 23 14:34:28 1957") --> 503822
  731. ;;;(cmpl-hours-since-1900 "Wed Jul 23 14:34:28 1957") --> 504542
  732. ;;;(cmpl-hours-since-1900 "Wed Aug 23 14:34:28 1957") --> 505286
  733. ;;;(cmpl-hours-since-1900 "Wed Sep 23 14:34:28 1957") --> 506030
  734. ;;;(cmpl-hours-since-1900 "Wed Oct 23 14:34:28 1957") --> 506750
  735. ;;;(cmpl-hours-since-1900 "Wed Nov 23 14:34:28 1957") --> 507494
  736. ;;;(cmpl-hours-since-1900 "Wed Dec 23 14:34:28 1957") --> 508214
  737.  
  738.  
  739. ;;;---------------------------------------------------------------------------
  740. ;;; "Symbol" parsing functions
  741. ;;;---------------------------------------------------------------------------
  742. ;;; The functions symbol-before-point, symbol-under-point, etc. quickly return
  743. ;;; an appropriate symbol string.  The strategy is to temporarily change
  744. ;;; the syntax table to enable fast symbol searching.  There are three classes
  745. ;;; of syntax in these "symbol" syntax tables ::
  746. ;;;
  747. ;;; syntax (?_) - "symbol" chars (e.g. alphanumerics)
  748. ;;; syntax (?w) - symbol chars to ignore at end of words (e.g. period).  
  749. ;;; syntax (? ) - everything else
  750. ;;;
  751. ;;; Thus by judicious use of scan-sexps and forward-word, we can get
  752. ;;; the word we want relatively fast and without consing.  
  753. ;;;
  754. ;;; Why do we need a separate category for "symbol chars to ignore at ends" ?
  755. ;;; For example, in LISP we want starting :'s trimmed 
  756. ;;; so keyword argument specifiers also define the keyword completion.  And,
  757. ;;; for example, in C we want `.' appearing in a structure ref. to
  758. ;;; be kept intact in order to store the whole structure ref.; however, if 
  759. ;;; it appears at the end of a symbol it should be discarded because it is
  760. ;;; probably used as a period.
  761.  
  762. ;;; Here is the default completion syntax ::
  763. ;;; Symbol chars :: A-Z a-z 0-9 @ / \ * + ~ $ < > %
  764. ;;; Symbol chars to ignore at ends :: _ : . -
  765. ;;; Separator chars. :: <tab> <space> ! ^ & ( ) = ` | { } [ ] ; " ' #
  766. ;;;                     , ? <Everything else>
  767.  
  768. ;;; Mode specific differences and notes ::
  769. ;;;  LISP diffs ->
  770. ;;;    Symbol chars :: ! & ? = ^
  771. ;;;
  772. ;;; C diffs ->
  773. ;;;   Separator chars :: + * / : %
  774. ;;;  A note on the hypen (`-').  Perhaps, the hypen should also be a separator
  775. ;;; char., however, we wanted to have completion symbols include pointer 
  776. ;;; references.  For example, "foo->bar" is a symbol as far as completion is
  777. ;;; concerned.
  778. ;;;
  779. ;;; FORTRAN diffs ->
  780. ;;;   Separator chars :: + - * / :
  781. ;;;
  782. ;;; Pathname diffs ->
  783. ;;;   Symbol chars :: .
  784. ;;;  Of course there is no pathname "mode" and in fact we have not implemented
  785. ;;; this table.  However, if there was such a mode, this is what it would look
  786. ;;; like.
  787.  
  788. ;;;-----------------------------------------------
  789. ;;; Table definitions
  790. ;;;-----------------------------------------------
  791.  
  792. (defun make-standard-completion-syntax-table ()
  793.   (let ((table (make-vector 256 0)) ;; default syntax is whitespace
  794.     )
  795.     ;; alpha chars
  796.     (dotimes (i 26)
  797.       (modify-syntax-entry (+ ?a i) "_" table)
  798.       (modify-syntax-entry (+ ?A i) "_" table))
  799.     ;; digit chars.
  800.     (dotimes (i 10)
  801.       (modify-syntax-entry (+ ?0 i) "_" table))
  802.     ;; Other ones
  803.     (let ((symbol-chars '(?@ ?/ ?\\ ?* ?+ ?~ ?$ ?< ?> ?%))
  804.       (symbol-chars-ignore '(?_ ?- ?: ?.))
  805.       )
  806.       (dolist (char symbol-chars)
  807.     (modify-syntax-entry char "_" table))
  808.       (dolist (char symbol-chars-ignore)
  809.     (modify-syntax-entry char "w" table)
  810.     )
  811.       )
  812.     table))
  813.  
  814. (defconst cmpl-standard-syntax-table (make-standard-completion-syntax-table))
  815.  
  816. (defun make-lisp-completion-syntax-table ()
  817.   (let ((table (copy-syntax-table cmpl-standard-syntax-table))
  818.     (symbol-chars '(?! ?& ?? ?= ?^))
  819.     )
  820.     (dolist (char symbol-chars)
  821.       (modify-syntax-entry char "_" table))
  822.     table))
  823.        
  824. (defun make-c-completion-syntax-table ()
  825.   (let ((table (copy-syntax-table cmpl-standard-syntax-table))
  826.     (separator-chars '(?+ ?* ?/ ?: ?%))
  827.     )
  828.     (dolist (char separator-chars)
  829.       (modify-syntax-entry char " " table))
  830.     table))
  831.  
  832. (defun make-fortran-completion-syntax-table ()
  833.   (let ((table (copy-syntax-table cmpl-standard-syntax-table))
  834.     (separator-chars '(?+ ?- ?* ?/ ?:))
  835.     )
  836.     (dolist (char separator-chars)
  837.       (modify-syntax-entry char " " table))
  838.     table))
  839.  
  840. (defconst cmpl-lisp-syntax-table       (make-lisp-completion-syntax-table))
  841. (defconst cmpl-c-syntax-table          (make-c-completion-syntax-table))
  842. (defconst cmpl-fortran-syntax-table    (make-fortran-completion-syntax-table))
  843.  
  844. (defvar cmpl-syntax-table cmpl-standard-syntax-table
  845.   "This variable holds the current completion syntax table.")
  846. (make-variable-buffer-local 'cmpl-syntax-table)
  847.  
  848. ;;;-----------------------------------------------
  849. ;;; Installing the appropriate mode tables
  850. ;;;-----------------------------------------------
  851.  
  852. (completion-advise lisp-mode-variables :after
  853.   (setq cmpl-syntax-table cmpl-lisp-syntax-table)
  854.   )
  855.  
  856. (completion-advise c-mode :after
  857.   (setq cmpl-syntax-table cmpl-c-syntax-table)
  858.   )
  859.  
  860. (completion-advise fortran-mode :after
  861.   (setq cmpl-syntax-table cmpl-fortran-syntax-table)
  862.   (completion-setup-fortran-mode)
  863.   )
  864.  
  865. ;;;-----------------------------------------------
  866. ;;; Symbol functions
  867. ;;;-----------------------------------------------
  868. (defvar cmpl-symbol-start nil
  869.   "Set to the first character of the symbol after one of the completion
  870. symbol functions is called.")
  871. (defvar cmpl-symbol-end nil
  872.   "Set to the last character of the symbol after one of the completion
  873. symbol functions is called.")
  874. ;;; These are temp. vars. we use to avoid using let.
  875. ;;;   Why ?  Small speed improvement.
  876. (defvar cmpl-saved-syntax nil)
  877. (defvar cmpl-saved-point nil)
  878.  
  879. (defun symbol-under-point ()
  880.   "Returns the symbol that the point is currently on if it is longer
  881. than *completion-min-length*."
  882.   (setq cmpl-saved-syntax (syntax-table))
  883.   (set-syntax-table cmpl-syntax-table)
  884.   (cond 
  885.   ;; Cursor is on following-char and after preceding-char
  886.     ((memq (char-syntax (following-char)) '(?w ?_))     
  887.      (setq cmpl-saved-point (point)
  888.        cmpl-symbol-start (scan-sexps (1+ cmpl-saved-point) -1)
  889.        cmpl-symbol-end (scan-sexps cmpl-saved-point 1))
  890.      ;; remove chars to ignore at the start
  891.      (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
  892.         (goto-char cmpl-symbol-start)
  893.         (forward-word 1)
  894.         (setq cmpl-symbol-start (point))
  895.         (goto-char cmpl-saved-point)
  896.         ))
  897.      ;; remove chars to ignore at the end
  898.      (cond ((= (char-syntax (char-after (1- cmpl-symbol-end))) ?w)
  899.         (goto-char cmpl-symbol-end)
  900.         (forward-word -1)
  901.         (setq cmpl-symbol-end (point))
  902.         (goto-char cmpl-saved-point)
  903.         ))
  904.      ;; restore state
  905.      (set-syntax-table cmpl-saved-syntax)
  906.      ;; Return completion if the length is reasonable
  907.      (if (and (<= (read-time-eval *completion-min-length*)
  908.           (- cmpl-symbol-end cmpl-symbol-start))
  909.           (<= (- cmpl-symbol-end cmpl-symbol-start)
  910.           (read-time-eval *completion-max-length*)))
  911.      (buffer-substring cmpl-symbol-start cmpl-symbol-end))
  912.      )
  913.     (t 
  914.      ;; restore table if no symbol
  915.      (set-syntax-table cmpl-saved-syntax)
  916.      nil)
  917.     ))
  918.  
  919. ;;; tests for symbol-under-point
  920. ;;;  `^' indicates cursor pos. where value is returned
  921. ;;;  simple-word-test
  922. ;;;  ^^^^^^^^^^^^^^^^  --> simple-word-test
  923. ;;;  _harder_word_test_
  924. ;;;  ^^^^^^^^^^^^^^^^^^ --> harder_word_test
  925. ;;;  .___.______.
  926. ;;;  --> nil
  927. ;;;  /foo/bar/quux.hello
  928. ;;;  ^^^^^^^^^^^^^^^^^^^ --> /foo/bar/quux.hello
  929. ;;;
  930.  
  931. (defun symbol-before-point ()
  932.   "Returns a string of the symbol immediately before point
  933. or nil if there isn't one longer than *completion-min-length*."       
  934.   ;; This is called when a word separator is typed so it must be FAST !
  935.   (setq cmpl-saved-syntax (syntax-table))
  936.   (set-syntax-table cmpl-syntax-table)
  937.   ;; Cursor is on following-char and after preceding-char
  938.   (cond ((= (setq cmpl-preceding-syntax (char-syntax (preceding-char))) ?_)
  939.      ;; No chars. to ignore at end
  940.      (setq cmpl-symbol-end (point)
  941.            cmpl-symbol-start (scan-sexps (1+ cmpl-symbol-end) -1)
  942.            )
  943.      ;; remove chars to ignore at the start
  944.      (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
  945.         (goto-char cmpl-symbol-start)
  946.         (forward-word 1)
  947.         (setq cmpl-symbol-start (point))
  948.         (goto-char cmpl-symbol-end)
  949.         ))
  950.      ;; restore state
  951.      (set-syntax-table cmpl-saved-syntax)
  952.      ;; return value if long enough
  953.      (if (>= cmpl-symbol-end
  954.          (+ cmpl-symbol-start
  955.             (read-time-eval *completion-min-length*)))
  956.          (buffer-substring cmpl-symbol-start cmpl-symbol-end))
  957.      )
  958.     ((= cmpl-preceding-syntax ?w)
  959.      ;; chars to ignore at end
  960.      (setq cmpl-saved-point (point)
  961.            cmpl-symbol-start (scan-sexps (1+ cmpl-saved-point) -1))
  962.      ;; take off chars. from end
  963.      (forward-word -1)
  964.      (setq cmpl-symbol-end (point))
  965.      ;; remove chars to ignore at the start
  966.      (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
  967.         (goto-char cmpl-symbol-start)
  968.         (forward-word 1)
  969.         (setq cmpl-symbol-start (point))
  970.         ))
  971.      ;; restore state
  972.      (goto-char cmpl-saved-point)
  973.      (set-syntax-table cmpl-saved-syntax)
  974.      ;; Return completion if the length is reasonable
  975.      (if (and (<= (read-time-eval *completion-min-length*)
  976.               (- cmpl-symbol-end cmpl-symbol-start))
  977.           (<= (- cmpl-symbol-end cmpl-symbol-start)
  978.               (read-time-eval *completion-max-length*)))
  979.          (buffer-substring cmpl-symbol-start cmpl-symbol-end))
  980.      )
  981.     (t 
  982.      ;; restore table if no symbol
  983.      (set-syntax-table cmpl-saved-syntax)
  984.      nil)
  985.     ))
  986.  
  987. ;;; tests for symbol-before-point
  988. ;;;  `^' indicates cursor pos. where value is returned
  989. ;;;  simple-word-test
  990. ;;;  ^ --> nil
  991. ;;;   ^ --> nil
  992. ;;;          ^  --> simple-w
  993. ;;;                  ^ --> simple-word-test
  994. ;;;  _harder_word_test_
  995. ;;;                   ^  --> harder_word_test
  996. ;;;                    ^  --> harder_word_test
  997. ;;;          ^ --> harder
  998. ;;;  .___....
  999. ;;;  --> nil
  1000. (defun symbol-under-or-before-point ()
  1001.   ;;; This could be made slightly faster but it is better to avoid
  1002.   ;;; copying all the code.
  1003.   ;;; However, it is only used by the completion string prompter.
  1004.   ;;; If it comes into common use, it could be rewritten.
  1005.   (setq cmpl-saved-syntax (syntax-table))
  1006.   (set-syntax-table cmpl-syntax-table)
  1007.   (cond ((memq (char-syntax (following-char)) '(?w ?_))
  1008.      (set-syntax-table cmpl-saved-syntax)
  1009.      (symbol-under-point))
  1010.     (t
  1011.      (set-syntax-table cmpl-saved-syntax)
  1012.      (symbol-before-point))
  1013.     ))
  1014.  
  1015.  
  1016. (defun symbol-before-point-for-complete ()
  1017.   ;; "Returns a string of the symbol immediately before point
  1018.   ;; or nil if there isn't one.  Like symbol-before-point but doesn't trim the
  1019.   ;; end chars."
  1020.   ;; Cursor is on following-char and after preceding-char
  1021.   (setq cmpl-saved-syntax (syntax-table))
  1022.   (set-syntax-table cmpl-syntax-table)
  1023.   (cond ((memq (setq cmpl-preceding-syntax (char-syntax (preceding-char)))
  1024.            '(?_ ?w))
  1025.      (setq cmpl-symbol-end (point)
  1026.            cmpl-symbol-start (scan-sexps (1+ cmpl-symbol-end) -1)
  1027.            )
  1028.      ;; remove chars to ignore at the start
  1029.      (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
  1030.         (goto-char cmpl-symbol-start)
  1031.         (forward-word 1)
  1032.         (setq cmpl-symbol-start (point))
  1033.         (goto-char cmpl-symbol-end)
  1034.         ))
  1035.      ;; restore state
  1036.      (set-syntax-table cmpl-saved-syntax)
  1037.      ;; Return completion if the length is reasonable
  1038.      (if (and (<= (read-time-eval
  1039.                *completion-prefix-min-length*)
  1040.               (- cmpl-symbol-end cmpl-symbol-start))
  1041.           (<= (- cmpl-symbol-end cmpl-symbol-start)
  1042.               (read-time-eval *completion-max-length*)))
  1043.          (buffer-substring cmpl-symbol-start cmpl-symbol-end))
  1044.      )
  1045.     (t 
  1046.      ;; restore table if no symbol
  1047.      (set-syntax-table cmpl-saved-syntax)
  1048.      nil)
  1049.     ))
  1050.  
  1051. ;;; tests for symbol-before-point-for-complete
  1052. ;;;  `^' indicates cursor pos. where value is returned
  1053. ;;;  simple-word-test
  1054. ;;;  ^ --> nil
  1055. ;;;   ^ --> nil
  1056. ;;;          ^  --> simple-w
  1057. ;;;                  ^ --> simple-word-test
  1058. ;;;  _harder_word_test_
  1059. ;;;                   ^  --> harder_word_test
  1060. ;;;                    ^  --> harder_word_test_
  1061. ;;;          ^ --> harder_
  1062. ;;;  .___....
  1063. ;;;  --> nil
  1064.  
  1065.  
  1066.  
  1067. ;;;---------------------------------------------------------------------------
  1068. ;;; Statistics Recording
  1069. ;;;---------------------------------------------------------------------------
  1070.  
  1071. ;;; Note that the guts of this has been turned off.  The guts
  1072. ;;; are in completion-stats.el.
  1073.  
  1074. ;;;-----------------------------------------------
  1075. ;;; Conditionalizing code on *record-cmpl-statistics-p*
  1076. ;;;-----------------------------------------------
  1077. ;;; All statistics code outside this block should use this
  1078. (defmacro cmpl-statistics-block (&rest body)
  1079.   "Only executes body if we are recording statistics."
  1080.   (list 'cond
  1081.     (list* '*record-cmpl-statistics-p* body)
  1082.     ))         
  1083.  
  1084. ;;;-----------------------------------------------
  1085. ;;; Completion Sources
  1086. ;;;-----------------------------------------------
  1087.  
  1088. ;; ID numbers
  1089. (defconst cmpl-source-unknown 0)
  1090. (defconst cmpl-source-init-file 1)
  1091. (defconst cmpl-source-file-parsing 2)
  1092. (defconst cmpl-source-separator 3)
  1093. (defconst cmpl-source-cursor-moves 4)
  1094. (defconst cmpl-source-interactive 5)
  1095. (defconst cmpl-source-cdabbrev 6)
  1096. (defconst num-cmpl-sources 7)
  1097. (defvar current-completion-source cmpl-source-unknown)
  1098.  
  1099.  
  1100.  
  1101. ;;;---------------------------------------------------------------------------
  1102. ;;; Completion Method #2: dabbrev-expand style
  1103. ;;;---------------------------------------------------------------------------
  1104. ;;;
  1105. ;;;   This method is used if there are no useful stored completions.  It is 
  1106. ;;; based on dabbrev-expand with these differences :
  1107. ;;;   1) Faster (we don't use regexps)
  1108. ;;;   2) case coercion handled correctly
  1109. ;;; This is called cdabbrev to differentiate it.
  1110. ;;;   We simply search backwards through the file looking for words which
  1111. ;;; start with the same letters we are trying to complete.
  1112. ;;;
  1113.  
  1114. (defvar cdabbrev-completions-tried nil)
  1115. ;;;  "A list of all the cdabbrev completions since the last reset.")
  1116.  
  1117. (defvar cdabbrev-current-point 0)
  1118. ;;;  "The current point position the cdabbrev search is at.")
  1119.  
  1120. (defvar cdabbrev-current-window nil)
  1121. ;;;  "The current window we are looking for cdabbrevs in.  T if looking in
  1122. ;;; (other-buffer), NIL if no more  cdabbrevs.")
  1123.  
  1124. (defvar cdabbrev-wrapped-p nil)
  1125. ;;;  "T if the cdabbrev search has wrapped around the file.")
  1126.  
  1127. (defvar cdabbrev-abbrev-string "")
  1128. (defvar cdabbrev-start-point 0)
  1129.  
  1130. ;;; Test strings for cdabbrev
  1131. ;;; cdat-upcase   ;;same namestring
  1132. ;;; CDAT-UPCASE   ;;ok
  1133. ;;; cdat2         ;;too short
  1134. ;;; cdat-1-2-3-4  ;;ok
  1135. ;;; a-cdat-1      ;;doesn't start correctly
  1136. ;;; cdat-simple   ;;ok
  1137.  
  1138.  
  1139. (defun reset-cdabbrev (abbrev-string &optional initial-completions-tried)
  1140.   "Resets the cdabbrev search to search for abbrev-string.
  1141. initial-completions-tried is a list of downcased strings to ignore
  1142. during the search."
  1143.   (setq cdabbrev-abbrev-string abbrev-string
  1144.     cdabbrev-completions-tried
  1145.     (cons (downcase abbrev-string) initial-completions-tried)
  1146.     )
  1147.   (reset-cdabbrev-window t)
  1148.   )
  1149.  
  1150. (defun set-cdabbrev-buffer ()
  1151.   ;; cdabbrev-current-window must not be NIL
  1152.   (set-buffer (if (eq cdabbrev-current-window t)
  1153.           (other-buffer)
  1154.           (window-buffer cdabbrev-current-window)))
  1155.   )
  1156.  
  1157.  
  1158. (defun reset-cdabbrev-window (&optional initializep)
  1159.   "Resets the cdabbrev search to search for abbrev-string.
  1160. initial-completions-tried is a list of downcased strings to ignore
  1161. during the search."
  1162.   ;; Set the window
  1163.   (cond (initializep
  1164.      (setq cdabbrev-current-window (selected-window))
  1165.      )
  1166.     ((eq cdabbrev-current-window t)
  1167.      ;; Everything has failed
  1168.      (setq cdabbrev-current-window nil))
  1169.     (cdabbrev-current-window
  1170.      (setq cdabbrev-current-window (next-window cdabbrev-current-window))
  1171.      (if (eq cdabbrev-current-window (selected-window))
  1172.          ;; No more windows, try other buffer.
  1173.          (setq cdabbrev-current-window t)))
  1174.     )
  1175.   (when cdabbrev-current-window
  1176.     (save-excursion
  1177.       (set-cdabbrev-buffer)
  1178.       (setq cdabbrev-current-point (point)
  1179.         cdabbrev-start-point cdabbrev-current-point
  1180.         cdabbrev-stop-point
  1181.         (if *cdabbrev-radius*
  1182.         (max (point-min)
  1183.              (- cdabbrev-start-point *cdabbrev-radius*))
  1184.         (point-min))
  1185.         cdabbrev-wrapped-p nil)
  1186.       )))
  1187.  
  1188. (defun next-cdabbrev ()
  1189.   "Return the next possible cdabbrev expansion or nil if there isn't one.
  1190. reset-cdabbrev must've been called.  This is sensitive to case-fold-search."
  1191.   ;; note that case-fold-search affects the behavior of this function
  1192.   ;; Bug: won't pick up an expansion that starts at the top of buffer
  1193.   (when cdabbrev-current-window
  1194.     (let (saved-point 
  1195.       saved-syntax
  1196.       (expansion nil)
  1197.       downcase-expansion tried-list syntax saved-point-2)
  1198.       (save-excursion
  1199.     (unwind-protect
  1200.         (progn
  1201.           ;; Switch to current completion buffer
  1202.           (set-cdabbrev-buffer)
  1203.           ;; Save current buffer state
  1204.           (setq saved-point  (point)
  1205.             saved-syntax (syntax-table))
  1206.           ;; Restore completion state
  1207.           (set-syntax-table cmpl-syntax-table)
  1208.           (goto-char cdabbrev-current-point)
  1209.           ;; Loop looking for completions
  1210.           (while
  1211.           ;; This code returns t if it should loop again
  1212.           (cond
  1213.             (;; search for the string
  1214.              (search-backward cdabbrev-abbrev-string cdabbrev-stop-point t)
  1215.              ;; return nil if the completion is valid
  1216.              (not
  1217.               (and
  1218.                ;; does it start with a separator char ?
  1219.                (or (= (setq syntax (char-syntax (preceding-char))) ? )
  1220.                (and (= syntax ?w)
  1221.                 ;; symbol char to ignore at end.  Are we at end ?
  1222.                 (progn
  1223.                   (setq saved-point-2 (point))
  1224.                   (forward-word -1)
  1225.                   (prog1
  1226.                     (= (char-syntax (preceding-char)) ? )
  1227.                     (goto-char saved-point-2)
  1228.                     ))))
  1229.                ;; is the symbol long enough ?
  1230.                (setq expansion (symbol-under-point))
  1231.                ;; have we not tried this one before
  1232.                (progn
  1233.              ;; See if we've already used it
  1234.              (setq tried-list cdabbrev-completions-tried
  1235.                    downcase-expansion (downcase expansion))
  1236.              (while (and tried-list
  1237.                      (not (string-equal downcase-expansion
  1238.                             (car tried-list))))
  1239.                ;; Already tried, don't choose this one
  1240.                (setq tried-list (cdr tried-list))
  1241.                )
  1242.              ;; at this point tried-list will be nil if this
  1243.              ;; expansion has not yet been tried
  1244.              (if tried-list
  1245.                  (setq expansion nil)
  1246.                  t)
  1247.              ))))
  1248.             ;; search failed
  1249.             (cdabbrev-wrapped-p
  1250.              ;; If already wrapped, then we've failed completely
  1251.              nil)
  1252.             (t
  1253.              ;; need to wrap
  1254.              (goto-char (setq cdabbrev-current-point
  1255.                       (if *cdabbrev-radius*
  1256.                       (min (point-max) (+ cdabbrev-start-point *cdabbrev-radius*))
  1257.                       (point-max))))
  1258.         
  1259.              (setq cdabbrev-wrapped-p t))
  1260.             ))
  1261.           ;; end of while loop
  1262.           (cond (expansion
  1263.              ;; successful
  1264.              (setq cdabbrev-completions-tried
  1265.                (cons downcase-expansion cdabbrev-completions-tried)
  1266.                cdabbrev-current-point (point))))
  1267.           )
  1268.       (set-syntax-table saved-syntax)
  1269.       (goto-char saved-point)
  1270.       ))
  1271.       ;; If no expansion, go to next window
  1272.       (cond (expansion)
  1273.         (t (reset-cdabbrev-window)
  1274.            (next-cdabbrev)))
  1275.       )))
  1276.  
  1277. ;;; The following must be eval'd in the minibuffer ::
  1278. ;;; (reset-cdabbrev "cdat")
  1279. ;;; (next-cdabbrev)  --> "cdat-simple"
  1280. ;;; (next-cdabbrev)  --> "cdat-1-2-3-4"
  1281. ;;; (next-cdabbrev)  --> "CDAT-UPCASE"
  1282. ;;; (next-cdabbrev)  --> "cdat-wrapping"
  1283. ;;; (next-cdabbrev)  --> "cdat_start_sym"
  1284. ;;; (next-cdabbrev)  --> nil
  1285. ;;; (next-cdabbrev)  --> nil
  1286. ;;; (next-cdabbrev)  --> nil
  1287.  
  1288. ;;; _cdat_start_sym
  1289. ;;; cdat-wrapping
  1290.  
  1291.  
  1292. ;;;---------------------------------------------------------------------------
  1293. ;;; Completion Database
  1294. ;;;---------------------------------------------------------------------------
  1295.  
  1296. ;;; We use two storage modes for the two search types ::
  1297. ;;;  1) Prefix {cmpl-prefix-obarray} for looking up possible completions
  1298. ;;;      Used by search-completion-next
  1299. ;;;      the value of the symbol is nil or a cons of head and tail pointers
  1300. ;;;  2) Interning {cmpl-obarray} to see if it's in the database
  1301. ;;;      Used by find-exact-completion, completion-in-database-p
  1302. ;;;      The value of the symbol is the completion entry
  1303.  
  1304. ;;; bad things may happen if this length is changed due to the way
  1305. ;;; GNU implements obarrays
  1306. (defconst cmpl-obarray-length 511)
  1307.  
  1308. (defvar cmpl-prefix-obarray (make-vector cmpl-obarray-length 0)
  1309.   "An obarray used to store the downcased completion prefices.
  1310. Each symbol is bound to a list of completion entries.")
  1311.  
  1312. (defvar cmpl-obarray (make-vector cmpl-obarray-length 0)
  1313.   "An obarray used to store the downcased completions.
  1314. Each symbol is bound to a single completion entry.")
  1315.  
  1316. ;;;-----------------------------------------------
  1317. ;;; Completion Entry Structure Definition
  1318. ;;;-----------------------------------------------
  1319.  
  1320. ;;; A completion entry is a LIST of string, prefix-symbol num-uses, and
  1321. ;;; last-use-time (the time the completion was last used)
  1322. ;;; last-use-time is T if the string should be kept permanently
  1323. ;;; num-uses is incremented everytime the completion is used.
  1324.  
  1325. ;;; We chose lists because (car foo) is faster than (aref foo 0) and the 
  1326. ;;; creation time is about the same.
  1327.  
  1328. ;;; READER MACROS
  1329.  
  1330. (defmacro completion-string (completion-entry)
  1331.   (list 'car completion-entry))
  1332.  
  1333. (defmacro completion-num-uses (completion-entry)
  1334.   ;;  "The number of times it has used.  Used to decide whether to save 
  1335.   ;; it."
  1336.   (list 'car (list 'cdr completion-entry)))
  1337.  
  1338. (defmacro completion-last-use-time (completion-entry)
  1339.   ;;  "The time it was last used.  In hours since 1900.  Used to decide
  1340.   ;; whether to save it.  T if one should always save it."
  1341.   (list 'nth 2 completion-entry))
  1342.  
  1343. (defmacro completion-source (completion-entry)
  1344.   (list 'nth 3 completion-entry))
  1345.  
  1346. ;;; WRITER MACROS
  1347. (defmacro set-completion-string (completion-entry string)
  1348.   (list 'setcar completion-entry string))
  1349.  
  1350. (defmacro set-completion-num-uses (completion-entry num-uses)
  1351.   (list 'setcar (list 'cdr completion-entry) num-uses))
  1352.  
  1353. (defmacro set-completion-last-use-time (completion-entry last-use-time)
  1354.   (list 'setcar (list 'cdr (list 'cdr completion-entry)) last-use-time))
  1355.  
  1356. ;;; CONSTRUCTOR
  1357. (defun make-completion (string)
  1358.   "Returns a list of a completion entry."
  1359.   (list (list string 0 nil current-completion-source)))
  1360.  
  1361. ;; Obsolete
  1362. ;;(defmacro cmpl-prefix-entry-symbol (completion-entry)
  1363. ;;  (list 'car (list 'cdr completion-entry)))
  1364.  
  1365.  
  1366.  
  1367. ;;;-----------------------------------------------
  1368. ;;; Prefix symbol entry definition
  1369. ;;;-----------------------------------------------
  1370. ;;; A cons of (head . tail)
  1371.  
  1372. ;;; READER Macros
  1373.  
  1374. (defmacro cmpl-prefix-entry-head (prefix-entry)
  1375.   (list 'car prefix-entry))
  1376.  
  1377. (defmacro cmpl-prefix-entry-tail (prefix-entry)
  1378.   (list 'cdr prefix-entry))
  1379.  
  1380. ;;; WRITER Macros
  1381.  
  1382. (defmacro set-cmpl-prefix-entry-head (prefix-entry new-head)
  1383.   (list 'setcar prefix-entry new-head))
  1384.  
  1385. (defmacro set-cmpl-prefix-entry-tail (prefix-entry new-tail)
  1386.   (list 'setcdr prefix-entry new-tail))
  1387.  
  1388. ;;; Contructor
  1389.  
  1390. (defun make-cmpl-prefix-entry (completion-entry-list)
  1391.   "Makes a new prefix entry containing only completion-entry."
  1392.   (cons completion-entry-list completion-entry-list))
  1393.  
  1394. ;;;-----------------------------------------------
  1395. ;;; Completion Database - Utilities
  1396. ;;;-----------------------------------------------
  1397.  
  1398. (defun clear-all-completions ()
  1399.   "Initializes the completion storage.  All existing completions are lost."
  1400.   (interactive)
  1401.   (setq cmpl-prefix-obarray (make-vector cmpl-obarray-length 0))
  1402.   (setq cmpl-obarray (make-vector cmpl-obarray-length 0))
  1403.   (cmpl-statistics-block
  1404.     (record-clear-all-completions))
  1405.   )
  1406.  
  1407. (defun list-all-completions ()
  1408.   "Returns a list of all the known completion entries."
  1409.   (let ((return-completions nil))
  1410.     (mapatoms 'list-all-completions-1 cmpl-prefix-obarray)
  1411.     return-completions))
  1412.  
  1413. (defun list-all-completions-1 (prefix-symbol)
  1414.   (if (boundp prefix-symbol)
  1415.       (setq return-completions
  1416.         (append (cmpl-prefix-entry-head (symbol-value prefix-symbol))
  1417.             return-completions))))
  1418.  
  1419. (defun list-all-completions-by-hash-bucket ()
  1420.   "Returns a list of lists of all the known completion entries organized by 
  1421. hash bucket."
  1422.   (let ((return-completions nil))
  1423.     (mapatoms 'list-all-completions-by-hash-bucket-1 cmpl-prefix-obarray)
  1424.     return-completions))
  1425.  
  1426. (defun list-all-completions-by-hash-bucket-1 (prefix-symbol)
  1427.   (if (boundp prefix-symbol)
  1428.       (setq return-completions
  1429.         (cons (cmpl-prefix-entry-head (symbol-value prefix-symbol))
  1430.           return-completions))))
  1431.  
  1432.  
  1433. ;;;-----------------------------------------------
  1434. ;;; Updating the database
  1435. ;;;-----------------------------------------------
  1436. ;;;
  1437. ;;;   These are the internal functions used to update the datebase
  1438. ;;;
  1439. ;;;
  1440. (defvar completion-to-accept nil)
  1441.   ;;"Set to a string that is pending its acceptance."
  1442.   ;; this checked by the top level reading functions
  1443.  
  1444. (defvar cmpl-db-downcase-string nil)
  1445.   ;; "Setup by find-exact-completion, etc.  The given string, downcased."
  1446. (defvar cmpl-db-symbol nil)
  1447.   ;; "The interned symbol corresponding to cmpl-db-downcase-string.
  1448.   ;; Set up by cmpl-db-symbol."
  1449. (defvar cmpl-db-prefix-symbol nil)
  1450.   ;; "The interned prefix symbol corresponding to cmpl-db-downcase-string."
  1451. (defvar cmpl-db-entry nil)
  1452. (defvar cmpl-db-debug-p nil
  1453.   "Set to T if you want to debug the database.")
  1454.  
  1455. ;;; READS
  1456. (defun find-exact-completion (string)
  1457.   "Returns the completion entry for string or nil.
  1458. Sets up cmpl-db-downcase-string and cmpl-db-symbol."
  1459.   (and (boundp (setq cmpl-db-symbol
  1460.              (intern (setq cmpl-db-downcase-string (downcase string))
  1461.                  cmpl-obarray)))
  1462.        (symbol-value cmpl-db-symbol)
  1463.        ))
  1464.  
  1465. (defun find-cmpl-prefix-entry (prefix-string)
  1466.   "Returns the prefix entry for string. Sets cmpl-db-prefix-symbol.
  1467. Prefix-string must be exactly *completion-prefix-min-length* long
  1468. and downcased.  Sets up cmpl-db-prefix-symbol."
  1469.   (and (boundp (setq cmpl-db-prefix-symbol
  1470.              (intern prefix-string cmpl-prefix-obarray)))
  1471.        (symbol-value cmpl-db-prefix-symbol)))
  1472.  
  1473. (defvar inside-locate-completion-entry nil)
  1474. ;; used to trap lossage in silent error correction
  1475.  
  1476. (defun locate-completion-entry (completion-entry prefix-entry)
  1477.   "Locates the completion entry.  Returns a pointer to the element
  1478. before the completion entry or nil if the completion entry is at the head.
  1479. Must be called after find-exact-completion."
  1480.   (let ((prefix-list (cmpl-prefix-entry-head prefix-entry))
  1481.      next-prefix-list
  1482.      )
  1483.     (cond
  1484.       ((not (eq (car prefix-list) completion-entry))
  1485.        ;; not already at head
  1486.        (while (and prefix-list
  1487.            (not (eq completion-entry
  1488.                 (car (setq next-prefix-list (cdr prefix-list)))
  1489.                 )))
  1490.      (setq prefix-list next-prefix-list))
  1491.        (cond (;; found
  1492.           prefix-list)
  1493.          ;; Didn't find it.  Database is messed up.
  1494.          (cmpl-db-debug-p
  1495.           ;; not found, error if debug mode
  1496.           (error "Completion entry exists but not on prefix list - %s"
  1497.              string))
  1498.          (inside-locate-completion-entry
  1499.           ;; recursive error: really scrod
  1500.           (locate-completion-db-error))
  1501.          (t
  1502.            ;; Patch out
  1503.            (set cmpl-db-symbol nil)
  1504.            ;; Retry
  1505.            (locate-completion-entry-retry completion-entry)
  1506.            ))))))
  1507.  
  1508. (defun locate-completion-entry-retry (old-entry)
  1509.   (let ((inside-locate-completion-entry t))
  1510.     (add-completion (completion-string old-entry)
  1511.             (completion-num-uses old-entry)
  1512.             (completion-last-use-time old-entry))
  1513.     (let ((cmpl-entry (find-exact-completion (completion-string old-entry)))
  1514.       (pref-entry
  1515.        (if cmpl-entry
  1516.            (find-cmpl-prefix-entry
  1517.          (substring cmpl-db-downcase-string
  1518.                 0 *completion-prefix-min-length*))))
  1519.       )
  1520.       (if (and cmpl-entry pref-entry)
  1521.       ;; try again
  1522.       (locate-completion-entry cmpl-entry pref-entry)
  1523.       ;; still losing
  1524.       (locate-completion-db-error))
  1525.       )))
  1526.  
  1527. (defun locate-completion-db-error ()
  1528.   ;; recursive error: really scrod
  1529.   (error "Completion database corrupted.  Try M-x clear-all-completions.  Send bug report.")
  1530.   )
  1531.  
  1532. ;;; WRITES
  1533. (defun add-completion-to-tail-if-new (string)
  1534.   "If the string is not in the database it is added to the end of the
  1535. approppriate prefix list with num-uses = 0.  The database is unchanged if it 
  1536. is there.  string must be longer than *completion-prefix-min-length*.
  1537. This must be very fast.
  1538. Returns the completion entry."
  1539.   (or (find-exact-completion string)
  1540.       ;; not there
  1541.       (let (;; create an entry
  1542.         (entry (make-completion string))
  1543.         ;; setup the prefix
  1544.         (prefix-entry (find-cmpl-prefix-entry
  1545.                 (substring cmpl-db-downcase-string 0
  1546.                        (read-time-eval
  1547.                     *completion-prefix-min-length*))))
  1548.         )
  1549.     ;; The next two forms should happen as a unit (atomically) but
  1550.     ;; no fatal errors should result if that is not the case.
  1551.     (cond (prefix-entry
  1552.            ;; These two should be atomic, but nothing fatal will happen
  1553.            ;; if they're not.
  1554.            (setcdr (cmpl-prefix-entry-tail prefix-entry) entry)
  1555.            (set-cmpl-prefix-entry-tail prefix-entry entry))
  1556.           (t
  1557.            (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))
  1558.            ))
  1559.     ;; statistics
  1560.     (cmpl-statistics-block
  1561.       (note-added-completion))
  1562.     ;; set symbol
  1563.     (set cmpl-db-symbol (car entry))
  1564.     )))
  1565.  
  1566. (defun add-completion-to-head (string)
  1567.   "If the string is not in the database it is added to the head of the
  1568. approppriate prefix list.  Otherwise it is moved to the head of the list.
  1569. string must be longer than *completion-prefix-min-length*.
  1570. Updates the saved string with the supplied string.
  1571. This must be very fast.
  1572. Returns the completion entry."
  1573.   ;; Handle pending acceptance
  1574.   (if completion-to-accept (accept-completion))
  1575.   ;; test if already in database
  1576.   (if (setq cmpl-db-entry (find-exact-completion string))
  1577.       ;; found
  1578.       (let* ((prefix-entry (find-cmpl-prefix-entry
  1579.                  (substring cmpl-db-downcase-string 0
  1580.                     (read-time-eval
  1581.                      *completion-prefix-min-length*))))
  1582.          (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry))
  1583.          (cmpl-ptr (cdr splice-ptr))
  1584.          )
  1585.     ;; update entry
  1586.     (set-completion-string cmpl-db-entry string)
  1587.     ;; move to head (if necessary)
  1588.     (cond (splice-ptr
  1589.            ;; These should all execute atomically but it is not fatal if
  1590.            ;; they don't.
  1591.            ;; splice it out
  1592.            (or (setcdr splice-ptr (cdr cmpl-ptr))
  1593.            ;; fix up tail if necessary
  1594.            (set-cmpl-prefix-entry-tail prefix-entry splice-ptr))
  1595.            ;; splice in at head
  1596.            (setcdr cmpl-ptr (cmpl-prefix-entry-head prefix-entry))
  1597.            (set-cmpl-prefix-entry-head prefix-entry cmpl-ptr)
  1598.            ))
  1599.     cmpl-db-entry)
  1600.     ;; not there
  1601.     (let (;; create an entry
  1602.       (entry (make-completion string))
  1603.       ;; setup the prefix
  1604.       (prefix-entry (find-cmpl-prefix-entry
  1605.               (substring cmpl-db-downcase-string 0
  1606.                      (read-time-eval
  1607.                       *completion-prefix-min-length*))))
  1608.       )
  1609.       (cond (prefix-entry
  1610.          ;; Splice in at head
  1611.          (setcdr entry (cmpl-prefix-entry-head prefix-entry))
  1612.          (set-cmpl-prefix-entry-head prefix-entry entry))
  1613.         (t
  1614.          ;; Start new prefix entry
  1615.          (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))
  1616.          ))
  1617.       ;; statistics
  1618.       (cmpl-statistics-block
  1619.     (note-added-completion))
  1620.       ;; Add it to the symbol
  1621.       (set cmpl-db-symbol (car entry))
  1622.       )))
  1623.       
  1624. (defun delete-completion (string)
  1625.   "Deletes the completion from the database.  string must be longer than
  1626. *completion-prefix-min-length*."
  1627.   ;; Handle pending acceptance
  1628.   (if completion-to-accept (accept-completion))
  1629.   (if (setq cmpl-db-entry (find-exact-completion string))
  1630.       ;; found
  1631.       (let* ((prefix-entry (find-cmpl-prefix-entry 
  1632.                  (substring cmpl-db-downcase-string 0
  1633.                     (read-time-eval
  1634.                      *completion-prefix-min-length*))))
  1635.          (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry))
  1636.          )
  1637.      ;; delete symbol reference
  1638.      (set cmpl-db-symbol nil)
  1639.      ;; remove from prefix list
  1640.      (cond (splice-ptr
  1641.         ;; not at head
  1642.         (or (setcdr splice-ptr (cdr (cdr splice-ptr)))
  1643.             ;; fix up tail if necessary
  1644.             (set-cmpl-prefix-entry-tail prefix-entry splice-ptr))
  1645.         )
  1646.            (t
  1647.         ;; at head
  1648.         (or (set-cmpl-prefix-entry-head
  1649.               prefix-entry (cdr (cmpl-prefix-entry-head prefix-entry)))
  1650.             ;; List is now empty
  1651.             (set cmpl-db-prefix-symbol nil))
  1652.         ))
  1653.      (cmpl-statistics-block
  1654.        (note-completion-deleted))
  1655.      )
  1656.       (error "Unknown completion: %s.  Couldn't delete it." string)
  1657.       ))
  1658.  
  1659. ;;; Tests --
  1660. ;;;  - Add and Find -
  1661. ;;; (add-completion-to-head "banana")     --> ("banana" 0 nil)
  1662. ;;; (find-exact-completion "banana")      --> ("banana" 0 nil)
  1663. ;;; (find-exact-completion "bana")        --> nil
  1664. ;;; (car (find-cmpl-prefix-entry "ban"))  --> (("banana" ...))
  1665. ;;; (cdr (find-cmpl-prefix-entry "ban"))  --> (("banana" ...))
  1666. ;;; (add-completion-to-head "banish")     --> ("banish" 0 nil)
  1667. ;;; (find-exact-completion "banish")      --> ("banish" 0 nil)
  1668. ;;; (car (find-cmpl-prefix-entry "ban"))  --> (("banish" ...) ("banana" ...))
  1669. ;;; (cdr (find-cmpl-prefix-entry "ban"))  --> (("banana" ...))
  1670. ;;; (add-completion-to-head "banana")     --> ("banana" 0 nil)
  1671. ;;; (car (find-cmpl-prefix-entry "ban"))  --> (("banana" ...) ("banish" ...))
  1672. ;;; (cdr (find-cmpl-prefix-entry "ban"))  --> (("banish" ...))
  1673. ;;;
  1674. ;;;  - Deleting -
  1675. ;;; (add-completion-to-head "banner")     --> ("banner" 0 nil)
  1676. ;;; (delete-completion "banner")        
  1677. ;;; (find-exact-completion "banner")      --> nil
  1678. ;;; (car (find-cmpl-prefix-entry "ban"))  --> (("banana" ...) ("banish" ...))
  1679. ;;; (cdr (find-cmpl-prefix-entry "ban"))  --> (("banish" ...))
  1680. ;;; (add-completion-to-head "banner")     --> ("banner" 0 nil) 
  1681. ;;; (delete-completion "banana")        
  1682. ;;; (car (find-cmpl-prefix-entry "ban"))  --> (("banner" ...) ("banish" ...))
  1683. ;;; (cdr (find-cmpl-prefix-entry "ban"))  --> (("banish" ...))
  1684. ;;; (delete-completion "banner")        
  1685. ;;; (find-cmpl-prefix-entry "ban")        --> nil
  1686. ;;; (delete-completion "banner")          --> error
  1687. ;;;
  1688. ;;; - Tail -
  1689. ;;; (add-completion-to-tail-if-new "banana") --> ("banana" 0 nil)
  1690. ;;; (car (find-cmpl-prefix-entry "ban"))     --> (("banana" ...))
  1691. ;;; (cdr (find-cmpl-prefix-entry "ban"))     --> (("banana" ...))
  1692. ;;; (add-completion-to-tail-if-new "banish") --> ("banish" 0 nil)
  1693. ;;; (car (find-cmpl-prefix-entry "ban"))     -->(("banana" ...) ("banish" ...))
  1694. ;;; (cdr (find-cmpl-prefix-entry "ban"))     -->(("banish" ...))
  1695. ;;;
  1696.  
  1697.  
  1698. ;;;---------------------------------------------------------------------------
  1699. ;;; Database Update :: Interface level routines
  1700. ;;;---------------------------------------------------------------------------
  1701. ;;; 
  1702. ;;; These lie on top of the database ref. functions but below the standard
  1703. ;;; user interface level
  1704.  
  1705.  
  1706. (defun interactive-completion-string-reader (prompt)
  1707.   (let* ((default (symbol-under-or-before-point))
  1708.      (new-prompt
  1709.       (if default
  1710.           (format "%s: (default: %s) " prompt default)
  1711.           (format "%s: " prompt))
  1712.        )
  1713.      (read (completing-read new-prompt cmpl-obarray))
  1714.      )
  1715.     (if (zerop (length read)) (setq read (or default "")))
  1716.     (list read)
  1717.     ))
  1718.  
  1719. (defun check-completion-length (string)
  1720.   (if (< (length string) *completion-min-length*)
  1721.       (error "The string \"%s\" is too short to be saved as a completion."
  1722.          string)
  1723.       (list string)))
  1724.  
  1725. (defun add-completion (string &optional num-uses last-use-time)
  1726.   "If the string is not there, it is added to the head of the completion list.
  1727. Otherwise, it is moved to the head of the list.
  1728. The completion is altered appropriately if num-uses and/or last-use-time is 
  1729. specified."
  1730.   (interactive (interactive-completion-string-reader "Completion to add"))
  1731.   (check-completion-length string)
  1732.   (let* ((current-completion-source (if (interactive-p)
  1733.                     cmpl-source-interactive
  1734.                     current-completion-source))
  1735.      (entry (add-completion-to-head string)))
  1736.     
  1737.     (if num-uses (set-completion-num-uses entry num-uses))
  1738.     (if last-use-time
  1739.     (set-completion-last-use-time entry last-use-time))
  1740.     ))
  1741.  
  1742. (defun add-permanent-completion (string)
  1743.   "Adds string if it isn't already there and and makes it a permanent string."
  1744.   (interactive
  1745.     (interactive-completion-string-reader "Completion to add permanently"))
  1746.   (let ((current-completion-source (if (interactive-p)
  1747.                        cmpl-source-interactive
  1748.                        current-completion-source))
  1749.     )
  1750.     (add-completion string nil t)
  1751.     ))
  1752.  
  1753. (defun kill-completion (string)
  1754.   (interactive (interactive-completion-string-reader "Completion to kill"))
  1755.   (check-completion-length string)
  1756.   (delete-completion string)
  1757.   )
  1758.  
  1759. (defun accept-completion ()
  1760.   "Accepts the pending completion in completion-to-accept.
  1761. This bumps num-uses.  Called by add-completion-to-head and 
  1762. completion-search-reset."
  1763.   (let ((string completion-to-accept)
  1764.     ;; if this is added afresh here, then it must be a cdabbrev
  1765.     (current-completion-source cmpl-source-cdabbrev)
  1766.     entry
  1767.     )
  1768.     (setq completion-to-accept nil)
  1769.     (setq entry (add-completion-to-head string))
  1770.     (set-completion-num-uses entry (1+ (completion-num-uses entry)))
  1771.     (setq cmpl-completions-accepted-p t)
  1772.     ))
  1773.  
  1774. (defun use-completion-under-point ()
  1775.   "Call this to add the completion symbol underneath the point into
  1776. the completion buffer."
  1777.   (let ((string (and *completep* (symbol-under-point)))
  1778.     (current-completion-source cmpl-source-cursor-moves))
  1779.     (if string (add-completion-to-head string))))
  1780.     
  1781. (defun use-completion-before-point ()
  1782.   "Call this to add the completion symbol before point into
  1783. the completion buffer."
  1784.   (let ((string (and *completep* (symbol-before-point)))
  1785.     (current-completion-source cmpl-source-cursor-moves))
  1786.     (if string (add-completion-to-head string))))
  1787.  
  1788. (defun use-completion-under-or-before-point ()
  1789.   "Call this to add the completion symbol before point into
  1790. the completion buffer."
  1791.   (let ((string (and *completep* (symbol-under-or-before-point)))
  1792.     (current-completion-source cmpl-source-cursor-moves))
  1793.     (if string (add-completion-to-head string))))
  1794.  
  1795. (defun use-completion-before-separator ()
  1796.   "Call this to add the completion symbol before point into
  1797. the completion buffer.  Completions added this way will automatically be
  1798. saved if *separator-character-uses-completion-p* is non-nil."
  1799.   (let ((string (and *completep* (symbol-before-point)))
  1800.     (current-completion-source cmpl-source-separator)
  1801.     entry)
  1802.     (cmpl-statistics-block
  1803.       (note-separator-character string)
  1804.       )
  1805.     (cond (string
  1806.        (setq entry (add-completion-to-head string))
  1807.        (when (and *separator-character-uses-completion-p*
  1808.               (zerop (completion-num-uses entry)))
  1809.          (set-completion-num-uses entry 1)
  1810.          (setq cmpl-completions-accepted-p t)
  1811.          )))
  1812.     ))
  1813.  
  1814. ;;; Tests --
  1815. ;;;  - Add and Find -
  1816. ;;; (add-completion "banana" 5 10)  
  1817. ;;; (find-exact-completion "banana")  --> ("banana" 5 10)
  1818. ;;; (add-completion "banana" 6)     
  1819. ;;; (find-exact-completion "banana")  --> ("banana" 6 10)
  1820. ;;; (add-completion "banish")
  1821. ;;; (car (find-cmpl-prefix-entry "ban"))  --> (("banish" ...) ("banana" ...))
  1822. ;;;
  1823. ;;;  - Accepting -
  1824. ;;; (setq completion-to-accept "banana")
  1825. ;;; (accept-completion)                   
  1826. ;;; (find-exact-completion "banana")      --> ("banana" 7 10)
  1827. ;;; (car (find-cmpl-prefix-entry "ban"))  --> (("banana" ...) ("banish" ...))
  1828. ;;; (setq completion-to-accept "banish")
  1829. ;;; (add-completion "banner")           
  1830. ;;; (car (find-cmpl-prefix-entry "ban"))
  1831. ;;;        --> (("banner" ...) ("banish" ...) ("banana" ...))
  1832. ;;;
  1833. ;;;  - Deleting -
  1834. ;;; (kill-completion "banish")
  1835. ;;; (car (find-cmpl-prefix-entry "ban"))  --> (("banner" ...) ("banana" ...))
  1836.  
  1837.  
  1838. ;;;---------------------------------------------------------------------------
  1839. ;;; Searching the database
  1840. ;;;---------------------------------------------------------------------------
  1841. ;;; Functions outside this block must call completion-search-reset followed
  1842. ;;; by calls to completion-search-next or completion-search-peek
  1843. ;;;
  1844.  
  1845. ;;; Status variables
  1846. ;; Commented out to improve loading speed
  1847. (defvar cmpl-test-string "")
  1848. ;;  "The current string used by completion-search-next."
  1849. (defvar cmpl-test-regexp "")
  1850. ;;  "The current regexp used by completion-search-next. 
  1851. ;;   (derived from cmpl-test-string)"
  1852. (defvar cmpl-last-index 0)
  1853. ;;  "The last index that completion-search-next was called with."
  1854. (defvar cmpl-cdabbrev-reset-p nil)
  1855. ;;  "Set to t when cdabbrevs have been reset."
  1856. (defvar cmpl-next-possibilities nil)
  1857. ;;   "A pointer to the element BEFORE the next set of possible completions.
  1858. ;;  cadr of this is the cmpl-next-possibility"
  1859. (defvar cmpl-starting-possibilities nil)
  1860. ;;  "The initial list of starting possibilities."
  1861. (defvar cmpl-next-possibility nil)
  1862. ;;   "The cached next possibility."
  1863. (defvar cmpl-tried-list nil)
  1864. ;;   "A downcased list of all the completions we have tried."
  1865.  
  1866.  
  1867. (defun completion-search-reset (string)
  1868.   "Given a string, sets up the get-completion and completion-search-next functions.
  1869. String must be longer than *completion-prefix-min-length*."
  1870.   (if completion-to-accept (accept-completion))
  1871.   (setq cmpl-starting-possibilities
  1872.     (cmpl-prefix-entry-head
  1873.       (find-cmpl-prefix-entry (downcase (substring string 0 3))))
  1874.     cmpl-test-string string
  1875.     cmpl-test-regexp (concat (regexp-quote string) "."))
  1876.   (completion-search-reset-1)
  1877.   )
  1878.  
  1879. (defun completion-search-reset-1 ()
  1880.   (setq cmpl-next-possibilities cmpl-starting-possibilities
  1881.     cmpl-next-possibility   nil
  1882.     cmpl-cdabbrev-reset-p nil
  1883.     cmpl-last-index -1
  1884.     cmpl-tried-list nil
  1885.     ))
  1886.  
  1887. (defun completion-search-next (index)
  1888.   "Returns the next completion entry.  If index is out of sequence it resets
  1889. and starts from the top.  If there are no more entries it tries cdabbrev and 
  1890. returns only a string."
  1891.   (cond
  1892.     ((= index (setq cmpl-last-index (1+ cmpl-last-index)))
  1893.      (completion-search-peek t))
  1894.     ((minusp index)
  1895.      (completion-search-reset-1)
  1896.      (setq cmpl-last-index index)
  1897.      ;; reverse the possibilities list
  1898.      (setq cmpl-next-possibilities (reverse cmpl-starting-possibilities))
  1899.      ;; do a "normal" search
  1900.      (while (and (completion-search-peek nil)
  1901.          (minusp (setq index (1+ index))))
  1902.        (setq cmpl-next-possibility nil)
  1903.        )
  1904.      (cond ((not cmpl-next-possibilities))
  1905.         ;; If no more possibilities, leave it that way
  1906.        ((= -1 cmpl-last-index)
  1907.         ;; next completion is at index 0.  reset next-possibility list 
  1908.         ;; to start at beginning
  1909.         (setq cmpl-next-possibilities cmpl-starting-possibilities))
  1910.        (t
  1911.         ;; otherwise point to one before current
  1912.         (setq cmpl-next-possibilities
  1913.           (nthcdr (- (length cmpl-starting-possibilities)
  1914.                  (length cmpl-next-possibilities))
  1915.               cmpl-starting-possibilities))
  1916.         )))
  1917.     (t
  1918.      ;; non-negative index, reset and search
  1919.      ;;(prin1 'reset)
  1920.      (completion-search-reset-1)
  1921.      (setq cmpl-last-index index)
  1922.      (while (and (completion-search-peek t)
  1923.          (not (minusp (setq index (1- index)))))
  1924.        (setq cmpl-next-possibility nil)
  1925.        ))
  1926.     )
  1927.   (prog1
  1928.       cmpl-next-possibility
  1929.     (setq cmpl-next-possibility nil)
  1930.     ))
  1931.       
  1932.  
  1933. (defun completion-search-peek (use-cdabbrev)
  1934.   "Returns the next completion entry without actually moving the pointers.
  1935. Calling this again or calling completion-search-next will result in the same 
  1936. string being returned.  Depends on case-fold-search.
  1937. If there are no more entries it tries cdabbrev and then returns only a string."
  1938.   (cond
  1939.     ;; return the cached value if we have it
  1940.     (cmpl-next-possibility)
  1941.     ((and cmpl-next-possibilities
  1942.       ;; still a few possibilities left
  1943.       (progn
  1944.         (while
  1945.         (and (not (eq 0 (string-match cmpl-test-regexp
  1946.                           (completion-string (car cmpl-next-possibilities)))))
  1947.              (setq cmpl-next-possibilities (cdr cmpl-next-possibilities))
  1948.              ))
  1949.         cmpl-next-possibilities
  1950.         ))
  1951.      ;; successful match
  1952.      (setq cmpl-next-possibility (car cmpl-next-possibilities)
  1953.        cmpl-tried-list (cons (downcase (completion-string cmpl-next-possibility))
  1954.                  cmpl-tried-list)
  1955.        cmpl-next-possibilities (cdr cmpl-next-possibilities)
  1956.        )
  1957.      cmpl-next-possibility)
  1958.     (use-cdabbrev
  1959.      ;; unsuccessful, use cdabbrev
  1960.      (cond ((not cmpl-cdabbrev-reset-p)
  1961.         (reset-cdabbrev cmpl-test-string cmpl-tried-list)
  1962.         (setq cmpl-cdabbrev-reset-p t)
  1963.         ))
  1964.      (setq cmpl-next-possibility (next-cdabbrev))
  1965.      )
  1966.     ;; Completely unsuccessful, return nil
  1967.     ))
  1968.  
  1969. ;;; Tests --
  1970. ;;;  - Add and Find -
  1971. ;;; (add-completion "banana")       
  1972. ;;; (completion-search-reset "ban")  
  1973. ;;; (completion-search-next 0)        --> "banana"
  1974. ;;;
  1975. ;;;  - Discrimination -
  1976. ;;; (add-completion "cumberland")       
  1977. ;;; (add-completion "cumberbund")       
  1978. ;;; cumbering   
  1979. ;;; (completion-search-reset "cumb")
  1980. ;;; (completion-search-peek t)        --> "cumberbund"
  1981. ;;; (completion-search-next 0)        --> "cumberbund"
  1982. ;;; (completion-search-peek t)        --> "cumberland"
  1983. ;;; (completion-search-next 1)        --> "cumberland"
  1984. ;;; (completion-search-peek nil)      --> nil
  1985. ;;; (completion-search-next 2)        --> "cumbering"  {cdabbrev}
  1986. ;;; (completion-search-next 3)        -->  nil or "cumming"{depends on context}
  1987. ;;; (completion-search-next 1)        --> "cumberland"
  1988. ;;; (completion-search-peek t)        --> "cumbering"  {cdabbrev}
  1989. ;;;
  1990. ;;;  - Accepting -
  1991. ;;; (completion-search-next 1)        --> "cumberland"
  1992. ;;; (setq completion-to-accept "cumberland")
  1993. ;;; (completion-search-reset "foo")
  1994. ;;; (completion-search-reset "cum")
  1995. ;;; (completion-search-next 0)        --> "cumberland"
  1996. ;;;
  1997. ;;;  - Deleting -
  1998. ;;; (kill-completion "cumberland")
  1999. ;;; cummings    
  2000. ;;; (completion-search-reset "cum")
  2001. ;;; (completion-search-next 0)        --> "cumberbund"
  2002. ;;; (completion-search-next 1)        --> "cummings"
  2003. ;;;
  2004. ;;;  - Ignoring Capitalization -
  2005. ;;; (completion-search-reset "CuMb")
  2006. ;;; (completion-search-next 0)            --> "cumberbund"
  2007.  
  2008.  
  2009.  
  2010. ;;;-----------------------------------------------
  2011. ;;; COMPLETE
  2012. ;;;-----------------------------------------------
  2013.  
  2014. (defun completion-mode ()
  2015.   "Toggles whether or not new words are added to the database."
  2016.   (interactive)
  2017.   (setq *completep* (not *completep*))
  2018.   (message "Completion mode is now %s." (if *completep* "ON" "OFF"))
  2019.   )
  2020.     
  2021. (defvar cmpl-current-index 0)
  2022. (defvar cmpl-original-string nil)
  2023. (defvar cmpl-last-insert-location -1)
  2024. (defvar cmpl-leave-point-at-start nil)
  2025.  
  2026. (defun complete (&optional arg)
  2027.   "Inserts a completion at point.  
  2028. Point is left at end.  Consective calls rotate through all possibilities.
  2029. Prefix args ::
  2030.   control-u :: leave the point at the beginning of the completion rather 
  2031.                than at the end.
  2032.   a number  :: rotate through the possible completions by that amount
  2033.   `-'       :: same as -1 (insert previous completion)
  2034.  {See the comments at the top of completion.el for more info.}
  2035. "
  2036.   (interactive "*p")
  2037.   ;;; Set up variables
  2038.   (cond ((eq last-command this-command)
  2039.      ;; Undo last one
  2040.      (delete-region cmpl-last-insert-location (point))
  2041.      ;; get next completion
  2042.      (setq cmpl-current-index (+ cmpl-current-index (or arg 1)))
  2043.      )
  2044.     (t
  2045.      (if (not cmpl-initialized-p)
  2046.          (initialize-completions)) ;; make sure everything's loaded
  2047.      (cond ((consp current-prefix-arg) ;; control-u
  2048.         (setq arg 0)
  2049.         (setq cmpl-leave-point-at-start t)
  2050.         )
  2051.            (t
  2052.         (setq cmpl-leave-point-at-start nil)
  2053.         ))
  2054.      ;; get string
  2055.      (setq cmpl-original-string (symbol-before-point-for-complete))
  2056.      (cond ((not cmpl-original-string)
  2057.         (setq this-command 'failed-complete)
  2058.         (error "To complete, the point must be after a symbol at least %d character long."
  2059.                *completion-prefix-min-length*)))
  2060.      ;; get index         
  2061.      (setq cmpl-current-index (if current-prefix-arg arg 0))
  2062.      ;; statistics
  2063.      (cmpl-statistics-block
  2064.        (note-complete-entered-afresh cmpl-original-string))
  2065.      ;; reset database
  2066.      (completion-search-reset cmpl-original-string)
  2067.      ;; erase what we've got
  2068.      (delete-region cmpl-symbol-start cmpl-symbol-end)
  2069.      ))
  2070.  
  2071.   ;; point is at the point to insert the new symbol
  2072.   ;; Get the next completion
  2073.   (let* ((print-status-p
  2074.       (and (>= (baud-rate) *print-next-completion-speed-threshold*)
  2075.            (not (minibuffer-window-selected-p))))
  2076.      (insert-point (point))
  2077.      (entry (completion-search-next cmpl-current-index))
  2078.      string
  2079.      )
  2080.     ;; entry is either a completion entry or a string (if cdabbrev)
  2081.  
  2082.     ;; If found, insert
  2083.     (cond (entry
  2084.        ;; Setup for proper case
  2085.        (setq string (if (stringp entry)
  2086.                 entry (completion-string entry)))
  2087.        (setq string (cmpl-merge-string-cases
  2088.               string cmpl-original-string))
  2089.        ;; insert
  2090.        (insert string)
  2091.        ;; accept it
  2092.        (setq completion-to-accept string)
  2093.        ;; fixup and cache point
  2094.        (cond (cmpl-leave-point-at-start
  2095.           (setq cmpl-last-insert-location (point))
  2096.           (goto-char insert-point))
  2097.          (t;; point at end,
  2098.           (setq cmpl-last-insert-location insert-point))
  2099.          )
  2100.        ;; statistics
  2101.        (cmpl-statistics-block
  2102.          (note-complete-inserted entry cmpl-current-index))
  2103.        ;; Done ! cmpl-stat-complete-successful
  2104.        ;;display the next completion
  2105.        (cond
  2106.          ((and print-status-p
  2107.            ;; This updates the display and only prints if there
  2108.            ;; is no typeahead
  2109.            (sit-for 0)
  2110.            (setq entry
  2111.              (completion-search-peek
  2112.                *print-next-completion-does-cdabbrev-search-p*)))
  2113.           (setq string (if (stringp entry)
  2114.                    entry (completion-string entry)))
  2115.           (setq string (cmpl-merge-string-cases
  2116.                  string cmpl-original-string))
  2117.           (message "Next completion: %s" string)
  2118.           ))
  2119.        )
  2120.       (t;; none found, insert old 
  2121.        (insert cmpl-original-string)
  2122.        ;; Don't accept completions
  2123.        (setq completion-to-accept nil)
  2124.        ;; print message
  2125.        (if (and print-status-p (sit-for 0))
  2126.            (message "No %scompletions."
  2127.             (if (eq this-command last-command) "more " "")))
  2128.        ;; statistics
  2129.        (cmpl-statistics-block
  2130.          (record-complete-failed cmpl-current-index))
  2131.        ;; Pretend that we were never here
  2132.        (setq this-command 'failed-complete)
  2133.        ))))
  2134.  
  2135.  
  2136. ;;;-----------------------------------------------
  2137. ;;; "Complete" Key Keybindings
  2138. ;;;-----------------------------------------------
  2139.  
  2140. ;;; Complete key definition
  2141. ;;;  These define c-return and meta-return
  2142. ;;; In any case you really want to bind this to a single keystroke
  2143. (if (fboundp 'key-for-others-chord)
  2144.     (condition-case e
  2145.      ;; this can fail if some of the prefix chars. are already used
  2146.      ;; as commands (this happens on wyses)
  2147.      (global-set-key (key-for-others-chord "return" '(control)) 'complete)
  2148.       (error)
  2149.       ))
  2150. (if (fboundp 'gmacs-keycode)
  2151.     (global-set-key (gmacs-keycode "return" '(control)) 'complete)
  2152.     )
  2153. (global-set-key "\M-\r" 'complete)
  2154.  
  2155. ;;; Tests -
  2156. ;;; (add-completion "cumberland")
  2157. ;;; (add-completion "cumberbund")
  2158. ;;; cum
  2159. ;;; Cumber
  2160. ;;; cumbering
  2161. ;;; cumb
  2162.  
  2163.  
  2164. ;;;---------------------------------------------------------------------------
  2165. ;;; Parsing definitions from files into the database
  2166. ;;;---------------------------------------------------------------------------
  2167.  
  2168. ;;;-----------------------------------------------
  2169. ;;; Top Level functions ::
  2170. ;;;-----------------------------------------------
  2171.  
  2172. ;;; User interface
  2173. (defun add-completions-from-file (file)
  2174.   "Parses all the definition names from a Lisp mode file and adds them to the 
  2175. completion database."
  2176.   (interactive "fFile: ")
  2177.   (setq file (if (fboundp 'expand-file-name-defaulting)
  2178.          (expand-file-name-defaulting file)
  2179.          (expand-file-name file)))
  2180.   (let* ((buffer (get-file-buffer file))
  2181.      (buffer-already-there-p buffer)
  2182.      )
  2183.     (when (not buffer-already-there-p)
  2184.       (let ((*modes-for-completion-find-file-hook* nil))
  2185.     (setq buffer (find-file-noselect file))
  2186.     ))
  2187.     (unwind-protect
  2188.      (save-excursion
  2189.        (set-buffer buffer)
  2190.        (add-completions-from-buffer)
  2191.        )
  2192.       (when (not buffer-already-there-p)
  2193.     (kill-buffer buffer))
  2194.       )))
  2195.  
  2196. (defun add-completions-from-buffer ()
  2197.   (interactive)
  2198.   (let ((current-completion-{urce cmpl-source-file-parsing)
  2199.     (start-num
  2200.      (cmpl-statistics-block
  2201.       (aref completion-add-count-vector cmpl-source-file-parsing)))
  2202.     mode
  2203.     )
  2204.     (cond ((memq major-mode '(emacs-lisp-mode lisp-mode))
  2205.        (add-completions-from-lisp-buffer)
  2206.        (setq mode 'lisp)
  2207.        )
  2208.       ((memq major-mode '(c-mode))
  2209.        (add-completions-from-c-buffer)
  2210.        (setq mode 'c)
  2211.        )
  2212.       (t
  2213.        (error "Do not know how to parse completions in %s buffers."
  2214.           major-mode)
  2215.        ))
  2216.     (cmpl-statistics-block
  2217.       (record-cmpl-parse-file
  2218.     mode (point-max)
  2219.     (- (aref completion-add-count-vector cmpl-source-file-parsing)
  2220.        start-num)))
  2221.     ))
  2222.  
  2223. ;;; Find file hook
  2224. (defun cmpl-find-file-hook ()
  2225.   (cond (*completep*
  2226.      (cond ((and (memq major-mode '(emacs-lisp-mode lisp-mode))
  2227.              (memq 'lisp *modes-for-completion-find-file-hook*)
  2228.              )
  2229.         (add-completions-from-buffer))
  2230.            ((and (memq major-mode '(c-mode))
  2231.              (memq 'c *modes-for-completion-find-file-hook*)
  2232.              )
  2233.         (add-completions-from-buffer)
  2234.         )))
  2235.     ))
  2236.     
  2237. (pushnew 'cmpl-find-file-hook find-file-hooks)
  2238.  
  2239.  
  2240. ;;;-----------------------------------------------
  2241. ;;; Lisp File completion parsing
  2242. ;;;-----------------------------------------------
  2243. ;;;   This merely looks for phrases beginning with (def.... or
  2244. ;;; (package:def ... and takes the next word.
  2245. ;;;
  2246. ;;; We tried using forward-lines and explicit searches but the regexp technique
  2247. ;;; was faster.  (About 100K characters per second)
  2248. ;;;
  2249. (defconst *lisp-def-regexp*
  2250.   "\n(\\(\\w*:\\)?def\\(\\w\\|\\s_\\)*\\s +(*"
  2251.   "A regexp that searches for lisp definition form."
  2252.   )
  2253.  
  2254. ;;; Tests -
  2255. ;;;  (and (string-match *lisp-def-regexp* "\n(defun foo") (match-end 0)) -> 8
  2256. ;;;  (and (string-match *lisp-def-regexp* "\n(si:def foo") (match-end 0)) -> 9
  2257. ;;;  (and (string-match *lisp-def-regexp* "\n(def-bar foo")(match-end 0)) -> 10
  2258. ;;;  (and (string-match *lisp-def-regexp* "\n(defun (foo") (match-end 0)) -> 9
  2259.  
  2260. (defun add-completions-from-lisp-buffer ()
  2261.   "Parses all the definition names from a Lisp mode buffer and adds them to 
  2262. the completion database."
  2263.   ;;; Benchmarks
  2264.   ;;;  Sun-3/280 - 1500 to 3000 lines of lisp code per second
  2265.   (let (string)
  2266.     (save-excursion
  2267.       (goto-char (point-min))
  2268.       (condition-case e
  2269.        (while t
  2270.          (re-search-forward *lisp-def-regexp*)
  2271.          (and (setq string (symbol-under-point))
  2272.           (add-completion-to-tail-if-new string))
  2273.          )
  2274.      (search-failed)
  2275.      ))))
  2276.  
  2277.  
  2278. ;;;-----------------------------------------------
  2279. ;;; C file completion parsing
  2280. ;;;-----------------------------------------------
  2281. ;;; C :
  2282. ;;;  Looks for #define or [<storage class>] [<type>] <name>{,<name>}
  2283. ;;; or structure, array or pointer defs.
  2284. ;;; It gets most of the definition names.
  2285. ;;;
  2286. ;;; As you might suspect by now, we use some symbol table hackery
  2287. ;;;
  2288. ;;; Symbol separator chars (have whitespace syntax) --> , ; * = (
  2289. ;;; Opening char --> [ {
  2290. ;;; Closing char --> ] }
  2291. ;;; openning and closing must be skipped over
  2292. ;;; Whitespace chars (have symbol syntax)
  2293. ;;; Everything else has word syntax
  2294.  
  2295. (defun make-c-def-completion-syntax-table ()
  2296.   (let ((table (make-vector 256 0))
  2297.     (whitespace-chars '(?  ?\n ?\t ?\f  ?\v ?\r))
  2298.     ;; unforunately the ?( causes the parens to appear unbalanced
  2299.     (separator-chars '(?, ?* ?= ?\( ?\;
  2300.                ))
  2301.     )
  2302.     ;; default syntax is whitespace
  2303.     (dotimes (i 256)
  2304.       (modify-syntax-entry i "w" table))
  2305.     (dolist (char whitespace-chars)
  2306.       (modify-syntax-entry char "_" table))
  2307.     (dolist (char separator-chars)
  2308.       (modify-syntax-entry char " " table))
  2309.     (modify-syntax-entry ?\[ "(]" table)
  2310.     (modify-syntax-entry ?\{ "(}" table)
  2311.     (modify-syntax-entry ?\] ")[" table)
  2312.     (modify-syntax-entry ?\} "){" table)
  2313.     table))
  2314.  
  2315. (defconst cmpl-c-def-syntax-table (make-c-def-completion-syntax-table))
  2316.  
  2317. ;;; Regexps
  2318. (defconst *c-def-regexp*
  2319.     ;; This stops on lines with possible definitions
  2320.     "\n[_a-zA-Z#]"
  2321.   ;; This stops after the symbol to add.
  2322.   ;;"\n\\(#define\\s +.\\|\\(\\(\\w\\|\\s_\\)+\\b\\s *\\)+[(;,[*{=]\\)"
  2323.   ;; This stops before the symbol to add.  {Test cases in parens. below}
  2324.   ;;"\n\\(\\(\\w\\|\\s_\\)+\\s *(\\|\\(\\(#define\\|auto\\|extern\\|register\\|static\\|int\\|long\\|short\\|unsigned\\|char\\|void\\|float\\|double\\|enum\\|struct\\|union\\|typedef\\)\\s +\\)+\\)"
  2325.   ;; this simple version picks up too much extraneous stuff
  2326.   ;; "\n\\(\\w\\|\\s_\\|#\\)\\B"
  2327.   "A regexp that searches for a definition form."
  2328.   )
  2329. ;
  2330. ;(defconst *c-cont-regexp*
  2331. ;  "\\(\\w\\|\\s_\\)+\\b\\s *\\({\\|\\(\\[[0-9\t ]*\\]\\s *\\)*,\\(*\\|\\s \\)*\\b\\)"
  2332. ;  "This regexp should be used in a looking-at to parse for lists of variables.")
  2333. ;
  2334. ;(defconst *c-struct-regexp*
  2335. ;  "\\(*\\|\\s \\)*\\b"
  2336. ;  "This regexp should be used to test whether a symbol follows a structure definition.")
  2337.  
  2338. ;(defun test-c-def-regexp (regexp string)
  2339. ;  (and (eq 0 (string-match regexp string)) (match-end 0))
  2340. ;  )
  2341.  
  2342. ;;; Tests -
  2343. ;;;  (test-c-def-regexp *c-def-regexp* "\n#define foo") -> 10 (9)
  2344. ;;;  (test-c-def-regexp *c-def-regexp* "\nfoo (x, y) {") -> 6 (6)
  2345. ;;;  (test-c-def-regexp *c-def-regexp* "\nint foo (x, y)") -> 10 (5)
  2346. ;;;  (test-c-def-regexp *c-def-regexp* "\n int foo (x, y)") -> nil
  2347. ;;;  (test-c-def-regexp *c-cont-regexp* "oo, bar") -> 4
  2348. ;;;  (test-c-def-regexp *c-cont-regexp* "oo, *bar") -> 5
  2349. ;;;  (test-c-def-regexp *c-cont-regexp* "a [5][6], bar") -> 10
  2350. ;;;  (test-c-def-regexp *c-cont-regexp* "oo(x,y)") -> nil
  2351. ;;;  (test-c-def-regexp *c-cont-regexp* "a [6] ,\t bar") -> 9
  2352. ;;;  (test-c-def-regexp *c-cont-regexp* "oo {trout =1} my_carp;") -> 14
  2353. ;;;  (test-c-def-regexp *c-cont-regexp* "truct_p complex foon") -> nil
  2354.  
  2355. (defun add-completions-from-c-buffer ()
  2356.   "Parses all the definition names from a C mode buffer and adds them to the 
  2357. completion database."
  2358.   ;; Benchmark --
  2359.   ;;  Sun 3/280-- 1250 lines/sec.
  2360.  
  2361.   (let (string next-point char
  2362.     (saved-syntax (syntax-table))
  2363.     )
  2364.     (save-excursion
  2365.       (goto-char (point-min))
  2366.       (catch 'finish-add-completions
  2367.     (unwind-protect
  2368.          (while t
  2369.            ;; we loop here only when scan-sexps fails
  2370.            ;; (i.e. unbalance exps.)
  2371.            (set-syntax-table cmpl-c-def-syntax-table)
  2372.            (condition-case e
  2373.             (while t
  2374.               (re-search-forward *c-def-regexp*)
  2375.               (cond
  2376.             ((= (preceding-char) ?#)
  2377.              ;; preprocessor macro, see if it's one we handle
  2378.              (setq string (buffer-substring (point) (+ (point) 6)))
  2379.              (cond ((or (string-equal string "define")
  2380.                     (string-equal string "ifdef ")
  2381.                     )
  2382.                 ;; skip forward over definition symbol
  2383.                 ;; and add it to database
  2384.                 (and (forward-word 2)
  2385.                      (setq string (symbol-before-point))
  2386.                      ;;(push string foo)
  2387.                      (add-completion-to-tail-if-new string)
  2388.                      ))))
  2389.             (t
  2390.              ;; C definition
  2391.              (setq next-point (point))
  2392.              (while (and
  2393.                   next-point
  2394.                   ;; scan to next separator char.
  2395.                   (setq next-point (scan-sexps next-point 1))
  2396.                   )
  2397.                ;; position the point on the word we want to add
  2398.                (goto-char next-point)
  2399.                (while (= (setq char (following-char)) ?*)
  2400.                  ;; handle pointer ref
  2401.                  ;; move to next separator char.
  2402.                  (goto-char
  2403.                    (setq next-point (scan-sexps (point) 1)))
  2404.                  )
  2405.                (forward-word -1)
  2406.                ;; add to database
  2407.                (if (setq string (symbol-under-point))
  2408.                    ;; (push string foo)
  2409.                    (add-completion-to-tail-if-new string)
  2410.                    ;; Local TMC hack (useful for parsing paris.h)
  2411.                    (if (and (looking-at "_AP") ;; "ansi prototype"
  2412.                     (progn
  2413.                       (forward-word -1)
  2414.                       (setq string
  2415.                         (symbol-under-point))
  2416.                       ))
  2417.                    (add-completion-to-tail-if-new string)
  2418.                    )
  2419.                    )
  2420.                ;; go to next
  2421.                (goto-char next-point)
  2422.                ;; (push (format "%c" (following-char)) foo)
  2423.                (if (= (char-syntax char) ?\()
  2424.                    ;; if on an opening delimiter, go to end
  2425.                    (while (= (char-syntax char) ?\()
  2426.                  (setq next-point (scan-sexps next-point 1)
  2427.                        char (char-after next-point))
  2428.                  )
  2429.                    (or (= char ?,)
  2430.                    ;; Current char is an end char.
  2431.                    (setq next-point nil)
  2432.                    ))
  2433.                ))))
  2434.           (search-failed ;;done
  2435.             (throw 'finish-add-completions t)
  2436.             )
  2437.           (error
  2438.             ;; Check for failure in scan-sexps
  2439.             (if (or (string-equal (second e)
  2440.                       "Containing expression ends prematurely")
  2441.                 (string-equal (second e) "Unbalanced parentheses"))
  2442.             ;; unbalanced paren., keep going
  2443.             ;;(ding)
  2444.             (forward-line 1)
  2445.             (message "Error parsing C buffer for completions.  Please bug report.")
  2446.             (throw 'finish-add-completions t)
  2447.             ))
  2448.           ))
  2449.       (set-syntax-table saved-syntax)
  2450.       )))))
  2451.  
  2452.  
  2453. ;;;---------------------------------------------------------------------------
  2454. ;;; Init files
  2455. ;;;---------------------------------------------------------------------------
  2456.  
  2457. (defun kill-emacs-save-completions ()
  2458.   "The version of save-completions-to-file called at kill-emacs
  2459. time."
  2460.   (when (and *save-completions-p* *completep* cmpl-initialized-p)
  2461.     (cond
  2462.       ((not cmpl-completions-accepted-p)
  2463.        (message "Completions database has not changed - not writing."))
  2464.       (t
  2465.        (save-completions-to-file)
  2466.        ))
  2467.     ))
  2468.  
  2469. (defconst saved-cmpl-file-header
  2470.     ";;; Completion Initialization file.
  2471. ;;; Version = %d
  2472. ;;; Format is (<string> . <last-use-time>)
  2473. ;;;  <string> is the completion
  2474. ;;;  <last-use-time> is the time the completion was last used
  2475. ;;;    If it is t, the completion will never be pruned from the file.
  2476. ;;;    Otherwise it is in hours since 1900.
  2477. \n")
  2478.  
  2479. (defun completion-backup-filename (filename)
  2480.   (concat filename ".BAK"))
  2481.  
  2482. (defun save-completions-to-file (&optional filename)
  2483.   "Saves a completion init file.  If file is not specified,
  2484.    then *saved-completions-filename* is used."
  2485.   (interactive)
  2486.   (setq filename (expand-file-name (or filename *saved-completions-filename*)))
  2487.   (when (file-writable-p filename)
  2488.     (if (not cmpl-initialized-p)
  2489.     (initialize-completions));; make sure everything's loaded
  2490.     (message "Saving completions to file %s" filename)
  2491.  
  2492.     (let* ((list-all-completions (list-all-completions))
  2493.        (trim-versions-without-asking t)
  2494.        (kept-old-versions 0)
  2495.        (kept-new-versions *completion-file-versions-kept*)
  2496.        last-use-time
  2497.        (current-time (cmpl-hours-since-1900))
  2498.        (total-in-db 0)
  2499.        (total-perm 0)
  2500.        (total-saved 0)
  2501.        (backup-filename (completion-backup-filename filename))
  2502.        )
  2503.     
  2504.       (save-excursion
  2505.     (get-buffer-create " *completion-save-buffer*")
  2506.     (set-buffer  " *completion-save-buffer*")
  2507.     (setq buffer-file-name filename)
  2508.  
  2509.     (when (not (verify-visited-file-modtime (current-buffer)))
  2510.       ;; file has changed on disk.  Bring us up-to-date
  2511.       (message "Completion file has changed.  Merging. . .")
  2512.       (load-completions-from-file filename t)
  2513.       (message "Merging finished.  Saving completions to file %s" filename)
  2514.       )
  2515.  
  2516.     ;; prepare the buffer to be modified
  2517.     (clear-visited-file-modtime)
  2518.     (erase-buffer)
  2519.     ;; (/ 1 0)
  2520.     (insert (format saved-cmpl-file-header *completion-version*))
  2521.     (dolist (completion list-all-completions)
  2522.       (setq total-in-db (1+ total-in-db))
  2523.       (setq last-use-time (completion-last-use-time completion))
  2524.       ;; Update num uses and maybe write completion to a file
  2525.       (cond ((or;; Write to file if
  2526.           ;; permanent
  2527.           (and (eq last-use-time t)
  2528.                (setq total-perm (1+ total-perm)))
  2529.           ;; or if
  2530.           (if (plusp (completion-num-uses completion))
  2531.               ;; it's been used
  2532.               (setq last-use-time current-time)
  2533.               ;; or it was saved before and
  2534.               (and last-use-time
  2535.                ;; *saved-completion-retention-time* is nil
  2536.                (or (not *saved-completion-retention-time*)
  2537.                    ;; or time since last use is < ...retention-time*
  2538.                    (< (- current-time last-use-time)
  2539.                   *saved-completion-retention-time*))
  2540.                )))
  2541.          ;; write to file
  2542.          (setq total-saved (1+ total-saved))
  2543.          (insert (prin1-to-string (cons (completion-string completion)
  2544.                         last-use-time)) "\n")
  2545.          )))
  2546.     
  2547.     ;; write the buffer
  2548.     (condition-case e
  2549.          (let ((file-exists-p (file-exists-p filename)))
  2550.            (when file-exists-p
  2551.          ;; If file exists . . .
  2552.          ;; Save a backup(so GNU doesn't screw us when we're out of disk)
  2553.          ;; (GNU leaves a 0 length file if it gets a disk full error!)
  2554.            
  2555.          ;; If backup doesn't exit, Rename current to backup
  2556.          ;;  {If backup exists the primary file is probably messed up}
  2557.          (unless (file-exists-p backup-filename)
  2558.            (rename-file filename backup-filename))
  2559.          ;; Copy the backup back to the current name
  2560.          ;; (so versioning works)
  2561.          (copy-file backup-filename filename t)
  2562.          )
  2563.            ;; Save it
  2564.            (save-buffer)
  2565.            (when file-exists-p
  2566.          ;; If successful, remove backup
  2567.          (delete-file backup-filename)
  2568.          ))
  2569.        (error
  2570.         (set-buffer-modified-p nil)
  2571.         (message "Couldn't save completion file %s." filename)
  2572.         ))
  2573.     ;; Reset accepted-p flag
  2574.     (setq cmpl-completions-accepted-p nil) 
  2575.     )
  2576.       (cmpl-statistics-block
  2577.        (record-save-completions total-in-db total-perm total-saved))
  2578.       )))
  2579.  
  2580. (defun autosave-completions ()
  2581.   (when (and *save-completions-p* *completep* cmpl-initialized-p
  2582.          *completion-auto-save-period*
  2583.          (> cmpl-emacs-idle-time *completion-auto-save-period*)
  2584.          cmpl-completions-accepted-p)
  2585.     (save-completions-to-file)
  2586.     ))
  2587.  
  2588. (pushnew 'autosave-completions cmpl-emacs-idle-time-hooks)
  2589.  
  2590. (defun load-completions-from-file (&optional filename no-message-p)
  2591.   "loads a completion init file.  If file is not specified,
  2592.    then *saved-completions-filename* is used"
  2593.   (interactive)
  2594.   (setq filename (expand-file-name (or filename *saved-completions-filename*)))
  2595.   (let* ((backup-filename (completion-backup-filename filename))
  2596.      (backup-readable-p (file-readable-p backup-filename))
  2597.      )
  2598.     (when backup-readable-p (setq filename backup-filename))
  2599.     (when (file-readable-p filename)
  2600.       (if (not no-message-p)
  2601.       (message "Loading completions from %sfile %s . . ."
  2602.            (if backup-readable-p "backup " "") filename))
  2603.       (save-excursion
  2604.     (get-buffer-create " *completion-save-buffer*")
  2605.     (set-buffer  " *completion-save-buffer*")
  2606.     (setq buffer-file-name filename)
  2607.     ;; prepare the buffer to be modified
  2608.     (clear-visited-file-modtime)
  2609.     (erase-buffer)
  2610.   
  2611.     (let ((insert-okay-p nil)
  2612.           (buffer (current-buffer))
  2613.           (current-time (cmpl-hours-since-1900))
  2614.           string num-uses entry last-use-time
  2615.           cmpl-entry cmpl-last-use-time
  2616.           (current-completion-source cmpl-source-init-file)
  2617.           (start-num
  2618.            (cmpl-statistics-block
  2619.         (aref completion-add-count-vector cmpl-source-file-parsing)))
  2620.           (total-in-file 0) (total-perm 0)
  2621.           )
  2622.       ;; insert the file into a buffer
  2623.       (condition-case e
  2624.            (progn (insert-file-contents filename t)
  2625.               (setq insert-okay-p t))
  2626.  
  2627.          (file-error 
  2628.           (message "File error trying to load completion file %s."
  2629.                filename)))
  2630.       ;; parse it 
  2631.       (when insert-okay-p
  2632.         (goto-char (point-min))
  2633.  
  2634.         (condition-case e
  2635.          (while t
  2636.            (setq entry (read buffer))
  2637.            (setq total-in-file (1+ total-in-file))
  2638.            (cond
  2639.              ((and (consp entry)
  2640.                (stringp (setq string (car entry)))
  2641.                (cond
  2642.                  ((eq (setq last-use-time (cdr entry)) 'T)
  2643.                   ;; handle case sensitivity
  2644.                   (setq total-perm (1+ total-perm))
  2645.                   (setq last-use-time t))
  2646.                  ((eq last-use-time t)
  2647.                   (setq total-perm (1+ total-perm)))
  2648.                  ((integerp last-use-time))
  2649.                  ))
  2650.               ;; Valid entry
  2651.               ;; add it in
  2652.               (setq cmpl-last-use-time
  2653.                 (completion-last-use-time
  2654.                  (setq cmpl-entry
  2655.                    (add-completion-to-tail-if-new string))
  2656.                  ))
  2657.               (if (or (eq last-use-time t) 
  2658.                   (and (> last-use-time 1000);;backcompatibility
  2659.                    (not (eq cmpl-last-use-time t))
  2660.                    (or (not cmpl-last-use-time)
  2661.                        ;; more recent
  2662.                        (> last-use-time  cmpl-last-use-time))
  2663.                    ))
  2664.               ;; update last-use-time
  2665.               (set-completion-last-use-time cmpl-entry last-use-time)
  2666.               ))
  2667.              (t
  2668.               ;; Bad format
  2669.               (message "Error: invalid saved completion - %s"
  2670.                    (prin1-to-string entry))
  2671.               ;; try to get back in sync
  2672.               (search-forward "\n(")
  2673.               )))
  2674.            (search-failed
  2675.         (message "End of file while reading completions.")
  2676.         )
  2677.            (end-of-file
  2678.         (if (= (point) (point-max))
  2679.             (if (not no-message-p)
  2680.             (message "Loading completions from file %s . . . Done."
  2681.                  filename))
  2682.             (message "End of file while reading completions.")
  2683.             ))
  2684.            ))
  2685.  
  2686.       (cmpl-statistics-block
  2687.        (record-load-completions
  2688.         total-in-file total-perm
  2689.         (- (aref completion-add-count-vector cmpl-source-init-file)
  2690.            start-num)))
  2691.  
  2692.       )))))
  2693.  
  2694. (defun initialize-completions ()
  2695.   "Loads the default completions file and sets up so that exiting emacs will
  2696. automatically save the file."
  2697.   (interactive)
  2698.   (cond ((not cmpl-initialized-p)
  2699.      (load-completions-from-file)
  2700.      ))
  2701.   (init-cmpl-emacs-idle-process)
  2702.   (setq cmpl-initialized-p t)
  2703.   )
  2704.  
  2705.  
  2706. ;;;-----------------------------------------------
  2707. ;;; Kill EMACS patch
  2708. ;;;-----------------------------------------------
  2709.  
  2710. (completion-advise kill-emacs :before
  2711.     ;; | All completion code should go in here
  2712.     ;;\ /
  2713.     (kill-emacs-save-completions)
  2714.     ;;/ \
  2715.     ;; | All completion code should go in here
  2716.     (cmpl-statistics-block
  2717.       (record-cmpl-kill-emacs))
  2718.     )
  2719.  
  2720.  
  2721. ;;;-----------------------------------------------
  2722. ;;; Kill region patch
  2723. ;;;-----------------------------------------------
  2724.  
  2725. ;;; Patched to remove the most recent completion
  2726. (defvar $$$cmpl-old-kill-region (symbol-function 'kill-region))
  2727.  
  2728. (defun kill-region (&optional beg end)
  2729.   "Kill between point and mark.
  2730. The text is deleted but saved in the kill ring.
  2731. The command \\[yank] can retrieve it from there.
  2732. /(If you want to kill and then yank immediately, use \\[copy-region-as-kill].)
  2733.  
  2734. This is the primitive for programs to kill text (as opposed to deleting it).
  2735. Supply two arguments, character numbers indicating the stretch of text
  2736.  to be killed.
  2737. Any command that calls this function is a \"kill command\".
  2738. If the previous command was also a kill command,
  2739. the text killed this time appends to the text killed last time
  2740. to make one entry in the kill ring.
  2741. Patched to remove the most recent completion."
  2742.   (interactive "*")  
  2743.   (cond ((and (eq last-command 'complete) (eq last-command-char ?\C-w))
  2744.      (delete-region (point) cmpl-last-insert-location)
  2745.      (insert cmpl-original-string)
  2746.      (setq completion-to-accept nil)
  2747.      (cmpl-statistics-block
  2748.        (record-complete-failed))
  2749.      )
  2750.     (t
  2751.       (if (not beg)
  2752.           (setq beg (min (point) (mark))
  2753.             end (max (point) (mark)))
  2754.         )
  2755.      (funcall $$$cmpl-old-kill-region beg end)
  2756.      )))
  2757.  
  2758. ;;;-----------------------------------------------
  2759. ;;; Patches to self-insert-command.
  2760. ;;;-----------------------------------------------
  2761.  
  2762. ;;; Need 2 versions: generic seperator chars. and space (to get auto fill
  2763. ;;; to work)
  2764.  
  2765. ;;; All common separators (eg. space "(" ")" """) characters go through a
  2766. ;;; function to add new words to the list of words to complete from:
  2767. ;;;  COMPLETION-SEPARATOR-SELF-INSERT-COMMAND (arg).
  2768. ;;; If the character before this was an alpha-numeric then this adds the 
  2769. ;;; symbol befoe point to the completion list (using ADD-COMPLETION).
  2770.  
  2771. (defun completion-separator-self-insert-command (arg)
  2772.   (interactive "p")
  2773.   (use-completion-before-separator)
  2774.   (self-insert-command arg)
  2775.   )
  2776.  
  2777. (defun completion-separator-self-insert-autofilling (arg)
  2778.   (interactive "p")
  2779.   (use-completion-before-separator)
  2780.   (self-insert-command arg)
  2781.   (and (> (current-column) fill-column)
  2782.        auto-fill-hook
  2783.        (funcall auto-fill-hook))
  2784.   )
  2785.  
  2786. ;;;-----------------------------------------------
  2787. ;;; Wrapping Macro
  2788. ;;;-----------------------------------------------
  2789.  
  2790. ;;; Note that because of the way byte compiling works, none of 
  2791. ;;; the functions defined with this macro get byte compiled.
  2792.  
  2793. (defmacro def-completion-wrapper (function-name type &optional new-name)
  2794.   "Add a call to update the completion database before the function is
  2795. executed.  TYPE is the type of the wrapper to be added.  Can be :before or
  2796. :under."
  2797.   (completion-advise-1
  2798.    function-name ':before
  2799.    (ecase type
  2800.      (:before '((use-completion-before-point)))
  2801.      (:separator '((use-completion-before-separator)))
  2802.      (:under '((use-completion-under-point)))
  2803.      (:under-or-before
  2804.       '((use-completion-under-or-before-point)))
  2805.      (:minibuffer-separator
  2806.       '((let ((cmpl-syntax-table cmpl-standard-syntax-table))
  2807.       (use-completion-before-separator))))
  2808.      )
  2809.    new-name
  2810.    ))
  2811.  
  2812. ;;;(defun foo (x y z) (+ x y z))
  2813. ;;;foo
  2814. ;;;(macroexpand '(def-completion-wrapper foo :under))
  2815. ;;;(progn (defvar $$$cmpl-foo (symbol-function (quote foo))) (defun foo (&rest arglist) (use-completion-under-point) (apply $$$cmpl-foo arglist)))
  2816. ;;;
  2817. ;;;(defun bar (x y z) "Documentation" (+ x y z))
  2818. ;;;bar
  2819. ;;;(macroexpand '(def-completion-wrapper bar :under))
  2820. ;;;(progn (defvar $$$cmpl-bar (symbol-function (quote bar))) (defun bar (&rest arglist) "Documentation" (use-completion-under-point) (apply $$$cmpl-bar arglist)))
  2821. ;;;
  2822. ;;;(defun quuz (x &optional y z) "Documentation" (interactive "P") (+ x y z))
  2823. ;;;quuz
  2824. ;;;(macroexpand '(def-completion-wrapper quuz :before))
  2825. ;;;(progn (defvar $$$cmpl-quuz (symbol-function (quote quuz))) (defun quuz (&rest arglist) "Documentation" (interactive) (use-completion-before-point) (if (interactive-p) (call-interactively $$$cmpl-quuz) (apply $$$cmpl-quuz arglist))))
  2826.  
  2827.  
  2828. ;;;---------------------------------------------------------------------------
  2829. ;;; Patches to standard keymaps insert completions
  2830. ;;;---------------------------------------------------------------------------
  2831.  
  2832. ;;;-----------------------------------------------
  2833. ;;; Separators
  2834. ;;;-----------------------------------------------
  2835. ;;; We've used the completion syntax table given  as a guide.
  2836. ;;;
  2837. ;;; Global separator chars.
  2838. ;;;  We left out <tab> because there are too many special cases for it.  Also,
  2839. ;;; in normal coding it's rarely typed after a word.
  2840. (global-set-key " " 'completion-separator-self-insert-autofilling)
  2841. (global-set-key "!" 'completion-separator-self-insert-command)
  2842. (global-set-key "%" 'completion-separator-self-insert-command)
  2843. (global-set-key "^" 'completion-separator-self-insert-command)
  2844. (global-set-key "&" 'completion-separator-self-insert-command)
  2845. (global-set-key "(" 'completion-separator-self-insert-command)
  2846. (global-set-key ")" 'completion-separator-self-insert-command)
  2847. (global-set-key "=" 'completion-separator-self-insert-command)
  2848. (global-set-key "`" 'completion-separator-self-insert-command)
  2849. (global-set-key "|" 'completion-separator-self-insert-command)
  2850. (global-set-key "{" 'completion-separator-self-insert-command)
  2851. (global-set-key "}" 'completion-separator-self-insert-command)
  2852. (global-set-key "[" 'completion-separator-self-insert-command)
  2853. (global-set-key "]" 'completion-separator-self-insert-command)
  2854. (global-set-key ";" 'completion-separator-self-insert-command)
  2855. (global-set-key "\"" 'completion-separator-self-insert-command)
  2856. (global-set-key "'" 'completion-separator-self-insert-command)
  2857. (global-set-key "#" 'completion-separator-self-insert-command)
  2858. (global-set-key "," 'completion-separator-self-insert-command)
  2859. (global-set-key "?" 'completion-separator-self-insert-command)
  2860.  
  2861. ;;; We include period and colon even though they are symbol chars because :
  2862. ;;;  - in text we want to pick up the last word in a sentence.
  2863. ;;;  - in C pointer refs. we want to pick up the first symbol
  2864. ;;;  - it won't make a difference for lisp mode (package names are short)
  2865. (global-set-key "." 'completion-separator-self-insert-command)
  2866. (global-set-key ":" 'completion-separator-self-insert-command)
  2867.  
  2868. ;;; Lisp Mode diffs
  2869. (define-key lisp-mode-map "!" 'self-insert-command)
  2870. (define-key lisp-mode-map "&" 'self-insert-command)
  2871. (define-key lisp-mode-map "%" 'self-insert-command)
  2872. (define-key lisp-mode-map "?" 'self-insert-command)
  2873. (define-key lisp-mode-map "=" 'self-insert-command)
  2874. (define-key lisp-mode-map "^" 'self-insert-command)
  2875.  
  2876. ;;; C mode diffs.
  2877. (def-completion-wrapper electric-c-semi :separator)
  2878. (define-key c-mode-map "+" 'completion-separator-self-insert-command)
  2879. (define-key c-mode-map "*" 'completion-separator-self-insert-command)
  2880. (define-key c-mode-map "/" 'completion-separator-self-insert-command)
  2881.  
  2882. ;;; FORTRAN mode diffs. (these are defined when fortran is called)
  2883. (defun completion-setup-fortran-mode ()
  2884.   (define-key fortran-mode-map "+" 'completion-separator-self-insert-command)
  2885.   (define-key fortran-mode-map "-" 'completion-separator-self-insert-command)
  2886.   (define-key fortran-mode-map "*" 'completion-separator-self-insert-command)
  2887.   (define-key fortran-mode-map "/" 'completion-separator-self-insert-command)
  2888.   )
  2889.  
  2890. ;;;-----------------------------------------------
  2891. ;;; End of line chars.
  2892. ;;;-----------------------------------------------
  2893. (def-completion-wrapper newline :separator)
  2894. (def-completion-wrapper newline-and-indent :separator)
  2895. (if (function-defined-and-loaded 'shell-send-input)
  2896.     (def-completion-wrapper shell-send-input :separator))
  2897. (def-completion-wrapper exit-minibuffer :minibuffer-separator)
  2898. (def-completion-wrapper eval-print-last-sexp :separator)
  2899. (def-completion-wrapper eval-last-sexp :separator)
  2900. ;;(def-completion-wrapper minibuffer-complete-and-exit :minibuffer)
  2901.  
  2902. ;;;-----------------------------------------------
  2903. ;;; Cursor movement
  2904. ;;;-----------------------------------------------
  2905.  
  2906. (def-completion-wrapper next-line :under-or-before)
  2907. (def-completion-wrapper previous-line :under-or-before)
  2908. (def-completion-wrapper beginning-of-buffer :under-or-before)
  2909. (def-completion-wrapper end-of-buffer :under-or-before)
  2910.  
  2911. ;; we patch these explicitly so they byte compile and so we don't have to
  2912. ;; patch the faster underlying function.
  2913.  
  2914. (defun cmpl-beginning-of-line (&optional n)
  2915.   "Move point to beginning of current line.\n\
  2916. With argument ARG not nil or 1, move forward ARG - 1 lines first.\n\
  2917. If scan reaches end of buffer, stop there without error."
  2918.   (interactive "p")
  2919.   (use-completion-under-or-before-point)
  2920.   (beginning-of-line n)
  2921.   )
  2922.  
  2923. (defun cmpl-end-of-line (&optional n)
  2924.   "Move point to end of current line.\n\
  2925. With argument ARG not nil or 1, move forward ARG - 1 lines first.\n\
  2926. If scan reaches end of buffer, stop there without error."
  2927.   (interactive "p")
  2928.   (use-completion-under-or-before-point)
  2929.   (end-of-line n)
  2930.   )
  2931.  
  2932. (defun cmpl-forward-char (&optional n)
  2933.   "Move point right ARG characters (left if ARG negative).\n\
  2934. On reaching end of buffer, stop and signal error."
  2935.   (interactive "p")
  2936.   (use-completion-under-or-before-point)
  2937.   (forward-char n)
  2938.   )
  2939. (defun cmpl-backward-char (&optional n)
  2940.   "Move point left ARG characters (right if ARG negative).\n\
  2941. On attempt to pass beginning or end of buffer, stop and signal error."
  2942.   (interactive "p")
  2943.   (use-completion-under-point)
  2944.   (if (eq last-command 'complete)
  2945.       ;; probably a failed completion if you have to back up
  2946.       (cmpl-statistics-block (record-complete-failed)))
  2947.   (backward-char n)
  2948.   )
  2949.  
  2950. (defun cmpl-forward-word (&optional n)
  2951.   "Move point forward ARG words (backward if ARG is negative).\n\
  2952. Normally returns t.\n\
  2953. If an edge of the buffer is reached, point is left there\n\
  2954. and nil is returned."
  2955.   (interactive "p")
  2956.   (use-completion-under-or-before-point)
  2957.   (forward-word n)
  2958.   )
  2959. (defun cmpl-backward-word (&optional n)
  2960.   "Move backward until encountering the end of a word.
  2961. With argument, do this that many times.
  2962. In programs, it is faster to call forward-word with negative arg."
  2963.   (interactive "p")
  2964.   (use-completion-under-point)
  2965.   (if (eq last-command 'complete)
  2966.       ;; probably a failed completion if you have to back up
  2967.       (cmpl-statistics-block (record-complete-failed)))
  2968.   (forward-word (- n))
  2969.   )
  2970.  
  2971. (defun cmpl-forward-sexp (&optional n)
  2972.   "Move forward across one balanced expression.
  2973. With argument, do this that many times."
  2974.   (interactive "p")
  2975.   (use-completion-under-or-before-point)
  2976.   (forward-sexp n)
  2977.   )
  2978. (defun cmpl-backward-sexp (&optional n)
  2979.   "Move backward across one balanced expression.
  2980. With argument, do this that many times."
  2981.   (interactive "p")
  2982.   (use-completion-under-point)
  2983.   (if (eq last-command 'complete)
  2984.       ;; probably a failed completion if you have to back up
  2985.       (cmpl-statistics-block (record-complete-failed)))
  2986.   (backward-sexp n)
  2987.   )
  2988.  
  2989. (defun cmpl-delete-backward-char (n killflag)
  2990.   "Delete the previous ARG characters (following, with negative ARG).\n\
  2991. Optional second arg KILLFLAG non-nil means kill instead (save in kill ring).\n\
  2992. Interactively, ARG is the prefix arg, and KILLFLAG is set if\n\
  2993. ARG was explicitly specified."
  2994.   (interactive "p\nP")
  2995.   (if (eq last-command 'complete)
  2996.       ;; probably a failed completion if you have to back up
  2997.       (cmpl-statistics-block (record-complete-failed)))
  2998.   (delete-backward-char n killflag)
  2999.   )
  3000.  
  3001. (defvar $$$cmpl-old-backward-delete-char-untabify
  3002.   (symbol-function 'backward-delete-char-untabify))
  3003.  
  3004. (defun backward-delete-char-untabify (arg &optional killp)
  3005.   "Delete characters backward, changing tabs into spaces.
  3006. Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
  3007. Interactively, ARG is the prefix arg (default 1)
  3008. and KILLP is t if prefix arg is was specified."
  3009.   (interactive "*p\nP")
  3010.   (if (eq last-command 'complete)
  3011.       ;; probably a failed completion if you have to back up
  3012.       (cmpl-statistics-block (record-complete-failed)))
  3013.   (funcall $$$cmpl-old-backward-delete-char-untabify arg killp)
  3014.   )
  3015.  
  3016.  
  3017. (global-set-key "\C-?" 'cmpl-delete-backward-char)
  3018. (global-set-key "\M-\C-F" 'cmpl-forward-sexp)
  3019. (global-set-key "\M-\C-B" 'cmpl-backward-sexp)
  3020. (global-set-key "\M-F" 'cmpl-forward-word)
  3021. (global-set-key "\M-B" 'cmpl-backward-word)
  3022. (global-set-key "\C-F" 'cmpl-forward-char)
  3023. (global-set-key "\C-B" 'cmpl-backward-char)
  3024. (global-set-key "\C-A" 'cmpl-beginning-of-line)
  3025. (global-set-key "\C-E" 'cmpl-end-of-line)
  3026.  
  3027. ;;;-----------------------------------------------
  3028. ;;; Misc.
  3029. ;;;-----------------------------------------------
  3030.  
  3031. (def-completion-wrapper electric-buffer-list :under-or-before)
  3032. (def-completion-wrapper list-buffers :under-or-before)
  3033. (def-completion-wrapper scroll-up :under-or-before)
  3034. (def-completion-wrapper scroll-down :under-or-before)
  3035. (def-completion-wrapper execute-extended-command
  3036.     :under-or-before)
  3037. (def-completion-wrapper other-window :under-or-before)
  3038.  
  3039. ;;;-----------------------------------------------
  3040. ;;; Local Thinking Machines stuff
  3041. ;;;-----------------------------------------------
  3042.  
  3043. (if (fboundp 'up-ten-lines)
  3044.     (def-completion-wrapper up-ten-lines :under-or-before))
  3045. (if (fboundp 'down-ten-lines)
  3046.     (def-completion-wrapper down-ten-lines :under-or-before))
  3047. (if (fboundp 'tmc-scroll-up)
  3048.     (def-completion-wrapper tmc-scroll-up :under-or-before))
  3049. (if (fboundp 'tmc-scroll-down)
  3050.     (def-completion-wrapper tmc-scroll-down :under-or-before))
  3051. (if (fboundp 'execute-extended-command-and-check-for-bindings)
  3052.     (def-completion-wrapper execute-extended-command-and-check-for-bindings
  3053.     :under-or-before))
  3054.  
  3055. ;;; Tests --
  3056. ;;; foobarbiz
  3057. ;;; foobar 
  3058. ;;; fooquux 
  3059. ;;; fooper
  3060.  
  3061. (cmpl-statistics-block
  3062.   (record-completion-file-loaded))
  3063.