minibuffer.el 132 KB

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