completion.el 92 KB

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