minibuffer.el 160 KB

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