completion.el 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367
  1. ;;; completion.el --- dynamic word-completion code
  2. ;; Copyright (C) 1990, 1993, 1995, 1997, 2001-2015 Free Software
  3. ;; Foundation, Inc.
  4. ;; Maintainer: emacs-devel@gnu.org
  5. ;; Keywords: abbrev convenience
  6. ;; Author: Jim Salem <alem@bbnplanet.com> of Thinking Machines Inc.
  7. ;; (ideas suggested by Brewster Kahle)
  8. ;; This file is part of GNU Emacs.
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;; What to put in .emacs
  21. ;;-----------------------
  22. ;; (dynamic-completion-mode)
  23. ;;---------------------------------------------------------------------------
  24. ;; Documentation [Slightly out of date]
  25. ;;---------------------------------------------------------------------------
  26. ;; (also check the documentation string of the functions)
  27. ;;
  28. ;; Introduction
  29. ;;---------------
  30. ;;
  31. ;; After you type a few characters, pressing the "complete" key inserts
  32. ;; the rest of the word you are likely to type.
  33. ;;
  34. ;; This watches all the words that you type and remembers them. When
  35. ;; typing a new word, pressing "complete" (meta-return) "completes" the
  36. ;; word by inserting the most recently used word that begins with the
  37. ;; same characters. If you press meta-return repeatedly, it cycles
  38. ;; through all the words it knows about.
  39. ;;
  40. ;; If you like the completion then just continue typing, it is as if you
  41. ;; entered the text by hand. If you want the inserted extra characters
  42. ;; to go away, type control-w or delete. More options are described below.
  43. ;;
  44. ;; The guesses are made in the order of the most recently "used". Typing
  45. ;; in a word and then typing a separator character (such as a space) "uses"
  46. ;; the word. So does moving a cursor over the word. If no words are found,
  47. ;; it uses an extended version of the dabbrev style completion.
  48. ;;
  49. ;; You automatically save the completions you use to a file between
  50. ;; sessions.
  51. ;;
  52. ;; Completion enables programmers to enter longer, more descriptive
  53. ;; variable names while typing fewer keystrokes than they normally would.
  54. ;;
  55. ;;
  56. ;; Full documentation
  57. ;;---------------------
  58. ;;
  59. ;; A "word" is any string containing characters with either word or symbol
  60. ;; syntax. [E.G. Any alphanumeric string with hyphens, underscores, etc.]
  61. ;; Unless you change the constants, you must type at least three characters
  62. ;; for the word to be recognized. Only words longer than 6 characters are
  63. ;; saved.
  64. ;;
  65. ;; When you load this file, completion will be on. I suggest you use the
  66. ;; compiled version (because it is noticeably faster).
  67. ;;
  68. ;; M-x completion-mode toggles whether or not new words are added to the
  69. ;; database by changing the value of enable-completion.
  70. ;;
  71. ;; SAVING/LOADING COMPLETIONS
  72. ;; Completions are automatically saved from one session to another
  73. ;; (unless save-completions-flag or enable-completion is nil).
  74. ;; Activating this minor-mode (calling completion-initialize) loads
  75. ;; a completions database for a saved completions file
  76. ;; (default: ~/.completions). When you exit, Emacs saves a copy of the
  77. ;; completions that you often use. When you next start, Emacs loads in
  78. ;; the saved completion file.
  79. ;;
  80. ;; The number of completions saved depends loosely on
  81. ;; *saved-completions-decay-factor*. Completions that have never been
  82. ;; inserted via "complete" are not saved. You are encouraged to experiment
  83. ;; with different functions (see compute-completion-min-num-uses).
  84. ;;
  85. ;; Some completions are permanent and are always saved out. These
  86. ;; completions have their num-uses slot set to T. Use
  87. ;; add-permanent-completion to do this
  88. ;;
  89. ;; Completions are saved only if enable-completion is T. The number of old
  90. ;; versions kept of the saved completions file is controlled by
  91. ;; completions-file-versions-kept.
  92. ;;
  93. ;; COMPLETE KEY OPTIONS
  94. ;; The complete function takes a numeric arguments.
  95. ;; control-u :: leave the point at the beginning of the completion rather
  96. ;; than the middle.
  97. ;; a number :: rotate through the possible completions by that amount
  98. ;; `-' :: same as -1 (insert previous completion)
  99. ;;
  100. ;; HOW THE DATABASE IS MAINTAINED
  101. ;; <write>
  102. ;;
  103. ;; UPDATING THE DATABASE MANUALLY
  104. ;; m-x kill-completion
  105. ;; kills the completion at point.
  106. ;; m-x add-completion
  107. ;; m-x add-permanent-completion
  108. ;;
  109. ;; UPDATING THE DATABASE FROM A SOURCE CODE FILE
  110. ;; m-x add-completions-from-buffer
  111. ;; Parses all the definition names from a C or LISP mode buffer and
  112. ;; adds them to the completion database.
  113. ;;
  114. ;; m-x add-completions-from-lisp-file
  115. ;; Parses all the definition names from a C or Lisp mode file and
  116. ;; adds them to the completion database.
  117. ;;
  118. ;; UPDATING THE DATABASE FROM A TAGS TABLE
  119. ;; m-x add-completions-from-tags-table
  120. ;; Adds completions from the current tags-table-buffer.
  121. ;;
  122. ;; HOW A COMPLETION IS FOUND
  123. ;; <write>
  124. ;;
  125. ;; STRING CASING
  126. ;; Completion is string case independent if case-fold-search has its
  127. ;; normal default of T. Also when the completion is inserted the case of the
  128. ;; entry is coerced appropriately.
  129. ;; [E.G. APP --> APPROPRIATELY app --> appropriately
  130. ;; App --> Appropriately]
  131. ;;
  132. ;; INITIALIZATION
  133. ;; The form `(completion-initialize)' initializes the completion system by
  134. ;; trying to load in the user's completions. After the first call, further
  135. ;; calls have no effect so one should be careful not to put the form in a
  136. ;; site's standard site-init file.
  137. ;;
  138. ;;---------------------------------------------------------------------------
  139. ;;
  140. ;;
  141. ;;---------------------------------------------------------------------------
  142. ;; Functions you might like to call
  143. ;;---------------------------------------------------------------------------
  144. ;;
  145. ;; add-completion string &optional num-uses
  146. ;; Adds a new string to the database
  147. ;;
  148. ;; add-permanent-completion string
  149. ;; Adds a new string to the database with num-uses = T
  150. ;;
  151. ;; kill-completion string
  152. ;; Kills the completion from the database.
  153. ;;
  154. ;; clear-all-completions
  155. ;; Clears the database
  156. ;;
  157. ;; list-all-completions
  158. ;; Returns a list of all completions.
  159. ;;
  160. ;;
  161. ;; next-completion string &optional index
  162. ;; Returns a completion entry that starts with string.
  163. ;;
  164. ;; find-exact-completion string
  165. ;; Returns a completion entry that exactly matches string.
  166. ;;
  167. ;; complete
  168. ;; Inserts a completion at point
  169. ;;
  170. ;; completion-initialize
  171. ;; Loads the completions file and sets up so that exiting emacs will
  172. ;; save them.
  173. ;;
  174. ;; save-completions-to-file &optional filename
  175. ;; load-completions-from-file &optional filename
  176. ;;
  177. ;;-----------------------------------------------
  178. ;; Other functions
  179. ;;-----------------------------------------------
  180. ;;
  181. ;; get-completion-list string
  182. ;;
  183. ;; These things are for manipulating the structure
  184. ;; make-completion string num-uses
  185. ;; completion-num-uses completion
  186. ;; completion-string completion
  187. ;; set-completion-num-uses completion num-uses
  188. ;; set-completion-string completion string
  189. ;;
  190. ;;
  191. ;;-----------------------------------------------
  192. ;; To Do :: (anybody ?)
  193. ;;-----------------------------------------------
  194. ;;
  195. ;; Implement Lookup and keyboard interface in C
  196. ;; Add package prefix smarts (for Common Lisp)
  197. ;; Add autoprompting of possible completions after every keystroke (fast
  198. ;; terminals only !)
  199. ;; Add doc. to texinfo
  200. ;;
  201. ;;
  202. ;;-----------------------------------------------
  203. ;;; Change Log:
  204. ;;-----------------------------------------------
  205. ;; Sometime in '84 Brewster implemented a somewhat buggy version for
  206. ;; Symbolics LISPMs.
  207. ;; Jan. '85 Jim became enamored of the idea and implemented a faster,
  208. ;; more robust version.
  209. ;; With input from many users at TMC, (rose, craig, and gls come to mind),
  210. ;; the current style of interface was developed.
  211. ;; 9/87, Jim and Brewster took terminals home. Yuck. After
  212. ;; complaining for a while Brewster implemented a subset of the current
  213. ;; LISPM version for GNU Emacs.
  214. ;; 8/88 After complaining for a while (and with sufficient
  215. ;; promised rewards), Jim reimplemented a version of GNU completion
  216. ;; superior to that of the LISPM version.
  217. ;;
  218. ;;-----------------------------------------------
  219. ;; Acknowledgments
  220. ;;-----------------------------------------------
  221. ;; Cliff Lasser (cal@think.com), Kevin Herbert (kph@cisco.com),
  222. ;; eero@media-lab, kgk@cs.brown.edu, jla@ai.mit.edu,
  223. ;;
  224. ;;-----------------------------------------------
  225. ;; Change Log
  226. ;;-----------------------------------------------
  227. ;; From version 9 to 10
  228. ;; - Allowance for non-integral *completion-version* nos.
  229. ;; - Fix cmpl-apply-as-top-level for keyboard macros
  230. ;; - Fix broken completion merging (in save-completions-to-file)
  231. ;; - More misc. fixes for version 19.0 of emacs
  232. ;;
  233. ;; From Version 8 to 9
  234. ;; - Ported to version 19.0 of emacs (backcompatible with version 18)
  235. ;; - Added add-completions-from-tags-table (with thanks to eero@media-lab)
  236. ;;
  237. ;; From Version 7 to 8
  238. ;; - Misc. changes to comments
  239. ;; - new completion key bindings: c-x o, M->, M-<, c-a, c-e
  240. ;; - cdabbrev now checks all the visible window buffers and the "other buffer"
  241. ;; - `%' is now a symbol character rather than a separator (except in C mode)
  242. ;;
  243. ;; From Version 6 to 7
  244. ;; - Fixed bug with saving out .completion file the first time
  245. ;;
  246. ;; From Version 5 to 6
  247. ;; - removed statistics recording
  248. ;; - reworked advise to handle autoloads
  249. ;; - Fixed fortran mode support
  250. ;; - Added new cursor motion triggers
  251. ;;
  252. ;; From Version 4 to 5
  253. ;; - doesn't bother saving if nothing has changed
  254. ;; - auto-save if haven't used for a 1/2 hour
  255. ;; - save period extended to two weeks
  256. ;; - minor fix to capitalization code
  257. ;; - added *completion-auto-save-period* to variables recorded.
  258. ;; - added reenter protection to cmpl-record-statistics-filter
  259. ;; - added backup protection to save-completions-to-file (prevents
  260. ;; problems with disk full errors)
  261. ;;; Code:
  262. ;;---------------------------------------------------------------------------
  263. ;; User changeable parameters
  264. ;;---------------------------------------------------------------------------
  265. (defgroup completion nil
  266. "Dynamic word-completion code."
  267. :group 'matching
  268. :group 'convenience)
  269. (defcustom enable-completion t
  270. "Non-nil means enable recording and saving of completions.
  271. If nil, no new words are added to the database or saved to the init file."
  272. :type 'boolean
  273. :group 'completion)
  274. (defcustom save-completions-flag t
  275. "Non-nil means save most-used completions when exiting Emacs.
  276. See also `save-completions-retention-time'."
  277. :type 'boolean
  278. :group 'completion)
  279. (defcustom save-completions-file-name
  280. (locate-user-emacs-file "completions" ".completions")
  281. "The filename to save completions to."
  282. :type 'file
  283. :group 'completion)
  284. (defcustom save-completions-retention-time 336
  285. "Discard a completion if unused for this many hours.
  286. \(1 day = 24, 1 week = 168). If this is 0, non-permanent completions
  287. will not be saved unless these are used. Default is two weeks."
  288. :type 'integer
  289. :group 'completion)
  290. (defcustom completion-on-separator-character nil
  291. "Non-nil means separator characters mark previous word as used.
  292. This means the word will be saved as a completion."
  293. :type 'boolean
  294. :group 'completion)
  295. (defcustom completions-file-versions-kept kept-new-versions
  296. "Number of versions to keep for the saved completions file."
  297. :type 'integer
  298. :group 'completion)
  299. (defcustom completion-prompt-speed-threshold 4800
  300. "Minimum output speed at which to display next potential completion."
  301. :type 'integer
  302. :group 'completion)
  303. (defcustom completion-cdabbrev-prompt-flag nil
  304. "If non-nil, the next completion prompt does a cdabbrev search.
  305. This can be time consuming."
  306. :type 'boolean
  307. :group 'completion)
  308. (defcustom completion-search-distance 15000
  309. "How far to search in the buffer when looking for completions.
  310. In number of characters. If nil, search the whole buffer."
  311. :type 'integer
  312. :group 'completion)
  313. (defcustom completions-merging-modes '(lisp c)
  314. "List of modes {`c' or `lisp'} for automatic completions merging.
  315. Definitions from visited files which have these modes
  316. are automatically added to the completion database."
  317. :type '(set (const lisp) (const c))
  318. :group 'completion)
  319. ;;(defvar *completion-auto-save-period* 1800
  320. ;; "The period in seconds to wait for emacs to be idle before autosaving
  321. ;;the completions. Default is a 1/2 hour.")
  322. (defvar completion-min-length 6
  323. "The minimum length of a stored completion.
  324. DON'T CHANGE WITHOUT RECOMPILING ! This is used by macros.")
  325. (defvar completion-max-length 200
  326. "The maximum length of a stored completion.
  327. DON'T CHANGE WITHOUT RECOMPILING ! This is used by macros.")
  328. (defvar completion-prefix-min-length 3
  329. "The minimum length of a completion search string.
  330. DON'T CHANGE WITHOUT RECOMPILING ! This is used by macros.")
  331. ;;---------------------------------------------------------------------------
  332. ;; Internal Variables
  333. ;;---------------------------------------------------------------------------
  334. (defvar cmpl-initialized-p nil
  335. "Set to t when the completion system is initialized.
  336. Indicates that the old completion file has been read in.")
  337. (defvar cmpl-completions-accepted-p nil
  338. "Set to t as soon as the first completion has been accepted.
  339. Used to decide whether to save completions.")
  340. (defvar cmpl-preceding-syntax)
  341. (defvar cmpl--completion-string)
  342. ;;---------------------------------------------------------------------------
  343. ;; Low level tools
  344. ;;---------------------------------------------------------------------------
  345. ;;-----------------------------------------------
  346. ;; String case coercion
  347. ;;-----------------------------------------------
  348. (defun cmpl-string-case-type (string)
  349. "Return :capitalized, :up, :down, :mixed, or :neither for case of STRING."
  350. (let ((case-fold-search nil))
  351. (cond ((string-match "[[:lower:]]" string)
  352. (cond ((string-match "[[:upper:]]" string)
  353. (cond ((and (> (length string) 1)
  354. (null (string-match "[[:upper:]]" string 1)))
  355. :capitalized)
  356. (t
  357. :mixed)))
  358. (t :down)))
  359. (t
  360. (cond ((string-match "[[:upper:]]" string)
  361. :up)
  362. (t :neither))))))
  363. ;; Tests -
  364. ;; (cmpl-string-case-type "123ABCDEF456") --> :up
  365. ;; (cmpl-string-case-type "123abcdef456") --> :down
  366. ;; (cmpl-string-case-type "123aBcDeF456") --> :mixed
  367. ;; (cmpl-string-case-type "123456") --> :neither
  368. ;; (cmpl-string-case-type "Abcde123") --> :capitalized
  369. (defun cmpl-coerce-string-case (string case-type)
  370. (cond ((eq case-type :down) (downcase string))
  371. ((eq case-type :up) (upcase string))
  372. ((eq case-type :capitalized)
  373. (setq string (downcase string))
  374. (aset string 0 (logand ?\337 (aref string 0)))
  375. string)
  376. (t string)))
  377. (defun cmpl-merge-string-cases (string-to-coerce given-string)
  378. (let ((string-case-type (cmpl-string-case-type string-to-coerce)))
  379. (cond ((memq string-case-type '(:down :up :capitalized))
  380. ;; Found string is in a standard case. Coerce to a type based on
  381. ;; the given string
  382. (cmpl-coerce-string-case string-to-coerce
  383. (cmpl-string-case-type given-string)))
  384. (t
  385. ;; If the found string is in some unusual case, just insert it
  386. ;; as is
  387. string-to-coerce))))
  388. ;; Tests -
  389. ;; (cmpl-merge-string-cases "AbCdEf456" "abc") --> AbCdEf456
  390. ;; (cmpl-merge-string-cases "abcdef456" "ABC") --> ABCDEF456
  391. ;; (cmpl-merge-string-cases "ABCDEF456" "Abc") --> Abcdef456
  392. ;; (cmpl-merge-string-cases "ABCDEF456" "abc") --> abcdef456
  393. (defun cmpl-hours-since-origin ()
  394. (floor (float-time) 3600))
  395. ;;---------------------------------------------------------------------------
  396. ;; "Symbol" parsing functions
  397. ;;---------------------------------------------------------------------------
  398. ;; The functions symbol-before-point, symbol-under-point, etc. quickly return
  399. ;; an appropriate symbol string. The strategy is to temporarily change
  400. ;; the syntax table to enable fast symbol searching. There are three classes
  401. ;; of syntax in these "symbol" syntax tables ::
  402. ;;
  403. ;; syntax (?_) - "symbol" chars (e.g. alphanumerics)
  404. ;; syntax (?w) - symbol chars to ignore at end of words (e.g. period).
  405. ;; syntax (? ) - everything else
  406. ;;
  407. ;; Thus by judicious use of scan-sexps and forward-word, we can get
  408. ;; the word we want relatively fast and without consing.
  409. ;;
  410. ;; Why do we need a separate category for "symbol chars to ignore at ends" ?
  411. ;; For example, in LISP we want starting :'s trimmed
  412. ;; so keyword argument specifiers also define the keyword completion. And,
  413. ;; for example, in C we want `.' appearing in a structure ref. to
  414. ;; be kept intact in order to store the whole structure ref.; however, if
  415. ;; it appears at the end of a symbol it should be discarded because it is
  416. ;; probably used as a period.
  417. ;; Here is the default completion syntax ::
  418. ;; Symbol chars :: A-Z a-z 0-9 @ / \ * + ~ $ < > %
  419. ;; Symbol chars to ignore at ends :: _ : . -
  420. ;; Separator chars. :: <tab> <space> ! ^ & ( ) = ` | { } [ ] ; " ' #
  421. ;; , ? <Everything else>
  422. ;; Mode specific differences and notes ::
  423. ;; LISP diffs ->
  424. ;; Symbol chars :: ! & ? = ^
  425. ;;
  426. ;; C diffs ->
  427. ;; Separator chars :: + * / : %
  428. ;; A note on the hyphen (`-'). Perhaps the hyphen should also be a separator
  429. ;; char., however, we wanted to have completion symbols include pointer
  430. ;; references. For example, "foo->bar" is a symbol as far as completion is
  431. ;; concerned.
  432. ;;
  433. ;; FORTRAN diffs ->
  434. ;; Separator chars :: + - * / :
  435. ;;
  436. ;; Pathname diffs ->
  437. ;; Symbol chars :: .
  438. ;; Of course there is no pathname "mode" and in fact we have not implemented
  439. ;; this table. However, if there was such a mode, this is what it would look
  440. ;; like.
  441. ;;-----------------------------------------------
  442. ;; Table definitions
  443. ;;-----------------------------------------------
  444. (defconst completion-standard-syntax-table
  445. (let ((table (make-syntax-table))
  446. i)
  447. ;; Default syntax is whitespace.
  448. (setq i 0)
  449. (while (< i 256)
  450. (modify-syntax-entry i " " table)
  451. (setq i (1+ i)))
  452. ;; alpha chars
  453. (setq i 0)
  454. (while (< i 26)
  455. (modify-syntax-entry (+ ?a i) "_" table)
  456. (modify-syntax-entry (+ ?A i) "_" table)
  457. (setq i (1+ i)))
  458. ;; digit chars.
  459. (setq i 0)
  460. (while (< i 10)
  461. (modify-syntax-entry (+ ?0 i) "_" table)
  462. (setq i (1+ i)))
  463. ;; Other ones
  464. (let ((symbol-chars '(?@ ?/ ?\\ ?* ?+ ?~ ?$ ?< ?> ?%))
  465. (symbol-chars-ignore '(?_ ?- ?: ?.)))
  466. (dolist (char symbol-chars)
  467. (modify-syntax-entry char "_" table))
  468. (dolist (char symbol-chars-ignore)
  469. (modify-syntax-entry char "w" table)))
  470. table))
  471. (defvar completion-syntax-table completion-standard-syntax-table
  472. "This variable holds the current completion syntax table.")
  473. (make-variable-buffer-local 'completion-syntax-table)
  474. ;;-----------------------------------------------
  475. ;; Symbol functions
  476. ;;-----------------------------------------------
  477. (defvar cmpl-symbol-start nil
  478. "Holds first character of symbol, after any completion symbol function.")
  479. (defvar cmpl-symbol-end nil
  480. "Holds last character of symbol, after any completion symbol function.")
  481. (defun symbol-under-point ()
  482. "Return the symbol that the point is currently on.
  483. But only if it is longer than `completion-min-length'."
  484. (with-syntax-table completion-syntax-table
  485. (when (memq (char-syntax (following-char)) '(?w ?_))
  486. ;; Cursor is on following-char and after preceding-char
  487. (let ((saved-point (point)))
  488. (setq cmpl-symbol-start (scan-sexps (1+ saved-point) -1)
  489. cmpl-symbol-end (scan-sexps saved-point 1))
  490. ;; Remove chars to ignore at the start.
  491. (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
  492. (goto-char cmpl-symbol-start)
  493. (forward-word 1)
  494. (setq cmpl-symbol-start (point))
  495. (goto-char saved-point)))
  496. ;; Remove chars to ignore at the end.
  497. (cond ((= (char-syntax (char-after (1- cmpl-symbol-end))) ?w)
  498. (goto-char cmpl-symbol-end)
  499. (forward-word -1)
  500. (setq cmpl-symbol-end (point))
  501. (goto-char saved-point)))
  502. ;; Return completion if the length is reasonable.
  503. (if (and (<= completion-min-length
  504. (- cmpl-symbol-end cmpl-symbol-start))
  505. (<= (- cmpl-symbol-end cmpl-symbol-start)
  506. completion-max-length))
  507. (buffer-substring-no-properties
  508. cmpl-symbol-start cmpl-symbol-end))))))
  509. ;; tests for symbol-under-point
  510. ;; `^' indicates cursor pos. where value is returned
  511. ;; simple-word-test
  512. ;; ^^^^^^^^^^^^^^^^ --> simple-word-test
  513. ;; _harder_word_test_
  514. ;; ^^^^^^^^^^^^^^^^^^ --> harder_word_test
  515. ;; .___.______.
  516. ;; --> nil
  517. ;; /foo/bar/quux.hello
  518. ;; ^^^^^^^^^^^^^^^^^^^ --> /foo/bar/quux.hello
  519. ;;
  520. (defun symbol-before-point ()
  521. "Return a string of the symbol immediately before point.
  522. Returns nil if there isn't one longer than `completion-min-length'."
  523. ;; This is called when a word separator is typed so it must be FAST !
  524. (with-syntax-table completion-syntax-table
  525. ;; Cursor is on following-char and after preceding-char
  526. (cond ((= (setq cmpl-preceding-syntax (char-syntax (preceding-char))) ?_)
  527. ;; Number of chars to ignore at end.
  528. (setq cmpl-symbol-end (point)
  529. cmpl-symbol-start (scan-sexps cmpl-symbol-end -1))
  530. ;; Remove chars to ignore at the start.
  531. (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
  532. (goto-char cmpl-symbol-start)
  533. (forward-word 1)
  534. (setq cmpl-symbol-start (point))
  535. (goto-char cmpl-symbol-end)))
  536. ;; Return value if long enough.
  537. (if (>= cmpl-symbol-end
  538. (+ cmpl-symbol-start completion-min-length))
  539. (buffer-substring-no-properties
  540. cmpl-symbol-start cmpl-symbol-end)))
  541. ((= cmpl-preceding-syntax ?w)
  542. ;; chars to ignore at end
  543. (let ((saved-point (point)))
  544. (setq cmpl-symbol-start (scan-sexps saved-point -1))
  545. ;; take off chars. from end
  546. (forward-word -1)
  547. (setq cmpl-symbol-end (point))
  548. ;; remove chars to ignore at the start
  549. (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
  550. (goto-char cmpl-symbol-start)
  551. (forward-word 1)
  552. (setq cmpl-symbol-start (point))))
  553. ;; Restore state.
  554. (goto-char saved-point)
  555. ;; Return completion if the length is reasonable
  556. (if (and (<= completion-min-length
  557. (- cmpl-symbol-end cmpl-symbol-start))
  558. (<= (- cmpl-symbol-end cmpl-symbol-start)
  559. completion-max-length))
  560. (buffer-substring-no-properties
  561. cmpl-symbol-start cmpl-symbol-end)))))))
  562. ;; tests for symbol-before-point
  563. ;; `^' indicates cursor pos. where value is returned
  564. ;; simple-word-test
  565. ;; ^ --> nil
  566. ;; ^ --> nil
  567. ;; ^ --> simple-w
  568. ;; ^ --> simple-word-test
  569. ;; _harder_word_test_
  570. ;; ^ --> harder_word_test
  571. ;; ^ --> harder_word_test
  572. ;; ^ --> harder
  573. ;; .___....
  574. ;; --> nil
  575. (defun symbol-under-or-before-point ()
  576. ;; This could be made slightly faster but it is better to avoid
  577. ;; copying all the code.
  578. ;; However, it is only used by the completion string prompter.
  579. ;; If it comes into common use, it could be rewritten.
  580. (if (memq (with-syntax-table completion-syntax-table
  581. (char-syntax (following-char)))
  582. '(?w ?_))
  583. (symbol-under-point)
  584. (symbol-before-point)))
  585. (defun symbol-before-point-for-complete ()
  586. ;; "Returns a string of the symbol immediately before point
  587. ;; or nil if there isn't one. Like symbol-before-point but doesn't trim the
  588. ;; end chars."
  589. ;; Cursor is on following-char and after preceding-char
  590. (with-syntax-table completion-syntax-table
  591. (cond ((memq (setq cmpl-preceding-syntax (char-syntax (preceding-char)))
  592. '(?_ ?w))
  593. (setq cmpl-symbol-end (point)
  594. cmpl-symbol-start (scan-sexps cmpl-symbol-end -1))
  595. ;; Remove chars to ignore at the start.
  596. (cond ((= (char-syntax (char-after cmpl-symbol-start)) ?w)
  597. (goto-char cmpl-symbol-start)
  598. (forward-word 1)
  599. (setq cmpl-symbol-start (point))
  600. (goto-char cmpl-symbol-end)))
  601. ;; Return completion if the length is reasonable.
  602. (if (and (<= completion-prefix-min-length
  603. (- cmpl-symbol-end cmpl-symbol-start))
  604. (<= (- cmpl-symbol-end cmpl-symbol-start)
  605. completion-max-length))
  606. (buffer-substring-no-properties
  607. cmpl-symbol-start cmpl-symbol-end))))))
  608. ;; tests for symbol-before-point-for-complete
  609. ;; `^' indicates cursor pos. where value is returned
  610. ;; simple-word-test
  611. ;; ^ --> nil
  612. ;; ^ --> nil
  613. ;; ^ --> simple-w
  614. ;; ^ --> simple-word-test
  615. ;; _harder_word_test_
  616. ;; ^ --> harder_word_test
  617. ;; ^ --> harder_word_test_
  618. ;; ^ --> harder_
  619. ;; .___....
  620. ;; --> nil
  621. ;;---------------------------------------------------------------------------
  622. ;; Statistics Recording
  623. ;;---------------------------------------------------------------------------
  624. ;; Note that the guts of this has been turned off. The guts
  625. ;; are in completion-stats.el.
  626. ;;-----------------------------------------------
  627. ;; Completion Sources
  628. ;;-----------------------------------------------
  629. ;; ID numbers
  630. (defconst cmpl-source-unknown 0)
  631. (defconst cmpl-source-init-file 1)
  632. (defconst cmpl-source-file-parsing 2)
  633. (defconst cmpl-source-separator 3)
  634. (defconst cmpl-source-cursor-moves 4)
  635. (defconst cmpl-source-interactive 5)
  636. (defconst cmpl-source-cdabbrev 6)
  637. (defconst num-cmpl-sources 7)
  638. (defvar current-completion-source cmpl-source-unknown)
  639. ;;---------------------------------------------------------------------------
  640. ;; Completion Method #2: dabbrev-expand style
  641. ;;---------------------------------------------------------------------------
  642. ;;
  643. ;; This method is used if there are no useful stored completions. It is
  644. ;; based on dabbrev-expand with these differences :
  645. ;; 1) Faster (we don't use regexps)
  646. ;; 2) case coercion handled correctly
  647. ;; This is called cdabbrev to differentiate it.
  648. ;; We simply search backwards through the file looking for words which
  649. ;; start with the same letters we are trying to complete.
  650. ;;
  651. (defvar cdabbrev-completions-tried nil)
  652. ;; "A list of all the cdabbrev completions since the last reset.")
  653. (defvar cdabbrev-current-point 0)
  654. ;; "The current point position the cdabbrev search is at.")
  655. (defvar cdabbrev-current-window nil)
  656. ;; "The current window we are looking for cdabbrevs in.
  657. ;; Return t if looking in (other-buffer), nil if no more cdabbrevs.")
  658. (defvar cdabbrev-wrapped-p nil)
  659. ;; "Return t if the cdabbrev search has wrapped around the file.")
  660. (defvar cdabbrev-abbrev-string "")
  661. (defvar cdabbrev-start-point 0)
  662. (defvar cdabbrev-stop-point)
  663. ;; Test strings for cdabbrev
  664. ;; cdat-upcase ;;same namestring
  665. ;; CDAT-UPCASE ;;ok
  666. ;; cdat2 ;;too short
  667. ;; cdat-1-2-3-4 ;;ok
  668. ;; a-cdat-1 ;;doesn't start correctly
  669. ;; cdat-simple ;;ok
  670. (defun reset-cdabbrev (abbrev-string &optional initial-completions-tried)
  671. "Reset the cdabbrev search to search for ABBREV-STRING.
  672. INITIAL-COMPLETIONS-TRIED is a list of downcased strings to ignore
  673. during the search."
  674. (setq cdabbrev-abbrev-string abbrev-string
  675. cdabbrev-completions-tried
  676. (cons (downcase abbrev-string) initial-completions-tried))
  677. (reset-cdabbrev-window t))
  678. (defun set-cdabbrev-buffer ()
  679. ;; cdabbrev-current-window must not be nil
  680. (set-buffer (if (eq cdabbrev-current-window t)
  681. (other-buffer)
  682. (window-buffer cdabbrev-current-window))))
  683. (defun reset-cdabbrev-window (&optional initializep)
  684. "Reset the cdabbrev search to search for abbrev-string."
  685. ;; Set the window
  686. (cond (initializep
  687. (setq cdabbrev-current-window (selected-window)))
  688. ((eq cdabbrev-current-window t)
  689. ;; Everything has failed
  690. (setq cdabbrev-current-window nil))
  691. (cdabbrev-current-window
  692. (setq cdabbrev-current-window (next-window cdabbrev-current-window))
  693. (if (eq cdabbrev-current-window (selected-window))
  694. ;; No more windows, try other buffer.
  695. (setq cdabbrev-current-window t))))
  696. (if cdabbrev-current-window
  697. (save-excursion
  698. (set-cdabbrev-buffer)
  699. (setq cdabbrev-current-point (point)
  700. cdabbrev-start-point cdabbrev-current-point
  701. cdabbrev-stop-point
  702. (if completion-search-distance
  703. (max (point-min)
  704. (- cdabbrev-start-point completion-search-distance))
  705. (point-min))
  706. cdabbrev-wrapped-p nil))))
  707. (defun next-cdabbrev ()
  708. "Return the next possible cdabbrev expansion or nil if there isn't one.
  709. `reset-cdabbrev' must've been called already.
  710. This is sensitive to `case-fold-search'."
  711. ;; note that case-fold-search affects the behavior of this function
  712. ;; Bug: won't pick up an expansion that starts at the top of buffer
  713. (if cdabbrev-current-window
  714. (let (saved-point
  715. saved-syntax
  716. (expansion nil)
  717. downcase-expansion tried-list syntax saved-point-2)
  718. (save-excursion
  719. (unwind-protect
  720. (progn
  721. ;; Switch to current completion buffer
  722. (set-cdabbrev-buffer)
  723. ;; Save current buffer state
  724. (setq saved-point (point)
  725. saved-syntax (syntax-table))
  726. ;; Restore completion state
  727. (set-syntax-table completion-syntax-table)
  728. (goto-char cdabbrev-current-point)
  729. ;; Loop looking for completions
  730. (while
  731. ;; This code returns t if it should loop again
  732. (cond
  733. (;; search for the string
  734. (search-backward cdabbrev-abbrev-string cdabbrev-stop-point t)
  735. ;; return nil if the completion is valid
  736. (not
  737. (and
  738. ;; does it start with a separator char ?
  739. (or (= (setq syntax (char-syntax (preceding-char))) ? )
  740. (and (= syntax ?w)
  741. ;; symbol char to ignore at end. Are we at end ?
  742. (progn
  743. (setq saved-point-2 (point))
  744. (forward-word -1)
  745. (prog1
  746. (= (char-syntax (preceding-char)) ? )
  747. (goto-char saved-point-2)))))
  748. ;; is the symbol long enough ?
  749. (setq expansion (symbol-under-point))
  750. ;; have we not tried this one before
  751. (progn
  752. ;; See if we've already used it
  753. (setq tried-list cdabbrev-completions-tried
  754. downcase-expansion (downcase expansion))
  755. (while (and tried-list
  756. (not (string-equal downcase-expansion
  757. (car tried-list))))
  758. ;; Already tried, don't choose this one
  759. (setq tried-list (cdr tried-list)))
  760. ;; at this point tried-list will be nil if this
  761. ;; expansion has not yet been tried
  762. (if tried-list
  763. (setq expansion nil)
  764. t)))))
  765. ;; search failed
  766. (cdabbrev-wrapped-p
  767. ;; If already wrapped, then we've failed completely
  768. nil)
  769. (t
  770. ;; need to wrap
  771. (goto-char (setq cdabbrev-current-point
  772. (if completion-search-distance
  773. (min (point-max) (+ cdabbrev-start-point completion-search-distance))
  774. (point-max))))
  775. (setq cdabbrev-wrapped-p t))))
  776. ;; end of while loop
  777. (cond (expansion
  778. ;; successful
  779. (setq cdabbrev-completions-tried
  780. (cons downcase-expansion cdabbrev-completions-tried)
  781. cdabbrev-current-point (point)))))
  782. (set-syntax-table saved-syntax)
  783. (goto-char saved-point)))
  784. ;; If no expansion, go to next window
  785. (cond (expansion)
  786. (t (reset-cdabbrev-window)
  787. (next-cdabbrev))))))
  788. ;; The following must be eval'd in the minibuffer ::
  789. ;; (reset-cdabbrev "cdat")
  790. ;; (next-cdabbrev) --> "cdat-simple"
  791. ;; (next-cdabbrev) --> "cdat-1-2-3-4"
  792. ;; (next-cdabbrev) --> "CDAT-UPCASE"
  793. ;; (next-cdabbrev) --> "cdat-wrapping"
  794. ;; (next-cdabbrev) --> "cdat_start_sym"
  795. ;; (next-cdabbrev) --> nil
  796. ;; (next-cdabbrev) --> nil
  797. ;; (next-cdabbrev) --> nil
  798. ;; _cdat_start_sym
  799. ;; cdat-wrapping
  800. ;;---------------------------------------------------------------------------
  801. ;; Completion Database
  802. ;;---------------------------------------------------------------------------
  803. ;; We use two storage modes for the two search types ::
  804. ;; 1) Prefix {cmpl-prefix-obarray} for looking up possible completions
  805. ;; Used by search-completion-next
  806. ;; the value of the symbol is nil or a cons of head and tail pointers
  807. ;; 2) Interning {cmpl-obarray} to see if it's in the database
  808. ;; Used by find-exact-completion, completion-in-database-p
  809. ;; The value of the symbol is the completion entry
  810. ;; bad things may happen if this length is changed due to the way
  811. ;; GNU implements obarrays
  812. (defconst cmpl-obarray-length 511)
  813. (defvar cmpl-prefix-obarray (make-vector cmpl-obarray-length 0)
  814. "An obarray used to store the downcased completion prefixes.
  815. Each symbol is bound to a list of completion entries.")
  816. (defvar cmpl-obarray (make-vector cmpl-obarray-length 0)
  817. "An obarray used to store the downcased completions.
  818. Each symbol is bound to a single completion entry.")
  819. ;;-----------------------------------------------
  820. ;; Completion Entry Structure Definition
  821. ;;-----------------------------------------------
  822. ;; A completion entry is a LIST of string, prefix-symbol num-uses, and
  823. ;; last-use-time (the time the completion was last used)
  824. ;; last-use-time is t if the string should be kept permanently
  825. ;; num-uses is incremented every time the completion is used.
  826. ;; We chose lists because (car foo) is faster than (aref foo 0) and the
  827. ;; creation time is about the same.
  828. ;; READER MACROS
  829. (defmacro completion-string (completion-entry)
  830. (list 'car completion-entry))
  831. (defmacro completion-num-uses (completion-entry)
  832. ;; "The number of times it has used. Used to decide whether to save
  833. ;; it."
  834. (list 'car (list 'cdr completion-entry)))
  835. (defmacro completion-last-use-time (completion-entry)
  836. ;; "The time it was last used. In hours since origin. Used to decide
  837. ;; whether to save it. t if one should always save it."
  838. (list 'nth 2 completion-entry))
  839. (defmacro completion-source (completion-entry)
  840. (list 'nth 3 completion-entry))
  841. ;; WRITER MACROS
  842. (defmacro set-completion-string (completion-entry string)
  843. (list 'setcar completion-entry string))
  844. (defmacro set-completion-num-uses (completion-entry num-uses)
  845. (list 'setcar (list 'cdr completion-entry) num-uses))
  846. (defmacro set-completion-last-use-time (completion-entry last-use-time)
  847. (list 'setcar (list 'cdr (list 'cdr completion-entry)) last-use-time))
  848. ;; CONSTRUCTOR
  849. (defun make-completion (string)
  850. "Return a completion entry."
  851. (list string 0 nil current-completion-source))
  852. ;; Obsolete
  853. ;;(defmacro cmpl-prefix-entry-symbol (completion-entry)
  854. ;; (list 'car (list 'cdr completion-entry)))
  855. ;;-----------------------------------------------
  856. ;; Prefix symbol entry definition
  857. ;;-----------------------------------------------
  858. ;; A cons of (head . tail)
  859. ;; READER Macros
  860. (defalias 'cmpl-prefix-entry-head 'car)
  861. (defalias 'cmpl-prefix-entry-tail 'cdr)
  862. ;; WRITER Macros
  863. (defmacro set-cmpl-prefix-entry-head (prefix-entry new-head)
  864. (list 'setcar prefix-entry new-head))
  865. (defmacro set-cmpl-prefix-entry-tail (prefix-entry new-tail)
  866. (list 'setcdr prefix-entry new-tail))
  867. ;; Constructor
  868. (defun make-cmpl-prefix-entry (completion-entry-list)
  869. "Make a new prefix entry containing only completion-entry."
  870. (cons completion-entry-list completion-entry-list))
  871. ;;-----------------------------------------------
  872. ;; Completion Database - Utilities
  873. ;;-----------------------------------------------
  874. (defun clear-all-completions ()
  875. "Initialize the completion storage. All existing completions are lost."
  876. (interactive)
  877. (setq cmpl-prefix-obarray (make-vector cmpl-obarray-length 0))
  878. (setq cmpl-obarray (make-vector cmpl-obarray-length 0)))
  879. (defvar completions-list-return-value)
  880. (defun list-all-completions ()
  881. "Return a list of all the known completion entries."
  882. (let ((completions-list-return-value nil))
  883. (mapatoms 'list-all-completions-1 cmpl-prefix-obarray)
  884. completions-list-return-value))
  885. (defun list-all-completions-1 (prefix-symbol)
  886. (if (boundp prefix-symbol)
  887. (setq completions-list-return-value
  888. (append (cmpl-prefix-entry-head (symbol-value prefix-symbol))
  889. completions-list-return-value))))
  890. (defun list-all-completions-by-hash-bucket ()
  891. "Return list of lists of known completion entries, organized by hash bucket."
  892. (let ((completions-list-return-value nil))
  893. (mapatoms 'list-all-completions-by-hash-bucket-1 cmpl-prefix-obarray)
  894. completions-list-return-value))
  895. (defun list-all-completions-by-hash-bucket-1 (prefix-symbol)
  896. (if (boundp prefix-symbol)
  897. (setq completions-list-return-value
  898. (cons (cmpl-prefix-entry-head (symbol-value prefix-symbol))
  899. completions-list-return-value))))
  900. ;;-----------------------------------------------
  901. ;; Updating the database
  902. ;;-----------------------------------------------
  903. ;;
  904. ;; These are the internal functions used to update the datebase
  905. ;;
  906. ;;
  907. (defvar completion-to-accept nil
  908. "Set to a string that is pending its acceptance.")
  909. ;; this checked by the top level reading functions
  910. (defvar cmpl-db-downcase-string nil
  911. "Setup by `find-exact-completion', etc. The given string, downcased.")
  912. (defvar cmpl-db-symbol nil
  913. "The interned symbol corresponding to `cmpl-db-downcase-string'.
  914. Set up by `cmpl-db-symbol'.")
  915. (defvar cmpl-db-prefix-symbol nil
  916. "The interned prefix symbol corresponding to `cmpl-db-downcase-string'.")
  917. (defvar cmpl-db-entry nil)
  918. (defvar cmpl-db-debug-p nil
  919. "Set to t if you want to debug the database.")
  920. ;; READS
  921. (defun find-exact-completion (string)
  922. "Return the completion entry for STRING or nil.
  923. Sets up `cmpl-db-downcase-string' and `cmpl-db-symbol'."
  924. (and (boundp (setq cmpl-db-symbol
  925. (intern (setq cmpl-db-downcase-string (downcase string))
  926. cmpl-obarray)))
  927. (symbol-value cmpl-db-symbol)))
  928. (defun find-cmpl-prefix-entry (prefix-string)
  929. "Return the prefix entry for string.
  930. Sets `cmpl-db-prefix-symbol'.
  931. Prefix-string must be exactly `completion-prefix-min-length' long
  932. and downcased. Sets up `cmpl-db-prefix-symbol'."
  933. (and (boundp (setq cmpl-db-prefix-symbol
  934. (intern prefix-string cmpl-prefix-obarray)))
  935. (symbol-value cmpl-db-prefix-symbol)))
  936. (defvar inside-locate-completion-entry nil)
  937. ;; used to trap lossage in silent error correction
  938. (defun locate-completion-entry (completion-entry prefix-entry)
  939. "Locate the completion entry.
  940. Returns a pointer to the element before the completion entry or nil if
  941. the completion entry is at the head.
  942. Must be called after `find-exact-completion'."
  943. (let ((prefix-list (cmpl-prefix-entry-head prefix-entry))
  944. next-prefix-list)
  945. (cond
  946. ((not (eq (car prefix-list) completion-entry))
  947. ;; not already at head
  948. (while (and prefix-list
  949. (not (eq completion-entry
  950. (car (setq next-prefix-list (cdr prefix-list))))))
  951. (setq prefix-list next-prefix-list))
  952. (cond (;; found
  953. prefix-list)
  954. ;; Didn't find it. Database is messed up.
  955. (cmpl-db-debug-p
  956. ;; not found, error if debug mode
  957. (error "Completion entry exists but not on prefix list - %s"
  958. cmpl--completion-string))
  959. (inside-locate-completion-entry
  960. ;; recursive error: really scrod
  961. (locate-completion-db-error))
  962. (t
  963. ;; Patch out
  964. (set cmpl-db-symbol nil)
  965. ;; Retry
  966. (locate-completion-entry-retry completion-entry)))))))
  967. (defun locate-completion-entry-retry (old-entry)
  968. (let ((inside-locate-completion-entry t))
  969. (add-completion (completion-string old-entry)
  970. (completion-num-uses old-entry)
  971. (completion-last-use-time old-entry))
  972. (let* ((cmpl-entry (find-exact-completion (completion-string old-entry)))
  973. (pref-entry
  974. (if cmpl-entry
  975. (find-cmpl-prefix-entry
  976. (substring cmpl-db-downcase-string
  977. 0 completion-prefix-min-length)))))
  978. (if (and cmpl-entry pref-entry)
  979. ;; try again
  980. (locate-completion-entry cmpl-entry pref-entry)
  981. ;; still losing
  982. (locate-completion-db-error)))))
  983. (defun locate-completion-db-error ()
  984. ;; recursive error: really scrod
  985. (error "Completion database corrupted. Try M-x clear-all-completions. Send bug report"))
  986. ;; WRITES
  987. (defun add-completion-to-tail-if-new (string)
  988. "If STRING is not in the database add it to appropriate prefix list.
  989. STRING is added to the end of the appropriate prefix list with
  990. num-uses = 0. The database is unchanged if it is there. STRING must be
  991. longer than `completion-prefix-min-length'.
  992. This must be very fast.
  993. Returns the completion entry."
  994. (or (find-exact-completion string)
  995. ;; not there
  996. (let (;; create an entry
  997. (entry (list (make-completion string)))
  998. ;; setup the prefix
  999. (prefix-entry (find-cmpl-prefix-entry
  1000. (substring cmpl-db-downcase-string 0
  1001. completion-prefix-min-length))))
  1002. ;; The next two forms should happen as a unit (atomically) but
  1003. ;; no fatal errors should result if that is not the case.
  1004. (cond (prefix-entry
  1005. ;; These two should be atomic, but nothing fatal will happen
  1006. ;; if they're not.
  1007. (setcdr (cmpl-prefix-entry-tail prefix-entry) entry)
  1008. (set-cmpl-prefix-entry-tail prefix-entry entry))
  1009. (t
  1010. (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))))
  1011. ;; set symbol
  1012. (set cmpl-db-symbol (car entry)))))
  1013. (defun add-completion-to-head (completion-string)
  1014. "If COMPLETION-STRING is not in the database, add it to prefix list.
  1015. We add COMPLETION-STRING to the head of the appropriate prefix list,
  1016. or to the head of the list.
  1017. COMPLETION-STRING must be longer than `completion-prefix-min-length'.
  1018. Updates the saved string with the supplied string.
  1019. This must be very fast.
  1020. Returns the completion entry."
  1021. (let ((cmpl--completion-string completion-string))
  1022. ;; Handle pending acceptance
  1023. (if completion-to-accept (accept-completion))
  1024. ;; test if already in database
  1025. (if (setq cmpl-db-entry (find-exact-completion completion-string))
  1026. ;; found
  1027. (let* ((prefix-entry (find-cmpl-prefix-entry
  1028. (substring cmpl-db-downcase-string 0
  1029. completion-prefix-min-length)))
  1030. (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry))
  1031. (cmpl-ptr (cdr splice-ptr)))
  1032. ;; update entry
  1033. (set-completion-string cmpl-db-entry completion-string)
  1034. ;; move to head (if necessary)
  1035. (cond (splice-ptr
  1036. ;; These should all execute atomically but it is not fatal if
  1037. ;; they don't.
  1038. ;; splice it out
  1039. (or (setcdr splice-ptr (cdr cmpl-ptr))
  1040. ;; fix up tail if necessary
  1041. (set-cmpl-prefix-entry-tail prefix-entry splice-ptr))
  1042. ;; splice in at head
  1043. (setcdr cmpl-ptr (cmpl-prefix-entry-head prefix-entry))
  1044. (set-cmpl-prefix-entry-head prefix-entry cmpl-ptr)))
  1045. cmpl-db-entry)
  1046. ;; not there
  1047. (let ( ;; create an entry
  1048. (entry (list (make-completion completion-string)))
  1049. ;; setup the prefix
  1050. (prefix-entry (find-cmpl-prefix-entry
  1051. (substring cmpl-db-downcase-string 0
  1052. completion-prefix-min-length))))
  1053. (cond (prefix-entry
  1054. ;; Splice in at head
  1055. (setcdr entry (cmpl-prefix-entry-head prefix-entry))
  1056. (set-cmpl-prefix-entry-head prefix-entry entry))
  1057. (t
  1058. ;; Start new prefix entry
  1059. (set cmpl-db-prefix-symbol (make-cmpl-prefix-entry entry))))
  1060. ;; Add it to the symbol
  1061. (set cmpl-db-symbol (car entry))))))
  1062. (defun delete-completion (completion-string)
  1063. "Delete the completion from the database.
  1064. String must be longer than `completion-prefix-min-length'."
  1065. ;; Handle pending acceptance
  1066. (let ((cmpl--completion-string completion-string))
  1067. (if completion-to-accept (accept-completion))
  1068. (if (setq cmpl-db-entry (find-exact-completion completion-string))
  1069. ;; found
  1070. (let* ((prefix-entry (find-cmpl-prefix-entry
  1071. (substring cmpl-db-downcase-string 0
  1072. completion-prefix-min-length)))
  1073. (splice-ptr (locate-completion-entry cmpl-db-entry prefix-entry)))
  1074. ;; delete symbol reference
  1075. (set cmpl-db-symbol nil)
  1076. ;; remove from prefix list
  1077. (cond (splice-ptr
  1078. ;; not at head
  1079. (or (setcdr splice-ptr (cdr (cdr splice-ptr)))
  1080. ;; fix up tail if necessary
  1081. (set-cmpl-prefix-entry-tail prefix-entry splice-ptr)))
  1082. (t
  1083. ;; at head
  1084. (or (set-cmpl-prefix-entry-head
  1085. prefix-entry (cdr (cmpl-prefix-entry-head prefix-entry)))
  1086. ;; List is now empty
  1087. (set cmpl-db-prefix-symbol nil)))))
  1088. (error "Unknown completion `%s'" completion-string))))
  1089. ;; Tests --
  1090. ;; - Add and Find -
  1091. ;; (add-completion-to-head "banana") --> ("banana" 0 nil 0)
  1092. ;; (find-exact-completion "banana") --> ("banana" 0 nil 0)
  1093. ;; (find-exact-completion "bana") --> nil
  1094. ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
  1095. ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
  1096. ;; (add-completion-to-head "banish") --> ("banish" 0 nil 0)
  1097. ;; (find-exact-completion "banish") --> ("banish" 0 nil 0)
  1098. ;; (car (find-cmpl-prefix-entry "ban")) --> (("banish" ...) ("banana" ...))
  1099. ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
  1100. ;; (add-completion-to-head "banana") --> ("banana" 0 nil 0)
  1101. ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
  1102. ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
  1103. ;;
  1104. ;; - Deleting -
  1105. ;; (add-completion-to-head "banner") --> ("banner" 0 nil 0)
  1106. ;; (delete-completion "banner")
  1107. ;; (find-exact-completion "banner") --> nil
  1108. ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
  1109. ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
  1110. ;; (add-completion-to-head "banner") --> ("banner" 0 nil 0)
  1111. ;; (delete-completion "banana")
  1112. ;; (car (find-cmpl-prefix-entry "ban")) --> (("banner" ...) ("banish" ...))
  1113. ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banish" ...))
  1114. ;; (delete-completion "banner")
  1115. ;; (delete-completion "banish")
  1116. ;; (find-cmpl-prefix-entry "ban") --> nil
  1117. ;; (delete-completion "banner") --> error
  1118. ;;
  1119. ;; - Tail -
  1120. ;; (add-completion-to-tail-if-new "banana") --> ("banana" 0 nil 0)
  1121. ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
  1122. ;; (cdr (find-cmpl-prefix-entry "ban")) --> (("banana" ...))
  1123. ;; (add-completion-to-tail-if-new "banish") --> ("banish" 0 nil 0)
  1124. ;; (car (find-cmpl-prefix-entry "ban")) -->(("banana" ...) ("banish" ...))
  1125. ;; (cdr (find-cmpl-prefix-entry "ban")) -->(("banish" ...))
  1126. ;;
  1127. ;;---------------------------------------------------------------------------
  1128. ;; Database Update :: Interface level routines
  1129. ;;---------------------------------------------------------------------------
  1130. ;;
  1131. ;; These lie on top of the database ref. functions but below the standard
  1132. ;; user interface level
  1133. (defun interactive-completion-string-reader (prompt)
  1134. (let* ((default (symbol-under-or-before-point))
  1135. (new-prompt
  1136. (if default
  1137. (format "%s (default %s): " prompt default)
  1138. (format "%s: " prompt)))
  1139. (read (completing-read new-prompt cmpl-obarray)))
  1140. (if (zerop (length read)) (setq read (or default "")))
  1141. (list read)))
  1142. (defun check-completion-length (string)
  1143. (if (< (length string) completion-min-length)
  1144. (user-error "The string `%s' is too short to be saved as a completion"
  1145. string)
  1146. (list string)))
  1147. (defun add-completion (string &optional num-uses last-use-time)
  1148. "Add STRING to completion list, or move it to head of list.
  1149. The completion is altered appropriately if NUM-USES and/or LAST-USE-TIME
  1150. are specified."
  1151. (interactive (interactive-completion-string-reader "Completion to add"))
  1152. (check-completion-length string)
  1153. (let* ((current-completion-source (if (called-interactively-p 'interactive)
  1154. cmpl-source-interactive
  1155. current-completion-source))
  1156. (entry (add-completion-to-head string)))
  1157. (if num-uses (set-completion-num-uses entry num-uses))
  1158. (if last-use-time
  1159. (set-completion-last-use-time entry last-use-time))))
  1160. (defun add-permanent-completion (string)
  1161. "Add STRING if it isn't already listed, and mark it permanent."
  1162. (interactive
  1163. (interactive-completion-string-reader "Completion to add permanently"))
  1164. (let ((current-completion-source (if (called-interactively-p 'interactive)
  1165. cmpl-source-interactive
  1166. current-completion-source)))
  1167. (add-completion string nil t)))
  1168. (defun kill-completion (string)
  1169. (interactive (interactive-completion-string-reader "Completion to kill"))
  1170. (check-completion-length string)
  1171. (delete-completion string))
  1172. (defun accept-completion ()
  1173. "Accept the pending completion in `completion-to-accept'.
  1174. This bumps num-uses. Called by `add-completion-to-head' and
  1175. `completion-search-reset'."
  1176. (let ((string completion-to-accept)
  1177. ;; if this is added afresh here, then it must be a cdabbrev
  1178. (current-completion-source cmpl-source-cdabbrev)
  1179. entry)
  1180. (setq completion-to-accept nil)
  1181. (setq entry (add-completion-to-head string))
  1182. (set-completion-num-uses entry (1+ (completion-num-uses entry)))
  1183. (setq cmpl-completions-accepted-p t)))
  1184. (defun use-completion-under-point ()
  1185. "Add the completion symbol underneath the point into the completion buffer."
  1186. (let ((string (and enable-completion (symbol-under-point)))
  1187. (current-completion-source cmpl-source-cursor-moves))
  1188. (if string (add-completion-to-head string))))
  1189. (defun use-completion-before-point ()
  1190. "Add the completion symbol before point into the completion buffer."
  1191. (let ((string (and enable-completion (symbol-before-point)))
  1192. (current-completion-source cmpl-source-cursor-moves))
  1193. (if string (add-completion-to-head string))))
  1194. (defun use-completion-under-or-before-point ()
  1195. "Add the completion symbol before point into the completion buffer."
  1196. (let ((string (and enable-completion (symbol-under-or-before-point)))
  1197. (current-completion-source cmpl-source-cursor-moves))
  1198. (if string (add-completion-to-head string))))
  1199. (defun use-completion-before-separator ()
  1200. "Add the completion symbol before point into the completion buffer.
  1201. Completions added this way will automatically be saved if
  1202. `completion-on-separator-character' is non-nil."
  1203. (let ((string (and enable-completion (symbol-before-point)))
  1204. (current-completion-source cmpl-source-separator)
  1205. entry)
  1206. (cond (string
  1207. (setq entry (add-completion-to-head string))
  1208. (if (and completion-on-separator-character
  1209. (zerop (completion-num-uses entry)))
  1210. (progn
  1211. (set-completion-num-uses entry 1)
  1212. (setq cmpl-completions-accepted-p t)))))))
  1213. ;; Tests --
  1214. ;; - Add and Find -
  1215. ;; (add-completion "banana" 5 10)
  1216. ;; (find-exact-completion "banana") --> ("banana" 5 10 0)
  1217. ;; (add-completion "banana" 6)
  1218. ;; (find-exact-completion "banana") --> ("banana" 6 10 0)
  1219. ;; (add-completion "banish")
  1220. ;; (car (find-cmpl-prefix-entry "ban")) --> (("banish" ...) ("banana" ...))
  1221. ;;
  1222. ;; - Accepting -
  1223. ;; (setq completion-to-accept "banana")
  1224. ;; (accept-completion)
  1225. ;; (find-exact-completion "banana") --> ("banana" 7 10)
  1226. ;; (car (find-cmpl-prefix-entry "ban")) --> (("banana" ...) ("banish" ...))
  1227. ;; (setq completion-to-accept "banish")
  1228. ;; (add-completion "banner")
  1229. ;; (car (find-cmpl-prefix-entry "ban"))
  1230. ;; --> (("banner" ...) ("banish" 1 ...) ("banana" 7 ...))
  1231. ;;
  1232. ;; - Deleting -
  1233. ;; (kill-completion "banish")
  1234. ;; (car (find-cmpl-prefix-entry "ban")) --> (("banner" ...) ("banana" ...))
  1235. ;;---------------------------------------------------------------------------
  1236. ;; Searching the database
  1237. ;;---------------------------------------------------------------------------
  1238. ;; Functions outside this block must call completion-search-reset followed
  1239. ;; by calls to completion-search-next or completion-search-peek
  1240. ;;
  1241. ;; Status variables
  1242. ;; Commented out to improve loading speed
  1243. (defvar cmpl-test-string "")
  1244. ;; "The current string used by completion-search-next."
  1245. (defvar cmpl-test-regexp "")
  1246. ;; "The current regexp used by completion-search-next.
  1247. ;; (derived from cmpl-test-string)"
  1248. (defvar cmpl-last-index 0)
  1249. ;; "The last index that completion-search-next was called with."
  1250. (defvar cmpl-cdabbrev-reset-p nil)
  1251. ;; "Set to t when cdabbrevs have been reset."
  1252. (defvar cmpl-next-possibilities nil)
  1253. ;; "A pointer to the element BEFORE the next set of possible completions.
  1254. ;; cadr of this is the cmpl-next-possibility"
  1255. (defvar cmpl-starting-possibilities nil)
  1256. ;; "The initial list of starting possibilities."
  1257. (defvar cmpl-next-possibility nil)
  1258. ;; "The cached next possibility."
  1259. (defvar cmpl-tried-list nil)
  1260. ;; "A downcased list of all the completions we have tried."
  1261. (defun completion-search-reset (string)
  1262. "Set up the for completion searching for STRING.
  1263. STRING must be longer than `completion-prefix-min-length'."
  1264. (if completion-to-accept (accept-completion))
  1265. (setq cmpl-starting-possibilities
  1266. (cmpl-prefix-entry-head
  1267. (find-cmpl-prefix-entry
  1268. (downcase (substring string 0 completion-prefix-min-length))))
  1269. cmpl-test-string string
  1270. cmpl-test-regexp (concat (regexp-quote string) "."))
  1271. (completion-search-reset-1))
  1272. (defun completion-search-reset-1 ()
  1273. (setq cmpl-next-possibilities cmpl-starting-possibilities
  1274. cmpl-next-possibility nil
  1275. cmpl-cdabbrev-reset-p nil
  1276. cmpl-last-index -1
  1277. cmpl-tried-list nil))
  1278. (defun completion-search-next (index)
  1279. "Return the next completion entry.
  1280. If INDEX is out of sequence, reset and start from the top.
  1281. If there are no more entries, try cdabbrev and return only a string."
  1282. (cond
  1283. ((= index (setq cmpl-last-index (1+ cmpl-last-index)))
  1284. (completion-search-peek t))
  1285. ((< index 0)
  1286. (completion-search-reset-1)
  1287. (setq cmpl-last-index index)
  1288. ;; reverse the possibilities list
  1289. (setq cmpl-next-possibilities (reverse cmpl-starting-possibilities))
  1290. ;; do a "normal" search
  1291. (while (and (completion-search-peek nil)
  1292. (< (setq index (1+ index)) 0))
  1293. (setq cmpl-next-possibility nil))
  1294. (cond ((not cmpl-next-possibilities))
  1295. ;; If no more possibilities, leave it that way
  1296. ((= -1 cmpl-last-index)
  1297. ;; next completion is at index 0. reset next-possibility list
  1298. ;; to start at beginning
  1299. (setq cmpl-next-possibilities cmpl-starting-possibilities))
  1300. (t
  1301. ;; otherwise point to one before current
  1302. (setq cmpl-next-possibilities
  1303. (nthcdr (- (length cmpl-starting-possibilities)
  1304. (length cmpl-next-possibilities))
  1305. cmpl-starting-possibilities)))))
  1306. (t
  1307. ;; non-negative index, reset and search
  1308. ;;(prin1 'reset)
  1309. (completion-search-reset-1)
  1310. (setq cmpl-last-index index)
  1311. (while (and (completion-search-peek t)
  1312. (not (< (setq index (1- index)) 0)))
  1313. (setq cmpl-next-possibility nil))))
  1314. (prog1
  1315. cmpl-next-possibility
  1316. (setq cmpl-next-possibility nil)))
  1317. (defun completion-search-peek (use-cdabbrev)
  1318. "Return the next completion entry without actually moving the pointers.
  1319. Calling this again or calling `completion-search-next' results in the same
  1320. string being returned. Depends on `case-fold-search'.
  1321. If there are no more entries, try cdabbrev and then return only a string."
  1322. (cond
  1323. ;; return the cached value if we have it
  1324. (cmpl-next-possibility)
  1325. ((and cmpl-next-possibilities
  1326. ;; still a few possibilities left
  1327. (progn
  1328. (while
  1329. (and (not (eq 0 (string-match cmpl-test-regexp
  1330. (completion-string (car cmpl-next-possibilities)))))
  1331. (setq cmpl-next-possibilities (cdr cmpl-next-possibilities))))
  1332. cmpl-next-possibilities))
  1333. ;; successful match
  1334. (setq cmpl-next-possibility (car cmpl-next-possibilities)
  1335. cmpl-tried-list (cons (downcase (completion-string cmpl-next-possibility))
  1336. cmpl-tried-list)
  1337. cmpl-next-possibilities (cdr cmpl-next-possibilities))
  1338. cmpl-next-possibility)
  1339. (use-cdabbrev
  1340. ;; unsuccessful, use cdabbrev
  1341. (cond ((not cmpl-cdabbrev-reset-p)
  1342. (reset-cdabbrev cmpl-test-string cmpl-tried-list)
  1343. (setq cmpl-cdabbrev-reset-p t)))
  1344. (setq cmpl-next-possibility (next-cdabbrev)))
  1345. ;; Completely unsuccessful, return nil
  1346. ))
  1347. ;; Tests --
  1348. ;; - Add and Find -
  1349. ;; (add-completion "banana")
  1350. ;; (completion-search-reset "ban")
  1351. ;; (completion-search-next 0) --> "banana"
  1352. ;;
  1353. ;; - Discrimination -
  1354. ;; (add-completion "cumberland")
  1355. ;; (add-completion "cumberbund")
  1356. ;; cumbering
  1357. ;; (completion-search-reset "cumb")
  1358. ;; (completion-search-peek t) --> "cumberbund"
  1359. ;; (completion-search-next 0) --> "cumberbund"
  1360. ;; (completion-search-peek t) --> "cumberland"
  1361. ;; (completion-search-next 1) --> "cumberland"
  1362. ;; (completion-search-peek nil) --> nil
  1363. ;; (completion-search-next 2) --> "cumbering" {cdabbrev}
  1364. ;; (completion-search-next 3) --> nil or "cumming"{depends on context}
  1365. ;; (completion-search-next 1) --> "cumberland"
  1366. ;; (completion-search-peek t) --> "cumbering" {cdabbrev}
  1367. ;;
  1368. ;; - Accepting -
  1369. ;; (completion-search-next 1) --> "cumberland"
  1370. ;; (setq completion-to-accept "cumberland")
  1371. ;; (completion-search-reset "foo")
  1372. ;; (completion-search-reset "cum")
  1373. ;; (completion-search-next 0) --> "cumberland"
  1374. ;;
  1375. ;; - Deleting -
  1376. ;; (kill-completion "cumberland")
  1377. ;; cummings
  1378. ;; (completion-search-reset "cum")
  1379. ;; (completion-search-next 0) --> "cumberbund"
  1380. ;; (completion-search-next 1) --> "cummings"
  1381. ;;
  1382. ;; - Ignoring Capitalization -
  1383. ;; (completion-search-reset "CuMb")
  1384. ;; (completion-search-next 0) --> "cumberbund"
  1385. ;;-----------------------------------------------
  1386. ;; COMPLETE
  1387. ;;-----------------------------------------------
  1388. (defun completion-mode ()
  1389. "Toggle whether or not to add new words to the completion database."
  1390. (interactive)
  1391. (setq enable-completion (not enable-completion))
  1392. (message "Completion mode is now %s." (if enable-completion "ON" "OFF")))
  1393. (defvar cmpl-current-index 0)
  1394. (defvar cmpl-original-string nil)
  1395. (defvar cmpl-last-insert-location -1)
  1396. (defvar cmpl-leave-point-at-start nil)
  1397. (defun complete (&optional arg)
  1398. "Fill out a completion of the word before point.
  1399. Point is left at end. Consecutive calls rotate through all possibilities.
  1400. Prefix args ::
  1401. control-u :: leave the point at the beginning of the completion rather
  1402. than at the end.
  1403. a number :: rotate through the possible completions by that amount
  1404. `-' :: same as -1 (insert previous completion)
  1405. {See the comments at the top of `completion.el' for more info.}"
  1406. (interactive "*p")
  1407. ;;; Set up variables
  1408. (cond ((eq last-command this-command)
  1409. ;; Undo last one
  1410. (delete-region cmpl-last-insert-location (point))
  1411. ;; get next completion
  1412. (setq cmpl-current-index (+ cmpl-current-index (or arg 1))))
  1413. (t
  1414. (if (not cmpl-initialized-p)
  1415. (completion-initialize)) ;; make sure everything's loaded
  1416. (cond ((consp current-prefix-arg) ;; control-u
  1417. (setq arg 0)
  1418. (setq cmpl-leave-point-at-start t))
  1419. (t
  1420. (setq cmpl-leave-point-at-start nil)))
  1421. ;; get string
  1422. (setq cmpl-original-string (symbol-before-point-for-complete))
  1423. (cond ((not cmpl-original-string)
  1424. (setq this-command 'failed-complete)
  1425. (error "To complete, point must be after a symbol at least %d character long"
  1426. completion-prefix-min-length)))
  1427. ;; get index
  1428. (setq cmpl-current-index (if current-prefix-arg arg 0))
  1429. ;; reset database
  1430. (completion-search-reset cmpl-original-string)
  1431. ;; erase what we've got
  1432. (delete-region cmpl-symbol-start cmpl-symbol-end)))
  1433. ;; point is at the point to insert the new symbol
  1434. ;; Get the next completion
  1435. (let* ((print-status-p
  1436. (and (>= baud-rate completion-prompt-speed-threshold)
  1437. (not (window-minibuffer-p))))
  1438. (insert-point (point))
  1439. (entry (completion-search-next cmpl-current-index))
  1440. string)
  1441. ;; entry is either a completion entry or a string (if cdabbrev)
  1442. ;; If found, insert
  1443. (cond (entry
  1444. ;; Setup for proper case
  1445. (setq string (if (stringp entry)
  1446. entry (completion-string entry)))
  1447. (setq string (cmpl-merge-string-cases
  1448. string cmpl-original-string))
  1449. ;; insert
  1450. (insert string)
  1451. ;; accept it
  1452. (setq completion-to-accept string)
  1453. ;; fixup and cache point
  1454. (cond (cmpl-leave-point-at-start
  1455. (setq cmpl-last-insert-location (point))
  1456. (goto-char insert-point))
  1457. (t;; point at end,
  1458. (setq cmpl-last-insert-location insert-point)))
  1459. ;; Done ! cmpl-stat-complete-successful
  1460. ;;display the next completion
  1461. (cond
  1462. ((and print-status-p
  1463. ;; This updates the display and only prints if there
  1464. ;; is no typeahead
  1465. (sit-for 0)
  1466. (setq entry
  1467. (completion-search-peek
  1468. completion-cdabbrev-prompt-flag)))
  1469. (setq string (if (stringp entry)
  1470. entry (completion-string entry)))
  1471. (setq string (cmpl-merge-string-cases
  1472. string cmpl-original-string))
  1473. (message "Next completion: %s" string))))
  1474. (t;; none found, insert old
  1475. (insert cmpl-original-string)
  1476. ;; Don't accept completions
  1477. (setq completion-to-accept nil)
  1478. ;; print message
  1479. ;; This used to call cmpl19-sit-for, an undefined function.
  1480. ;; I hope that sit-for does the right thing; I don't know -- rms.
  1481. (if (and print-status-p (sit-for 0))
  1482. (message "No %scompletions."
  1483. (if (eq this-command last-command) "more " "")))
  1484. ;; Pretend that we were never here
  1485. (setq this-command 'failed-complete)))))
  1486. ;;---------------------------------------------------------------------------
  1487. ;; Parsing definitions from files into the database
  1488. ;;---------------------------------------------------------------------------
  1489. ;;-----------------------------------------------
  1490. ;; Top Level functions ::
  1491. ;;-----------------------------------------------
  1492. ;; User interface
  1493. (defun add-completions-from-file (file)
  1494. "Parse possible completions from a FILE and add them to database."
  1495. (interactive "fFile: ")
  1496. (setq file (expand-file-name file))
  1497. (let* ((buffer (get-file-buffer file))
  1498. (buffer-already-there-p buffer))
  1499. (if (not buffer-already-there-p)
  1500. (let ((completions-merging-modes nil))
  1501. (setq buffer (find-file-noselect file))))
  1502. (unwind-protect
  1503. (with-current-buffer buffer
  1504. (add-completions-from-buffer))
  1505. (if (not buffer-already-there-p)
  1506. (kill-buffer buffer)))))
  1507. (defun add-completions-from-buffer ()
  1508. (interactive)
  1509. (let ((current-completion-source cmpl-source-file-parsing))
  1510. (cond ((memq major-mode '(emacs-lisp-mode lisp-mode))
  1511. (add-completions-from-lisp-buffer))
  1512. ((memq major-mode '(c-mode))
  1513. (add-completions-from-c-buffer))
  1514. (t
  1515. (error "Cannot parse completions in %s buffers"
  1516. major-mode)))))
  1517. ;; Find file hook
  1518. (defun completion-find-file-hook ()
  1519. (cond (enable-completion
  1520. (cond ((and (memq major-mode '(emacs-lisp-mode lisp-mode))
  1521. (memq 'lisp completions-merging-modes))
  1522. (add-completions-from-buffer))
  1523. ((and (memq major-mode '(c-mode))
  1524. (memq 'c completions-merging-modes))
  1525. (add-completions-from-buffer))))))
  1526. ;;-----------------------------------------------
  1527. ;; Tags Table Completions
  1528. ;;-----------------------------------------------
  1529. (defun add-completions-from-tags-table ()
  1530. ;; Inspired by eero@media-lab.media.mit.edu
  1531. "Add completions from the current tags table."
  1532. (interactive)
  1533. (visit-tags-table-buffer) ;this will prompt if no tags-table
  1534. (save-excursion
  1535. (goto-char (point-min))
  1536. (let (string)
  1537. (condition-case nil
  1538. (while t
  1539. (search-forward "\177")
  1540. (backward-char 3)
  1541. (and (setq string (symbol-under-point))
  1542. (add-completion-to-tail-if-new string))
  1543. (forward-char 3))
  1544. (search-failed)))))
  1545. ;;-----------------------------------------------
  1546. ;; Lisp File completion parsing
  1547. ;;-----------------------------------------------
  1548. ;; This merely looks for phrases beginning with (def.... or
  1549. ;; (package:def ... and takes the next word.
  1550. ;;
  1551. ;; We tried using forward-lines and explicit searches but the regexp technique
  1552. ;; was faster. (About 100K characters per second)
  1553. ;;
  1554. (defconst *lisp-def-regexp*
  1555. "\n(\\(\\w*:\\)?def\\(\\w\\|\\s_\\)*\\s +(*"
  1556. "A regexp that searches for Lisp definition form.")
  1557. ;; Tests -
  1558. ;; (and (string-match *lisp-def-regexp* "\n(defun foo") (match-end 0)) -> 8
  1559. ;; (and (string-match *lisp-def-regexp* "\n(si:def foo") (match-end 0)) -> 9
  1560. ;; (and (string-match *lisp-def-regexp* "\n(def-bar foo")(match-end 0)) -> 10
  1561. ;; (and (string-match *lisp-def-regexp* "\n(defun (foo") (match-end 0)) -> 9
  1562. ;; Parses all the definition names from a Lisp mode buffer and adds them to
  1563. ;; the completion database.
  1564. (defun add-completions-from-lisp-buffer ()
  1565. ;;; Benchmarks
  1566. ;;; Sun-3/280 - 1500 to 3000 lines of lisp code per second
  1567. (let (string)
  1568. (save-excursion
  1569. (goto-char (point-min))
  1570. (condition-case nil
  1571. (while t
  1572. (re-search-forward *lisp-def-regexp*)
  1573. (and (setq string (symbol-under-point))
  1574. (add-completion-to-tail-if-new string)))
  1575. (search-failed)))))
  1576. ;;-----------------------------------------------
  1577. ;; C file completion parsing
  1578. ;;-----------------------------------------------
  1579. ;; C :
  1580. ;; Looks for #define or [<storage class>] [<type>] <name>{,<name>}
  1581. ;; or structure, array or pointer defs.
  1582. ;; It gets most of the definition names.
  1583. ;;
  1584. ;; As you might suspect by now, we use some symbol table hackery
  1585. ;;
  1586. ;; Symbol separator chars (have whitespace syntax) --> , ; * = (
  1587. ;; Opening char --> [ {
  1588. ;; Closing char --> ] }
  1589. ;; opening and closing must be skipped over
  1590. ;; Whitespace chars (have symbol syntax)
  1591. ;; Everything else has word syntax
  1592. (defconst completion-c-def-syntax-table
  1593. (let ((table (make-syntax-table))
  1594. (whitespace-chars '(? ?\n ?\t ?\f ?\v ?\r))
  1595. ;; unfortunately the ?( causes the parens to appear unbalanced
  1596. (separator-chars '(?, ?* ?= ?\( ?\;))
  1597. i)
  1598. ;; default syntax is whitespace
  1599. (setq i 0)
  1600. (while (< i 256)
  1601. (modify-syntax-entry i "w" table)
  1602. (setq i (1+ i)))
  1603. (dolist (char whitespace-chars)
  1604. (modify-syntax-entry char "_" table))
  1605. (dolist (char separator-chars)
  1606. (modify-syntax-entry char " " table))
  1607. (modify-syntax-entry ?\[ "(]" table)
  1608. (modify-syntax-entry ?\{ "(}" table)
  1609. (modify-syntax-entry ?\] ")[" table)
  1610. (modify-syntax-entry ?\} "){" table)
  1611. table))
  1612. ;; Regexps
  1613. (defconst *c-def-regexp*
  1614. ;; This stops on lines with possible definitions
  1615. "\n[_a-zA-Z#]"
  1616. ;; This stops after the symbol to add.
  1617. ;;"\n\\(#define\\s +.\\|\\(\\(\\w\\|\\s_\\)+\\b\\s *\\)+[(;,[*{=]\\)"
  1618. ;; This stops before the symbol to add. {Test cases in parens. below}
  1619. ;;"\n\\(\\(\\w\\|\\s_\\)+\\s *(\\|\\(\\(#define\\|auto\\|extern\\|register\\|static\\|int\\|long\\|short\\|unsigned\\|char\\|void\\|float\\|double\\|enum\\|struct\\|union\\|typedef\\)\\s +\\)+\\)"
  1620. ;; this simple version picks up too much extraneous stuff
  1621. ;; "\n\\(\\w\\|\\s_\\|#\\)\\B"
  1622. "A regexp that searches for a definition form.")
  1623. ;
  1624. ;(defconst *c-cont-regexp*
  1625. ; "\\(\\w\\|\\s_\\)+\\b\\s *\\({\\|\\(\\[[0-9\t ]*\\]\\s *\\)*,\\(*\\|\\s \\)*\\b\\)"
  1626. ; "This regexp should be used in a looking-at to parse for lists of variables.")
  1627. ;
  1628. ;(defconst *c-struct-regexp*
  1629. ; "\\(*\\|\\s \\)*\\b"
  1630. ; "This regexp should be used to test whether a symbol follows a structure definition.")
  1631. ;(defun test-c-def-regexp (regexp string)
  1632. ; (and (eq 0 (string-match regexp string)) (match-end 0))
  1633. ; )
  1634. ;; Tests -
  1635. ;; (test-c-def-regexp *c-def-regexp* "\n#define foo") -> 10 (9)
  1636. ;; (test-c-def-regexp *c-def-regexp* "\nfoo (x, y) {") -> 6 (6)
  1637. ;; (test-c-def-regexp *c-def-regexp* "\nint foo (x, y)") -> 10 (5)
  1638. ;; (test-c-def-regexp *c-def-regexp* "\n int foo (x, y)") -> nil
  1639. ;; (test-c-def-regexp *c-cont-regexp* "oo, bar") -> 4
  1640. ;; (test-c-def-regexp *c-cont-regexp* "oo, *bar") -> 5
  1641. ;; (test-c-def-regexp *c-cont-regexp* "a [5][6], bar") -> 10
  1642. ;; (test-c-def-regexp *c-cont-regexp* "oo(x,y)") -> nil
  1643. ;; (test-c-def-regexp *c-cont-regexp* "a [6] ,\t bar") -> 9
  1644. ;; (test-c-def-regexp *c-cont-regexp* "oo {trout =1} my_carp;") -> 14
  1645. ;; (test-c-def-regexp *c-cont-regexp* "truct_p complex foon") -> nil
  1646. ;; Parses all the definition names from a C mode buffer and adds them to the
  1647. ;; completion database.
  1648. (defun add-completions-from-c-buffer ()
  1649. ;; Benchmark --
  1650. ;; Sun 3/280-- 1250 lines/sec.
  1651. (let (string next-point char)
  1652. (save-excursion
  1653. (goto-char (point-min))
  1654. (catch 'finish-add-completions
  1655. (with-syntax-table completion-c-def-syntax-table
  1656. (while t
  1657. ;; we loop here only when scan-sexps fails
  1658. ;; (i.e. unbalance exps.)
  1659. (condition-case e
  1660. (while t
  1661. (re-search-forward *c-def-regexp*)
  1662. (cond
  1663. ((= (preceding-char) ?#)
  1664. ;; preprocessor macro, see if it's one we handle
  1665. (cond ((looking-at "\\(define\\|ifdef\\)\\>")
  1666. ;; skip forward over definition symbol
  1667. ;; and add it to database
  1668. (and (forward-word 2)
  1669. (setq string (symbol-before-point))
  1670. ;;(push string foo)
  1671. (add-completion-to-tail-if-new string)))))
  1672. (t
  1673. ;; C definition
  1674. (setq next-point (point))
  1675. (while (and
  1676. next-point
  1677. ;; scan to next separator char.
  1678. (setq next-point (scan-sexps next-point 1)))
  1679. ;; position the point on the word we want to add
  1680. (goto-char next-point)
  1681. (while (= (setq char (following-char)) ?*)
  1682. ;; handle pointer ref
  1683. ;; move to next separator char.
  1684. (goto-char
  1685. (setq next-point (scan-sexps (point) 1))))
  1686. (forward-word -1)
  1687. ;; add to database
  1688. (if (setq string (symbol-under-point))
  1689. ;; (push string foo)
  1690. (add-completion-to-tail-if-new string)
  1691. ;; Local TMC hack (useful for parsing paris.h)
  1692. (if (and (looking-at "_AP") ;; "ansi prototype"
  1693. (progn
  1694. (forward-word -1)
  1695. (setq string
  1696. (symbol-under-point))))
  1697. (add-completion-to-tail-if-new string)))
  1698. ;; go to next
  1699. (goto-char next-point)
  1700. ;; (push (format "%c" (following-char)) foo)
  1701. (if (= (char-syntax char) ?\()
  1702. ;; if on an opening delimiter, go to end
  1703. (while (= (char-syntax char) ?\()
  1704. (setq next-point (scan-sexps next-point 1)
  1705. char (char-after next-point)))
  1706. (or (= char ?,)
  1707. ;; Current char is an end char.
  1708. (setq next-point nil)))))))
  1709. (search-failed ;;done
  1710. (throw 'finish-add-completions t))
  1711. (error
  1712. ;; Check for failure in scan-sexps
  1713. (if (member (nth 1 e)
  1714. '("Containing expression ends prematurely"
  1715. "Unbalanced parentheses"))
  1716. ;; unbalanced paren., keep going
  1717. ;;(ding)
  1718. (forward-line 1)
  1719. (message "Error parsing C buffer for completions--please send bug report")
  1720. (throw 'finish-add-completions t))))))))))
  1721. ;;---------------------------------------------------------------------------
  1722. ;; Init files
  1723. ;;---------------------------------------------------------------------------
  1724. ;; The version of save-completions-to-file called at kill-emacs time.
  1725. (defun kill-emacs-save-completions ()
  1726. (if (and save-completions-flag enable-completion cmpl-initialized-p)
  1727. (cond
  1728. ((not cmpl-completions-accepted-p)
  1729. (message "Completions database has not changed - not writing."))
  1730. (t
  1731. (save-completions-to-file)))))
  1732. ;; There is no point bothering to change this again
  1733. ;; unless the package changes so much that it matters
  1734. ;; for people that have saved completions.
  1735. (defconst completion-version "11")
  1736. (defconst saved-cmpl-file-header
  1737. ";;; Completion Initialization file.
  1738. ;; Version = %s
  1739. ;; Format is (<string> . <last-use-time>)
  1740. ;; <string> is the completion
  1741. ;; <last-use-time> is the time the completion was last used
  1742. ;; If it is t, the completion will never be pruned from the file.
  1743. ;; Otherwise it is in hours since origin.
  1744. \n")
  1745. (defun completion-backup-filename (filename)
  1746. (concat filename ".BAK"))
  1747. (defun save-completions-to-file (&optional filename)
  1748. "Save completions in init file FILENAME.
  1749. If file name is not specified, use `save-completions-file-name'."
  1750. (interactive)
  1751. (setq filename (expand-file-name (or filename save-completions-file-name)))
  1752. (if (file-writable-p filename)
  1753. (progn
  1754. (if (not cmpl-initialized-p)
  1755. (completion-initialize)) ;; make sure everything's loaded
  1756. (message "Saving completions to file %s" filename)
  1757. (let* ((delete-old-versions t)
  1758. (kept-old-versions 0)
  1759. (kept-new-versions completions-file-versions-kept)
  1760. last-use-time
  1761. (this-use-time (cmpl-hours-since-origin))
  1762. (total-in-db 0)
  1763. (total-perm 0)
  1764. (total-saved 0)
  1765. (backup-filename (completion-backup-filename filename)))
  1766. (with-current-buffer (get-buffer-create " *completion-save-buffer*")
  1767. (setq buffer-file-name filename)
  1768. (if (not (verify-visited-file-modtime (current-buffer)))
  1769. (progn
  1770. ;; file has changed on disk. Bring us up-to-date
  1771. (message "Completion file has changed. Merging. . .")
  1772. (load-completions-from-file filename t)
  1773. (message "Merging finished. Saving completions to file %s" filename)))
  1774. ;; prepare the buffer to be modified
  1775. (clear-visited-file-modtime)
  1776. (erase-buffer)
  1777. ;; (/ 1 0)
  1778. (insert (format saved-cmpl-file-header completion-version))
  1779. (dolist (completion (list-all-completions))
  1780. (setq total-in-db (1+ total-in-db))
  1781. (setq last-use-time (completion-last-use-time completion))
  1782. ;; Update num uses and maybe write completion to a file
  1783. (cond ((or;; Write to file if
  1784. ;; permanent
  1785. (and (eq last-use-time t)
  1786. (setq total-perm (1+ total-perm)))
  1787. ;; or if
  1788. (if (> (completion-num-uses completion) 0)
  1789. ;; it's been used
  1790. (setq last-use-time this-use-time)
  1791. ;; or it was saved before and
  1792. (and last-use-time
  1793. ;; save-completions-retention-time is nil
  1794. (or (not save-completions-retention-time)
  1795. ;; or time since last use is < ...retention-time*
  1796. (< (- this-use-time last-use-time)
  1797. save-completions-retention-time)))))
  1798. ;; write to file
  1799. (setq total-saved (1+ total-saved))
  1800. (insert (prin1-to-string (cons (completion-string completion)
  1801. last-use-time)) "\n"))))
  1802. ;; write the buffer
  1803. (condition-case nil
  1804. (let ((file-exists-p (file-exists-p filename)))
  1805. (if file-exists-p
  1806. (progn
  1807. ;; If file exists . . .
  1808. ;; Save a backup(so GNU doesn't screw us when we're out of disk)
  1809. ;; (GNU leaves a 0 length file if it gets a disk full error!)
  1810. ;; If backup doesn't exit, Rename current to backup
  1811. ;; {If backup exists the primary file is probably messed up}
  1812. (or (file-exists-p backup-filename)
  1813. (rename-file filename backup-filename))
  1814. ;; Copy the backup back to the current name
  1815. ;; (so versioning works)
  1816. (copy-file backup-filename filename t)))
  1817. ;; Save it
  1818. (save-buffer)
  1819. (if file-exists-p
  1820. ;; If successful, remove backup
  1821. (delete-file backup-filename)))
  1822. (error
  1823. (set-buffer-modified-p nil)
  1824. (message "Couldn't save completion file `%s'" filename)))
  1825. ;; Reset accepted-p flag
  1826. (setq cmpl-completions-accepted-p nil) )))))
  1827. ;;(defun auto-save-completions ()
  1828. ;; (if (and save-completions-flag enable-completion cmpl-initialized-p
  1829. ;; *completion-auto-save-period*
  1830. ;; (> cmpl-emacs-idle-time *completion-auto-save-period*)
  1831. ;; cmpl-completions-accepted-p)
  1832. ;; (save-completions-to-file)))
  1833. ;;(add-hook 'cmpl-emacs-idle-time-hooks 'auto-save-completions)
  1834. (defun load-completions-from-file (&optional filename no-message-p)
  1835. "Load a completion init file FILENAME.
  1836. If file is not specified, then use `save-completions-file-name'."
  1837. (interactive)
  1838. (setq filename (expand-file-name (or filename save-completions-file-name)))
  1839. (let* ((backup-filename (completion-backup-filename filename))
  1840. (backup-readable-p (file-readable-p backup-filename)))
  1841. (if backup-readable-p (setq filename backup-filename))
  1842. (if (file-readable-p filename)
  1843. (progn
  1844. (if (not no-message-p)
  1845. (message "Loading completions from %sfile %s . . ."
  1846. (if backup-readable-p "backup " "") filename))
  1847. (with-current-buffer (get-buffer-create " *completion-save-buffer*")
  1848. (setq buffer-file-name filename)
  1849. ;; prepare the buffer to be modified
  1850. (clear-visited-file-modtime)
  1851. (erase-buffer)
  1852. (let ((insert-okay-p nil)
  1853. (buffer (current-buffer))
  1854. string entry last-use-time
  1855. cmpl-entry cmpl-last-use-time
  1856. (current-completion-source cmpl-source-init-file)
  1857. (total-in-file 0) (total-perm 0))
  1858. ;; insert the file into a buffer
  1859. (condition-case nil
  1860. (progn (insert-file-contents filename t)
  1861. (setq insert-okay-p t))
  1862. (file-error
  1863. (message "File error trying to load completion file %s."
  1864. filename)))
  1865. ;; parse it
  1866. (if insert-okay-p
  1867. (progn
  1868. (goto-char (point-min))
  1869. (condition-case nil
  1870. (while t
  1871. (setq entry (read buffer))
  1872. (setq total-in-file (1+ total-in-file))
  1873. (cond
  1874. ((and (consp entry)
  1875. (stringp (setq string (car entry)))
  1876. (cond
  1877. ((eq (setq last-use-time (cdr entry)) 'T)
  1878. ;; handle case sensitivity
  1879. (setq total-perm (1+ total-perm))
  1880. (setq last-use-time t))
  1881. ((eq last-use-time t)
  1882. (setq total-perm (1+ total-perm)))
  1883. ((integerp last-use-time))))
  1884. ;; Valid entry
  1885. ;; add it in
  1886. (setq cmpl-last-use-time
  1887. (completion-last-use-time
  1888. (setq cmpl-entry
  1889. (add-completion-to-tail-if-new string))))
  1890. (if (or (eq last-use-time t)
  1891. (and (> last-use-time 1000);;backcompatibility
  1892. (not (eq cmpl-last-use-time t))
  1893. (or (not cmpl-last-use-time)
  1894. ;; more recent
  1895. (> last-use-time cmpl-last-use-time))))
  1896. ;; update last-use-time
  1897. (set-completion-last-use-time cmpl-entry last-use-time)))
  1898. (t
  1899. ;; Bad format
  1900. (message "Error: invalid saved completion - %s"
  1901. (prin1-to-string entry))
  1902. ;; try to get back in sync
  1903. (search-forward "\n("))))
  1904. (search-failed
  1905. (message "End of file while reading completions."))
  1906. (end-of-file
  1907. (if (= (point) (point-max))
  1908. (if (not no-message-p)
  1909. (message "Loading completions from file %s . . . Done."
  1910. filename))
  1911. (message "End of file while reading completions."))))))
  1912. ))))))
  1913. (defun completion-initialize ()
  1914. "Load the default completions file.
  1915. Also sets up so that exiting Emacs will automatically save the file."
  1916. (interactive)
  1917. (unless cmpl-initialized-p
  1918. (load-completions-from-file)
  1919. (setq cmpl-initialized-p t)))
  1920. ;;-----------------------------------------------
  1921. ;; Kill region patch
  1922. ;;-----------------------------------------------
  1923. (defun completion-kill-region (&optional beg end)
  1924. "Kill between point and mark.
  1925. The text is deleted but saved in the kill ring.
  1926. The command \\[yank] can retrieve it from there.
  1927. /(If you want to kill and then yank immediately, use \\[copy-region-as-kill].)
  1928. This is the primitive for programs to kill text (as opposed to deleting it).
  1929. Supply two arguments, character positions indicating the stretch of text
  1930. to be killed.
  1931. Any command that calls this function is a \"kill command\".
  1932. If the previous command was also a kill command,
  1933. the text killed this time appends to the text killed last time
  1934. to make one entry in the kill ring.
  1935. Patched to remove the most recent completion."
  1936. (interactive "r")
  1937. (cond ((eq last-command 'complete)
  1938. (delete-region (point) cmpl-last-insert-location)
  1939. (insert cmpl-original-string)
  1940. (setq completion-to-accept nil))
  1941. (t
  1942. (kill-region beg end))))
  1943. ;;-----------------------------------------------
  1944. ;; Patches to self-insert-command.
  1945. ;;-----------------------------------------------
  1946. ;; Need 2 versions: generic separator chars. and space (to get auto fill
  1947. ;; to work)
  1948. ;; All common separators (eg. space "(" ")" """) characters go through a
  1949. ;; function to add new words to the list of words to complete from.
  1950. ;; If the character before this was an alpha-numeric then this adds the
  1951. ;; symbol before point to the completion list (using ADD-COMPLETION).
  1952. (defvar completion-separator-chars
  1953. (append " !%^&()=`|{}[];\\'#,?"
  1954. ;; We include period and colon even though they are symbol
  1955. ;; chars because :
  1956. ;; - in text we want to pick up the last word in a sentence.
  1957. ;; - in C pointer refs. we want to pick up the first symbol
  1958. ;; - it won't make a difference for lisp mode (package names
  1959. ;; are short)
  1960. ".:" nil))
  1961. (defun completion--post-self-insert ()
  1962. (when (memq last-command-event completion-separator-chars)
  1963. (let ((after-pos (electric--after-char-pos)))
  1964. (when after-pos
  1965. (save-excursion
  1966. (goto-char (1- after-pos))
  1967. (use-completion-before-separator))))))
  1968. ;;-----------------------------------------------
  1969. ;; Wrapping Macro
  1970. ;;-----------------------------------------------
  1971. ;; Note that because of the way byte compiling works, none of
  1972. ;; the functions defined with this macro get byte compiled.
  1973. (defun completion-def-wrapper (function-name type)
  1974. "Add a call to update the completion database before function execution.
  1975. TYPE is the type of the wrapper to be added. Can be :before or :under."
  1976. (put function-name 'completion-function
  1977. (cdr (assq type
  1978. '((:separator . use-completion-before-separator)
  1979. (:before . use-completion-before-point)
  1980. (:backward-under . use-completion-backward-under)
  1981. (:backward . use-completion-backward)
  1982. (:under . use-completion-under-point)
  1983. (:under-or-before . use-completion-under-or-before-point)
  1984. (:minibuffer-separator
  1985. . use-completion-minibuffer-separator))))))
  1986. (defun use-completion-minibuffer-separator ()
  1987. (let ((completion-syntax-table completion-standard-syntax-table))
  1988. (use-completion-before-separator)))
  1989. (defun use-completion-backward-under ()
  1990. (use-completion-under-point))
  1991. (defun use-completion-backward ()
  1992. nil)
  1993. (defun completion-before-command ()
  1994. (funcall (or (and (symbolp this-command)
  1995. (get this-command 'completion-function))
  1996. 'use-completion-under-or-before-point)))
  1997. ;; Lisp mode diffs.
  1998. (defconst completion-lisp-syntax-table
  1999. (let ((table (copy-syntax-table completion-standard-syntax-table))
  2000. (symbol-chars '(?! ?& ?? ?= ?^)))
  2001. (dolist (char symbol-chars)
  2002. (modify-syntax-entry char "_" table))
  2003. table))
  2004. (defun completion-lisp-mode-hook ()
  2005. (setq completion-syntax-table completion-lisp-syntax-table)
  2006. ;; Lisp Mode diffs
  2007. (setq-local completion-separator-chars
  2008. (cl-set-difference completion-separator-chars
  2009. (append "!&%?=^" nil))))
  2010. ;; C mode diffs.
  2011. (defconst completion-c-syntax-table
  2012. (let ((table (copy-syntax-table completion-standard-syntax-table))
  2013. (separator-chars '(?+ ?* ?/ ?: ?%)))
  2014. (dolist (char separator-chars)
  2015. (modify-syntax-entry char " " table))
  2016. table))
  2017. (completion-def-wrapper 'electric-c-semi :separator)
  2018. (defun completion-c-mode-hook ()
  2019. (setq completion-syntax-table completion-c-syntax-table)
  2020. (setq-local completion-separator-chars
  2021. (append "+*/" completion-separator-chars)))
  2022. ;; FORTRAN mode diffs. (these are defined when fortran is called)
  2023. (defconst completion-fortran-syntax-table
  2024. (let ((table (copy-syntax-table completion-standard-syntax-table))
  2025. (separator-chars '(?+ ?- ?* ?/ ?:)))
  2026. (dolist (char separator-chars)
  2027. (modify-syntax-entry char " " table))
  2028. table))
  2029. (defun completion-setup-fortran-mode ()
  2030. (setq completion-syntax-table completion-fortran-syntax-table)
  2031. (setq-local completion-separator-chars
  2032. (append "+-*/" completion-separator-chars)))
  2033. ;; Enable completion mode.
  2034. (defvar fortran-mode-hook)
  2035. (defvar completion-saved-bindings nil)
  2036. ;;;###autoload
  2037. (define-minor-mode dynamic-completion-mode
  2038. "Toggle dynamic word-completion on or off.
  2039. With a prefix argument ARG, enable the mode if ARG is positive,
  2040. and disable it otherwise. If called from Lisp, enable the mode
  2041. if ARG is omitted or nil."
  2042. :global t
  2043. :group 'completion
  2044. ;; This is always good, not specific to dynamic-completion-mode.
  2045. (define-key function-key-map [C-return] [?\C-\r])
  2046. (dolist (x `((find-file-hook . ,#'completion-find-file-hook)
  2047. (pre-command-hook . ,#'completion-before-command)
  2048. ;; Save completions when killing Emacs.
  2049. (kill-emacs-hook . ,#'kill-emacs-save-completions)
  2050. (post-self-insert-hook . ,#'completion--post-self-insert)
  2051. ;; Install the appropriate mode tables.
  2052. (lisp-mode-hook . ,#'completion-lisp-mode-hook)
  2053. (c-mode-hook . ,#'completion-c-mode-hook)
  2054. (fortran-mode-hook . ,#'completion-setup-fortran-mode)))
  2055. (if dynamic-completion-mode
  2056. (add-hook (car x) (cdr x))
  2057. (remove-hook (car x) (cdr x))))
  2058. ;; "Complete" Key Keybindings. We don't want to use a minor-mode
  2059. ;; map because these have too high a priority. We could/should
  2060. ;; probably change the interpretation of minor-mode-map-alist such
  2061. ;; that a map has lower precedence if the symbol is not buffer-local.
  2062. (while completion-saved-bindings
  2063. (let ((binding (pop completion-saved-bindings)))
  2064. (global-set-key (car binding) (cdr binding))))
  2065. (when dynamic-completion-mode
  2066. (dolist (binding
  2067. '(("\M-\r" . complete)
  2068. ([?\C-\r] . complete)
  2069. ;; Tests -
  2070. ;; (add-completion "cumberland")
  2071. ;; (add-completion "cumberbund")
  2072. ;; cum
  2073. ;; Cumber
  2074. ;; cumbering
  2075. ;; cumb
  2076. ;; Patches to standard keymaps insert completions
  2077. ([remap kill-region] . completion-kill-region)))
  2078. (push (cons (car binding) (lookup-key global-map (car binding)))
  2079. completion-saved-bindings)
  2080. (global-set-key (car binding) (cdr binding)))
  2081. ;; Tests --
  2082. ;; foobarbiz
  2083. ;; foobar
  2084. ;; fooquux
  2085. ;; fooper
  2086. (completion-initialize)))
  2087. ;;-----------------------------------------------
  2088. ;; End of line chars.
  2089. ;;-----------------------------------------------
  2090. (completion-def-wrapper 'newline :separator)
  2091. (completion-def-wrapper 'newline-and-indent :separator)
  2092. (completion-def-wrapper 'comint-send-input :separator)
  2093. (completion-def-wrapper 'exit-minibuffer :minibuffer-separator)
  2094. (completion-def-wrapper 'eval-print-last-sexp :separator)
  2095. (completion-def-wrapper 'eval-last-sexp :separator)
  2096. ;;(completion-def-wrapper 'minibuffer-complete-and-exit :minibuffer)
  2097. ;;-----------------------------------------------
  2098. ;; Cursor movement
  2099. ;;-----------------------------------------------
  2100. (completion-def-wrapper 'next-line :under-or-before)
  2101. (completion-def-wrapper 'previous-line :under-or-before)
  2102. (completion-def-wrapper 'beginning-of-buffer :under-or-before)
  2103. (completion-def-wrapper 'end-of-buffer :under-or-before)
  2104. (completion-def-wrapper 'beginning-of-line :under-or-before)
  2105. (completion-def-wrapper 'end-of-line :under-or-before)
  2106. (completion-def-wrapper 'forward-char :under-or-before)
  2107. (completion-def-wrapper 'forward-word :under-or-before)
  2108. (completion-def-wrapper 'forward-sexp :under-or-before)
  2109. (completion-def-wrapper 'backward-char :backward-under)
  2110. (completion-def-wrapper 'backward-word :backward-under)
  2111. (completion-def-wrapper 'backward-sexp :backward-under)
  2112. (completion-def-wrapper 'delete-backward-char :backward)
  2113. (completion-def-wrapper 'delete-backward-char-untabify :backward)
  2114. ;; Old names, non-namespace-clean.
  2115. (defvaralias 'cmpl-syntax-table 'completion-syntax-table)
  2116. (defalias 'initialize-completions 'completion-initialize)
  2117. (provide 'completion)
  2118. ;;; completion.el ends here