minibuffer.el 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436
  1. ;;; minibuffer.el --- Minibuffer completion functions -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
  3. ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
  4. ;; Package: emacs
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; Names with "--" are for functions and variables that are meant to be for
  18. ;; internal use only.
  19. ;; Functional completion tables have an extended calling conventions:
  20. ;; The `action' can be (additionally to nil, t, and lambda) of the form
  21. ;; - (boundaries . SUFFIX) in which case it should return
  22. ;; (boundaries START . END). See `completion-boundaries'.
  23. ;; Any other return value should be ignored (so we ignore values returned
  24. ;; from completion tables that don't know about this new `action' form).
  25. ;; - `metadata' in which case it should return (metadata . ALIST) where
  26. ;; ALIST is the metadata of this table. See `completion-metadata'.
  27. ;; Any other return value should be ignored (so we ignore values returned
  28. ;; from completion tables that don't know about this new `action' form).
  29. ;;; Bugs:
  30. ;; - completion-all-sorted-completions lists all the completions, whereas
  31. ;; it should only lists the ones that `try-completion' would consider.
  32. ;; E.g. it should honor completion-ignored-extensions.
  33. ;; - choose-completion can't automatically figure out the boundaries
  34. ;; corresponding to the displayed completions because we only
  35. ;; provide the start info but not the end info in
  36. ;; completion-base-position.
  37. ;; - C-x C-f ~/*/sr ? should not list "~/./src".
  38. ;; - minibuffer-force-complete completes ~/src/emacs/t<!>/lisp/minibuffer.el
  39. ;; to ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
  40. ;;; Todo:
  41. ;; - Make *Completions* readable even if some of the completion
  42. ;; entries have LF chars or spaces in them (including at
  43. ;; beginning/end) or are very long.
  44. ;; - for M-x, cycle-sort commands that have no key binding first.
  45. ;; - Make things like icomplete-mode or lightning-completion work with
  46. ;; completion-in-region-mode.
  47. ;; - extend `metadata':
  48. ;; - indicate how to turn all-completion's output into
  49. ;; try-completion's output: e.g. completion-ignored-extensions.
  50. ;; maybe that could be merged with the "quote" operation.
  51. ;; - indicate that `all-completions' doesn't do prefix-completion
  52. ;; but just returns some list that relates in some other way to
  53. ;; the provided string (as is the case in filecache.el), in which
  54. ;; case partial-completion (for example) doesn't make any sense
  55. ;; and neither does the completions-first-difference highlight.
  56. ;; - indicate how to display the completions in *Completions* (turn
  57. ;; \n into something else, add special boundaries between
  58. ;; completions). E.g. when completing from the kill-ring.
  59. ;; - case-sensitivity currently confuses two issues:
  60. ;; - whether or not a particular completion table should be case-sensitive
  61. ;; (i.e. whether strings that differ only by case are semantically
  62. ;; equivalent)
  63. ;; - whether the user wants completion to pay attention to case.
  64. ;; e.g. we may want to make it possible for the user to say "first try
  65. ;; completion case-sensitively, and if that fails, try to ignore case".
  66. ;; Maybe the trick is that we should distinguish completion-ignore-case in
  67. ;; try/all-completions (obey user's preference) from its use in
  68. ;; test-completion (obey the underlying object's semantics).
  69. ;; - add support for ** to pcm.
  70. ;; - Add vc-file-name-completion-table to read-file-name-internal.
  71. ;; - A feature like completing-help.el.
  72. ;;; Code:
  73. (eval-when-compile (require 'cl-lib))
  74. ;;; Completion table manipulation
  75. ;; New completion-table operation.
  76. (defun completion-boundaries (string collection pred suffix)
  77. "Return the boundaries of text on which COLLECTION will operate.
  78. STRING is the string on which completion will be performed.
  79. SUFFIX is the string after point.
  80. If COLLECTION is a function, it is called with 3 arguments: STRING,
  81. PRED, and a cons cell of the form (boundaries . SUFFIX).
  82. The result is of the form (START . END) where START is the position
  83. in STRING of the beginning of the completion field and END is the position
  84. in SUFFIX of the end of the completion field.
  85. E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
  86. and for file names the result is the positions delimited by
  87. the closest directory separators."
  88. (let ((boundaries (if (functionp collection)
  89. (funcall collection string pred
  90. (cons 'boundaries suffix)))))
  91. (if (not (eq (car-safe boundaries) 'boundaries))
  92. (setq boundaries nil))
  93. (cons (or (cadr boundaries) 0)
  94. (or (cddr boundaries) (length suffix)))))
  95. (defun completion-metadata (string table pred)
  96. "Return the metadata of elements to complete at the end of STRING.
  97. This metadata is an alist. Currently understood keys are:
  98. - `category': the kind of objects returned by `all-completions'.
  99. Used by `completion-category-overrides'.
  100. - `annotation-function': function to add annotations in *Completions*.
  101. Takes one argument (STRING), which is a possible completion and
  102. returns a string to append to STRING.
  103. - `display-sort-function': function to sort entries in *Completions*.
  104. Takes one argument (COMPLETIONS) and should return a new list
  105. of completions. Can operate destructively.
  106. - `cycle-sort-function': function to sort entries when cycling.
  107. Works like `display-sort-function'.
  108. The metadata of a completion table should be constant between two boundaries."
  109. (let ((metadata (if (functionp table)
  110. (funcall table string pred 'metadata))))
  111. (if (eq (car-safe metadata) 'metadata)
  112. metadata
  113. '(metadata))))
  114. (defun completion--field-metadata (field-start)
  115. (completion-metadata (buffer-substring-no-properties field-start (point))
  116. minibuffer-completion-table
  117. minibuffer-completion-predicate))
  118. (defun completion-metadata-get (metadata prop)
  119. (cdr (assq prop metadata)))
  120. (defun completion--some (fun xs)
  121. "Apply FUN to each element of XS in turn.
  122. Return the first non-nil returned value.
  123. Like CL's `some'."
  124. (let ((firsterror nil)
  125. res)
  126. (while (and (not res) xs)
  127. (condition-case-unless-debug err
  128. (setq res (funcall fun (pop xs)))
  129. (error (unless firsterror (setq firsterror err)) nil)))
  130. (or res
  131. (if firsterror (signal (car firsterror) (cdr firsterror))))))
  132. (defun complete-with-action (action table string pred)
  133. "Perform completion ACTION.
  134. STRING is the string to complete.
  135. TABLE is the completion table.
  136. PRED is a completion predicate.
  137. ACTION can be one of nil, t or `lambda'."
  138. (cond
  139. ((functionp table) (funcall table string pred action))
  140. ((eq (car-safe action) 'boundaries) nil)
  141. ((eq action 'metadata) nil)
  142. (t
  143. (funcall
  144. (cond
  145. ((null action) 'try-completion)
  146. ((eq action t) 'all-completions)
  147. (t 'test-completion))
  148. string table pred))))
  149. (defun completion-table-dynamic (fun &optional switch-buffer)
  150. "Use function FUN as a dynamic completion table.
  151. FUN is called with one argument, the string for which completion is required,
  152. and it should return an alist containing all the intended possible completions.
  153. This alist may be a full list of possible completions so that FUN can ignore
  154. the value of its argument.
  155. If SWITCH-BUFFER is non-nil and completion is performed in the
  156. minibuffer, FUN will be called in the buffer from which the minibuffer
  157. was entered.
  158. The result of the `completion-table-dynamic' form is a function
  159. that can be used as the COLLECTION argument to `try-completion' and
  160. `all-completions'. See Info node `(elisp)Programmed Completion'.
  161. See also the related function `completion-table-with-cache'."
  162. (lambda (string pred action)
  163. (if (or (eq (car-safe action) 'boundaries) (eq action 'metadata))
  164. ;; `fun' is not supposed to return another function but a plain old
  165. ;; completion table, whose boundaries are always trivial.
  166. nil
  167. (with-current-buffer (if (not switch-buffer) (current-buffer)
  168. (let ((win (minibuffer-selected-window)))
  169. (if (window-live-p win) (window-buffer win)
  170. (current-buffer))))
  171. (complete-with-action action (funcall fun string) string pred)))))
  172. (defun completion-table-with-cache (fun &optional ignore-case)
  173. "Create dynamic completion table from function FUN, with cache.
  174. This is a wrapper for `completion-table-dynamic' that saves the last
  175. argument-result pair from FUN, so that several lookups with the
  176. same argument (or with an argument that starts with the first one)
  177. only need to call FUN once. This can be useful when FUN performs a
  178. relatively slow operation, such as calling an external process.
  179. When IGNORE-CASE is non-nil, FUN is expected to be case-insensitive."
  180. ;; See eg bug#11906.
  181. (let* (last-arg last-result
  182. (new-fun
  183. (lambda (arg)
  184. (if (and last-arg (string-prefix-p last-arg arg ignore-case))
  185. last-result
  186. (prog1
  187. (setq last-result (funcall fun arg))
  188. (setq last-arg arg))))))
  189. (completion-table-dynamic new-fun)))
  190. (defmacro lazy-completion-table (var fun)
  191. "Initialize variable VAR as a lazy completion table.
  192. If the completion table VAR is used for the first time (e.g., by passing VAR
  193. as an argument to `try-completion'), the function FUN is called with no
  194. arguments. FUN must return the completion table that will be stored in VAR.
  195. If completion is requested in the minibuffer, FUN will be called in the buffer
  196. from which the minibuffer was entered. The return value of
  197. `lazy-completion-table' must be used to initialize the value of VAR.
  198. You should give VAR a non-nil `risky-local-variable' property."
  199. (declare (debug (symbolp lambda-expr)))
  200. (let ((str (make-symbol "string")))
  201. `(completion-table-dynamic
  202. (lambda (,str)
  203. (when (functionp ,var)
  204. (setq ,var (funcall #',fun)))
  205. ,var)
  206. 'do-switch-buffer)))
  207. (defun completion-table-case-fold (table &optional dont-fold)
  208. "Return new completion TABLE that is case insensitive.
  209. If DONT-FOLD is non-nil, return a completion table that is
  210. case sensitive instead."
  211. (lambda (string pred action)
  212. (let ((completion-ignore-case (not dont-fold)))
  213. (complete-with-action action table string pred))))
  214. (defun completion-table-subvert (table s1 s2)
  215. "Return a completion table from TABLE with S1 replaced by S2.
  216. The result is a completion table which completes strings of the
  217. form (concat S1 S) in the same way as TABLE completes strings of
  218. the form (concat S2 S)."
  219. (lambda (string pred action)
  220. (let* ((str (if (string-prefix-p s1 string completion-ignore-case)
  221. (concat s2 (substring string (length s1)))))
  222. (res (if str (complete-with-action action table str pred))))
  223. (when res
  224. (cond
  225. ((eq (car-safe action) 'boundaries)
  226. (let ((beg (or (and (eq (car-safe res) 'boundaries) (cadr res)) 0)))
  227. `(boundaries
  228. ,(max (length s1)
  229. (+ beg (- (length s1) (length s2))))
  230. . ,(and (eq (car-safe res) 'boundaries) (cddr res)))))
  231. ((stringp res)
  232. (if (string-prefix-p s2 string completion-ignore-case)
  233. (concat s1 (substring res (length s2)))))
  234. ((eq action t)
  235. (let ((bounds (completion-boundaries str table pred "")))
  236. (if (>= (car bounds) (length s2))
  237. res
  238. (let ((re (concat "\\`"
  239. (regexp-quote (substring s2 (car bounds))))))
  240. (delq nil
  241. (mapcar (lambda (c)
  242. (if (string-match re c)
  243. (substring c (match-end 0))))
  244. res))))))
  245. ;; E.g. action=nil and it's the only completion.
  246. (res))))))
  247. (defun completion-table-with-context (prefix table string pred action)
  248. ;; TODO: add `suffix' maybe?
  249. (let ((pred
  250. (if (not (functionp pred))
  251. ;; Notice that `pred' may not be a function in some abusive cases.
  252. pred
  253. ;; Predicates are called differently depending on the nature of
  254. ;; the completion table :-(
  255. (cond
  256. ((vectorp table) ;Obarray.
  257. (lambda (sym) (funcall pred (concat prefix (symbol-name sym)))))
  258. ((hash-table-p table)
  259. (lambda (s _v) (funcall pred (concat prefix s))))
  260. ((functionp table)
  261. (lambda (s) (funcall pred (concat prefix s))))
  262. (t ;Lists and alists.
  263. (lambda (s)
  264. (funcall pred (concat prefix (if (consp s) (car s) s)))))))))
  265. (if (eq (car-safe action) 'boundaries)
  266. (let* ((len (length prefix))
  267. (bound (completion-boundaries string table pred (cdr action))))
  268. `(boundaries ,(+ (car bound) len) . ,(cdr bound)))
  269. (let ((comp (complete-with-action action table string pred)))
  270. (cond
  271. ;; In case of try-completion, add the prefix.
  272. ((stringp comp) (concat prefix comp))
  273. (t comp))))))
  274. (defun completion-table-with-terminator (terminator table string pred action)
  275. "Construct a completion table like TABLE but with an extra TERMINATOR.
  276. This is meant to be called in a curried way by first passing TERMINATOR
  277. and TABLE only (via `apply-partially').
  278. TABLE is a completion table, and TERMINATOR is a string appended to TABLE's
  279. completion if it is complete. TERMINATOR is also used to determine the
  280. completion suffix's boundary.
  281. TERMINATOR can also be a cons cell (TERMINATOR . TERMINATOR-REGEXP)
  282. in which case TERMINATOR-REGEXP is a regular expression whose submatch
  283. number 1 should match TERMINATOR. This is used when there is a need to
  284. distinguish occurrences of the TERMINATOR strings which are really terminators
  285. from others (e.g. escaped). In this form, the car of TERMINATOR can also be,
  286. instead of a string, a function that takes the completion and returns the
  287. \"terminated\" string."
  288. ;; FIXME: This implementation is not right since it only adds the terminator
  289. ;; in try-completion, so any completion-style that builds the completion via
  290. ;; all-completions won't get the terminator, and selecting an entry in
  291. ;; *Completions* won't get the terminator added either.
  292. (cond
  293. ((eq (car-safe action) 'boundaries)
  294. (let* ((suffix (cdr action))
  295. (bounds (completion-boundaries string table pred suffix))
  296. (terminator-regexp (if (consp terminator)
  297. (cdr terminator) (regexp-quote terminator)))
  298. (max (and terminator-regexp
  299. (string-match terminator-regexp suffix))))
  300. `(boundaries ,(car bounds)
  301. . ,(min (cdr bounds) (or max (length suffix))))))
  302. ((eq action nil)
  303. (let ((comp (try-completion string table pred)))
  304. (if (consp terminator) (setq terminator (car terminator)))
  305. (if (eq comp t)
  306. (if (functionp terminator)
  307. (funcall terminator string)
  308. (concat string terminator))
  309. (if (and (stringp comp) (not (zerop (length comp)))
  310. ;; Try to avoid the second call to try-completion, since
  311. ;; it may be very inefficient (because `comp' made us
  312. ;; jump to a new boundary, so we complete in that
  313. ;; boundary with an empty start string).
  314. (let ((newbounds (completion-boundaries comp table pred "")))
  315. (< (car newbounds) (length comp)))
  316. (eq (try-completion comp table pred) t))
  317. (if (functionp terminator)
  318. (funcall terminator comp)
  319. (concat comp terminator))
  320. comp))))
  321. ;; completion-table-with-terminator is always used for
  322. ;; "sub-completions" so it's only called if the terminator is missing,
  323. ;; in which case `test-completion' should return nil.
  324. ((eq action 'lambda) nil)
  325. (t
  326. ;; FIXME: We generally want the `try' and `all' behaviors to be
  327. ;; consistent so pcm can merge the `all' output to get the `try' output,
  328. ;; but that sometimes clashes with the need for `all' output to look
  329. ;; good in *Completions*.
  330. ;; (mapcar (lambda (s) (concat s terminator))
  331. ;; (all-completions string table pred))))
  332. (complete-with-action action table string pred))))
  333. (defun completion-table-with-predicate (table pred1 strict string pred2 action)
  334. "Make a completion table equivalent to TABLE but filtered through PRED1.
  335. PRED1 is a function of one argument which returns non-nil if and
  336. only if the argument is an element of TABLE which should be
  337. considered for completion. STRING, PRED2, and ACTION are the
  338. usual arguments to completion tables, as described in
  339. `try-completion', `all-completions', and `test-completion'. If
  340. STRICT is non-nil, the predicate always applies; if nil it only
  341. applies if it does not reduce the set of possible completions to
  342. nothing. Note: TABLE needs to be a proper completion table which
  343. obeys predicates."
  344. (cond
  345. ((and (not strict) (eq action 'lambda))
  346. ;; Ignore pred1 since it doesn't really have to apply anyway.
  347. (test-completion string table pred2))
  348. (t
  349. (or (complete-with-action action table string
  350. (if (not (and pred1 pred2))
  351. (or pred1 pred2)
  352. (lambda (x)
  353. ;; Call `pred1' first, so that `pred2'
  354. ;; really can't tell that `x' is in table.
  355. (and (funcall pred1 x) (funcall pred2 x)))))
  356. ;; If completion failed and we're not applying pred1 strictly, try
  357. ;; again without pred1.
  358. (and (not strict) pred1 pred2
  359. (complete-with-action action table string pred2))))))
  360. (defun completion-table-in-turn (&rest tables)
  361. "Create a completion table that tries each table in TABLES in turn."
  362. ;; FIXME: the boundaries may come from TABLE1 even when the completion list
  363. ;; is returned by TABLE2 (because TABLE1 returned an empty list).
  364. ;; Same potential problem if any of the tables use quoting.
  365. (lambda (string pred action)
  366. (completion--some (lambda (table)
  367. (complete-with-action action table string pred))
  368. tables)))
  369. (defun completion-table-merge (&rest tables)
  370. "Create a completion table that collects completions from all TABLES."
  371. ;; FIXME: same caveats as in `completion-table-in-turn'.
  372. (lambda (string pred action)
  373. (cond
  374. ((null action)
  375. (let ((retvals (mapcar (lambda (table)
  376. (try-completion string table pred))
  377. tables)))
  378. (if (member string retvals)
  379. string
  380. (try-completion string
  381. (mapcar (lambda (value)
  382. (if (eq value t) string value))
  383. (delq nil retvals))
  384. pred))))
  385. ((eq action t)
  386. (apply #'append (mapcar (lambda (table)
  387. (all-completions string table pred))
  388. tables)))
  389. (t
  390. (completion--some (lambda (table)
  391. (complete-with-action action table string pred))
  392. tables)))))
  393. (defun completion-table-with-quoting (table unquote requote)
  394. ;; A difficult part of completion-with-quoting is to map positions in the
  395. ;; quoted string to equivalent positions in the unquoted string and
  396. ;; vice-versa. There is no efficient and reliable algorithm that works for
  397. ;; arbitrary quote and unquote functions.
  398. ;; So to map from quoted positions to unquoted positions, we simply assume
  399. ;; that `concat' and `unquote' commute (which tends to be the case).
  400. ;; And we ask `requote' to do the work of mapping from unquoted positions
  401. ;; back to quoted positions.
  402. ;; FIXME: For some forms of "quoting" such as the truncation behavior of
  403. ;; substitute-in-file-name, it would be desirable not to requote completely.
  404. "Return a new completion table operating on quoted text.
  405. TABLE operates on the unquoted text.
  406. UNQUOTE is a function that takes a string and returns a new unquoted string.
  407. REQUOTE is a function of 2 args (UPOS QSTR) where
  408. QSTR is a string entered by the user (and hence indicating
  409. the user's preferred form of quoting); and
  410. UPOS is a position within the unquoted form of QSTR.
  411. REQUOTE should return a pair (QPOS . QFUN) such that QPOS is the
  412. position corresponding to UPOS but in QSTR, and QFUN is a function
  413. of one argument (a string) which returns that argument appropriately quoted
  414. for use at QPOS."
  415. ;; FIXME: One problem with the current setup is that `qfun' doesn't know if
  416. ;; its argument is "the end of the completion", so if the quoting used double
  417. ;; quotes (for example), we end up completing "fo" to "foobar and throwing
  418. ;; away the closing double quote.
  419. (lambda (string pred action)
  420. (cond
  421. ((eq action 'metadata)
  422. (append (completion-metadata string table pred)
  423. '((completion--unquote-requote . t))))
  424. ((eq action 'lambda) ;;test-completion
  425. (let ((ustring (funcall unquote string)))
  426. (test-completion ustring table pred)))
  427. ((eq (car-safe action) 'boundaries)
  428. (let* ((ustring (funcall unquote string))
  429. (qsuffix (cdr action))
  430. (ufull (if (zerop (length qsuffix)) ustring
  431. (funcall unquote (concat string qsuffix))))
  432. (_ (cl-assert (string-prefix-p ustring ufull)))
  433. (usuffix (substring ufull (length ustring)))
  434. (boundaries (completion-boundaries ustring table pred usuffix))
  435. (qlboundary (car (funcall requote (car boundaries) string)))
  436. (qrboundary (if (zerop (cdr boundaries)) 0 ;Common case.
  437. (let* ((urfullboundary
  438. (+ (cdr boundaries) (length ustring))))
  439. (- (car (funcall requote urfullboundary
  440. (concat string qsuffix)))
  441. (length string))))))
  442. `(boundaries ,qlboundary . ,qrboundary)))
  443. ;; In "normal" use a c-t-with-quoting completion table should never be
  444. ;; called with action in (t nil) because `completion--unquote' should have
  445. ;; been called before and would have returned a different completion table
  446. ;; to apply to the unquoted text. But there's still a lot of code around
  447. ;; that likes to use all/try-completions directly, so we do our best to
  448. ;; handle those calls as well as we can.
  449. ((eq action nil) ;;try-completion
  450. (let* ((ustring (funcall unquote string))
  451. (completion (try-completion ustring table pred)))
  452. ;; Most forms of quoting allow several ways to quote the same string.
  453. ;; So here we could simply requote `completion' in a kind of
  454. ;; "canonical" quoted form without paying attention to the way
  455. ;; `string' was quoted. But since we have to solve the more complex
  456. ;; problems of "pay attention to the original quoting" for
  457. ;; all-completions, we may as well use it here, since it provides
  458. ;; a nicer behavior.
  459. (if (not (stringp completion)) completion
  460. (car (completion--twq-try
  461. string ustring completion 0 unquote requote)))))
  462. ((eq action t) ;;all-completions
  463. ;; When all-completions is used for completion-try/all-completions
  464. ;; (e.g. for `pcm' style), we can't do the job properly here because
  465. ;; the caller will match our output against some pattern derived from
  466. ;; the user's (quoted) input, and we don't have access to that
  467. ;; pattern, so we can't know how to requote our output so that it
  468. ;; matches the quoting used in the pattern. It is to fix this
  469. ;; fundamental problem that we have to introduce the new
  470. ;; unquote-requote method so that completion-try/all-completions can
  471. ;; pass the unquoted string to the style functions.
  472. (pcase-let*
  473. ((ustring (funcall unquote string))
  474. (completions (all-completions ustring table pred))
  475. (boundary (car (completion-boundaries ustring table pred "")))
  476. (completions
  477. (completion--twq-all
  478. string ustring completions boundary unquote requote))
  479. (last (last completions)))
  480. (when (consp last) (setcdr last nil))
  481. completions))
  482. ((eq action 'completion--unquote)
  483. ;; PRED is really a POINT in STRING.
  484. ;; We should return a new set (STRING TABLE POINT REQUOTE)
  485. ;; where STRING is a new (unquoted) STRING to match against the new TABLE
  486. ;; using a new POINT inside it, and REQUOTE is a requoting function which
  487. ;; should reverse the unquoting, (i.e. it receives the completion result
  488. ;; of using the new TABLE and should turn it into the corresponding
  489. ;; quoted result).
  490. (let* ((qpos pred)
  491. (ustring (funcall unquote string))
  492. (uprefix (funcall unquote (substring string 0 qpos)))
  493. ;; FIXME: we really should pass `qpos' to `unquote' and have that
  494. ;; function give us the corresponding `uqpos'. But for now we
  495. ;; presume (more or less) that `concat' and `unquote' commute.
  496. (uqpos (if (string-prefix-p uprefix ustring)
  497. ;; Yay!! They do seem to commute!
  498. (length uprefix)
  499. ;; They don't commute this time! :-(
  500. ;; Maybe qpos is in some text that disappears in the
  501. ;; ustring (bug#17239). Let's try a second chance guess.
  502. (let ((usuffix (funcall unquote (substring string qpos))))
  503. (if (string-suffix-p usuffix ustring)
  504. ;; Yay!! They still "commute" in a sense!
  505. (- (length ustring) (length usuffix))
  506. ;; Still no luck! Let's just choose *some* position
  507. ;; within ustring.
  508. (/ (+ (min (length uprefix) (length ustring))
  509. (max (- (length ustring) (length usuffix)) 0))
  510. 2))))))
  511. (list ustring table uqpos
  512. (lambda (unquoted-result op)
  513. (pcase op
  514. (1 ;;try
  515. (if (not (stringp (car-safe unquoted-result)))
  516. unquoted-result
  517. (completion--twq-try
  518. string ustring
  519. (car unquoted-result) (cdr unquoted-result)
  520. unquote requote)))
  521. (2 ;;all
  522. (let* ((last (last unquoted-result))
  523. (base (or (cdr last) 0)))
  524. (when last
  525. (setcdr last nil)
  526. (completion--twq-all string ustring
  527. unquoted-result base
  528. unquote requote))))))))))))
  529. (defun completion--twq-try (string ustring completion point
  530. unquote requote)
  531. ;; Basically two cases: either the new result is
  532. ;; - commonprefix1 <point> morecommonprefix <qpos> suffix
  533. ;; - commonprefix <qpos> newprefix <point> suffix
  534. (pcase-let*
  535. ((prefix (fill-common-string-prefix ustring completion))
  536. (suffix (substring completion (max point (length prefix))))
  537. (`(,qpos . ,qfun) (funcall requote (length prefix) string))
  538. (qstr1 (if (> point (length prefix))
  539. (funcall qfun (substring completion (length prefix) point))))
  540. (qsuffix (funcall qfun suffix))
  541. (qstring (concat (substring string 0 qpos) qstr1 qsuffix))
  542. (qpoint
  543. (cond
  544. ((zerop point) 0)
  545. ((> point (length prefix)) (+ qpos (length qstr1)))
  546. (t (car (funcall requote point string))))))
  547. ;; Make sure `requote' worked.
  548. (if (equal (funcall unquote qstring) completion)
  549. (cons qstring qpoint)
  550. ;; If requote failed (e.g. because sifn-requote did not handle
  551. ;; Tramp's "/foo:/bar//baz -> /foo:/baz" truncation), then at least
  552. ;; try requote properly.
  553. (let ((qstr (funcall qfun completion)))
  554. (cons qstr (length qstr))))))
  555. (defun completion--string-equal-p (s1 s2)
  556. (eq t (compare-strings s1 nil nil s2 nil nil 'ignore-case)))
  557. (defun completion--twq-all (string ustring completions boundary
  558. _unquote requote)
  559. (when completions
  560. (pcase-let*
  561. ((prefix
  562. (let ((completion-regexp-list nil))
  563. (try-completion "" (cons (substring ustring boundary)
  564. completions))))
  565. (`(,qfullpos . ,qfun)
  566. (funcall requote (+ boundary (length prefix)) string))
  567. (qfullprefix (substring string 0 qfullpos))
  568. ;; FIXME: This assertion can be wrong, e.g. in Cygwin, where
  569. ;; (unquote "c:\bin") => "/usr/bin" but (unquote "c:\") => "/".
  570. ;;(cl-assert (completion--string-equal-p
  571. ;; (funcall unquote qfullprefix)
  572. ;; (concat (substring ustring 0 boundary) prefix))
  573. ;; t))
  574. (qboundary (car (funcall requote boundary string)))
  575. (_ (cl-assert (<= qboundary qfullpos)))
  576. ;; FIXME: this split/quote/concat business messes up the carefully
  577. ;; placed completions-common-part and completions-first-difference
  578. ;; faces. We could try within the mapcar loop to search for the
  579. ;; boundaries of those faces, pass them to `requote' to find their
  580. ;; equivalent positions in the quoted output and re-add the faces:
  581. ;; this might actually lead to correct results but would be
  582. ;; pretty expensive.
  583. ;; The better solution is to not quote the *Completions* display,
  584. ;; which nicely circumvents the problem. The solution I used here
  585. ;; instead is to hope that `qfun' preserves the text-properties and
  586. ;; presume that the `first-difference' is not within the `prefix';
  587. ;; this presumption is not always true, but at least in practice it is
  588. ;; true in most cases.
  589. (qprefix (propertize (substring qfullprefix qboundary)
  590. 'face 'completions-common-part)))
  591. ;; Here we choose to quote all elements returned, but a better option
  592. ;; would be to return unquoted elements together with a function to
  593. ;; requote them, so that *Completions* can show nicer unquoted values
  594. ;; which only get quoted when needed by choose-completion.
  595. (nconc
  596. (mapcar (lambda (completion)
  597. (cl-assert (string-prefix-p prefix completion 'ignore-case) t)
  598. (let* ((new (substring completion (length prefix)))
  599. (qnew (funcall qfun new))
  600. (qprefix
  601. (if (not completion-ignore-case)
  602. qprefix
  603. ;; Make qprefix inherit the case from `completion'.
  604. (let* ((rest (substring completion
  605. 0 (length prefix)))
  606. (qrest (funcall qfun rest)))
  607. (if (completion--string-equal-p qprefix qrest)
  608. (propertize qrest 'face
  609. 'completions-common-part)
  610. qprefix))))
  611. (qcompletion (concat qprefix qnew)))
  612. ;; FIXME: Similarly here, Cygwin's mapping trips this
  613. ;; assertion.
  614. ;;(cl-assert
  615. ;; (completion--string-equal-p
  616. ;; (funcall unquote
  617. ;; (concat (substring string 0 qboundary)
  618. ;; qcompletion))
  619. ;; (concat (substring ustring 0 boundary)
  620. ;; completion))
  621. ;; t)
  622. qcompletion))
  623. completions)
  624. qboundary))))
  625. ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
  626. ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
  627. (define-obsolete-function-alias
  628. 'complete-in-turn 'completion-table-in-turn "23.1")
  629. (define-obsolete-function-alias
  630. 'dynamic-completion-table 'completion-table-dynamic "23.1")
  631. ;;; Minibuffer completion
  632. (defgroup minibuffer nil
  633. "Controlling the behavior of the minibuffer."
  634. :link '(custom-manual "(emacs)Minibuffer")
  635. :group 'environment)
  636. (defun minibuffer-message (message &rest args)
  637. "Temporarily display MESSAGE at the end of the minibuffer.
  638. The text is displayed for `minibuffer-message-timeout' seconds,
  639. or until the next input event arrives, whichever comes first.
  640. Enclose MESSAGE in [...] if this is not yet the case.
  641. If ARGS are provided, then pass MESSAGE through `format-message'."
  642. (if (not (minibufferp (current-buffer)))
  643. (progn
  644. (if args
  645. (apply 'message message args)
  646. (message "%s" message))
  647. (prog1 (sit-for (or minibuffer-message-timeout 1000000))
  648. (message nil)))
  649. ;; Clear out any old echo-area message to make way for our new thing.
  650. (message nil)
  651. (setq message (if (and (null args)
  652. (string-match-p "\\` *\\[.+\\]\\'" message))
  653. ;; Make sure we can put-text-property.
  654. (copy-sequence message)
  655. (concat " [" message "]")))
  656. (when args (setq message (apply #'format-message message args)))
  657. (let ((ol (make-overlay (point-max) (point-max) nil t t))
  658. ;; A quit during sit-for normally only interrupts the sit-for,
  659. ;; but since minibuffer-message is used at the end of a command,
  660. ;; at a time when the command has virtually finished already, a C-g
  661. ;; should really cause an abort-recursive-edit instead (i.e. as if
  662. ;; the C-g had been typed at top-level). Binding inhibit-quit here
  663. ;; is an attempt to get that behavior.
  664. (inhibit-quit t))
  665. (unwind-protect
  666. (progn
  667. (unless (zerop (length message))
  668. ;; The current C cursor code doesn't know to use the overlay's
  669. ;; marker's stickiness to figure out whether to place the cursor
  670. ;; before or after the string, so let's spoon-feed it the pos.
  671. (put-text-property 0 1 'cursor t message))
  672. (overlay-put ol 'after-string message)
  673. (sit-for (or minibuffer-message-timeout 1000000)))
  674. (delete-overlay ol)))))
  675. (defun minibuffer-completion-contents ()
  676. "Return the user input in a minibuffer before point as a string.
  677. In Emacs-22, that was what completion commands operated on."
  678. (declare (obsolete nil "24.4"))
  679. (buffer-substring (minibuffer-prompt-end) (point)))
  680. (defun delete-minibuffer-contents ()
  681. "Delete all user input in a minibuffer.
  682. If the current buffer is not a minibuffer, erase its entire contents."
  683. (interactive)
  684. ;; We used to do `delete-field' here, but when file name shadowing
  685. ;; is on, the field doesn't cover the entire minibuffer contents.
  686. (delete-region (minibuffer-prompt-end) (point-max)))
  687. (defvar completion-show-inline-help t
  688. "If non-nil, print helpful inline messages during completion.")
  689. (defcustom completion-auto-help t
  690. "Non-nil means automatically provide help for invalid completion input.
  691. If the value is t the *Completions* buffer is displayed whenever completion
  692. is requested but cannot be done.
  693. If the value is `lazy', the *Completions* buffer is only displayed after
  694. the second failed attempt to complete."
  695. :type '(choice (const nil) (const t) (const lazy)))
  696. (defconst completion-styles-alist
  697. '((emacs21
  698. completion-emacs21-try-completion completion-emacs21-all-completions
  699. "Simple prefix-based completion.
  700. I.e. when completing \"foo_bar\" (where _ is the position of point),
  701. it will consider all completions candidates matching the glob
  702. pattern \"foobar*\".")
  703. (emacs22
  704. completion-emacs22-try-completion completion-emacs22-all-completions
  705. "Prefix completion that only operates on the text before point.
  706. I.e. when completing \"foo_bar\" (where _ is the position of point),
  707. it will consider all completions candidates matching the glob
  708. pattern \"foo*\" and will add back \"bar\" to the end of it.")
  709. (basic
  710. completion-basic-try-completion completion-basic-all-completions
  711. "Completion of the prefix before point and the suffix after point.
  712. I.e. when completing \"foo_bar\" (where _ is the position of point),
  713. it will consider all completions candidates matching the glob
  714. pattern \"foo*bar*\".")
  715. (partial-completion
  716. completion-pcm-try-completion completion-pcm-all-completions
  717. "Completion of multiple words, each one taken as a prefix.
  718. I.e. when completing \"l-co_h\" (where _ is the position of point),
  719. it will consider all completions candidates matching the glob
  720. pattern \"l*-co*h*\".
  721. Furthermore, for completions that are done step by step in subfields,
  722. the method is applied to all the preceding fields that do not yet match.
  723. E.g. C-x C-f /u/mo/s TAB could complete to /usr/monnier/src.
  724. Additionally the user can use the char \"*\" as a glob pattern.")
  725. (substring
  726. completion-substring-try-completion completion-substring-all-completions
  727. "Completion of the string taken as a substring.
  728. I.e. when completing \"foo_bar\" (where _ is the position of point),
  729. it will consider all completions candidates matching the glob
  730. pattern \"*foo*bar*\".")
  731. (initials
  732. completion-initials-try-completion completion-initials-all-completions
  733. "Completion of acronyms and initialisms.
  734. E.g. can complete M-x lch to list-command-history
  735. and C-x C-f ~/sew to ~/src/emacs/work."))
  736. "List of available completion styles.
  737. Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS DOC):
  738. where NAME is the name that should be used in `completion-styles',
  739. TRY-COMPLETION is the function that does the completion (it should
  740. follow the same calling convention as `completion-try-completion'),
  741. ALL-COMPLETIONS is the function that lists the completions (it should
  742. follow the calling convention of `completion-all-completions'),
  743. and DOC describes the way this style of completion works.")
  744. (defconst completion--styles-type
  745. `(repeat :tag "insert a new menu to add more styles"
  746. (choice ,@(mapcar (lambda (x) (list 'const (car x)))
  747. completion-styles-alist))))
  748. (defconst completion--cycling-threshold-type
  749. '(choice (const :tag "No cycling" nil)
  750. (const :tag "Always cycle" t)
  751. (integer :tag "Threshold")))
  752. (defcustom completion-styles
  753. ;; First, use `basic' because prefix completion has been the standard
  754. ;; for "ever" and works well in most cases, so using it first
  755. ;; ensures that we obey previous behavior in most cases.
  756. '(basic
  757. ;; Then use `partial-completion' because it has proven to
  758. ;; be a very convenient extension.
  759. partial-completion
  760. ;; Finally use `emacs22' so as to maintain (in many/most cases)
  761. ;; the previous behavior that when completing "foobar" with point
  762. ;; between "foo" and "bar" the completion try to complete "foo"
  763. ;; and simply add "bar" to the end of the result.
  764. emacs22)
  765. "List of completion styles to use.
  766. The available styles are listed in `completion-styles-alist'.
  767. Note that `completion-category-overrides' may override these
  768. styles for specific categories, such as files, buffers, etc."
  769. :type completion--styles-type
  770. :version "23.1")
  771. (defvar completion-category-defaults
  772. '((buffer (styles . (basic substring)))
  773. (unicode-name (styles . (basic substring)))
  774. (project-file (styles . (basic substring)))
  775. (info-menu (styles . (basic substring))))
  776. "Default settings for specific completion categories.
  777. Each entry has the shape (CATEGORY . ALIST) where ALIST is
  778. an association list that can specify properties such as:
  779. - `styles': the list of `completion-styles' to use for that category.
  780. - `cycle': the `completion-cycle-threshold' to use for that category.
  781. Categories are symbols such as `buffer' and `file', used when
  782. completing buffer and file names, respectively.")
  783. (defcustom completion-category-overrides nil
  784. "List of category-specific user overrides for completion styles.
  785. Each override has the shape (CATEGORY . ALIST) where ALIST is
  786. an association list that can specify properties such as:
  787. - `styles': the list of `completion-styles' to use for that category.
  788. - `cycle': the `completion-cycle-threshold' to use for that category.
  789. Categories are symbols such as `buffer' and `file', used when
  790. completing buffer and file names, respectively.
  791. This overrides the defaults specified in `completion-category-defaults'."
  792. :version "25.1"
  793. :type `(alist :key-type (choice :tag "Category"
  794. (const buffer)
  795. (const file)
  796. (const unicode-name)
  797. (const bookmark)
  798. symbol)
  799. :value-type
  800. (set :tag "Properties to override"
  801. (cons :tag "Completion Styles"
  802. (const :tag "Select a style from the menu;" styles)
  803. ,completion--styles-type)
  804. (cons :tag "Completion Cycling"
  805. (const :tag "Select one value from the menu." cycle)
  806. ,completion--cycling-threshold-type))))
  807. (defun completion--category-override (category tag)
  808. (or (assq tag (cdr (assq category completion-category-overrides)))
  809. (assq tag (cdr (assq category completion-category-defaults)))))
  810. (defun completion--styles (metadata)
  811. (let* ((cat (completion-metadata-get metadata 'category))
  812. (over (completion--category-override cat 'styles)))
  813. (if over
  814. (delete-dups (append (cdr over) (copy-sequence completion-styles)))
  815. completion-styles)))
  816. (defun completion--nth-completion (n string table pred point metadata)
  817. "Call the Nth method of completion styles."
  818. (unless metadata
  819. (setq metadata
  820. (completion-metadata (substring string 0 point) table pred)))
  821. ;; We provide special support for quoting/unquoting here because it cannot
  822. ;; reliably be done within the normal completion-table routines: Completion
  823. ;; styles such as `substring' or `partial-completion' need to match the
  824. ;; output of all-completions with the user's input, and since most/all
  825. ;; quoting mechanisms allow several equivalent quoted forms, the
  826. ;; completion-style can't do this matching (e.g. `substring' doesn't know
  827. ;; that "\a\b\e" is a valid (quoted) substring of "label").
  828. ;; The quote/unquote function needs to come from the completion table (rather
  829. ;; than from completion-extra-properties) because it may apply only to some
  830. ;; part of the string (e.g. substitute-in-file-name).
  831. (let ((requote
  832. (when (completion-metadata-get metadata 'completion--unquote-requote)
  833. (cl-assert (functionp table))
  834. (let ((new (funcall table string point 'completion--unquote)))
  835. (setq string (pop new))
  836. (setq table (pop new))
  837. (setq point (pop new))
  838. (cl-assert (<= point (length string)))
  839. (pop new))))
  840. (result
  841. (completion--some (lambda (style)
  842. (funcall (nth n (assq style
  843. completion-styles-alist))
  844. string table pred point))
  845. (completion--styles metadata))))
  846. (if requote
  847. (funcall requote result n)
  848. result)))
  849. (defun completion-try-completion (string table pred point &optional metadata)
  850. "Try to complete STRING using completion table TABLE.
  851. Only the elements of table that satisfy predicate PRED are considered.
  852. POINT is the position of point within STRING.
  853. The return value can be either nil to indicate that there is no completion,
  854. t to indicate that STRING is the only possible completion,
  855. or a pair (NEWSTRING . NEWPOINT) of the completed result string together with
  856. a new position for point."
  857. (completion--nth-completion 1 string table pred point metadata))
  858. (defun completion-all-completions (string table pred point &optional metadata)
  859. "List the possible completions of STRING in completion table TABLE.
  860. Only the elements of table that satisfy predicate PRED are considered.
  861. POINT is the position of point within STRING.
  862. The return value is a list of completions and may contain the base-size
  863. in the last `cdr'."
  864. ;; FIXME: We need to additionally return the info needed for the
  865. ;; second part of completion-base-position.
  866. (completion--nth-completion 2 string table pred point metadata))
  867. (defun minibuffer--bitset (modified completions exact)
  868. (logior (if modified 4 0)
  869. (if completions 2 0)
  870. (if exact 1 0)))
  871. (defun completion--replace (beg end newtext)
  872. "Replace the buffer text between BEG and END with NEWTEXT.
  873. Moves point to the end of the new text."
  874. ;; The properties on `newtext' include things like
  875. ;; completions-first-difference, which we don't want to include
  876. ;; upon insertion.
  877. (set-text-properties 0 (length newtext) nil newtext)
  878. ;; Maybe this should be in subr.el.
  879. ;; You'd think this is trivial to do, but details matter if you want
  880. ;; to keep markers "at the right place" and be robust in the face of
  881. ;; after-change-functions that may themselves modify the buffer.
  882. (let ((prefix-len 0))
  883. ;; Don't touch markers in the shared prefix (if any).
  884. (while (and (< prefix-len (length newtext))
  885. (< (+ beg prefix-len) end)
  886. (eq (char-after (+ beg prefix-len))
  887. (aref newtext prefix-len)))
  888. (setq prefix-len (1+ prefix-len)))
  889. (unless (zerop prefix-len)
  890. (setq beg (+ beg prefix-len))
  891. (setq newtext (substring newtext prefix-len))))
  892. (let ((suffix-len 0))
  893. ;; Don't touch markers in the shared suffix (if any).
  894. (while (and (< suffix-len (length newtext))
  895. (< beg (- end suffix-len))
  896. (eq (char-before (- end suffix-len))
  897. (aref newtext (- (length newtext) suffix-len 1))))
  898. (setq suffix-len (1+ suffix-len)))
  899. (unless (zerop suffix-len)
  900. (setq end (- end suffix-len))
  901. (setq newtext (substring newtext 0 (- suffix-len))))
  902. (goto-char beg)
  903. (let ((length (- end beg))) ;Read `end' before we insert the text.
  904. (insert-and-inherit newtext)
  905. (delete-region (point) (+ (point) length)))
  906. (forward-char suffix-len)))
  907. (defcustom completion-cycle-threshold nil
  908. "Number of completion candidates below which cycling is used.
  909. Depending on this setting `completion-in-region' may use cycling,
  910. like `minibuffer-force-complete'.
  911. If nil, cycling is never used.
  912. If t, cycling is always used.
  913. If an integer, cycling is used so long as there are not more
  914. completion candidates than this number."
  915. :version "24.1"
  916. :type completion--cycling-threshold-type)
  917. (defun completion--cycle-threshold (metadata)
  918. (let* ((cat (completion-metadata-get metadata 'category))
  919. (over (completion--category-override cat 'cycle)))
  920. (if over (cdr over) completion-cycle-threshold)))
  921. (defvar-local completion-all-sorted-completions nil)
  922. (defvar-local completion--all-sorted-completions-location nil)
  923. (defvar completion-cycling nil)
  924. (defvar completion-fail-discreetly nil
  925. "If non-nil, stay quiet when there is no match.")
  926. (defun completion--message (msg)
  927. (if completion-show-inline-help
  928. (minibuffer-message msg)))
  929. (defun completion--do-completion (beg end &optional
  930. try-completion-function expect-exact)
  931. "Do the completion and return a summary of what happened.
  932. M = completion was performed, the text was Modified.
  933. C = there were available Completions.
  934. E = after completion we now have an Exact match.
  935. MCE
  936. 000 0 no possible completion
  937. 001 1 was already an exact and unique completion
  938. 010 2 no completion happened
  939. 011 3 was already an exact completion
  940. 100 4 ??? impossible
  941. 101 5 ??? impossible
  942. 110 6 some completion happened
  943. 111 7 completed to an exact completion
  944. TRY-COMPLETION-FUNCTION is a function to use in place of `try-completion'.
  945. EXPECT-EXACT, if non-nil, means that there is no need to tell the user
  946. when the buffer's text is already an exact match."
  947. (let* ((string (buffer-substring beg end))
  948. (md (completion--field-metadata beg))
  949. (comp (funcall (or try-completion-function
  950. 'completion-try-completion)
  951. string
  952. minibuffer-completion-table
  953. minibuffer-completion-predicate
  954. (- (point) beg)
  955. md)))
  956. (cond
  957. ((null comp)
  958. (minibuffer-hide-completions)
  959. (unless completion-fail-discreetly
  960. (ding)
  961. (completion--message "No match"))
  962. (minibuffer--bitset nil nil nil))
  963. ((eq t comp)
  964. (minibuffer-hide-completions)
  965. (goto-char end)
  966. (completion--done string 'finished
  967. (unless expect-exact "Sole completion"))
  968. (minibuffer--bitset nil nil t)) ;Exact and unique match.
  969. (t
  970. ;; `completed' should be t if some completion was done, which doesn't
  971. ;; include simply changing the case of the entered string. However,
  972. ;; for appearance, the string is rewritten if the case changes.
  973. (let* ((comp-pos (cdr comp))
  974. (completion (car comp))
  975. (completed (not (eq t (compare-strings completion nil nil
  976. string nil nil t))))
  977. (unchanged (eq t (compare-strings completion nil nil
  978. string nil nil nil))))
  979. (if unchanged
  980. (goto-char end)
  981. ;; Insert in minibuffer the chars we got.
  982. (completion--replace beg end completion)
  983. (setq end (+ beg (length completion))))
  984. ;; Move point to its completion-mandated destination.
  985. (forward-char (- comp-pos (length completion)))
  986. (if (not (or unchanged completed))
  987. ;; The case of the string changed, but that's all. We're not sure
  988. ;; whether this is a unique completion or not, so try again using
  989. ;; the real case (this shouldn't recurse again, because the next
  990. ;; time try-completion will return either t or the exact string).
  991. (completion--do-completion beg end
  992. try-completion-function expect-exact)
  993. ;; It did find a match. Do we match some possibility exactly now?
  994. (let* ((exact (test-completion completion
  995. minibuffer-completion-table
  996. minibuffer-completion-predicate))
  997. (threshold (completion--cycle-threshold md))
  998. (comps
  999. ;; Check to see if we want to do cycling. We do it
  1000. ;; here, after having performed the normal completion,
  1001. ;; so as to take advantage of the difference between
  1002. ;; try-completion and all-completions, for things
  1003. ;; like completion-ignored-extensions.
  1004. (when (and threshold
  1005. ;; Check that the completion didn't make
  1006. ;; us jump to a different boundary.
  1007. (or (not completed)
  1008. (< (car (completion-boundaries
  1009. (substring completion 0 comp-pos)
  1010. minibuffer-completion-table
  1011. minibuffer-completion-predicate
  1012. ""))
  1013. comp-pos)))
  1014. (completion-all-sorted-completions beg end))))
  1015. (completion--flush-all-sorted-completions)
  1016. (cond
  1017. ((and (consp (cdr comps)) ;; There's something to cycle.
  1018. (not (ignore-errors
  1019. ;; This signal an (intended) error if comps is too
  1020. ;; short or if completion-cycle-threshold is t.
  1021. (consp (nthcdr threshold comps)))))
  1022. ;; Not more than completion-cycle-threshold remaining
  1023. ;; completions: let's cycle.
  1024. (setq completed t exact t)
  1025. (completion--cache-all-sorted-completions beg end comps)
  1026. (minibuffer-force-complete beg end))
  1027. (completed
  1028. ;; We could also decide to refresh the completions,
  1029. ;; if they're displayed (and assuming there are
  1030. ;; completions left).
  1031. (minibuffer-hide-completions)
  1032. (if exact
  1033. ;; If completion did not put point at end of field,
  1034. ;; it's a sign that completion is not finished.
  1035. (completion--done completion
  1036. (if (< comp-pos (length completion))
  1037. 'exact 'unknown))))
  1038. ;; Show the completion table, if requested.
  1039. ((not exact)
  1040. (if (pcase completion-auto-help
  1041. (`lazy (eq this-command last-command))
  1042. (_ completion-auto-help))
  1043. (minibuffer-completion-help beg end)
  1044. (completion--message "Next char not unique")))
  1045. ;; If the last exact completion and this one were the same, it
  1046. ;; means we've already given a "Complete, but not unique" message
  1047. ;; and the user's hit TAB again, so now we give him help.
  1048. (t
  1049. (if (and (eq this-command last-command) completion-auto-help)
  1050. (minibuffer-completion-help beg end))
  1051. (completion--done completion 'exact
  1052. (unless expect-exact
  1053. "Complete, but not unique"))))
  1054. (minibuffer--bitset completed t exact))))))))
  1055. (defun minibuffer-complete ()
  1056. "Complete the minibuffer contents as far as possible.
  1057. Return nil if there is no valid completion, else t.
  1058. If no characters can be completed, display a list of possible completions.
  1059. If you repeat this command after it displayed such a list,
  1060. scroll the window of possible completions."
  1061. (interactive)
  1062. (when (<= (minibuffer-prompt-end) (point))
  1063. (completion-in-region (minibuffer-prompt-end) (point-max)
  1064. minibuffer-completion-table
  1065. minibuffer-completion-predicate)))
  1066. (defun completion--in-region-1 (beg end)
  1067. ;; If the previous command was not this,
  1068. ;; mark the completion buffer obsolete.
  1069. (setq this-command 'completion-at-point)
  1070. (unless (eq 'completion-at-point last-command)
  1071. (completion--flush-all-sorted-completions)
  1072. (setq minibuffer-scroll-window nil))
  1073. (cond
  1074. ;; If there's a fresh completion window with a live buffer,
  1075. ;; and this command is repeated, scroll that window.
  1076. ((and (window-live-p minibuffer-scroll-window)
  1077. (eq t (frame-visible-p (window-frame minibuffer-scroll-window))))
  1078. (let ((window minibuffer-scroll-window))
  1079. (with-current-buffer (window-buffer window)
  1080. (if (pos-visible-in-window-p (point-max) window)
  1081. ;; If end is in view, scroll up to the beginning.
  1082. (set-window-start window (point-min) nil)
  1083. ;; Else scroll down one screen.
  1084. (with-selected-window window
  1085. (scroll-up)))
  1086. nil)))
  1087. ;; If we're cycling, keep on cycling.
  1088. ((and completion-cycling completion-all-sorted-completions)
  1089. (minibuffer-force-complete beg end)
  1090. t)
  1091. (t (pcase (completion--do-completion beg end)
  1092. (#b000 nil)
  1093. (_ t)))))
  1094. (defun completion--cache-all-sorted-completions (beg end comps)
  1095. (add-hook 'after-change-functions
  1096. 'completion--flush-all-sorted-completions nil t)
  1097. (setq completion--all-sorted-completions-location
  1098. (cons (copy-marker beg) (copy-marker end)))
  1099. (setq completion-all-sorted-completions comps))
  1100. (defun completion--flush-all-sorted-completions (&optional start end _len)
  1101. (unless (and start end
  1102. (or (> start (cdr completion--all-sorted-completions-location))
  1103. (< end (car completion--all-sorted-completions-location))))
  1104. (remove-hook 'after-change-functions
  1105. 'completion--flush-all-sorted-completions t)
  1106. (setq completion-cycling nil)
  1107. (setq completion-all-sorted-completions nil)))
  1108. (defun completion--metadata (string base md-at-point table pred)
  1109. ;; Like completion-metadata, but for the specific case of getting the
  1110. ;; metadata at `base', which tends to trigger pathological behavior for old
  1111. ;; completion tables which don't understand `metadata'.
  1112. (let ((bounds (completion-boundaries string table pred "")))
  1113. (if (eq (car bounds) base) md-at-point
  1114. (completion-metadata (substring string 0 base) table pred))))
  1115. (defun completion-all-sorted-completions (&optional start end)
  1116. (or completion-all-sorted-completions
  1117. (let* ((start (or start (minibuffer-prompt-end)))
  1118. (end (or end (point-max)))
  1119. (string (buffer-substring start end))
  1120. (md (completion--field-metadata start))
  1121. (all (completion-all-completions
  1122. string
  1123. minibuffer-completion-table
  1124. minibuffer-completion-predicate
  1125. (- (point) start)
  1126. md))
  1127. (last (last all))
  1128. (base-size (or (cdr last) 0))
  1129. (all-md (completion--metadata (buffer-substring-no-properties
  1130. start (point))
  1131. base-size md
  1132. minibuffer-completion-table
  1133. minibuffer-completion-predicate))
  1134. (sort-fun (completion-metadata-get all-md 'cycle-sort-function)))
  1135. (when last
  1136. (setcdr last nil)
  1137. ;; Delete duplicates: do it after setting last's cdr to nil (so
  1138. ;; it's a proper list), and be careful to reset `last' since it
  1139. ;; may be a different cons-cell.
  1140. (setq all (delete-dups all))
  1141. (setq last (last all))
  1142. (setq all (if sort-fun (funcall sort-fun all)
  1143. ;; Prefer shorter completions, by default.
  1144. (sort all (lambda (c1 c2) (< (length c1) (length c2))))))
  1145. ;; Prefer recently used completions.
  1146. (when (minibufferp)
  1147. (let ((hist (symbol-value minibuffer-history-variable)))
  1148. (setq all (sort all (lambda (c1 c2)
  1149. (> (length (member c1 hist))
  1150. (length (member c2 hist))))))))
  1151. ;; Cache the result. This is not just for speed, but also so that
  1152. ;; repeated calls to minibuffer-force-complete can cycle through
  1153. ;; all possibilities.
  1154. (completion--cache-all-sorted-completions
  1155. start end (nconc all base-size))))))
  1156. (defun minibuffer-force-complete-and-exit ()
  1157. "Complete the minibuffer with first of the matches and exit."
  1158. (interactive)
  1159. (minibuffer-force-complete)
  1160. (completion--complete-and-exit
  1161. (minibuffer-prompt-end) (point-max) #'exit-minibuffer
  1162. ;; If the previous completion completed to an element which fails
  1163. ;; test-completion, then we shouldn't exit, but that should be rare.
  1164. (lambda () (minibuffer-message "Incomplete"))))
  1165. (defun minibuffer-force-complete (&optional start end)
  1166. "Complete the minibuffer to an exact match.
  1167. Repeated uses step through the possible completions."
  1168. (interactive)
  1169. (setq minibuffer-scroll-window nil)
  1170. ;; FIXME: Need to deal with the extra-size issue here as well.
  1171. ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
  1172. ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
  1173. (let* ((start (copy-marker (or start (minibuffer-prompt-end))))
  1174. (end (or end (point-max)))
  1175. ;; (md (completion--field-metadata start))
  1176. (all (completion-all-sorted-completions start end))
  1177. (base (+ start (or (cdr (last all)) 0))))
  1178. (cond
  1179. ((not (consp all))
  1180. (completion--message
  1181. (if all "No more completions" "No completions")))
  1182. ((not (consp (cdr all)))
  1183. (let ((done (equal (car all) (buffer-substring-no-properties base end))))
  1184. (unless done (completion--replace base end (car all)))
  1185. (completion--done (buffer-substring-no-properties start (point))
  1186. 'finished (when done "Sole completion"))))
  1187. (t
  1188. (completion--replace base end (car all))
  1189. (setq end (+ base (length (car all))))
  1190. (completion--done (buffer-substring-no-properties start (point)) 'sole)
  1191. ;; Set cycling after modifying the buffer since the flush hook resets it.
  1192. (setq completion-cycling t)
  1193. (setq this-command 'completion-at-point) ;For completion-in-region.
  1194. ;; If completing file names, (car all) may be a directory, so we'd now
  1195. ;; have a new set of possible completions and might want to reset
  1196. ;; completion-all-sorted-completions to nil, but we prefer not to,
  1197. ;; so that repeated calls minibuffer-force-complete still cycle
  1198. ;; through the previous possible completions.
  1199. (let ((last (last all)))
  1200. (setcdr last (cons (car all) (cdr last)))
  1201. (completion--cache-all-sorted-completions start end (cdr all)))
  1202. ;; Make sure repeated uses cycle, even though completion--done might
  1203. ;; have added a space or something that moved us outside of the field.
  1204. ;; (bug#12221).
  1205. (let* ((table minibuffer-completion-table)
  1206. (pred minibuffer-completion-predicate)
  1207. (extra-prop completion-extra-properties)
  1208. (cmd
  1209. (lambda () "Cycle through the possible completions."
  1210. (interactive)
  1211. (let ((completion-extra-properties extra-prop))
  1212. (completion-in-region start (point) table pred)))))
  1213. (set-transient-map
  1214. (let ((map (make-sparse-keymap)))
  1215. (define-key map [remap completion-at-point] cmd)
  1216. (define-key map (vector last-command-event) cmd)
  1217. map)))))))
  1218. (defvar minibuffer-confirm-exit-commands
  1219. '(completion-at-point minibuffer-complete
  1220. minibuffer-complete-word PC-complete PC-complete-word)
  1221. "A list of commands which cause an immediately following
  1222. `minibuffer-complete-and-exit' to ask for extra confirmation.")
  1223. (defun minibuffer-complete-and-exit ()
  1224. "Exit if the minibuffer contains a valid completion.
  1225. Otherwise, try to complete the minibuffer contents. If
  1226. completion leads to a valid completion, a repetition of this
  1227. command will exit.
  1228. If `minibuffer-completion-confirm' is `confirm', do not try to
  1229. complete; instead, ask for confirmation and accept any input if
  1230. confirmed.
  1231. If `minibuffer-completion-confirm' is `confirm-after-completion',
  1232. do not try to complete; instead, ask for confirmation if the
  1233. preceding minibuffer command was a member of
  1234. `minibuffer-confirm-exit-commands', and accept the input
  1235. otherwise."
  1236. (interactive)
  1237. (completion-complete-and-exit (minibuffer-prompt-end) (point-max)
  1238. #'exit-minibuffer))
  1239. (defun completion-complete-and-exit (beg end exit-function)
  1240. (completion--complete-and-exit
  1241. beg end exit-function
  1242. (lambda ()
  1243. (pcase (condition-case nil
  1244. (completion--do-completion beg end
  1245. nil 'expect-exact)
  1246. (error 1))
  1247. ((or #b001 #b011) (funcall exit-function))
  1248. (#b111 (if (not minibuffer-completion-confirm)
  1249. (funcall exit-function)
  1250. (minibuffer-message "Confirm")
  1251. nil))
  1252. (_ nil)))))
  1253. (defun completion--complete-and-exit (beg end
  1254. exit-function completion-function)
  1255. "Exit from `require-match' minibuffer.
  1256. COMPLETION-FUNCTION is called if the current buffer's content does not
  1257. appear to be a match."
  1258. (cond
  1259. ;; Allow user to specify null string
  1260. ((= beg end) (funcall exit-function))
  1261. ((test-completion (buffer-substring beg end)
  1262. minibuffer-completion-table
  1263. minibuffer-completion-predicate)
  1264. ;; FIXME: completion-ignore-case has various slightly
  1265. ;; incompatible meanings. E.g. it can reflect whether the user
  1266. ;; wants completion to pay attention to case, or whether the
  1267. ;; string will be used in a context where case is significant.
  1268. ;; E.g. usually try-completion should obey the first, whereas
  1269. ;; test-completion should obey the second.
  1270. (when completion-ignore-case
  1271. ;; Fixup case of the field, if necessary.
  1272. (let* ((string (buffer-substring beg end))
  1273. (compl (try-completion
  1274. string
  1275. minibuffer-completion-table
  1276. minibuffer-completion-predicate)))
  1277. (when (and (stringp compl) (not (equal string compl))
  1278. ;; If it weren't for this piece of paranoia, I'd replace
  1279. ;; the whole thing with a call to do-completion.
  1280. ;; This is important, e.g. when the current minibuffer's
  1281. ;; content is a directory which only contains a single
  1282. ;; file, so `try-completion' actually completes to
  1283. ;; that file.
  1284. (= (length string) (length compl)))
  1285. (completion--replace beg end compl))))
  1286. (funcall exit-function))
  1287. ((memq minibuffer-completion-confirm '(confirm confirm-after-completion))
  1288. ;; The user is permitted to exit with an input that's rejected
  1289. ;; by test-completion, after confirming her choice.
  1290. (if (or (eq last-command this-command)
  1291. ;; For `confirm-after-completion' we only ask for confirmation
  1292. ;; if trying to exit immediately after typing TAB (this
  1293. ;; catches most minibuffer typos).
  1294. (and (eq minibuffer-completion-confirm 'confirm-after-completion)
  1295. (not (memq last-command minibuffer-confirm-exit-commands))))
  1296. (funcall exit-function)
  1297. (minibuffer-message "Confirm")
  1298. nil))
  1299. (t
  1300. ;; Call do-completion, but ignore errors.
  1301. (funcall completion-function))))
  1302. (defun completion--try-word-completion (string table predicate point md)
  1303. (let ((comp (completion-try-completion string table predicate point md)))
  1304. (if (not (consp comp))
  1305. comp
  1306. ;; If completion finds next char not unique,
  1307. ;; consider adding a space or a hyphen.
  1308. (when (= (length string) (length (car comp)))
  1309. ;; Mark the added char with the `completion-word' property, so it
  1310. ;; can be handled specially by completion styles such as
  1311. ;; partial-completion.
  1312. ;; We used to remove `partial-completion' from completion-styles
  1313. ;; instead, but it was too blunt, leading to situations where SPC
  1314. ;; was the only insertable char at point but minibuffer-complete-word
  1315. ;; refused inserting it.
  1316. (let ((exts (mapcar (lambda (str) (propertize str 'completion-try-word t))
  1317. '(" " "-")))
  1318. (before (substring string 0 point))
  1319. (after (substring string point))
  1320. tem)
  1321. ;; If both " " and "-" lead to completions, prefer " " so SPC behaves
  1322. ;; a bit more like a self-inserting key (bug#17375).
  1323. (while (and exts (not (consp tem)))
  1324. (setq tem (completion-try-completion
  1325. (concat before (pop exts) after)
  1326. table predicate (1+ point) md)))
  1327. (if (consp tem) (setq comp tem))))
  1328. ;; Completing a single word is actually more difficult than completing
  1329. ;; as much as possible, because we first have to find the "current
  1330. ;; position" in `completion' in order to find the end of the word
  1331. ;; we're completing. Normally, `string' is a prefix of `completion',
  1332. ;; which makes it trivial to find the position, but with fancier
  1333. ;; completion (plus env-var expansion, ...) `completion' might not
  1334. ;; look anything like `string' at all.
  1335. (let* ((comppoint (cdr comp))
  1336. (completion (car comp))
  1337. (before (substring string 0 point))
  1338. (combined (concat before "\n" completion)))
  1339. ;; Find in completion the longest text that was right before point.
  1340. (when (string-match "\\(.+\\)\n.*?\\1" combined)
  1341. (let* ((prefix (match-string 1 before))
  1342. ;; We used non-greedy match to make `rem' as long as possible.
  1343. (rem (substring combined (match-end 0)))
  1344. ;; Find in the remainder of completion the longest text
  1345. ;; that was right after point.
  1346. (after (substring string point))
  1347. (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
  1348. (concat after "\n" rem))
  1349. (match-string 1 after))))
  1350. ;; The general idea is to try and guess what text was inserted
  1351. ;; at point by the completion. Problem is: if we guess wrong,
  1352. ;; we may end up treating as "added by completion" text that was
  1353. ;; actually painfully typed by the user. So if we then cut
  1354. ;; after the first word, we may throw away things the
  1355. ;; user wrote. So let's try to be as conservative as possible:
  1356. ;; only cut after the first word, if we're reasonably sure that
  1357. ;; our guess is correct.
  1358. ;; Note: a quick survey on emacs-devel seemed to indicate that
  1359. ;; nobody actually cares about the "word-at-a-time" feature of
  1360. ;; minibuffer-complete-word, whose real raison-d'être is that it
  1361. ;; tries to add "-" or " ". One more reason to only cut after
  1362. ;; the first word, if we're really sure we're right.
  1363. (when (and (or suffix (zerop (length after)))
  1364. (string-match (concat
  1365. ;; Make submatch 1 as small as possible
  1366. ;; to reduce the risk of cutting
  1367. ;; valuable text.
  1368. ".*" (regexp-quote prefix) "\\(.*?\\)"
  1369. (if suffix (regexp-quote suffix) "\\'"))
  1370. completion)
  1371. ;; The new point in `completion' should also be just
  1372. ;; before the suffix, otherwise something more complex
  1373. ;; is going on, and we're not sure where we are.
  1374. (eq (match-end 1) comppoint)
  1375. ;; (match-beginning 1)..comppoint is now the stretch
  1376. ;; of text in `completion' that was completed at point.
  1377. (string-match "\\W" completion (match-beginning 1))
  1378. ;; Is there really something to cut?
  1379. (> comppoint (match-end 0)))
  1380. ;; Cut after the first word.
  1381. (let ((cutpos (match-end 0)))
  1382. (setq completion (concat (substring completion 0 cutpos)
  1383. (substring completion comppoint)))
  1384. (setq comppoint cutpos)))))
  1385. (cons completion comppoint)))))
  1386. (defun minibuffer-complete-word ()
  1387. "Complete the minibuffer contents at most a single word.
  1388. After one word is completed as much as possible, a space or hyphen
  1389. is added, provided that matches some possible completion.
  1390. Return nil if there is no valid completion, else t."
  1391. (interactive)
  1392. (completion-in-region--single-word
  1393. (minibuffer-prompt-end) (point-max)
  1394. minibuffer-completion-table minibuffer-completion-predicate))
  1395. (defun completion-in-region--single-word (beg end collection
  1396. &optional predicate)
  1397. (let ((minibuffer-completion-table collection)
  1398. (minibuffer-completion-predicate predicate))
  1399. (pcase (completion--do-completion beg end
  1400. #'completion--try-word-completion)
  1401. (#b000 nil)
  1402. (_ t))))
  1403. (defface completions-annotations '((t :inherit italic))
  1404. "Face to use for annotations in the *Completions* buffer.")
  1405. (defcustom completions-format 'horizontal
  1406. "Define the appearance and sorting of completions.
  1407. If the value is `vertical', display completions sorted vertically
  1408. in columns in the *Completions* buffer.
  1409. If the value is `horizontal', display completions sorted
  1410. horizontally in alphabetical order, rather than down the screen."
  1411. :type '(choice (const horizontal) (const vertical))
  1412. :version "23.2")
  1413. (defun completion--insert-strings (strings)
  1414. "Insert a list of STRINGS into the current buffer.
  1415. Uses columns to keep the listing readable but compact.
  1416. It also eliminates runs of equal strings."
  1417. (when (consp strings)
  1418. (let* ((length (apply 'max
  1419. (mapcar (lambda (s)
  1420. (if (consp s)
  1421. (+ (string-width (car s))
  1422. (string-width (cadr s)))
  1423. (string-width s)))
  1424. strings)))
  1425. (window (get-buffer-window (current-buffer) 0))
  1426. (wwidth (if window (1- (window-width window)) 79))
  1427. (columns (min
  1428. ;; At least 2 columns; at least 2 spaces between columns.
  1429. (max 2 (/ wwidth (+ 2 length)))
  1430. ;; Don't allocate more columns than we can fill.
  1431. ;; Windows can't show less than 3 lines anyway.
  1432. (max 1 (/ (length strings) 2))))
  1433. (colwidth (/ wwidth columns))
  1434. (column 0)
  1435. (rows (/ (length strings) columns))
  1436. (row 0)
  1437. (first t)
  1438. (laststring nil))
  1439. ;; The insertion should be "sensible" no matter what choices were made
  1440. ;; for the parameters above.
  1441. (dolist (str strings)
  1442. (unless (equal laststring str) ; Remove (consecutive) duplicates.
  1443. (setq laststring str)
  1444. ;; FIXME: `string-width' doesn't pay attention to
  1445. ;; `display' properties.
  1446. (let ((length (if (consp str)
  1447. (+ (string-width (car str))
  1448. (string-width (cadr str)))
  1449. (string-width str))))
  1450. (cond
  1451. ((eq completions-format 'vertical)
  1452. ;; Vertical format
  1453. (when (> row rows)
  1454. (forward-line (- -1 rows))
  1455. (setq row 0 column (+ column colwidth)))
  1456. (when (> column 0)
  1457. (end-of-line)
  1458. (while (> (current-column) column)
  1459. (if (eobp)
  1460. (insert "\n")
  1461. (forward-line 1)
  1462. (end-of-line)))
  1463. (insert " \t")
  1464. (set-text-properties (1- (point)) (point)
  1465. `(display (space :align-to ,column)))))
  1466. (t
  1467. ;; Horizontal format
  1468. (unless first
  1469. (if (< wwidth (+ (max colwidth length) column))
  1470. ;; No space for `str' at point, move to next line.
  1471. (progn (insert "\n") (setq column 0))
  1472. (insert " \t")
  1473. ;; Leave the space unpropertized so that in the case we're
  1474. ;; already past the goal column, there is still
  1475. ;; a space displayed.
  1476. (set-text-properties (1- (point)) (point)
  1477. ;; We can't just set tab-width, because
  1478. ;; completion-setup-function will kill
  1479. ;; all local variables :-(
  1480. `(display (space :align-to ,column)))
  1481. nil))))
  1482. (setq first nil)
  1483. (if (not (consp str))
  1484. (put-text-property (point) (progn (insert str) (point))
  1485. 'mouse-face 'highlight)
  1486. (put-text-property (point) (progn (insert (car str)) (point))
  1487. 'mouse-face 'highlight)
  1488. (let ((beg (point))
  1489. (end (progn (insert (cadr str)) (point))))
  1490. (put-text-property beg end 'mouse-face nil)
  1491. (font-lock-prepend-text-property beg end 'face
  1492. 'completions-annotations)))
  1493. (cond
  1494. ((eq completions-format 'vertical)
  1495. ;; Vertical format
  1496. (if (> column 0)
  1497. (forward-line)
  1498. (insert "\n"))
  1499. (setq row (1+ row)))
  1500. (t
  1501. ;; Horizontal format
  1502. ;; Next column to align to.
  1503. (setq column (+ column
  1504. ;; Round up to a whole number of columns.
  1505. (* colwidth (ceiling length colwidth))))))))))))
  1506. (defvar completion-common-substring nil)
  1507. (make-obsolete-variable 'completion-common-substring nil "23.1")
  1508. (defvar completion-setup-hook nil
  1509. "Normal hook run at the end of setting up a completion list buffer.
  1510. When this hook is run, the current buffer is the one in which the
  1511. command to display the completion list buffer was run.
  1512. The completion list buffer is available as the value of `standard-output'.
  1513. See also `display-completion-list'.")
  1514. (defface completions-first-difference
  1515. '((t (:inherit bold)))
  1516. "Face for the first uncommon character in completions.
  1517. See also the face `completions-common-part'.")
  1518. (defface completions-common-part '((t nil))
  1519. "Face for the common prefix substring in completions.
  1520. The idea of this face is that you can use it to make the common parts
  1521. less visible than normal, so that the differing parts are emphasized
  1522. by contrast.
  1523. See also the face `completions-first-difference'.")
  1524. (defun completion-hilit-commonality (completions prefix-len &optional base-size)
  1525. "Apply font-lock highlighting to a list of completions, COMPLETIONS.
  1526. PREFIX-LEN is an integer. BASE-SIZE is an integer or nil (meaning zero).
  1527. This adds the face `completions-common-part' to the first
  1528. \(PREFIX-LEN - BASE-SIZE) characters of each completion, and the face
  1529. `completions-first-difference' to the first character after that.
  1530. It returns a list with font-lock properties applied to each element,
  1531. and with BASE-SIZE appended as the last element."
  1532. (when completions
  1533. (let ((com-str-len (- prefix-len (or base-size 0))))
  1534. (nconc
  1535. (mapcar
  1536. (lambda (elem)
  1537. (let ((str
  1538. ;; Don't modify the string itself, but a copy, since the
  1539. ;; the string may be read-only or used for other purposes.
  1540. ;; Furthermore, since `completions' may come from
  1541. ;; display-completion-list, `elem' may be a list.
  1542. (if (consp elem)
  1543. (car (setq elem (cons (copy-sequence (car elem))
  1544. (cdr elem))))
  1545. (setq elem (copy-sequence elem)))))
  1546. (font-lock-prepend-text-property
  1547. 0
  1548. ;; If completion-boundaries returns incorrect
  1549. ;; values, all-completions may return strings
  1550. ;; that don't contain the prefix.
  1551. (min com-str-len (length str))
  1552. 'face 'completions-common-part str)
  1553. (if (> (length str) com-str-len)
  1554. (font-lock-prepend-text-property com-str-len (1+ com-str-len)
  1555. 'face
  1556. 'completions-first-difference
  1557. str)))
  1558. elem)
  1559. completions)
  1560. base-size))))
  1561. (defun display-completion-list (completions &optional common-substring)
  1562. "Display the list of completions, COMPLETIONS, using `standard-output'.
  1563. Each element may be just a symbol or string
  1564. or may be a list of two strings to be printed as if concatenated.
  1565. If it is a list of two strings, the first is the actual completion
  1566. alternative, the second serves as annotation.
  1567. `standard-output' must be a buffer.
  1568. The actual completion alternatives, as inserted, are given `mouse-face'
  1569. properties of `highlight'.
  1570. At the end, this runs the normal hook `completion-setup-hook'.
  1571. It can find the completion buffer in `standard-output'."
  1572. (declare (advertised-calling-convention (completions) "24.4"))
  1573. (if common-substring
  1574. (setq completions (completion-hilit-commonality
  1575. completions (length common-substring)
  1576. ;; We don't know the base-size.
  1577. nil)))
  1578. (if (not (bufferp standard-output))
  1579. ;; This *never* (ever) happens, so there's no point trying to be clever.
  1580. (with-temp-buffer
  1581. (let ((standard-output (current-buffer))
  1582. (completion-setup-hook nil))
  1583. (display-completion-list completions common-substring))
  1584. (princ (buffer-string)))
  1585. (with-current-buffer standard-output
  1586. (goto-char (point-max))
  1587. (if (null completions)
  1588. (insert "There are no possible completions of what you have typed.")
  1589. (insert "Possible completions are:\n")
  1590. (completion--insert-strings completions))))
  1591. ;; The hilit used to be applied via completion-setup-hook, so there
  1592. ;; may still be some code that uses completion-common-substring.
  1593. (with-no-warnings
  1594. (let ((completion-common-substring common-substring))
  1595. (run-hooks 'completion-setup-hook)))
  1596. nil)
  1597. (defvar completion-extra-properties nil
  1598. "Property list of extra properties of the current completion job.
  1599. These include:
  1600. `:annotation-function': Function to annotate the completions buffer.
  1601. The function must accept one argument, a completion string,
  1602. and return either nil or a string which is to be displayed
  1603. next to the completion (but which is not part of the
  1604. completion). The function can access the completion data via
  1605. `minibuffer-completion-table' and related variables.
  1606. `:exit-function': Function to run after completion is performed.
  1607. The function must accept two arguments, STRING and STATUS.
  1608. STRING is the text to which the field was completed, and
  1609. STATUS indicates what kind of operation happened:
  1610. `finished' - text is now complete
  1611. `sole' - text cannot be further completed but
  1612. completion is not finished
  1613. `exact' - text is a valid completion but may be further
  1614. completed.")
  1615. (defvar completion-annotate-function
  1616. nil
  1617. ;; Note: there's a lot of scope as for when to add annotations and
  1618. ;; what annotations to add. E.g. completing-help.el allowed adding
  1619. ;; the first line of docstrings to M-x completion. But there's
  1620. ;; a tension, since such annotations, while useful at times, can
  1621. ;; actually drown the useful information.
  1622. ;; So completion-annotate-function should be used parsimoniously, or
  1623. ;; else only used upon a user's request (e.g. we could add a command
  1624. ;; to completion-list-mode to add annotations to the current
  1625. ;; completions).
  1626. "Function to add annotations in the *Completions* buffer.
  1627. The function takes a completion and should either return nil, or a string that
  1628. will be displayed next to the completion. The function can access the
  1629. completion table and predicates via `minibuffer-completion-table' and related
  1630. variables.")
  1631. (make-obsolete-variable 'completion-annotate-function
  1632. 'completion-extra-properties "24.1")
  1633. (defun completion--done (string &optional finished message)
  1634. (let* ((exit-fun (plist-get completion-extra-properties :exit-function))
  1635. (pre-msg (and exit-fun (current-message))))
  1636. (cl-assert (memq finished '(exact sole finished unknown)))
  1637. (when exit-fun
  1638. (when (eq finished 'unknown)
  1639. (setq finished
  1640. (if (eq (try-completion string
  1641. minibuffer-completion-table
  1642. minibuffer-completion-predicate)
  1643. t)
  1644. 'finished 'exact)))
  1645. (funcall exit-fun string finished))
  1646. (when (and message
  1647. ;; Don't output any message if the exit-fun already did so.
  1648. (equal pre-msg (and exit-fun (current-message))))
  1649. (completion--message message))))
  1650. (defun minibuffer-completion-help (&optional start end)
  1651. "Display a list of possible completions of the current minibuffer contents."
  1652. (interactive)
  1653. (message "Making completion list...")
  1654. (let* ((start (or start (minibuffer-prompt-end)))
  1655. (end (or end (point-max)))
  1656. (string (buffer-substring start end))
  1657. (md (completion--field-metadata start))
  1658. (completions (completion-all-completions
  1659. string
  1660. minibuffer-completion-table
  1661. minibuffer-completion-predicate
  1662. (- (point) start)
  1663. md)))
  1664. (message nil)
  1665. (if (or (null completions)
  1666. (and (not (consp (cdr completions)))
  1667. (equal (car completions) string)))
  1668. (progn
  1669. ;; If there are no completions, or if the current input is already
  1670. ;; the sole completion, then hide (previous&stale) completions.
  1671. (minibuffer-hide-completions)
  1672. (ding)
  1673. (minibuffer-message
  1674. (if completions "Sole completion" "No completions")))
  1675. (let* ((last (last completions))
  1676. (base-size (or (cdr last) 0))
  1677. (prefix (unless (zerop base-size) (substring string 0 base-size)))
  1678. (all-md (completion--metadata (buffer-substring-no-properties
  1679. start (point))
  1680. base-size md
  1681. minibuffer-completion-table
  1682. minibuffer-completion-predicate))
  1683. (afun (or (completion-metadata-get all-md 'annotation-function)
  1684. (plist-get completion-extra-properties
  1685. :annotation-function)
  1686. completion-annotate-function))
  1687. ;; If the *Completions* buffer is shown in a new
  1688. ;; window, mark it as softly-dedicated, so bury-buffer in
  1689. ;; minibuffer-hide-completions will know whether to
  1690. ;; delete the window or not.
  1691. (display-buffer-mark-dedicated 'soft)
  1692. ;; Disable `pop-up-windows' temporarily to allow
  1693. ;; `display-buffer--maybe-pop-up-frame-or-window'
  1694. ;; in the display actions below to pop up a frame
  1695. ;; if `pop-up-frames' is non-nil, but not to pop up a window.
  1696. (pop-up-windows nil))
  1697. (with-displayed-buffer-window
  1698. "*Completions*"
  1699. ;; This is a copy of `display-buffer-fallback-action'
  1700. ;; where `display-buffer-use-some-window' is replaced
  1701. ;; with `display-buffer-at-bottom'.
  1702. `((display-buffer--maybe-same-window
  1703. display-buffer-reuse-window
  1704. display-buffer--maybe-pop-up-frame-or-window
  1705. ;; Use `display-buffer-below-selected' for inline completions,
  1706. ;; but not in the minibuffer (e.g. in `eval-expression')
  1707. ;; for which `display-buffer-at-bottom' is used.
  1708. ,(if (eq (selected-window) (minibuffer-window))
  1709. 'display-buffer-at-bottom
  1710. 'display-buffer-below-selected))
  1711. ,(if temp-buffer-resize-mode
  1712. '(window-height . resize-temp-buffer-window)
  1713. '(window-height . fit-window-to-buffer))
  1714. ,(when temp-buffer-resize-mode
  1715. '(preserve-size . (nil . t))))
  1716. nil
  1717. ;; Remove the base-size tail because `sort' requires a properly
  1718. ;; nil-terminated list.
  1719. (when last (setcdr last nil))
  1720. (setq completions
  1721. ;; FIXME: This function is for the output of all-completions,
  1722. ;; not completion-all-completions. Often it's the same, but
  1723. ;; not always.
  1724. (let ((sort-fun (completion-metadata-get
  1725. all-md 'display-sort-function)))
  1726. (if sort-fun
  1727. (funcall sort-fun completions)
  1728. (sort completions 'string-lessp))))
  1729. (when afun
  1730. (setq completions
  1731. (mapcar (lambda (s)
  1732. (let ((ann (funcall afun s)))
  1733. (if ann (list s ann) s)))
  1734. completions)))
  1735. (with-current-buffer standard-output
  1736. (set (make-local-variable 'completion-base-position)
  1737. (list (+ start base-size)
  1738. ;; FIXME: We should pay attention to completion
  1739. ;; boundaries here, but currently
  1740. ;; completion-all-completions does not give us the
  1741. ;; necessary information.
  1742. end))
  1743. (set (make-local-variable 'completion-list-insert-choice-function)
  1744. (let ((ctable minibuffer-completion-table)
  1745. (cpred minibuffer-completion-predicate)
  1746. (cprops completion-extra-properties))
  1747. (lambda (start end choice)
  1748. (unless (or (zerop (length prefix))
  1749. (equal prefix
  1750. (buffer-substring-no-properties
  1751. (max (point-min)
  1752. (- start (length prefix)))
  1753. start)))
  1754. (message "*Completions* out of date"))
  1755. ;; FIXME: Use `md' to do quoting&terminator here.
  1756. (completion--replace start end choice)
  1757. (let* ((minibuffer-completion-table ctable)
  1758. (minibuffer-completion-predicate cpred)
  1759. (completion-extra-properties cprops)
  1760. (result (concat prefix choice))
  1761. (bounds (completion-boundaries
  1762. result ctable cpred "")))
  1763. ;; If the completion introduces a new field, then
  1764. ;; completion is not finished.
  1765. (completion--done result
  1766. (if (eq (car bounds) (length result))
  1767. 'exact 'finished)))))))
  1768. (display-completion-list completions))))
  1769. nil))
  1770. (defun minibuffer-hide-completions ()
  1771. "Get rid of an out-of-date *Completions* buffer."
  1772. ;; FIXME: We could/should use minibuffer-scroll-window here, but it
  1773. ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
  1774. (let ((win (get-buffer-window "*Completions*" 0)))
  1775. (if win (with-selected-window win (bury-buffer)))))
  1776. (defun exit-minibuffer ()
  1777. "Terminate this minibuffer argument."
  1778. (interactive)
  1779. ;; If the command that uses this has made modifications in the minibuffer,
  1780. ;; we don't want them to cause deactivation of the mark in the original
  1781. ;; buffer.
  1782. ;; A better solution would be to make deactivate-mark buffer-local
  1783. ;; (or to turn it into a list of buffers, ...), but in the mean time,
  1784. ;; this should do the trick in most cases.
  1785. (setq deactivate-mark nil)
  1786. (throw 'exit nil))
  1787. (defun self-insert-and-exit ()
  1788. "Terminate minibuffer input."
  1789. (interactive)
  1790. (if (characterp last-command-event)
  1791. (call-interactively 'self-insert-command)
  1792. (ding))
  1793. (exit-minibuffer))
  1794. (defvar completion-in-region-functions nil
  1795. "Wrapper hook around `completion--in-region'.
  1796. \(See `with-wrapper-hook' for details about wrapper hooks.)")
  1797. (make-obsolete-variable 'completion-in-region-functions
  1798. 'completion-in-region-function "24.4")
  1799. (defvar completion-in-region-function #'completion--in-region
  1800. "Function to perform the job of `completion-in-region'.
  1801. The function is called with 4 arguments: START END COLLECTION PREDICATE.
  1802. The arguments and expected return value are as specified for
  1803. `completion-in-region'.")
  1804. (defvar completion-in-region--data nil)
  1805. (defvar completion-in-region-mode-predicate nil
  1806. "Predicate to tell `completion-in-region-mode' when to exit.
  1807. It is called with no argument and should return nil when
  1808. `completion-in-region-mode' should exit (and hence pop down
  1809. the *Completions* buffer).")
  1810. (defvar completion-in-region-mode--predicate nil
  1811. "Copy of the value of `completion-in-region-mode-predicate'.
  1812. This holds the value `completion-in-region-mode-predicate' had when
  1813. we entered `completion-in-region-mode'.")
  1814. (defun completion-in-region (start end collection &optional predicate)
  1815. "Complete the text between START and END using COLLECTION.
  1816. Point needs to be somewhere between START and END.
  1817. PREDICATE (a function called with no arguments) says when to exit.
  1818. This calls the function that `completion-in-region-function' specifies
  1819. \(passing the same four arguments that it received) to do the work,
  1820. and returns whatever it does. The return value should be nil
  1821. if there was no valid completion, else t."
  1822. (cl-assert (<= start (point)) (<= (point) end))
  1823. (funcall completion-in-region-function start end collection predicate))
  1824. (defcustom read-file-name-completion-ignore-case
  1825. (if (memq system-type '(ms-dos windows-nt darwin cygwin))
  1826. t nil)
  1827. "Non-nil means when reading a file name completion ignores case."
  1828. :type 'boolean
  1829. :version "22.1")
  1830. (defun completion--in-region (start end collection &optional predicate)
  1831. "Default function to use for `completion-in-region-function'.
  1832. Its arguments and return value are as specified for `completion-in-region'.
  1833. Also respects the obsolete wrapper hook `completion-in-region-functions'.
  1834. \(See `with-wrapper-hook' for details about wrapper hooks.)"
  1835. (subr--with-wrapper-hook-no-warnings
  1836. ;; FIXME: Maybe we should use this hook to provide a "display
  1837. ;; completions" operation as well.
  1838. completion-in-region-functions (start end collection predicate)
  1839. (let ((minibuffer-completion-table collection)
  1840. (minibuffer-completion-predicate predicate))
  1841. ;; HACK: if the text we are completing is already in a field, we
  1842. ;; want the completion field to take priority (e.g. Bug#6830).
  1843. (when completion-in-region-mode-predicate
  1844. (setq completion-in-region--data
  1845. `(,(if (markerp start) start (copy-marker start))
  1846. ,(copy-marker end t) ,collection ,predicate))
  1847. (completion-in-region-mode 1))
  1848. (completion--in-region-1 start end))))
  1849. (defvar completion-in-region-mode-map
  1850. (let ((map (make-sparse-keymap)))
  1851. ;; FIXME: Only works if completion-in-region-mode was activated via
  1852. ;; completion-at-point called directly.
  1853. (define-key map "\M-?" 'completion-help-at-point)
  1854. (define-key map "\t" 'completion-at-point)
  1855. map)
  1856. "Keymap activated during `completion-in-region'.")
  1857. ;; It is difficult to know when to exit completion-in-region-mode (i.e. hide
  1858. ;; the *Completions*). Here's how previous packages did it:
  1859. ;; - lisp-mode: never.
  1860. ;; - comint: only do it if you hit SPC at the right time.
  1861. ;; - pcomplete: pop it down on SPC or after some time-delay.
  1862. ;; - semantic: use a post-command-hook check similar to this one.
  1863. (defun completion-in-region--postch ()
  1864. (or unread-command-events ;Don't pop down the completions in the middle of
  1865. ;mouse-drag-region/mouse-set-point.
  1866. (and completion-in-region--data
  1867. (and (eq (marker-buffer (nth 0 completion-in-region--data))
  1868. (current-buffer))
  1869. (>= (point) (nth 0 completion-in-region--data))
  1870. (<= (point)
  1871. (save-excursion
  1872. (goto-char (nth 1 completion-in-region--data))
  1873. (line-end-position)))
  1874. (funcall completion-in-region-mode--predicate)))
  1875. (completion-in-region-mode -1)))
  1876. ;; (defalias 'completion-in-region--prech 'completion-in-region--postch)
  1877. (defvar completion-in-region-mode nil) ;Explicit defvar, i.s.o defcustom.
  1878. (define-minor-mode completion-in-region-mode
  1879. "Transient minor mode used during `completion-in-region'."
  1880. :global t
  1881. :group 'minibuffer
  1882. ;; Prevent definition of a custom-variable since it makes no sense to
  1883. ;; customize this variable.
  1884. :variable completion-in-region-mode
  1885. ;; (remove-hook 'pre-command-hook #'completion-in-region--prech)
  1886. (remove-hook 'post-command-hook #'completion-in-region--postch)
  1887. (setq minor-mode-overriding-map-alist
  1888. (delq (assq 'completion-in-region-mode minor-mode-overriding-map-alist)
  1889. minor-mode-overriding-map-alist))
  1890. (if (null completion-in-region-mode)
  1891. (progn
  1892. (setq completion-in-region--data nil)
  1893. (unless (equal "*Completions*" (buffer-name (window-buffer)))
  1894. (minibuffer-hide-completions)))
  1895. ;; (add-hook 'pre-command-hook #'completion-in-region--prech)
  1896. (cl-assert completion-in-region-mode-predicate)
  1897. (setq completion-in-region-mode--predicate
  1898. completion-in-region-mode-predicate)
  1899. (add-hook 'post-command-hook #'completion-in-region--postch)
  1900. (push `(completion-in-region-mode . ,completion-in-region-mode-map)
  1901. minor-mode-overriding-map-alist)))
  1902. ;; Define-minor-mode added our keymap to minor-mode-map-alist, but we want it
  1903. ;; on minor-mode-overriding-map-alist instead.
  1904. (setq minor-mode-map-alist
  1905. (delq (assq 'completion-in-region-mode minor-mode-map-alist)
  1906. minor-mode-map-alist))
  1907. (defvar completion-at-point-functions '(tags-completion-at-point-function)
  1908. "Special hook to find the completion table for the entity at point.
  1909. Each function on this hook is called in turn without any argument and
  1910. should return either nil, meaning it is not applicable at point,
  1911. or a function of no arguments to perform completion (discouraged),
  1912. or a list of the form (START END COLLECTION . PROPS), where:
  1913. START and END delimit the entity to complete and should include point,
  1914. COLLECTION is the completion table to use to complete the entity, and
  1915. PROPS is a property list for additional information.
  1916. Currently supported properties are all the properties that can appear in
  1917. `completion-extra-properties' plus:
  1918. `:predicate' a predicate that completion candidates need to satisfy.
  1919. `:exclusive' value of `no' means that if the completion table fails to
  1920. match the text at point, then instead of reporting a completion
  1921. failure, the completion should try the next completion function.
  1922. As is the case with most hooks, the functions are responsible for
  1923. preserving things like point and current buffer.")
  1924. (defvar completion--capf-misbehave-funs nil
  1925. "List of functions found on `completion-at-point-functions' that misbehave.
  1926. These are functions that neither return completion data nor a completion
  1927. function but instead perform completion right away.")
  1928. (defvar completion--capf-safe-funs nil
  1929. "List of well-behaved functions found on `completion-at-point-functions'.
  1930. These are functions which return proper completion data rather than
  1931. a completion function or god knows what else.")
  1932. (defun completion--capf-wrapper (fun which)
  1933. ;; FIXME: The safe/misbehave handling assumes that a given function will
  1934. ;; always return the same kind of data, but this breaks down with functions
  1935. ;; like comint-completion-at-point or mh-letter-completion-at-point, which
  1936. ;; could be sometimes safe and sometimes misbehaving (and sometimes neither).
  1937. (if (pcase which
  1938. (`all t)
  1939. (`safe (member fun completion--capf-safe-funs))
  1940. (`optimist (not (member fun completion--capf-misbehave-funs))))
  1941. (let ((res (funcall fun)))
  1942. (cond
  1943. ((and (consp res) (not (functionp res)))
  1944. (unless (member fun completion--capf-safe-funs)
  1945. (push fun completion--capf-safe-funs))
  1946. (and (eq 'no (plist-get (nthcdr 3 res) :exclusive))
  1947. ;; FIXME: Here we'd need to decide whether there are
  1948. ;; valid completions against the current text. But this depends
  1949. ;; on the actual completion UI (e.g. with the default completion
  1950. ;; it depends on completion-style) ;-(
  1951. ;; We approximate this result by checking whether prefix
  1952. ;; completion might work, which means that non-prefix completion
  1953. ;; will not work (or not right) for completion functions that
  1954. ;; are non-exclusive.
  1955. (null (try-completion (buffer-substring-no-properties
  1956. (car res) (point))
  1957. (nth 2 res)
  1958. (plist-get (nthcdr 3 res) :predicate)))
  1959. (setq res nil)))
  1960. ((not (or (listp res) (functionp res)))
  1961. (unless (member fun completion--capf-misbehave-funs)
  1962. (message
  1963. "Completion function %S uses a deprecated calling convention" fun)
  1964. (push fun completion--capf-misbehave-funs))))
  1965. (if res (cons fun res)))))
  1966. (defun completion-at-point ()
  1967. "Perform completion on the text around point.
  1968. The completion method is determined by `completion-at-point-functions'."
  1969. (interactive)
  1970. (let ((res (run-hook-wrapped 'completion-at-point-functions
  1971. #'completion--capf-wrapper 'all)))
  1972. (pcase res
  1973. (`(,_ . ,(and (pred functionp) f)) (funcall f))
  1974. (`(,hookfun . (,start ,end ,collection . ,plist))
  1975. (unless (markerp start) (setq start (copy-marker start)))
  1976. (let* ((completion-extra-properties plist)
  1977. (completion-in-region-mode-predicate
  1978. (lambda ()
  1979. ;; We're still in the same completion field.
  1980. (let ((newstart (car-safe (funcall hookfun))))
  1981. (and newstart (= newstart start))))))
  1982. (completion-in-region start end collection
  1983. (plist-get plist :predicate))))
  1984. ;; Maybe completion already happened and the function returned t.
  1985. (_
  1986. (when (cdr res)
  1987. (message "Warning: %S failed to return valid completion data!"
  1988. (car res)))
  1989. (cdr res)))))
  1990. (defun completion-help-at-point ()
  1991. "Display the completions on the text around point.
  1992. The completion method is determined by `completion-at-point-functions'."
  1993. (interactive)
  1994. (let ((res (run-hook-wrapped 'completion-at-point-functions
  1995. ;; Ignore misbehaving functions.
  1996. #'completion--capf-wrapper 'optimist)))
  1997. (pcase res
  1998. (`(,_ . ,(and (pred functionp) f))
  1999. (message "Don't know how to show completions for %S" f))
  2000. (`(,hookfun . (,start ,end ,collection . ,plist))
  2001. (unless (markerp start) (setq start (copy-marker start)))
  2002. (let* ((minibuffer-completion-table collection)
  2003. (minibuffer-completion-predicate (plist-get plist :predicate))
  2004. (completion-extra-properties plist)
  2005. (completion-in-region-mode-predicate
  2006. (lambda ()
  2007. ;; We're still in the same completion field.
  2008. (let ((newstart (car-safe (funcall hookfun))))
  2009. (and newstart (= newstart start))))))
  2010. ;; FIXME: We should somehow (ab)use completion-in-region-function or
  2011. ;; introduce a corresponding hook (plus another for word-completion,
  2012. ;; and another for force-completion, maybe?).
  2013. (setq completion-in-region--data
  2014. `(,start ,(copy-marker end t) ,collection
  2015. ,(plist-get plist :predicate)))
  2016. (completion-in-region-mode 1)
  2017. (minibuffer-completion-help start end)))
  2018. (`(,hookfun . ,_)
  2019. ;; The hook function already performed completion :-(
  2020. ;; Not much we can do at this point.
  2021. (message "%s already performed completion!" hookfun)
  2022. nil)
  2023. (_ (message "Nothing to complete at point")))))
  2024. ;;; Key bindings.
  2025. (let ((map minibuffer-local-map))
  2026. (define-key map "\C-g" 'abort-recursive-edit)
  2027. (define-key map "\r" 'exit-minibuffer)
  2028. (define-key map "\n" 'exit-minibuffer))
  2029. (defvar minibuffer-local-completion-map
  2030. (let ((map (make-sparse-keymap)))
  2031. (set-keymap-parent map minibuffer-local-map)
  2032. (define-key map "\t" 'minibuffer-complete)
  2033. ;; M-TAB is already abused for many other purposes, so we should find
  2034. ;; another binding for it.
  2035. ;; (define-key map "\e\t" 'minibuffer-force-complete)
  2036. (define-key map " " 'minibuffer-complete-word)
  2037. (define-key map "?" 'minibuffer-completion-help)
  2038. map)
  2039. "Local keymap for minibuffer input with completion.")
  2040. (defvar minibuffer-local-must-match-map
  2041. (let ((map (make-sparse-keymap)))
  2042. (set-keymap-parent map minibuffer-local-completion-map)
  2043. (define-key map "\r" 'minibuffer-complete-and-exit)
  2044. (define-key map "\n" 'minibuffer-complete-and-exit)
  2045. map)
  2046. "Local keymap for minibuffer input with completion, for exact match.")
  2047. (defvar minibuffer-local-filename-completion-map
  2048. (let ((map (make-sparse-keymap)))
  2049. (define-key map " " nil)
  2050. map)
  2051. "Local keymap for minibuffer input with completion for filenames.
  2052. Gets combined either with `minibuffer-local-completion-map' or
  2053. with `minibuffer-local-must-match-map'.")
  2054. (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
  2055. 'minibuffer-local-filename-must-match-map "23.1")
  2056. (defvar minibuffer-local-filename-must-match-map (make-sparse-keymap))
  2057. (make-obsolete-variable 'minibuffer-local-filename-must-match-map nil "24.1")
  2058. (let ((map minibuffer-local-ns-map))
  2059. (define-key map " " 'exit-minibuffer)
  2060. (define-key map "\t" 'exit-minibuffer)
  2061. (define-key map "?" 'self-insert-and-exit))
  2062. (defvar minibuffer-inactive-mode-map
  2063. (let ((map (make-keymap)))
  2064. (suppress-keymap map)
  2065. (define-key map "e" 'find-file-other-frame)
  2066. (define-key map "f" 'find-file-other-frame)
  2067. (define-key map "b" 'switch-to-buffer-other-frame)
  2068. (define-key map "i" 'info)
  2069. (define-key map "m" 'mail)
  2070. (define-key map "n" 'make-frame)
  2071. (define-key map [mouse-1] 'view-echo-area-messages)
  2072. ;; So the global down-mouse-1 binding doesn't clutter the execution of the
  2073. ;; above mouse-1 binding.
  2074. (define-key map [down-mouse-1] #'ignore)
  2075. map)
  2076. "Keymap for use in the minibuffer when it is not active.
  2077. The non-mouse bindings in this keymap can only be used in minibuffer-only
  2078. frames, since the minibuffer can normally not be selected when it is
  2079. not active.")
  2080. (define-derived-mode minibuffer-inactive-mode nil "InactiveMinibuffer"
  2081. :abbrev-table nil ;abbrev.el is not loaded yet during dump.
  2082. ;; Note: this major mode is called from minibuf.c.
  2083. "Major mode to use in the minibuffer when it is not active.
  2084. This is only used when the minibuffer area has no active minibuffer.")
  2085. ;;; Completion tables.
  2086. (defun minibuffer--double-dollars (str)
  2087. ;; Reuse the actual "$" from the string to preserve any text-property it
  2088. ;; might have, such as `face'.
  2089. (replace-regexp-in-string "\\$" (lambda (dollar) (concat dollar dollar))
  2090. str))
  2091. (defun minibuffer-maybe-quote-filename (filename)
  2092. "Protect FILENAME from `substitute-in-file-name', as needed.
  2093. Useful to give the user default values that won't be substituted."
  2094. (if (and (not (file-name-quoted-p filename))
  2095. (file-name-absolute-p filename)
  2096. (string-match-p (if (memq system-type '(windows-nt ms-dos))
  2097. "[/\\\\]~" "/~")
  2098. (file-local-name filename)))
  2099. (file-name-quote filename)
  2100. (minibuffer--double-dollars filename)))
  2101. (defun completion--make-envvar-table ()
  2102. (mapcar (lambda (enventry)
  2103. (substring enventry 0 (string-match-p "=" enventry)))
  2104. process-environment))
  2105. (defconst completion--embedded-envvar-re
  2106. ;; We can't reuse env--substitute-vars-regexp because we need to match only
  2107. ;; potentially-unfinished envvars at end of string.
  2108. (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
  2109. "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
  2110. (defun completion--embedded-envvar-table (string _pred action)
  2111. "Completion table for envvars embedded in a string.
  2112. The envvar syntax (and escaping) rules followed by this table are the
  2113. same as `substitute-in-file-name'."
  2114. ;; We ignore `pred', because the predicates passed to us via
  2115. ;; read-file-name-internal are not 100% correct and fail here:
  2116. ;; e.g. we get predicates like file-directory-p there, whereas the filename
  2117. ;; completed needs to be passed through substitute-in-file-name before it
  2118. ;; can be passed to file-directory-p.
  2119. (when (string-match completion--embedded-envvar-re string)
  2120. (let* ((beg (or (match-beginning 2) (match-beginning 1)))
  2121. (table (completion--make-envvar-table))
  2122. (prefix (substring string 0 beg)))
  2123. (cond
  2124. ((eq action 'lambda)
  2125. ;; This table is expected to be used in conjunction with some
  2126. ;; other table that provides the "main" completion. Let the
  2127. ;; other table handle the test-completion case.
  2128. nil)
  2129. ((or (eq (car-safe action) 'boundaries) (eq action 'metadata))
  2130. ;; Only return boundaries/metadata if there's something to complete,
  2131. ;; since otherwise when we're used in
  2132. ;; completion-table-in-turn, we could return boundaries and
  2133. ;; let some subsequent table return a list of completions.
  2134. ;; FIXME: Maybe it should rather be fixed in
  2135. ;; completion-table-in-turn instead, but it's difficult to
  2136. ;; do it efficiently there.
  2137. (when (try-completion (substring string beg) table nil)
  2138. ;; Compute the boundaries of the subfield to which this
  2139. ;; completion applies.
  2140. (if (eq action 'metadata)
  2141. '(metadata (category . environment-variable))
  2142. (let ((suffix (cdr action)))
  2143. `(boundaries
  2144. ,(or (match-beginning 2) (match-beginning 1))
  2145. . ,(when (string-match "[^[:alnum:]_]" suffix)
  2146. (match-beginning 0)))))))
  2147. (t
  2148. (if (eq (aref string (1- beg)) ?{)
  2149. (setq table (apply-partially 'completion-table-with-terminator
  2150. "}" table)))
  2151. ;; Even if file-name completion is case-insensitive, we want
  2152. ;; envvar completion to be case-sensitive.
  2153. (let ((completion-ignore-case nil))
  2154. (completion-table-with-context
  2155. prefix table (substring string beg) nil action)))))))
  2156. (defun completion-file-name-table (string pred action)
  2157. "Completion table for file names."
  2158. (condition-case nil
  2159. (cond
  2160. ((eq action 'metadata) '(metadata (category . file)))
  2161. ((string-match-p "\\`~[^/\\]*\\'" string)
  2162. (completion-table-with-context "~"
  2163. (mapcar (lambda (u) (concat u "/"))
  2164. (system-users))
  2165. (substring string 1)
  2166. pred action))
  2167. ((eq (car-safe action) 'boundaries)
  2168. (let ((start (length (file-name-directory string)))
  2169. (end (string-match-p "/" (cdr action))))
  2170. `(boundaries
  2171. ;; if `string' is "C:" in w32, (file-name-directory string)
  2172. ;; returns "C:/", so `start' is 3 rather than 2.
  2173. ;; Not quite sure what is The Right Fix, but clipping it
  2174. ;; back to 2 will work for this particular case. We'll
  2175. ;; see if we can come up with a better fix when we bump
  2176. ;; into more such problematic cases.
  2177. ,(min start (length string)) . ,end)))
  2178. ((eq action 'lambda)
  2179. (if (zerop (length string))
  2180. nil ;Not sure why it's here, but it probably doesn't harm.
  2181. (funcall (or pred 'file-exists-p) string)))
  2182. (t
  2183. (let* ((name (file-name-nondirectory string))
  2184. (specdir (file-name-directory string))
  2185. (realdir (or specdir default-directory)))
  2186. (cond
  2187. ((null action)
  2188. (let ((comp (file-name-completion name realdir pred)))
  2189. (if (stringp comp)
  2190. (concat specdir comp)
  2191. comp)))
  2192. ((eq action t)
  2193. (let ((all (file-name-all-completions name realdir)))
  2194. ;; Check the predicate, if necessary.
  2195. (unless (memq pred '(nil file-exists-p))
  2196. (let ((comp ())
  2197. (pred
  2198. (if (eq pred 'file-directory-p)
  2199. ;; Brute-force speed up for directory checking:
  2200. ;; Discard strings which don't end in a slash.
  2201. (lambda (s)
  2202. (let ((len (length s)))
  2203. (and (> len 0) (eq (aref s (1- len)) ?/))))
  2204. ;; Must do it the hard (and slow) way.
  2205. pred)))
  2206. (let ((default-directory (expand-file-name realdir)))
  2207. (dolist (tem all)
  2208. (if (funcall pred tem) (push tem comp))))
  2209. (setq all (nreverse comp))))
  2210. all))))))
  2211. (file-error nil))) ;PCM often calls with invalid directories.
  2212. (defvar read-file-name-predicate nil
  2213. "Current predicate used by `read-file-name-internal'.")
  2214. (make-obsolete-variable 'read-file-name-predicate
  2215. "use the regular PRED argument" "23.2")
  2216. (defun completion--sifn-requote (upos qstr)
  2217. ;; We're looking for `qpos' such that:
  2218. ;; (equal (substring (substitute-in-file-name qstr) 0 upos)
  2219. ;; (substitute-in-file-name (substring qstr 0 qpos)))
  2220. ;; Big problem here: we have to reverse engineer substitute-in-file-name to
  2221. ;; find the position corresponding to UPOS in QSTR, but
  2222. ;; substitute-in-file-name can do anything, depending on file-name-handlers.
  2223. ;; substitute-in-file-name does the following kind of things:
  2224. ;; - expand env-var references.
  2225. ;; - turn backslashes into slashes.
  2226. ;; - truncate some prefix of the input.
  2227. ;; - rewrite some prefix.
  2228. ;; Some of these operations are written in external libraries and we'd rather
  2229. ;; not hard code any assumptions here about what they actually do. IOW, we
  2230. ;; want to treat substitute-in-file-name as a black box, as much as possible.
  2231. ;; Kind of like in rfn-eshadow-update-overlay, only worse.
  2232. ;; Example of things we need to handle:
  2233. ;; - Tramp (substitute-in-file-name "/foo:~/bar//baz") => "/scpc:foo:/baz".
  2234. ;; - Cygwin (substitute-in-file-name "C:\bin") => "/usr/bin"
  2235. ;; (substitute-in-file-name "C:\") => "/"
  2236. ;; (substitute-in-file-name "C:\bi") => "/bi"
  2237. (let* ((ustr (substitute-in-file-name qstr))
  2238. (uprefix (substring ustr 0 upos))
  2239. qprefix)
  2240. ;; Main assumption: nothing after qpos should affect the text before upos,
  2241. ;; so we can work our way backward from the end of qstr, one character
  2242. ;; at a time.
  2243. ;; Second assumptions: If qpos is far from the end this can be a bit slow,
  2244. ;; so we speed it up by doing a first loop that skips a word at a time.
  2245. ;; This word-sized loop is careful not to cut in the middle of env-vars.
  2246. (while (let ((boundary (string-match "\\(\\$+{?\\)?\\w+\\W*\\'" qstr)))
  2247. (and boundary
  2248. (progn
  2249. (setq qprefix (substring qstr 0 boundary))
  2250. (string-prefix-p uprefix
  2251. (substitute-in-file-name qprefix)))))
  2252. (setq qstr qprefix))
  2253. (let ((qpos (length qstr)))
  2254. (while (and (> qpos 0)
  2255. (string-prefix-p uprefix
  2256. (substitute-in-file-name
  2257. (substring qstr 0 (1- qpos)))))
  2258. (setq qpos (1- qpos)))
  2259. (cons qpos #'minibuffer-maybe-quote-filename))))
  2260. (defalias 'completion--file-name-table
  2261. (completion-table-with-quoting #'completion-file-name-table
  2262. #'substitute-in-file-name
  2263. #'completion--sifn-requote)
  2264. "Internal subroutine for `read-file-name'. Do not call this.
  2265. This is a completion table for file names, like `completion-file-name-table'
  2266. except that it passes the file name through `substitute-in-file-name'.")
  2267. (defalias 'read-file-name-internal
  2268. (completion-table-in-turn #'completion--embedded-envvar-table
  2269. #'completion--file-name-table)
  2270. "Internal subroutine for `read-file-name'. Do not call this.")
  2271. (defvar read-file-name-function 'read-file-name-default
  2272. "The function called by `read-file-name' to do its work.
  2273. It should accept the same arguments as `read-file-name'.")
  2274. (defcustom insert-default-directory t
  2275. "Non-nil means when reading a filename start with default dir in minibuffer.
  2276. When the initial minibuffer contents show a name of a file or a directory,
  2277. typing RETURN without editing the initial contents is equivalent to typing
  2278. the default file name.
  2279. If this variable is non-nil, the minibuffer contents are always
  2280. initially non-empty, and typing RETURN without editing will fetch the
  2281. default name, if one is provided. Note however that this default name
  2282. is not necessarily the same as initial contents inserted in the minibuffer,
  2283. if the initial contents is just the default directory.
  2284. If this variable is nil, the minibuffer often starts out empty. In
  2285. that case you may have to explicitly fetch the next history element to
  2286. request the default name; typing RETURN without editing will leave
  2287. the minibuffer empty.
  2288. For some commands, exiting with an empty minibuffer has a special meaning,
  2289. such as making the current buffer visit no file in the case of
  2290. `set-visited-file-name'."
  2291. :type 'boolean)
  2292. ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
  2293. (declare-function x-file-dialog "xfns.c"
  2294. (prompt dir &optional default-filename mustmatch only-dir-p))
  2295. (defun read-file-name--defaults (&optional dir initial)
  2296. (let ((default
  2297. (cond
  2298. ;; With non-nil `initial', use `dir' as the first default.
  2299. ;; Essentially, this mean reversing the normal order of the
  2300. ;; current directory name and the current file name, i.e.
  2301. ;; 1. with normal file reading:
  2302. ;; 1.1. initial input is the current directory
  2303. ;; 1.2. the first default is the current file name
  2304. ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
  2305. ;; 2.2. initial input is the current file name
  2306. ;; 2.1. the first default is the current directory
  2307. (initial (abbreviate-file-name dir))
  2308. ;; In file buffers, try to get the current file name
  2309. (buffer-file-name
  2310. (abbreviate-file-name buffer-file-name))))
  2311. (file-name-at-point
  2312. (run-hook-with-args-until-success 'file-name-at-point-functions)))
  2313. (when file-name-at-point
  2314. (setq default (delete-dups
  2315. (delete "" (delq nil (list file-name-at-point default))))))
  2316. ;; Append new defaults to the end of existing `minibuffer-default'.
  2317. (append
  2318. (if (listp minibuffer-default) minibuffer-default (list minibuffer-default))
  2319. (if (listp default) default (list default)))))
  2320. (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
  2321. "Read file name, prompting with PROMPT and completing in directory DIR.
  2322. The return value is not expanded---you must call `expand-file-name' yourself.
  2323. DIR is the directory to use for completing relative file names.
  2324. It should be an absolute directory name, or nil (which means the
  2325. current buffer's value of `default-directory').
  2326. DEFAULT-FILENAME specifies the default file name to return if the
  2327. user exits the minibuffer with the same non-empty string inserted
  2328. by this function. If DEFAULT-FILENAME is a string, that serves
  2329. as the default. If DEFAULT-FILENAME is a list of strings, the
  2330. first string is the default. If DEFAULT-FILENAME is omitted or
  2331. nil, then if INITIAL is non-nil, the default is DIR combined with
  2332. INITIAL; otherwise, if the current buffer is visiting a file,
  2333. that file serves as the default; otherwise, the default is simply
  2334. the string inserted into the minibuffer.
  2335. If the user exits with an empty minibuffer, return an empty
  2336. string. (This happens only if the user erases the pre-inserted
  2337. contents, or if `insert-default-directory' is nil.)
  2338. Fourth arg MUSTMATCH can take the following values:
  2339. - nil means that the user can exit with any input.
  2340. - t means that the user is not allowed to exit unless
  2341. the input is (or completes to) an existing file.
  2342. - `confirm' means that the user can exit with any input, but she needs
  2343. to confirm her choice if the input is not an existing file.
  2344. - `confirm-after-completion' means that the user can exit with any
  2345. input, but she needs to confirm her choice if she called
  2346. `minibuffer-complete' right before `minibuffer-complete-and-exit'
  2347. and the input is not an existing file.
  2348. - anything else behaves like t except that typing RET does not exit if it
  2349. does non-null completion.
  2350. Fifth arg INITIAL specifies text to start with.
  2351. Sixth arg PREDICATE, if non-nil, should be a function of one
  2352. argument; then a file name is considered an acceptable completion
  2353. alternative only if PREDICATE returns non-nil with the file name
  2354. as its argument.
  2355. If this command was invoked with the mouse, use a graphical file
  2356. dialog if `use-dialog-box' is non-nil, and the window system or X
  2357. toolkit in use provides a file dialog box, and DIR is not a
  2358. remote file. For graphical file dialogs, any of the special values
  2359. of MUSTMATCH `confirm' and `confirm-after-completion' are
  2360. treated as equivalent to nil. Some graphical file dialogs respect
  2361. a MUSTMATCH value of t, and some do not (or it only has a cosmetic
  2362. effect, and does not actually prevent the user from entering a
  2363. non-existent file).
  2364. See also `read-file-name-completion-ignore-case'
  2365. and `read-file-name-function'."
  2366. ;; If x-gtk-use-old-file-dialog = t (xg_get_file_with_selection),
  2367. ;; then MUSTMATCH is enforced. But with newer Gtk
  2368. ;; (xg_get_file_with_chooser), it only has a cosmetic effect.
  2369. ;; The user can still type a non-existent file name.
  2370. (funcall (or read-file-name-function #'read-file-name-default)
  2371. prompt dir default-filename mustmatch initial predicate))
  2372. (defvar minibuffer-local-filename-syntax
  2373. (let ((table (make-syntax-table))
  2374. (punctuation (car (string-to-syntax "."))))
  2375. ;; Convert all punctuation entries to symbol.
  2376. (map-char-table (lambda (c syntax)
  2377. (when (eq (car syntax) punctuation)
  2378. (modify-syntax-entry c "_" table)))
  2379. table)
  2380. (mapc
  2381. (lambda (c)
  2382. (modify-syntax-entry c "." table))
  2383. '(?/ ?: ?\\))
  2384. table)
  2385. "Syntax table used when reading a file name in the minibuffer.")
  2386. ;; minibuffer-completing-file-name is a variable used internally in minibuf.c
  2387. ;; to determine whether to use minibuffer-local-filename-completion-map or
  2388. ;; minibuffer-local-completion-map. It shouldn't be exported to Elisp.
  2389. ;; FIXME: Actually, it is also used in rfn-eshadow.el we'd otherwise have to
  2390. ;; use (eq minibuffer-completion-table #'read-file-name-internal), which is
  2391. ;; probably even worse. Maybe We should add some read-file-name-setup-hook
  2392. ;; instead, but for now, let's keep this non-obsolete.
  2393. ;;(make-obsolete-variable 'minibuffer-completing-file-name nil "future" 'get)
  2394. (defun read-file-name-default (prompt &optional dir default-filename mustmatch initial predicate)
  2395. "Default method for reading file names.
  2396. See `read-file-name' for the meaning of the arguments."
  2397. (unless dir (setq dir (or default-directory "~/")))
  2398. (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
  2399. (unless default-filename
  2400. (setq default-filename (if initial (expand-file-name initial dir)
  2401. buffer-file-name)))
  2402. ;; If dir starts with user's homedir, change that to ~.
  2403. (setq dir (abbreviate-file-name dir))
  2404. ;; Likewise for default-filename.
  2405. (if default-filename
  2406. (setq default-filename
  2407. (if (consp default-filename)
  2408. (mapcar 'abbreviate-file-name default-filename)
  2409. (abbreviate-file-name default-filename))))
  2410. (let ((insdef (cond
  2411. ((and insert-default-directory (stringp dir))
  2412. (if initial
  2413. (cons (minibuffer-maybe-quote-filename (concat dir initial))
  2414. (length (minibuffer-maybe-quote-filename dir)))
  2415. (minibuffer-maybe-quote-filename dir)))
  2416. (initial (cons (minibuffer-maybe-quote-filename initial) 0)))))
  2417. (let ((completion-ignore-case read-file-name-completion-ignore-case)
  2418. (minibuffer-completing-file-name t)
  2419. (pred (or predicate 'file-exists-p))
  2420. (add-to-history nil))
  2421. (let* ((val
  2422. (if (or (not (next-read-file-uses-dialog-p))
  2423. ;; Graphical file dialogs can't handle remote
  2424. ;; files (Bug#99).
  2425. (file-remote-p dir))
  2426. ;; We used to pass `dir' to `read-file-name-internal' by
  2427. ;; abusing the `predicate' argument. It's better to
  2428. ;; just use `default-directory', but in order to avoid
  2429. ;; changing `default-directory' in the current buffer,
  2430. ;; we don't let-bind it.
  2431. (let ((dir (file-name-as-directory
  2432. (expand-file-name dir))))
  2433. (minibuffer-with-setup-hook
  2434. (lambda ()
  2435. (setq default-directory dir)
  2436. ;; When the first default in `minibuffer-default'
  2437. ;; duplicates initial input `insdef',
  2438. ;; reset `minibuffer-default' to nil.
  2439. (when (equal (or (car-safe insdef) insdef)
  2440. (or (car-safe minibuffer-default)
  2441. minibuffer-default))
  2442. (setq minibuffer-default
  2443. (cdr-safe minibuffer-default)))
  2444. ;; On the first request on `M-n' fill
  2445. ;; `minibuffer-default' with a list of defaults
  2446. ;; relevant for file-name reading.
  2447. (set (make-local-variable 'minibuffer-default-add-function)
  2448. (lambda ()
  2449. (with-current-buffer
  2450. (window-buffer (minibuffer-selected-window))
  2451. (read-file-name--defaults dir initial))))
  2452. (set-syntax-table minibuffer-local-filename-syntax))
  2453. (completing-read prompt 'read-file-name-internal
  2454. pred mustmatch insdef
  2455. 'file-name-history default-filename)))
  2456. ;; If DEFAULT-FILENAME not supplied and DIR contains
  2457. ;; a file name, split it.
  2458. (let ((file (file-name-nondirectory dir))
  2459. ;; When using a dialog, revert to nil and non-nil
  2460. ;; interpretation of mustmatch. confirm options
  2461. ;; need to be interpreted as nil, otherwise
  2462. ;; it is impossible to create new files using
  2463. ;; dialogs with the default settings.
  2464. (dialog-mustmatch
  2465. (not (memq mustmatch
  2466. '(nil confirm confirm-after-completion)))))
  2467. (when (and (not default-filename)
  2468. (not (zerop (length file))))
  2469. (setq default-filename file)
  2470. (setq dir (file-name-directory dir)))
  2471. (when default-filename
  2472. (setq default-filename
  2473. (expand-file-name (if (consp default-filename)
  2474. (car default-filename)
  2475. default-filename)
  2476. dir)))
  2477. (setq add-to-history t)
  2478. (x-file-dialog prompt dir default-filename
  2479. dialog-mustmatch
  2480. (eq predicate 'file-directory-p)))))
  2481. (replace-in-history (eq (car-safe file-name-history) val)))
  2482. ;; If completing-read returned the inserted default string itself
  2483. ;; (rather than a new string with the same contents),
  2484. ;; it has to mean that the user typed RET with the minibuffer empty.
  2485. ;; In that case, we really want to return ""
  2486. ;; so that commands such as set-visited-file-name can distinguish.
  2487. (when (consp default-filename)
  2488. (setq default-filename (car default-filename)))
  2489. (when (eq val default-filename)
  2490. ;; In this case, completing-read has not added an element
  2491. ;; to the history. Maybe we should.
  2492. (if (not replace-in-history)
  2493. (setq add-to-history t))
  2494. (setq val ""))
  2495. (unless val (error "No file name specified"))
  2496. (if (and default-filename
  2497. (string-equal val (if (consp insdef) (car insdef) insdef)))
  2498. (setq val default-filename))
  2499. (setq val (substitute-in-file-name val))
  2500. (if replace-in-history
  2501. ;; Replace what Fcompleting_read added to the history
  2502. ;; with what we will actually return. As an exception,
  2503. ;; if that's the same as the second item in
  2504. ;; file-name-history, it's really a repeat (Bug#4657).
  2505. (let ((val1 (minibuffer-maybe-quote-filename val)))
  2506. (if history-delete-duplicates
  2507. (setcdr file-name-history
  2508. (delete val1 (cdr file-name-history))))
  2509. (if (string= val1 (cadr file-name-history))
  2510. (pop file-name-history)
  2511. (setcar file-name-history val1)))
  2512. (if add-to-history
  2513. ;; Add the value to the history--but not if it matches
  2514. ;; the last value already there.
  2515. (let ((val1 (minibuffer-maybe-quote-filename val)))
  2516. (unless (and (consp file-name-history)
  2517. (equal (car file-name-history) val1))
  2518. (setq file-name-history
  2519. (cons val1
  2520. (if history-delete-duplicates
  2521. (delete val1 file-name-history)
  2522. file-name-history)))))))
  2523. val))))
  2524. (defun internal-complete-buffer-except (&optional buffer)
  2525. "Perform completion on all buffers excluding BUFFER.
  2526. BUFFER nil or omitted means use the current buffer.
  2527. Like `internal-complete-buffer', but removes BUFFER from the completion list."
  2528. (let ((except (if (stringp buffer) buffer (buffer-name buffer))))
  2529. (apply-partially 'completion-table-with-predicate
  2530. 'internal-complete-buffer
  2531. (lambda (name)
  2532. (not (equal (if (consp name) (car name) name) except)))
  2533. nil)))
  2534. ;;; Old-style completion, used in Emacs-21 and Emacs-22.
  2535. (defun completion-emacs21-try-completion (string table pred _point)
  2536. (let ((completion (try-completion string table pred)))
  2537. (if (stringp completion)
  2538. (cons completion (length completion))
  2539. completion)))
  2540. (defun completion-emacs21-all-completions (string table pred _point)
  2541. (completion-hilit-commonality
  2542. (all-completions string table pred)
  2543. (length string)
  2544. (car (completion-boundaries string table pred ""))))
  2545. (defun completion-emacs22-try-completion (string table pred point)
  2546. (let ((suffix (substring string point))
  2547. (completion (try-completion (substring string 0 point) table pred)))
  2548. (if (not (stringp completion))
  2549. completion
  2550. ;; Merge a trailing / in completion with a / after point.
  2551. ;; We used to only do it for word completion, but it seems to make
  2552. ;; sense for all completions.
  2553. ;; Actually, claiming this feature was part of Emacs-22 completion
  2554. ;; is pushing it a bit: it was only done in minibuffer-completion-word,
  2555. ;; which was (by default) not bound during file completion, where such
  2556. ;; slashes are most likely to occur.
  2557. (if (and (not (zerop (length completion)))
  2558. (eq ?/ (aref completion (1- (length completion))))
  2559. (not (zerop (length suffix)))
  2560. (eq ?/ (aref suffix 0)))
  2561. ;; This leaves point after the / .
  2562. (setq suffix (substring suffix 1)))
  2563. (cons (concat completion suffix) (length completion)))))
  2564. (defun completion-emacs22-all-completions (string table pred point)
  2565. (let ((beforepoint (substring string 0 point)))
  2566. (completion-hilit-commonality
  2567. (all-completions beforepoint table pred)
  2568. point
  2569. (car (completion-boundaries beforepoint table pred "")))))
  2570. ;;; Basic completion.
  2571. (defun completion--merge-suffix (completion point suffix)
  2572. "Merge end of COMPLETION with beginning of SUFFIX.
  2573. Simple generalization of the \"merge trailing /\" done in Emacs-22.
  2574. Return the new suffix."
  2575. (if (and (not (zerop (length suffix)))
  2576. (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
  2577. ;; Make sure we don't compress things to less
  2578. ;; than we started with.
  2579. point)
  2580. ;; Just make sure we didn't match some other \n.
  2581. (eq (match-end 1) (length completion)))
  2582. (substring suffix (- (match-end 1) (match-beginning 1)))
  2583. ;; Nothing to merge.
  2584. suffix))
  2585. (defun completion-basic--pattern (beforepoint afterpoint bounds)
  2586. (delete
  2587. "" (list (substring beforepoint (car bounds))
  2588. 'point
  2589. (substring afterpoint 0 (cdr bounds)))))
  2590. (defun completion-basic-try-completion (string table pred point)
  2591. (let* ((beforepoint (substring string 0 point))
  2592. (afterpoint (substring string point))
  2593. (bounds (completion-boundaries beforepoint table pred afterpoint)))
  2594. (if (zerop (cdr bounds))
  2595. ;; `try-completion' may return a subtly different result
  2596. ;; than `all+merge', so try to use it whenever possible.
  2597. (let ((completion (try-completion beforepoint table pred)))
  2598. (if (not (stringp completion))
  2599. completion
  2600. (cons
  2601. (concat completion
  2602. (completion--merge-suffix completion point afterpoint))
  2603. (length completion))))
  2604. (let* ((suffix (substring afterpoint (cdr bounds)))
  2605. (prefix (substring beforepoint 0 (car bounds)))
  2606. (pattern (delete
  2607. "" (list (substring beforepoint (car bounds))
  2608. 'point
  2609. (substring afterpoint 0 (cdr bounds)))))
  2610. (all (completion-pcm--all-completions prefix pattern table pred)))
  2611. (if minibuffer-completing-file-name
  2612. (setq all (completion-pcm--filename-try-filter all)))
  2613. (completion-pcm--merge-try pattern all prefix suffix)))))
  2614. (defun completion-basic-all-completions (string table pred point)
  2615. (let* ((beforepoint (substring string 0 point))
  2616. (afterpoint (substring string point))
  2617. (bounds (completion-boundaries beforepoint table pred afterpoint))
  2618. ;; (suffix (substring afterpoint (cdr bounds)))
  2619. (prefix (substring beforepoint 0 (car bounds)))
  2620. (pattern (delete
  2621. "" (list (substring beforepoint (car bounds))
  2622. 'point
  2623. (substring afterpoint 0 (cdr bounds)))))
  2624. (all (completion-pcm--all-completions prefix pattern table pred)))
  2625. (completion-hilit-commonality all point (car bounds))))
  2626. ;;; Partial-completion-mode style completion.
  2627. (defvar completion-pcm--delim-wild-regex nil
  2628. "Regular expression matching delimiters controlling the partial-completion.
  2629. Typically, this regular expression simply matches a delimiter, meaning
  2630. that completion can add something at (match-beginning 0), but if it has
  2631. a submatch 1, then completion can add something at (match-end 1).
  2632. This is used when the delimiter needs to be of size zero (e.g. the transition
  2633. from lowercase to uppercase characters).")
  2634. (defun completion-pcm--prepare-delim-re (delims)
  2635. (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
  2636. (defcustom completion-pcm-word-delimiters "-_./:| "
  2637. "A string of characters treated as word delimiters for completion.
  2638. Some arcane rules:
  2639. If `]' is in this string, it must come first.
  2640. If `^' is in this string, it must not come first.
  2641. If `-' is in this string, it must come first or right after `]'.
  2642. In other words, if S is this string, then `[S]' must be a valid Emacs regular
  2643. expression (not containing character ranges like `a-z')."
  2644. :set (lambda (symbol value)
  2645. (set-default symbol value)
  2646. ;; Refresh other vars.
  2647. (completion-pcm--prepare-delim-re value))
  2648. :initialize 'custom-initialize-reset
  2649. :type 'string)
  2650. (defcustom completion-pcm-complete-word-inserts-delimiters nil
  2651. "Treat the SPC or - inserted by `minibuffer-complete-word' as delimiters.
  2652. Those chars are treated as delimiters if this variable is non-nil.
  2653. I.e. if non-nil, M-x SPC will just insert a \"-\" in the minibuffer, whereas
  2654. if nil, it will list all possible commands in *Completions* because none of
  2655. the commands start with a \"-\" or a SPC."
  2656. :version "24.1"
  2657. :type 'boolean)
  2658. (defun completion-pcm--pattern-trivial-p (pattern)
  2659. (and (stringp (car pattern))
  2660. ;; It can be followed by `point' and "" and still be trivial.
  2661. (let ((trivial t))
  2662. (dolist (elem (cdr pattern))
  2663. (unless (member elem '(point ""))
  2664. (setq trivial nil)))
  2665. trivial)))
  2666. (defun completion-pcm--string->pattern (string &optional point)
  2667. "Split STRING into a pattern.
  2668. A pattern is a list where each element is either a string
  2669. or a symbol, see `completion-pcm--merge-completions'."
  2670. (if (and point (< point (length string)))
  2671. (let ((prefix (substring string 0 point))
  2672. (suffix (substring string point)))
  2673. (append (completion-pcm--string->pattern prefix)
  2674. '(point)
  2675. (completion-pcm--string->pattern suffix)))
  2676. (let* ((pattern nil)
  2677. (p 0)
  2678. (p0 p)
  2679. (pending nil))
  2680. (while (and (setq p (string-match completion-pcm--delim-wild-regex
  2681. string p))
  2682. (or completion-pcm-complete-word-inserts-delimiters
  2683. ;; If the char was added by minibuffer-complete-word,
  2684. ;; then don't treat it as a delimiter, otherwise
  2685. ;; "M-x SPC" ends up inserting a "-" rather than listing
  2686. ;; all completions.
  2687. (not (get-text-property p 'completion-try-word string))))
  2688. ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
  2689. ;; meaning that something can be added *before* it, but it can also
  2690. ;; match a prefix and postfix, in which case something can be added
  2691. ;; in-between (e.g. match [[:lower:]][[:upper:]]).
  2692. ;; This is determined by the presence of a submatch-1 which delimits
  2693. ;; the prefix.
  2694. (if (match-end 1) (setq p (match-end 1)))
  2695. (unless (= p0 p)
  2696. (if pending (push pending pattern))
  2697. (push (substring string p0 p) pattern))
  2698. (setq pending nil)
  2699. (if (eq (aref string p) ?*)
  2700. (progn
  2701. (push 'star pattern)
  2702. (setq p0 (1+ p)))
  2703. (push 'any pattern)
  2704. (if (match-end 1)
  2705. (setq p0 p)
  2706. (push (substring string p (match-end 0)) pattern)
  2707. ;; `any-delim' is used so that "a-b" also finds "array->beginning".
  2708. (setq pending 'any-delim)
  2709. (setq p0 (match-end 0))))
  2710. (setq p p0))
  2711. (when (> (length string) p0)
  2712. (if pending (push pending pattern))
  2713. (push (substring string p0) pattern))
  2714. ;; An empty string might be erroneously added at the beginning.
  2715. ;; It should be avoided properly, but it's so easy to remove it here.
  2716. (delete "" (nreverse pattern)))))
  2717. (defun completion-pcm--optimize-pattern (p)
  2718. ;; Remove empty strings in a separate phase since otherwise a ""
  2719. ;; might prevent some other optimization, as in '(any "" any).
  2720. (setq p (delete "" p))
  2721. (let ((n '()))
  2722. (while p
  2723. (pcase p
  2724. (`(,(and s1 (pred stringp)) ,(and s2 (pred stringp)) . ,rest)
  2725. (setq p (cons (concat s1 s2) rest)))
  2726. (`(,(and p1 (pred symbolp)) ,(and p2 (guard (eq p1 p2))) . ,_)
  2727. (setq p (cdr p)))
  2728. (`(star ,(pred symbolp) . ,rest) (setq p `(star . ,rest)))
  2729. (`(,(pred symbolp) star . ,rest) (setq p `(star . ,rest)))
  2730. (`(point ,(or `any `any-delim) . ,rest) (setq p `(point . ,rest)))
  2731. (`(,(or `any `any-delim) point . ,rest) (setq p `(point . ,rest)))
  2732. (`(any ,(or `any `any-delim) . ,rest) (setq p `(any . ,rest)))
  2733. (`(,(pred symbolp)) (setq p nil)) ;Implicit terminating `any'.
  2734. (_ (push (pop p) n))))
  2735. (nreverse n)))
  2736. (defun completion-pcm--pattern->regex (pattern &optional group)
  2737. (let ((re
  2738. (concat "\\`"
  2739. (mapconcat
  2740. (lambda (x)
  2741. (cond
  2742. ((stringp x) (regexp-quote x))
  2743. (t
  2744. (let ((re (if (eq x 'any-delim)
  2745. (concat completion-pcm--delim-wild-regex "*?")
  2746. ".*?")))
  2747. (if (if (consp group) (memq x group) group)
  2748. (concat "\\(" re "\\)")
  2749. re)))))
  2750. pattern
  2751. ""))))
  2752. ;; Avoid pathological backtracking.
  2753. (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
  2754. (setq re (replace-match "" t t re 1)))
  2755. re))
  2756. (defun completion-pcm--all-completions (prefix pattern table pred)
  2757. "Find all completions for PATTERN in TABLE obeying PRED.
  2758. PATTERN is as returned by `completion-pcm--string->pattern'."
  2759. ;; (cl-assert (= (car (completion-boundaries prefix table pred ""))
  2760. ;; (length prefix)))
  2761. ;; Find an initial list of possible completions.
  2762. (if (completion-pcm--pattern-trivial-p pattern)
  2763. ;; Minibuffer contains no delimiters -- simple case!
  2764. (all-completions (concat prefix (car pattern)) table pred)
  2765. ;; Use all-completions to do an initial cull. This is a big win,
  2766. ;; since all-completions is written in C!
  2767. (let* (;; Convert search pattern to a standard regular expression.
  2768. (regex (completion-pcm--pattern->regex pattern))
  2769. (case-fold-search completion-ignore-case)
  2770. (completion-regexp-list (cons regex completion-regexp-list))
  2771. (compl (all-completions
  2772. (concat prefix
  2773. (if (stringp (car pattern)) (car pattern) ""))
  2774. table pred)))
  2775. (if (not (functionp table))
  2776. ;; The internal functions already obeyed completion-regexp-list.
  2777. compl
  2778. (let ((poss ()))
  2779. (dolist (c compl)
  2780. (when (string-match-p regex c) (push c poss)))
  2781. (nreverse poss))))))
  2782. (defun completion-pcm--hilit-commonality (pattern completions)
  2783. (when completions
  2784. (let* ((re (completion-pcm--pattern->regex pattern '(point)))
  2785. (case-fold-search completion-ignore-case))
  2786. (mapcar
  2787. (lambda (str)
  2788. ;; Don't modify the string itself.
  2789. (setq str (copy-sequence str))
  2790. (unless (string-match re str)
  2791. (error "Internal error: %s does not match %s" re str))
  2792. (let ((pos (or (match-beginning 1) (match-end 0))))
  2793. (put-text-property 0 pos
  2794. 'font-lock-face 'completions-common-part
  2795. str)
  2796. (if (> (length str) pos)
  2797. (put-text-property pos (1+ pos)
  2798. 'font-lock-face 'completions-first-difference
  2799. str)))
  2800. str)
  2801. completions))))
  2802. (defun completion-pcm--find-all-completions (string table pred point
  2803. &optional filter)
  2804. "Find all completions for STRING at POINT in TABLE, satisfying PRED.
  2805. POINT is a position inside STRING.
  2806. FILTER is a function applied to the return value, that can be used, e.g. to
  2807. filter out additional entries (because TABLE might not obey PRED)."
  2808. (unless filter (setq filter 'identity))
  2809. (let* ((beforepoint (substring string 0 point))
  2810. (afterpoint (substring string point))
  2811. (bounds (completion-boundaries beforepoint table pred afterpoint))
  2812. (prefix (substring beforepoint 0 (car bounds)))
  2813. (suffix (substring afterpoint (cdr bounds)))
  2814. firsterror)
  2815. (setq string (substring string (car bounds) (+ point (cdr bounds))))
  2816. (let* ((relpoint (- point (car bounds)))
  2817. (pattern (completion-pcm--string->pattern string relpoint))
  2818. (all (condition-case-unless-debug err
  2819. (funcall filter
  2820. (completion-pcm--all-completions
  2821. prefix pattern table pred))
  2822. (error (setq firsterror err) nil))))
  2823. (when (and (null all)
  2824. (> (car bounds) 0)
  2825. (null (ignore-errors (try-completion prefix table pred))))
  2826. ;; The prefix has no completions at all, so we should try and fix
  2827. ;; that first.
  2828. (let ((substring (substring prefix 0 -1)))
  2829. (pcase-let ((`(,subpat ,suball ,subprefix ,_subsuffix)
  2830. (completion-pcm--find-all-completions
  2831. substring table pred (length substring) filter)))
  2832. (let ((sep (aref prefix (1- (length prefix))))
  2833. ;; Text that goes between the new submatches and the
  2834. ;; completion substring.
  2835. (between nil))
  2836. ;; Eliminate submatches that don't end with the separator.
  2837. (dolist (submatch (prog1 suball (setq suball ())))
  2838. (when (eq sep (aref submatch (1- (length submatch))))
  2839. (push submatch suball)))
  2840. (when suball
  2841. ;; Update the boundaries and corresponding pattern.
  2842. ;; We assume that all submatches result in the same boundaries
  2843. ;; since we wouldn't know how to merge them otherwise anyway.
  2844. ;; FIXME: COMPLETE REWRITE!!!
  2845. (let* ((newbeforepoint
  2846. (concat subprefix (car suball)
  2847. (substring string 0 relpoint)))
  2848. (leftbound (+ (length subprefix) (length (car suball))))
  2849. (newbounds (completion-boundaries
  2850. newbeforepoint table pred afterpoint)))
  2851. (unless (or (and (eq (cdr bounds) (cdr newbounds))
  2852. (eq (car newbounds) leftbound))
  2853. ;; Refuse new boundaries if they step over
  2854. ;; the submatch.
  2855. (< (car newbounds) leftbound))
  2856. ;; The new completed prefix does change the boundaries
  2857. ;; of the completed substring.
  2858. (setq suffix (substring afterpoint (cdr newbounds)))
  2859. (setq string
  2860. (concat (substring newbeforepoint (car newbounds))
  2861. (substring afterpoint 0 (cdr newbounds))))
  2862. (setq between (substring newbeforepoint leftbound
  2863. (car newbounds)))
  2864. (setq pattern (completion-pcm--string->pattern
  2865. string
  2866. (- (length newbeforepoint)
  2867. (car newbounds)))))
  2868. (dolist (submatch suball)
  2869. (setq all (nconc
  2870. (mapcar
  2871. (lambda (s) (concat submatch between s))
  2872. (funcall filter
  2873. (completion-pcm--all-completions
  2874. (concat subprefix submatch between)
  2875. pattern table pred)))
  2876. all)))
  2877. ;; FIXME: This can come in handy for try-completion,
  2878. ;; but isn't right for all-completions, since it lists
  2879. ;; invalid completions.
  2880. ;; (unless all
  2881. ;; ;; Even though we found expansions in the prefix, none
  2882. ;; ;; leads to a valid completion.
  2883. ;; ;; Let's keep the expansions, tho.
  2884. ;; (dolist (submatch suball)
  2885. ;; (push (concat submatch between newsubstring) all)))
  2886. ))
  2887. (setq pattern (append subpat (list 'any (string sep))
  2888. (if between (list between)) pattern))
  2889. (setq prefix subprefix)))))
  2890. (if (and (null all) firsterror)
  2891. (signal (car firsterror) (cdr firsterror))
  2892. (list pattern all prefix suffix)))))
  2893. (defun completion-pcm-all-completions (string table pred point)
  2894. (pcase-let ((`(,pattern ,all ,prefix ,_suffix)
  2895. (completion-pcm--find-all-completions string table pred point)))
  2896. (when all
  2897. (nconc (completion-pcm--hilit-commonality pattern all)
  2898. (length prefix)))))
  2899. (defun completion--common-suffix (strs)
  2900. "Return the common suffix of the strings STRS."
  2901. (nreverse (try-completion "" (mapcar #'reverse strs))))
  2902. (defun completion-pcm--merge-completions (strs pattern)
  2903. "Extract the commonality in STRS, with the help of PATTERN.
  2904. PATTERN can contain strings and symbols chosen among `star', `any', `point',
  2905. and `prefix'. They all match anything (aka \".*\") but are merged differently:
  2906. `any' only grows from the left (when matching \"a1b\" and \"a2b\" it gets
  2907. completed to just \"a\").
  2908. `prefix' only grows from the right (when matching \"a1b\" and \"a2b\" it gets
  2909. completed to just \"b\").
  2910. `star' grows from both ends and is reified into a \"*\" (when matching \"a1b\"
  2911. and \"a2b\" it gets completed to \"a*b\").
  2912. `point' is like `star' except that it gets reified as the position of point
  2913. instead of being reified as a \"*\" character.
  2914. The underlying idea is that we should return a string which still matches
  2915. the same set of elements."
  2916. ;; When completing while ignoring case, we want to try and avoid
  2917. ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
  2918. ;; So we try and make sure that the string we return is all made up
  2919. ;; of text from the completions rather than part from the
  2920. ;; completions and part from the input.
  2921. ;; FIXME: This reduces the problems of inconsistent capitalization
  2922. ;; but it doesn't fully fix it: we may still end up completing
  2923. ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
  2924. ;; '("foo-barr" "FOO-BARD").
  2925. (cond
  2926. ((null (cdr strs)) (list (car strs)))
  2927. (t
  2928. (let ((re (completion-pcm--pattern->regex pattern 'group))
  2929. (ccs ())) ;Chopped completions.
  2930. ;; First chop each string into the parts corresponding to each
  2931. ;; non-constant element of `pattern', using regexp-matching.
  2932. (let ((case-fold-search completion-ignore-case))
  2933. (dolist (str strs)
  2934. (unless (string-match re str)
  2935. (error "Internal error: %s doesn't match %s" str re))
  2936. (let ((chopped ())
  2937. (last 0)
  2938. (i 1)
  2939. next)
  2940. (while (setq next (match-end i))
  2941. (push (substring str last next) chopped)
  2942. (setq last next)
  2943. (setq i (1+ i)))
  2944. ;; Add the text corresponding to the implicit trailing `any'.
  2945. (push (substring str last) chopped)
  2946. (push (nreverse chopped) ccs))))
  2947. ;; Then for each of those non-constant elements, extract the
  2948. ;; commonality between them.
  2949. (let ((res ())
  2950. (fixed ""))
  2951. ;; Make the implicit trailing `any' explicit.
  2952. (dolist (elem (append pattern '(any)))
  2953. (if (stringp elem)
  2954. (setq fixed (concat fixed elem))
  2955. (let ((comps ()))
  2956. (dolist (cc (prog1 ccs (setq ccs nil)))
  2957. (push (car cc) comps)
  2958. (push (cdr cc) ccs))
  2959. ;; Might improve the likelihood to avoid choosing
  2960. ;; different capitalizations in different parts.
  2961. ;; In practice, it doesn't seem to make any difference.
  2962. (setq ccs (nreverse ccs))
  2963. (let* ((prefix (try-completion fixed comps))
  2964. (unique (or (and (eq prefix t) (setq prefix fixed))
  2965. (eq t (try-completion prefix comps)))))
  2966. (unless (or (eq elem 'prefix)
  2967. (equal prefix ""))
  2968. (push prefix res))
  2969. ;; If there's only one completion, `elem' is not useful
  2970. ;; any more: it can only match the empty string.
  2971. ;; FIXME: in some cases, it may be necessary to turn an
  2972. ;; `any' into a `star' because the surrounding context has
  2973. ;; changed such that string->pattern wouldn't add an `any'
  2974. ;; here any more.
  2975. (unless unique
  2976. (push elem res)
  2977. ;; Extract common suffix additionally to common prefix.
  2978. ;; Don't do it for `any' since it could lead to a merged
  2979. ;; completion that doesn't itself match the candidates.
  2980. (when (and (memq elem '(star point prefix))
  2981. ;; If prefix is one of the completions, there's no
  2982. ;; suffix left to find.
  2983. (not (assoc-string prefix comps t)))
  2984. (let ((suffix
  2985. (completion--common-suffix
  2986. (if (zerop (length prefix)) comps
  2987. ;; Ignore the chars in the common prefix, so we
  2988. ;; don't merge '("abc" "abbc") as "ab*bc".
  2989. (let ((skip (length prefix)))
  2990. (mapcar (lambda (str) (substring str skip))
  2991. comps))))))
  2992. (cl-assert (stringp suffix))
  2993. (unless (equal suffix "")
  2994. (push suffix res)))))
  2995. (setq fixed "")))))
  2996. ;; We return it in reverse order.
  2997. res)))))
  2998. (defun completion-pcm--pattern->string (pattern)
  2999. (mapconcat (lambda (x) (cond
  3000. ((stringp x) x)
  3001. ((eq x 'star) "*")
  3002. (t ""))) ;any, point, prefix.
  3003. pattern
  3004. ""))
  3005. ;; We want to provide the functionality of `try', but we use `all'
  3006. ;; and then merge it. In most cases, this works perfectly, but
  3007. ;; if the completion table doesn't consider the same completions in
  3008. ;; `try' as in `all', then we have a problem. The most common such
  3009. ;; case is for filename completion where completion-ignored-extensions
  3010. ;; is only obeyed by the `try' code. We paper over the difference
  3011. ;; here. Note that it is not quite right either: if the completion
  3012. ;; table uses completion-table-in-turn, this filtering may take place
  3013. ;; too late to correctly fallback from the first to the
  3014. ;; second alternative.
  3015. (defun completion-pcm--filename-try-filter (all)
  3016. "Filter to adjust `all' file completion to the behavior of `try'."
  3017. (when all
  3018. (let ((try ())
  3019. (re (concat "\\(?:\\`\\.\\.?/\\|"
  3020. (regexp-opt completion-ignored-extensions)
  3021. "\\)\\'")))
  3022. (dolist (f all)
  3023. (unless (string-match-p re f) (push f try)))
  3024. (or (nreverse try) all))))
  3025. (defun completion-pcm--merge-try (pattern all prefix suffix)
  3026. (cond
  3027. ((not (consp all)) all)
  3028. ((and (not (consp (cdr all))) ;Only one completion.
  3029. ;; Ignore completion-ignore-case here.
  3030. (equal (completion-pcm--pattern->string pattern) (car all)))
  3031. t)
  3032. (t
  3033. (let* ((mergedpat (completion-pcm--merge-completions all pattern))
  3034. ;; `mergedpat' is in reverse order. Place new point (by
  3035. ;; order of preference) either at the old point, or at
  3036. ;; the last place where there's something to choose, or
  3037. ;; at the very end.
  3038. (pointpat (or (memq 'point mergedpat)
  3039. (memq 'any mergedpat)
  3040. (memq 'star mergedpat)
  3041. ;; Not `prefix'.
  3042. mergedpat))
  3043. ;; New pos from the start.
  3044. (newpos (length (completion-pcm--pattern->string pointpat)))
  3045. ;; Do it afterwards because it changes `pointpat' by side effect.
  3046. (merged (completion-pcm--pattern->string (nreverse mergedpat))))
  3047. (setq suffix (completion--merge-suffix
  3048. ;; The second arg should ideally be "the position right
  3049. ;; after the last char of `merged' that comes from the text
  3050. ;; to be completed". But completion-pcm--merge-completions
  3051. ;; currently doesn't give us that info. So instead we just
  3052. ;; use the "last but one" position, which tends to work
  3053. ;; well in practice since `suffix' always starts
  3054. ;; with a boundary and we hence mostly/only care about
  3055. ;; merging this boundary (bug#15419).
  3056. merged (max 0 (1- (length merged))) suffix))
  3057. (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
  3058. (defun completion-pcm-try-completion (string table pred point)
  3059. (pcase-let ((`(,pattern ,all ,prefix ,suffix)
  3060. (completion-pcm--find-all-completions
  3061. string table pred point
  3062. (if minibuffer-completing-file-name
  3063. 'completion-pcm--filename-try-filter))))
  3064. (completion-pcm--merge-try pattern all prefix suffix)))
  3065. ;;; Substring completion
  3066. ;; Mostly derived from the code of `basic' completion.
  3067. (defun completion-substring--all-completions (string table pred point)
  3068. (let* ((beforepoint (substring string 0 point))
  3069. (afterpoint (substring string point))
  3070. (bounds (completion-boundaries beforepoint table pred afterpoint))
  3071. (suffix (substring afterpoint (cdr bounds)))
  3072. (prefix (substring beforepoint 0 (car bounds)))
  3073. (basic-pattern (completion-basic--pattern
  3074. beforepoint afterpoint bounds))
  3075. (pattern (if (not (stringp (car basic-pattern)))
  3076. basic-pattern
  3077. (cons 'prefix basic-pattern)))
  3078. (all (completion-pcm--all-completions prefix pattern table pred)))
  3079. (list all pattern prefix suffix (car bounds))))
  3080. (defun completion-substring-try-completion (string table pred point)
  3081. (pcase-let ((`(,all ,pattern ,prefix ,suffix ,_carbounds)
  3082. (completion-substring--all-completions
  3083. string table pred point)))
  3084. (if minibuffer-completing-file-name
  3085. (setq all (completion-pcm--filename-try-filter all)))
  3086. (completion-pcm--merge-try pattern all prefix suffix)))
  3087. (defun completion-substring-all-completions (string table pred point)
  3088. (pcase-let ((`(,all ,pattern ,prefix ,_suffix ,_carbounds)
  3089. (completion-substring--all-completions
  3090. string table pred point)))
  3091. (when all
  3092. (nconc (completion-pcm--hilit-commonality pattern all)
  3093. (length prefix)))))
  3094. ;; Initials completion
  3095. ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
  3096. (defun completion-initials-expand (str table pred)
  3097. (let ((bounds (completion-boundaries str table pred "")))
  3098. (unless (or (zerop (length str))
  3099. ;; Only check within the boundaries, since the
  3100. ;; boundary char (e.g. /) might be in delim-regexp.
  3101. (string-match completion-pcm--delim-wild-regex str
  3102. (car bounds)))
  3103. (if (zerop (car bounds))
  3104. ;; FIXME: Don't hardcode "-" (bug#17559).
  3105. (mapconcat 'string str "-")
  3106. ;; If there's a boundary, it's trickier. The main use-case
  3107. ;; we consider here is file-name completion. We'd like
  3108. ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
  3109. ;; But at the same time, we don't want /usr/share/ae to expand
  3110. ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
  3111. ;; so we probably don't want initials to touch anything that
  3112. ;; looks like /usr/share/foo. As a heuristic, we just check that
  3113. ;; the text before the boundary char is at most 1 char.
  3114. ;; This allows both ~/eee and /eee and not much more.
  3115. ;; FIXME: It sadly also disallows the use of ~/eee when that's
  3116. ;; embedded within something else (e.g. "(~/eee" in Info node
  3117. ;; completion or "ancestor:/eee" in bzr-revision completion).
  3118. (when (< (car bounds) 3)
  3119. (let ((sep (substring str (1- (car bounds)) (car bounds))))
  3120. ;; FIXME: the above string-match checks the whole string, whereas
  3121. ;; we end up only caring about the after-boundary part.
  3122. (concat (substring str 0 (car bounds))
  3123. (mapconcat 'string (substring str (car bounds)) sep))))))))
  3124. (defun completion-initials-all-completions (string table pred _point)
  3125. (let ((newstr (completion-initials-expand string table pred)))
  3126. (when newstr
  3127. (completion-pcm-all-completions newstr table pred (length newstr)))))
  3128. (defun completion-initials-try-completion (string table pred _point)
  3129. (let ((newstr (completion-initials-expand string table pred)))
  3130. (when newstr
  3131. (completion-pcm-try-completion newstr table pred (length newstr)))))
  3132. (defvar completing-read-function 'completing-read-default
  3133. "The function called by `completing-read' to do its work.
  3134. It should accept the same arguments as `completing-read'.")
  3135. (defun completing-read-default (prompt collection &optional predicate
  3136. require-match initial-input
  3137. hist def inherit-input-method)
  3138. "Default method for reading from the minibuffer with completion.
  3139. See `completing-read' for the meaning of the arguments."
  3140. (when (consp initial-input)
  3141. (setq initial-input
  3142. (cons (car initial-input)
  3143. ;; `completing-read' uses 0-based index while
  3144. ;; `read-from-minibuffer' uses 1-based index.
  3145. (1+ (cdr initial-input)))))
  3146. (let* ((minibuffer-completion-table collection)
  3147. (minibuffer-completion-predicate predicate)
  3148. (minibuffer-completion-confirm (unless (eq require-match t)
  3149. require-match))
  3150. (base-keymap (if require-match
  3151. minibuffer-local-must-match-map
  3152. minibuffer-local-completion-map))
  3153. (keymap (if (memq minibuffer-completing-file-name '(nil lambda))
  3154. base-keymap
  3155. ;; Layer minibuffer-local-filename-completion-map
  3156. ;; on top of the base map.
  3157. (make-composed-keymap
  3158. minibuffer-local-filename-completion-map
  3159. ;; Set base-keymap as the parent, so that nil bindings
  3160. ;; in minibuffer-local-filename-completion-map can
  3161. ;; override bindings in base-keymap.
  3162. base-keymap)))
  3163. (result (read-from-minibuffer prompt initial-input keymap
  3164. nil hist def inherit-input-method)))
  3165. (when (and (equal result "") def)
  3166. (setq result (if (consp def) (car def) def)))
  3167. result))
  3168. ;; Miscellaneous
  3169. (defun minibuffer-insert-file-name-at-point ()
  3170. "Get a file name at point in original buffer and insert it to minibuffer."
  3171. (interactive)
  3172. (let ((file-name-at-point
  3173. (with-current-buffer (window-buffer (minibuffer-selected-window))
  3174. (run-hook-with-args-until-success 'file-name-at-point-functions))))
  3175. (when file-name-at-point
  3176. (insert file-name-at-point))))
  3177. (provide 'minibuffer)
  3178. ;;; minibuffer.el ends here