subr.el 166 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239
  1. ;;; subr.el --- basic lisp subroutines for Emacs -*- coding: utf-8 -*-
  2. ;; Copyright (C) 1985-1986, 1992, 1994-1995, 1999-2012
  3. ;; Free Software Foundation, Inc.
  4. ;; Maintainer: FSF
  5. ;; Keywords: internal
  6. ;; Package: emacs
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;;; Code:
  20. (defvar custom-declare-variable-list nil
  21. "Record `defcustom' calls made before `custom.el' is loaded to handle them.
  22. Each element of this list holds the arguments to one call to `defcustom'.")
  23. ;; Use this, rather than defcustom, in subr.el and other files loaded
  24. ;; before custom.el.
  25. (defun custom-declare-variable-early (&rest arguments)
  26. (setq custom-declare-variable-list
  27. (cons arguments custom-declare-variable-list)))
  28. (defmacro declare-function (fn file &optional arglist fileonly)
  29. "Tell the byte-compiler that function FN is defined, in FILE.
  30. Optional ARGLIST is the argument list used by the function. The
  31. FILE argument is not used by the byte-compiler, but by the
  32. `check-declare' package, which checks that FILE contains a
  33. definition for FN. ARGLIST is used by both the byte-compiler and
  34. `check-declare' to check for consistency.
  35. FILE can be either a Lisp file (in which case the \".el\"
  36. extension is optional), or a C file. C files are expanded
  37. relative to the Emacs \"src/\" directory. Lisp files are
  38. searched for using `locate-library', and if that fails they are
  39. expanded relative to the location of the file containing the
  40. declaration. A FILE with an \"ext:\" prefix is an external file.
  41. `check-declare' will check such files if they are found, and skip
  42. them without error if they are not.
  43. FILEONLY non-nil means that `check-declare' will only check that
  44. FILE exists, not that it defines FN. This is intended for
  45. function-definitions that `check-declare' does not recognize, e.g.
  46. `defstruct'.
  47. To specify a value for FILEONLY without passing an argument list,
  48. set ARGLIST to t. This is necessary because nil means an
  49. empty argument list, rather than an unspecified one.
  50. Note that for the purposes of `check-declare', this statement
  51. must be the first non-whitespace on a line.
  52. For more information, see Info node `(elisp)Declaring Functions'."
  53. ;; Does nothing - byte-compile-declare-function does the work.
  54. nil)
  55. ;;;; Basic Lisp macros.
  56. (defalias 'not 'null)
  57. (defmacro noreturn (form)
  58. "Evaluate FORM, expecting it not to return.
  59. If FORM does return, signal an error."
  60. `(prog1 ,form
  61. (error "Form marked with `noreturn' did return")))
  62. (defmacro 1value (form)
  63. "Evaluate FORM, expecting a constant return value.
  64. This is the global do-nothing version. There is also `testcover-1value'
  65. that complains if FORM ever does return differing values."
  66. form)
  67. (defmacro def-edebug-spec (symbol spec)
  68. "Set the `edebug-form-spec' property of SYMBOL according to SPEC.
  69. Both SYMBOL and SPEC are unevaluated. The SPEC can be:
  70. 0 (instrument no arguments); t (instrument all arguments);
  71. a symbol (naming a function with an Edebug specification); or a list.
  72. The elements of the list describe the argument types; see
  73. Info node `(elisp)Specification List' for details."
  74. `(put (quote ,symbol) 'edebug-form-spec (quote ,spec)))
  75. (defmacro lambda (&rest cdr)
  76. "Return a lambda expression.
  77. A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
  78. self-quoting; the result of evaluating the lambda expression is the
  79. expression itself. The lambda expression may then be treated as a
  80. function, i.e., stored as the function value of a symbol, passed to
  81. `funcall' or `mapcar', etc.
  82. ARGS should take the same form as an argument list for a `defun'.
  83. DOCSTRING is an optional documentation string.
  84. If present, it should describe how to call the function.
  85. But documentation strings are usually not useful in nameless functions.
  86. INTERACTIVE should be a call to the function `interactive', which see.
  87. It may also be omitted.
  88. BODY should be a list of Lisp expressions.
  89. \(fn ARGS [DOCSTRING] [INTERACTIVE] BODY)"
  90. ;; Note that this definition should not use backquotes; subr.el should not
  91. ;; depend on backquote.el.
  92. (list 'function (cons 'lambda cdr)))
  93. (defun apply-partially (fun &rest args)
  94. "Return a function that is a partial application of FUN to ARGS.
  95. ARGS is a list of the first N arguments to pass to FUN.
  96. The result is a new function which does the same as FUN, except that
  97. the first N arguments are fixed at the values with which this function
  98. was called."
  99. `(closure (t) (&rest args)
  100. (apply ',fun ,@(mapcar (lambda (arg) `',arg) args) args)))
  101. (if (null (featurep 'cl))
  102. (progn
  103. ;; If we reload subr.el after having loaded CL, be careful not to
  104. ;; overwrite CL's extended definition of `dolist', `dotimes',
  105. ;; `declare', `push' and `pop'.
  106. (defmacro push (newelt listname)
  107. "Add NEWELT to the list stored in the symbol LISTNAME.
  108. This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
  109. LISTNAME must be a symbol."
  110. (declare (debug (form sexp)))
  111. (list 'setq listname
  112. (list 'cons newelt listname)))
  113. (defmacro pop (listname)
  114. "Return the first element of LISTNAME's value, and remove it from the list.
  115. LISTNAME must be a symbol whose value is a list.
  116. If the value is nil, `pop' returns nil but does not actually
  117. change the list."
  118. (declare (debug (sexp)))
  119. (list 'car
  120. (list 'prog1 listname
  121. (list 'setq listname (list 'cdr listname)))))
  122. ))
  123. (defmacro when (cond &rest body)
  124. "If COND yields non-nil, do BODY, else return nil.
  125. When COND yields non-nil, eval BODY forms sequentially and return
  126. value of last one, or nil if there are none.
  127. \(fn COND BODY...)"
  128. (declare (indent 1) (debug t))
  129. (list 'if cond (cons 'progn body)))
  130. (defmacro unless (cond &rest body)
  131. "If COND yields nil, do BODY, else return nil.
  132. When COND yields nil, eval BODY forms sequentially and return
  133. value of last one, or nil if there are none.
  134. \(fn COND BODY...)"
  135. (declare (indent 1) (debug t))
  136. (cons 'if (cons cond (cons nil body))))
  137. (if (null (featurep 'cl))
  138. (progn
  139. ;; If we reload subr.el after having loaded CL, be careful not to
  140. ;; overwrite CL's extended definition of `dolist', `dotimes',
  141. ;; `declare', `push' and `pop'.
  142. (defmacro dolist (spec &rest body)
  143. "Loop over a list.
  144. Evaluate BODY with VAR bound to each car from LIST, in turn.
  145. Then evaluate RESULT to get return value, default nil.
  146. \(fn (VAR LIST [RESULT]) BODY...)"
  147. (declare (indent 1) (debug ((symbolp form &optional form) body)))
  148. ;; It would be cleaner to create an uninterned symbol,
  149. ;; but that uses a lot more space when many functions in many files
  150. ;; use dolist.
  151. ;; FIXME: This cost disappears in byte-compiled lexical-binding files.
  152. (let ((temp '--dolist-tail--))
  153. ;; This is not a reliable test, but it does not matter because both
  154. ;; semantics are acceptable, tho one is slightly faster with dynamic
  155. ;; scoping and the other is slightly faster (and has cleaner semantics)
  156. ;; with lexical scoping.
  157. (if lexical-binding
  158. `(let ((,temp ,(nth 1 spec)))
  159. (while ,temp
  160. (let ((,(car spec) (car ,temp)))
  161. ,@body
  162. (setq ,temp (cdr ,temp))))
  163. ,@(if (cdr (cdr spec))
  164. ;; FIXME: This let often leads to "unused var" warnings.
  165. `((let ((,(car spec) nil)) ,@(cdr (cdr spec))))))
  166. `(let ((,temp ,(nth 1 spec))
  167. ,(car spec))
  168. (while ,temp
  169. (setq ,(car spec) (car ,temp))
  170. ,@body
  171. (setq ,temp (cdr ,temp)))
  172. ,@(if (cdr (cdr spec))
  173. `((setq ,(car spec) nil) ,@(cdr (cdr spec))))))))
  174. (defmacro dotimes (spec &rest body)
  175. "Loop a certain number of times.
  176. Evaluate BODY with VAR bound to successive integers running from 0,
  177. inclusive, to COUNT, exclusive. Then evaluate RESULT to get
  178. the return value (nil if RESULT is omitted).
  179. \(fn (VAR COUNT [RESULT]) BODY...)"
  180. (declare (indent 1) (debug dolist))
  181. ;; It would be cleaner to create an uninterned symbol,
  182. ;; but that uses a lot more space when many functions in many files
  183. ;; use dotimes.
  184. ;; FIXME: This cost disappears in byte-compiled lexical-binding files.
  185. (let ((temp '--dotimes-limit--)
  186. (start 0)
  187. (end (nth 1 spec)))
  188. ;; This is not a reliable test, but it does not matter because both
  189. ;; semantics are acceptable, tho one is slightly faster with dynamic
  190. ;; scoping and the other has cleaner semantics.
  191. (if lexical-binding
  192. (let ((counter '--dotimes-counter--))
  193. `(let ((,temp ,end)
  194. (,counter ,start))
  195. (while (< ,counter ,temp)
  196. (let ((,(car spec) ,counter))
  197. ,@body)
  198. (setq ,counter (1+ ,counter)))
  199. ,@(if (cddr spec)
  200. ;; FIXME: This let often leads to "unused var" warnings.
  201. `((let ((,(car spec) ,counter)) ,@(cddr spec))))))
  202. `(let ((,temp ,end)
  203. (,(car spec) ,start))
  204. (while (< ,(car spec) ,temp)
  205. ,@body
  206. (setq ,(car spec) (1+ ,(car spec))))
  207. ,@(cdr (cdr spec))))))
  208. (defmacro declare (&rest _specs)
  209. "Do not evaluate any arguments and return nil.
  210. Treated as a declaration when used at the right place in a
  211. `defmacro' form. \(See Info anchor `(elisp)Definition of declare'.)"
  212. nil)
  213. ))
  214. (defmacro ignore-errors (&rest body)
  215. "Execute BODY; if an error occurs, return nil.
  216. Otherwise, return result of last form in BODY."
  217. (declare (debug t) (indent 0))
  218. `(condition-case nil (progn ,@body) (error nil)))
  219. ;;;; Basic Lisp functions.
  220. (defun ignore (&rest _ignore)
  221. "Do nothing and return nil.
  222. This function accepts any number of arguments, but ignores them."
  223. (interactive)
  224. nil)
  225. ;; Signal a compile-error if the first arg is missing.
  226. (defun error (&rest args)
  227. "Signal an error, making error message by passing all args to `format'.
  228. In Emacs, the convention is that error messages start with a capital
  229. letter but *do not* end with a period. Please follow this convention
  230. for the sake of consistency."
  231. (while t
  232. (signal 'error (list (apply 'format args)))))
  233. (set-advertised-calling-convention 'error '(string &rest args) "23.1")
  234. ;; We put this here instead of in frame.el so that it's defined even on
  235. ;; systems where frame.el isn't loaded.
  236. (defun frame-configuration-p (object)
  237. "Return non-nil if OBJECT seems to be a frame configuration.
  238. Any list whose car is `frame-configuration' is assumed to be a frame
  239. configuration."
  240. (and (consp object)
  241. (eq (car object) 'frame-configuration)))
  242. ;;;; List functions.
  243. (defsubst caar (x)
  244. "Return the car of the car of X."
  245. (car (car x)))
  246. (defsubst cadr (x)
  247. "Return the car of the cdr of X."
  248. (car (cdr x)))
  249. (defsubst cdar (x)
  250. "Return the cdr of the car of X."
  251. (cdr (car x)))
  252. (defsubst cddr (x)
  253. "Return the cdr of the cdr of X."
  254. (cdr (cdr x)))
  255. (defun last (list &optional n)
  256. "Return the last link of LIST. Its car is the last element.
  257. If LIST is nil, return nil.
  258. If N is non-nil, return the Nth-to-last link of LIST.
  259. If N is bigger than the length of LIST, return LIST."
  260. (if n
  261. (and (>= n 0)
  262. (let ((m (safe-length list)))
  263. (if (< n m) (nthcdr (- m n) list) list)))
  264. (and list
  265. (nthcdr (1- (safe-length list)) list))))
  266. (defun butlast (list &optional n)
  267. "Return a copy of LIST with the last N elements removed."
  268. (if (and n (<= n 0)) list
  269. (nbutlast (copy-sequence list) n)))
  270. (defun nbutlast (list &optional n)
  271. "Modifies LIST to remove the last N elements."
  272. (let ((m (length list)))
  273. (or n (setq n 1))
  274. (and (< n m)
  275. (progn
  276. (if (> n 0) (setcdr (nthcdr (- (1- m) n) list) nil))
  277. list))))
  278. (defun delete-dups (list)
  279. "Destructively remove `equal' duplicates from LIST.
  280. Store the result in LIST and return it. LIST must be a proper list.
  281. Of several `equal' occurrences of an element in LIST, the first
  282. one is kept."
  283. (let ((tail list))
  284. (while tail
  285. (setcdr tail (delete (car tail) (cdr tail)))
  286. (setq tail (cdr tail))))
  287. list)
  288. (defun number-sequence (from &optional to inc)
  289. "Return a sequence of numbers from FROM to TO (both inclusive) as a list.
  290. INC is the increment used between numbers in the sequence and defaults to 1.
  291. So, the Nth element of the list is \(+ FROM \(* N INC)) where N counts from
  292. zero. TO is only included if there is an N for which TO = FROM + N * INC.
  293. If TO is nil or numerically equal to FROM, return \(FROM).
  294. If INC is positive and TO is less than FROM, or INC is negative
  295. and TO is larger than FROM, return nil.
  296. If INC is zero and TO is neither nil nor numerically equal to
  297. FROM, signal an error.
  298. This function is primarily designed for integer arguments.
  299. Nevertheless, FROM, TO and INC can be integer or float. However,
  300. floating point arithmetic is inexact. For instance, depending on
  301. the machine, it may quite well happen that
  302. \(number-sequence 0.4 0.6 0.2) returns the one element list \(0.4),
  303. whereas \(number-sequence 0.4 0.8 0.2) returns a list with three
  304. elements. Thus, if some of the arguments are floats and one wants
  305. to make sure that TO is included, one may have to explicitly write
  306. TO as \(+ FROM \(* N INC)) or use a variable whose value was
  307. computed with this exact expression. Alternatively, you can,
  308. of course, also replace TO with a slightly larger value
  309. \(or a slightly more negative value if INC is negative)."
  310. (if (or (not to) (= from to))
  311. (list from)
  312. (or inc (setq inc 1))
  313. (when (zerop inc) (error "The increment can not be zero"))
  314. (let (seq (n 0) (next from))
  315. (if (> inc 0)
  316. (while (<= next to)
  317. (setq seq (cons next seq)
  318. n (1+ n)
  319. next (+ from (* n inc))))
  320. (while (>= next to)
  321. (setq seq (cons next seq)
  322. n (1+ n)
  323. next (+ from (* n inc)))))
  324. (nreverse seq))))
  325. (defun copy-tree (tree &optional vecp)
  326. "Make a copy of TREE.
  327. If TREE is a cons cell, this recursively copies both its car and its cdr.
  328. Contrast to `copy-sequence', which copies only along the cdrs. With second
  329. argument VECP, this copies vectors as well as conses."
  330. (if (consp tree)
  331. (let (result)
  332. (while (consp tree)
  333. (let ((newcar (car tree)))
  334. (if (or (consp (car tree)) (and vecp (vectorp (car tree))))
  335. (setq newcar (copy-tree (car tree) vecp)))
  336. (push newcar result))
  337. (setq tree (cdr tree)))
  338. (nconc (nreverse result) tree))
  339. (if (and vecp (vectorp tree))
  340. (let ((i (length (setq tree (copy-sequence tree)))))
  341. (while (>= (setq i (1- i)) 0)
  342. (aset tree i (copy-tree (aref tree i) vecp)))
  343. tree)
  344. tree)))
  345. ;;;; Various list-search functions.
  346. (defun assoc-default (key alist &optional test default)
  347. "Find object KEY in a pseudo-alist ALIST.
  348. ALIST is a list of conses or objects. Each element
  349. (or the element's car, if it is a cons) is compared with KEY by
  350. calling TEST, with two arguments: (i) the element or its car,
  351. and (ii) KEY.
  352. If that is non-nil, the element matches; then `assoc-default'
  353. returns the element's cdr, if it is a cons, or DEFAULT if the
  354. element is not a cons.
  355. If no element matches, the value is nil.
  356. If TEST is omitted or nil, `equal' is used."
  357. (let (found (tail alist) value)
  358. (while (and tail (not found))
  359. (let ((elt (car tail)))
  360. (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
  361. (setq found t value (if (consp elt) (cdr elt) default))))
  362. (setq tail (cdr tail)))
  363. value))
  364. (make-obsolete 'assoc-ignore-case 'assoc-string "22.1")
  365. (defun assoc-ignore-case (key alist)
  366. "Like `assoc', but ignores differences in case and text representation.
  367. KEY must be a string. Upper-case and lower-case letters are treated as equal.
  368. Unibyte strings are converted to multibyte for comparison."
  369. (assoc-string key alist t))
  370. (make-obsolete 'assoc-ignore-representation 'assoc-string "22.1")
  371. (defun assoc-ignore-representation (key alist)
  372. "Like `assoc', but ignores differences in text representation.
  373. KEY must be a string.
  374. Unibyte strings are converted to multibyte for comparison."
  375. (assoc-string key alist nil))
  376. (defun member-ignore-case (elt list)
  377. "Like `member', but ignore differences in case and text representation.
  378. ELT must be a string. Upper-case and lower-case letters are treated as equal.
  379. Unibyte strings are converted to multibyte for comparison.
  380. Non-strings in LIST are ignored."
  381. (while (and list
  382. (not (and (stringp (car list))
  383. (eq t (compare-strings elt 0 nil (car list) 0 nil t)))))
  384. (setq list (cdr list)))
  385. list)
  386. (defun assq-delete-all (key alist)
  387. "Delete from ALIST all elements whose car is `eq' to KEY.
  388. Return the modified alist.
  389. Elements of ALIST that are not conses are ignored."
  390. (while (and (consp (car alist))
  391. (eq (car (car alist)) key))
  392. (setq alist (cdr alist)))
  393. (let ((tail alist) tail-cdr)
  394. (while (setq tail-cdr (cdr tail))
  395. (if (and (consp (car tail-cdr))
  396. (eq (car (car tail-cdr)) key))
  397. (setcdr tail (cdr tail-cdr))
  398. (setq tail tail-cdr))))
  399. alist)
  400. (defun rassq-delete-all (value alist)
  401. "Delete from ALIST all elements whose cdr is `eq' to VALUE.
  402. Return the modified alist.
  403. Elements of ALIST that are not conses are ignored."
  404. (while (and (consp (car alist))
  405. (eq (cdr (car alist)) value))
  406. (setq alist (cdr alist)))
  407. (let ((tail alist) tail-cdr)
  408. (while (setq tail-cdr (cdr tail))
  409. (if (and (consp (car tail-cdr))
  410. (eq (cdr (car tail-cdr)) value))
  411. (setcdr tail (cdr tail-cdr))
  412. (setq tail tail-cdr))))
  413. alist)
  414. (defun remove (elt seq)
  415. "Return a copy of SEQ with all occurrences of ELT removed.
  416. SEQ must be a list, vector, or string. The comparison is done with `equal'."
  417. (if (nlistp seq)
  418. ;; If SEQ isn't a list, there's no need to copy SEQ because
  419. ;; `delete' will return a new object.
  420. (delete elt seq)
  421. (delete elt (copy-sequence seq))))
  422. (defun remq (elt list)
  423. "Return LIST with all occurrences of ELT removed.
  424. The comparison is done with `eq'. Contrary to `delq', this does not use
  425. side-effects, and the argument LIST is not modified."
  426. (while (and (eq elt (car list)) (setq list (cdr list))))
  427. (if (memq elt list)
  428. (delq elt (copy-sequence list))
  429. list))
  430. ;;;; Keymap support.
  431. (defmacro kbd (keys)
  432. "Convert KEYS to the internal Emacs key representation.
  433. KEYS should be a string constant in the format used for
  434. saving keyboard macros (see `edmacro-mode')."
  435. (read-kbd-macro keys))
  436. (defun undefined ()
  437. "Beep to tell the user this binding is undefined."
  438. (interactive)
  439. (ding))
  440. ;; Prevent the \{...} documentation construct
  441. ;; from mentioning keys that run this command.
  442. (put 'undefined 'suppress-keymap t)
  443. (defun suppress-keymap (map &optional nodigits)
  444. "Make MAP override all normally self-inserting keys to be undefined.
  445. Normally, as an exception, digits and minus-sign are set to make prefix args,
  446. but optional second arg NODIGITS non-nil treats them like other chars."
  447. (define-key map [remap self-insert-command] 'undefined)
  448. (or nodigits
  449. (let (loop)
  450. (define-key map "-" 'negative-argument)
  451. ;; Make plain numbers do numeric args.
  452. (setq loop ?0)
  453. (while (<= loop ?9)
  454. (define-key map (char-to-string loop) 'digit-argument)
  455. (setq loop (1+ loop))))))
  456. (defun make-composed-keymap (maps &optional parent)
  457. "Construct a new keymap composed of MAPS and inheriting from PARENT.
  458. When looking up a key in the returned map, the key is looked in each
  459. keymap of MAPS in turn until a binding is found.
  460. If no binding is found in MAPS, the lookup continues in PARENT, if non-nil.
  461. As always with keymap inheritance, a nil binding in MAPS overrides
  462. any corresponding binding in PARENT, but it does not override corresponding
  463. bindings in other keymaps of MAPS.
  464. MAPS can be a list of keymaps or a single keymap.
  465. PARENT if non-nil should be a keymap."
  466. `(keymap
  467. ,@(if (keymapp maps) (list maps) maps)
  468. ,@parent))
  469. (defun define-key-after (keymap key definition &optional after)
  470. "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
  471. This is like `define-key' except that the binding for KEY is placed
  472. just after the binding for the event AFTER, instead of at the beginning
  473. of the map. Note that AFTER must be an event type (like KEY), NOT a command
  474. \(like DEFINITION).
  475. If AFTER is t or omitted, the new binding goes at the end of the keymap.
  476. AFTER should be a single event type--a symbol or a character, not a sequence.
  477. Bindings are always added before any inherited map.
  478. The order of bindings in a keymap only matters when it is used as
  479. a menu, so this function is not useful for non-menu keymaps."
  480. (unless after (setq after t))
  481. (or (keymapp keymap)
  482. (signal 'wrong-type-argument (list 'keymapp keymap)))
  483. (setq key
  484. (if (<= (length key) 1) (aref key 0)
  485. (setq keymap (lookup-key keymap
  486. (apply 'vector
  487. (butlast (mapcar 'identity key)))))
  488. (aref key (1- (length key)))))
  489. (let ((tail keymap) done inserted)
  490. (while (and (not done) tail)
  491. ;; Delete any earlier bindings for the same key.
  492. (if (eq (car-safe (car (cdr tail))) key)
  493. (setcdr tail (cdr (cdr tail))))
  494. ;; If we hit an included map, go down that one.
  495. (if (keymapp (car tail)) (setq tail (car tail)))
  496. ;; When we reach AFTER's binding, insert the new binding after.
  497. ;; If we reach an inherited keymap, insert just before that.
  498. ;; If we reach the end of this keymap, insert at the end.
  499. (if (or (and (eq (car-safe (car tail)) after)
  500. (not (eq after t)))
  501. (eq (car (cdr tail)) 'keymap)
  502. (null (cdr tail)))
  503. (progn
  504. ;; Stop the scan only if we find a parent keymap.
  505. ;; Keep going past the inserted element
  506. ;; so we can delete any duplications that come later.
  507. (if (eq (car (cdr tail)) 'keymap)
  508. (setq done t))
  509. ;; Don't insert more than once.
  510. (or inserted
  511. (setcdr tail (cons (cons key definition) (cdr tail))))
  512. (setq inserted t)))
  513. (setq tail (cdr tail)))))
  514. (defun map-keymap-sorted (function keymap)
  515. "Implement `map-keymap' with sorting.
  516. Don't call this function; it is for internal use only."
  517. (let (list)
  518. (map-keymap (lambda (a b) (push (cons a b) list))
  519. keymap)
  520. (setq list (sort list
  521. (lambda (a b)
  522. (setq a (car a) b (car b))
  523. (if (integerp a)
  524. (if (integerp b) (< a b)
  525. t)
  526. (if (integerp b) t
  527. ;; string< also accepts symbols.
  528. (string< a b))))))
  529. (dolist (p list)
  530. (funcall function (car p) (cdr p)))))
  531. (defun keymap--menu-item-binding (val)
  532. "Return the binding part of a menu-item."
  533. (cond
  534. ((not (consp val)) val) ;Not a menu-item.
  535. ((eq 'menu-item (car val))
  536. (let* ((binding (nth 2 val))
  537. (plist (nthcdr 3 val))
  538. (filter (plist-get plist :filter)))
  539. (if filter (funcall filter binding)
  540. binding)))
  541. ((and (consp (cdr val)) (stringp (cadr val)))
  542. (cddr val))
  543. ((stringp (car val))
  544. (cdr val))
  545. (t val))) ;Not a menu-item either.
  546. (defun keymap--menu-item-with-binding (item binding)
  547. "Build a menu-item like ITEM but with its binding changed to BINDING."
  548. (cond
  549. ((not (consp item)) binding) ;Not a menu-item.
  550. ((eq 'menu-item (car item))
  551. (setq item (copy-sequence item))
  552. (let ((tail (nthcdr 2 item)))
  553. (setcar tail binding)
  554. ;; Remove any potential filter.
  555. (if (plist-get (cdr tail) :filter)
  556. (setcdr tail (plist-put (cdr tail) :filter nil))))
  557. item)
  558. ((and (consp (cdr item)) (stringp (cadr item)))
  559. (cons (car item) (cons (cadr item) binding)))
  560. (t (cons (car item) binding))))
  561. (defun keymap--merge-bindings (val1 val2)
  562. "Merge bindings VAL1 and VAL2."
  563. (let ((map1 (keymap--menu-item-binding val1))
  564. (map2 (keymap--menu-item-binding val2)))
  565. (if (not (and (keymapp map1) (keymapp map2)))
  566. ;; There's nothing to merge: val1 takes precedence.
  567. val1
  568. (let ((map (list 'keymap map1 map2))
  569. (item (if (keymapp val1) (if (keymapp val2) nil val2) val1)))
  570. (keymap--menu-item-with-binding item map)))))
  571. (defun keymap-canonicalize (map)
  572. "Return a simpler equivalent keymap.
  573. This resolves inheritance and redefinitions. The returned keymap
  574. should behave identically to a copy of KEYMAP w.r.t `lookup-key'
  575. and use in active keymaps and menus.
  576. Subkeymaps may be modified but are not canonicalized."
  577. ;; FIXME: Problem with the difference between a nil binding
  578. ;; that hides a binding in an inherited map and a nil binding that's ignored
  579. ;; to let some further binding visible. Currently a nil binding hides all.
  580. ;; FIXME: we may want to carefully (re)order elements in case they're
  581. ;; menu-entries.
  582. (let ((bindings ())
  583. (ranges ())
  584. (prompt (keymap-prompt map)))
  585. (while (keymapp map)
  586. (setq map (map-keymap ;; -internal
  587. (lambda (key item)
  588. (if (consp key)
  589. ;; Treat char-ranges specially.
  590. (push (cons key item) ranges)
  591. (push (cons key item) bindings)))
  592. map)))
  593. ;; Create the new map.
  594. (setq map (funcall (if ranges 'make-keymap 'make-sparse-keymap) prompt))
  595. (dolist (binding ranges)
  596. ;; Treat char-ranges specially. FIXME: need to merge as well.
  597. (define-key map (vector (car binding)) (cdr binding)))
  598. ;; Process the bindings starting from the end.
  599. (dolist (binding (prog1 bindings (setq bindings ())))
  600. (let* ((key (car binding))
  601. (item (cdr binding))
  602. (oldbind (assq key bindings)))
  603. (push (if (not oldbind)
  604. ;; The normal case: no duplicate bindings.
  605. binding
  606. ;; This is the second binding for this key.
  607. (setq bindings (delq oldbind bindings))
  608. (cons key (keymap--merge-bindings (cdr binding)
  609. (cdr oldbind))))
  610. bindings)))
  611. (nconc map bindings)))
  612. (put 'keyboard-translate-table 'char-table-extra-slots 0)
  613. (defun keyboard-translate (from to)
  614. "Translate character FROM to TO at a low level.
  615. This function creates a `keyboard-translate-table' if necessary
  616. and then modifies one entry in it."
  617. (or (char-table-p keyboard-translate-table)
  618. (setq keyboard-translate-table
  619. (make-char-table 'keyboard-translate-table nil)))
  620. (aset keyboard-translate-table from to))
  621. ;;;; Key binding commands.
  622. (defun global-set-key (key command)
  623. "Give KEY a global binding as COMMAND.
  624. COMMAND is the command definition to use; usually it is
  625. a symbol naming an interactively-callable function.
  626. KEY is a key sequence; noninteractively, it is a string or vector
  627. of characters or event types, and non-ASCII characters with codes
  628. above 127 (such as ISO Latin-1) can be included if you use a vector.
  629. Note that if KEY has a local binding in the current buffer,
  630. that local binding will continue to shadow any global binding
  631. that you make with this function."
  632. (interactive "KSet key globally: \nCSet key %s to command: ")
  633. (or (vectorp key) (stringp key)
  634. (signal 'wrong-type-argument (list 'arrayp key)))
  635. (define-key (current-global-map) key command))
  636. (defun local-set-key (key command)
  637. "Give KEY a local binding as COMMAND.
  638. COMMAND is the command definition to use; usually it is
  639. a symbol naming an interactively-callable function.
  640. KEY is a key sequence; noninteractively, it is a string or vector
  641. of characters or event types, and non-ASCII characters with codes
  642. above 127 (such as ISO Latin-1) can be included if you use a vector.
  643. The binding goes in the current buffer's local map,
  644. which in most cases is shared with all other buffers in the same major mode."
  645. (interactive "KSet key locally: \nCSet key %s locally to command: ")
  646. (let ((map (current-local-map)))
  647. (or map
  648. (use-local-map (setq map (make-sparse-keymap))))
  649. (or (vectorp key) (stringp key)
  650. (signal 'wrong-type-argument (list 'arrayp key)))
  651. (define-key map key command)))
  652. (defun global-unset-key (key)
  653. "Remove global binding of KEY.
  654. KEY is a string or vector representing a sequence of keystrokes."
  655. (interactive "kUnset key globally: ")
  656. (global-set-key key nil))
  657. (defun local-unset-key (key)
  658. "Remove local binding of KEY.
  659. KEY is a string or vector representing a sequence of keystrokes."
  660. (interactive "kUnset key locally: ")
  661. (if (current-local-map)
  662. (local-set-key key nil))
  663. nil)
  664. ;;;; substitute-key-definition and its subroutines.
  665. (defvar key-substitution-in-progress nil
  666. "Used internally by `substitute-key-definition'.")
  667. (defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
  668. "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
  669. In other words, OLDDEF is replaced with NEWDEF where ever it appears.
  670. Alternatively, if optional fourth argument OLDMAP is specified, we redefine
  671. in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP.
  672. If you don't specify OLDMAP, you can usually get the same results
  673. in a cleaner way with command remapping, like this:
  674. \(define-key KEYMAP [remap OLDDEF] NEWDEF)
  675. \n(fn OLDDEF NEWDEF KEYMAP &optional OLDMAP)"
  676. ;; Don't document PREFIX in the doc string because we don't want to
  677. ;; advertise it. It's meant for recursive calls only. Here's its
  678. ;; meaning
  679. ;; If optional argument PREFIX is specified, it should be a key
  680. ;; prefix, a string. Redefined bindings will then be bound to the
  681. ;; original key, with PREFIX added at the front.
  682. (or prefix (setq prefix ""))
  683. (let* ((scan (or oldmap keymap))
  684. (prefix1 (vconcat prefix [nil]))
  685. (key-substitution-in-progress
  686. (cons scan key-substitution-in-progress)))
  687. ;; Scan OLDMAP, finding each char or event-symbol that
  688. ;; has any definition, and act on it with hack-key.
  689. (map-keymap
  690. (lambda (char defn)
  691. (aset prefix1 (length prefix) char)
  692. (substitute-key-definition-key defn olddef newdef prefix1 keymap))
  693. scan)))
  694. (defun substitute-key-definition-key (defn olddef newdef prefix keymap)
  695. (let (inner-def skipped menu-item)
  696. ;; Find the actual command name within the binding.
  697. (if (eq (car-safe defn) 'menu-item)
  698. (setq menu-item defn defn (nth 2 defn))
  699. ;; Skip past menu-prompt.
  700. (while (stringp (car-safe defn))
  701. (push (pop defn) skipped))
  702. ;; Skip past cached key-equivalence data for menu items.
  703. (if (consp (car-safe defn))
  704. (setq defn (cdr defn))))
  705. (if (or (eq defn olddef)
  706. ;; Compare with equal if definition is a key sequence.
  707. ;; That is useful for operating on function-key-map.
  708. (and (or (stringp defn) (vectorp defn))
  709. (equal defn olddef)))
  710. (define-key keymap prefix
  711. (if menu-item
  712. (let ((copy (copy-sequence menu-item)))
  713. (setcar (nthcdr 2 copy) newdef)
  714. copy)
  715. (nconc (nreverse skipped) newdef)))
  716. ;; Look past a symbol that names a keymap.
  717. (setq inner-def
  718. (or (indirect-function defn t) defn))
  719. ;; For nested keymaps, we use `inner-def' rather than `defn' so as to
  720. ;; avoid autoloading a keymap. This is mostly done to preserve the
  721. ;; original non-autoloading behavior of pre-map-keymap times.
  722. (if (and (keymapp inner-def)
  723. ;; Avoid recursively scanning
  724. ;; where KEYMAP does not have a submap.
  725. (let ((elt (lookup-key keymap prefix)))
  726. (or (null elt) (natnump elt) (keymapp elt)))
  727. ;; Avoid recursively rescanning keymap being scanned.
  728. (not (memq inner-def key-substitution-in-progress)))
  729. ;; If this one isn't being scanned already, scan it now.
  730. (substitute-key-definition olddef newdef keymap inner-def prefix)))))
  731. ;;;; The global keymap tree.
  732. ;; global-map, esc-map, and ctl-x-map have their values set up in
  733. ;; keymap.c; we just give them docstrings here.
  734. (defvar global-map nil
  735. "Default global keymap mapping Emacs keyboard input into commands.
  736. The value is a keymap which is usually (but not necessarily) Emacs's
  737. global map.")
  738. (defvar esc-map nil
  739. "Default keymap for ESC (meta) commands.
  740. The normal global definition of the character ESC indirects to this keymap.")
  741. (defvar ctl-x-map nil
  742. "Default keymap for C-x commands.
  743. The normal global definition of the character C-x indirects to this keymap.")
  744. (defvar ctl-x-4-map (make-sparse-keymap)
  745. "Keymap for subcommands of C-x 4.")
  746. (defalias 'ctl-x-4-prefix ctl-x-4-map)
  747. (define-key ctl-x-map "4" 'ctl-x-4-prefix)
  748. (defvar ctl-x-5-map (make-sparse-keymap)
  749. "Keymap for frame commands.")
  750. (defalias 'ctl-x-5-prefix ctl-x-5-map)
  751. (define-key ctl-x-map "5" 'ctl-x-5-prefix)
  752. ;;;; Event manipulation functions.
  753. (defconst listify-key-sequence-1 (logior 128 ?\M-\C-@))
  754. (defun listify-key-sequence (key)
  755. "Convert a key sequence to a list of events."
  756. (if (vectorp key)
  757. (append key nil)
  758. (mapcar (function (lambda (c)
  759. (if (> c 127)
  760. (logxor c listify-key-sequence-1)
  761. c)))
  762. key)))
  763. (defsubst eventp (obj)
  764. "True if the argument is an event object."
  765. (or (and (integerp obj)
  766. ;; Filter out integers too large to be events.
  767. ;; M is the biggest modifier.
  768. (zerop (logand obj (lognot (1- (lsh ?\M-\^@ 1)))))
  769. (characterp (event-basic-type obj)))
  770. (and (symbolp obj)
  771. (get obj 'event-symbol-elements))
  772. (and (consp obj)
  773. (symbolp (car obj))
  774. (get (car obj) 'event-symbol-elements))))
  775. (defun event-modifiers (event)
  776. "Return a list of symbols representing the modifier keys in event EVENT.
  777. The elements of the list may include `meta', `control',
  778. `shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
  779. and `down'.
  780. EVENT may be an event or an event type. If EVENT is a symbol
  781. that has never been used in an event that has been read as input
  782. in the current Emacs session, then this function may fail to include
  783. the `click' modifier."
  784. (let ((type event))
  785. (if (listp type)
  786. (setq type (car type)))
  787. (if (symbolp type)
  788. ;; Don't read event-symbol-elements directly since we're not
  789. ;; sure the symbol has already been parsed.
  790. (cdr (internal-event-symbol-parse-modifiers type))
  791. (let ((list nil)
  792. (char (logand type (lognot (logior ?\M-\^@ ?\C-\^@ ?\S-\^@
  793. ?\H-\^@ ?\s-\^@ ?\A-\^@)))))
  794. (if (not (zerop (logand type ?\M-\^@)))
  795. (push 'meta list))
  796. (if (or (not (zerop (logand type ?\C-\^@)))
  797. (< char 32))
  798. (push 'control list))
  799. (if (or (not (zerop (logand type ?\S-\^@)))
  800. (/= char (downcase char)))
  801. (push 'shift list))
  802. (or (zerop (logand type ?\H-\^@))
  803. (push 'hyper list))
  804. (or (zerop (logand type ?\s-\^@))
  805. (push 'super list))
  806. (or (zerop (logand type ?\A-\^@))
  807. (push 'alt list))
  808. list))))
  809. (defun event-basic-type (event)
  810. "Return the basic type of the given event (all modifiers removed).
  811. The value is a printing character (not upper case) or a symbol.
  812. EVENT may be an event or an event type. If EVENT is a symbol
  813. that has never been used in an event that has been read as input
  814. in the current Emacs session, then this function may return nil."
  815. (if (consp event)
  816. (setq event (car event)))
  817. (if (symbolp event)
  818. (car (get event 'event-symbol-elements))
  819. (let* ((base (logand event (1- ?\A-\^@)))
  820. (uncontrolled (if (< base 32) (logior base 64) base)))
  821. ;; There are some numbers that are invalid characters and
  822. ;; cause `downcase' to get an error.
  823. (condition-case ()
  824. (downcase uncontrolled)
  825. (error uncontrolled)))))
  826. (defsubst mouse-movement-p (object)
  827. "Return non-nil if OBJECT is a mouse movement event."
  828. (eq (car-safe object) 'mouse-movement))
  829. (defun mouse-event-p (object)
  830. "Return non-nil if OBJECT is a mouse click event."
  831. ;; is this really correct? maybe remove mouse-movement?
  832. (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement)))
  833. (defsubst event-start (event)
  834. "Return the starting position of EVENT.
  835. EVENT should be a click, drag, or key press event.
  836. If it is a key press event, the return value has the form
  837. (WINDOW POS (0 . 0) 0)
  838. If it is a click or drag event, it has the form
  839. (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
  840. IMAGE (DX . DY) (WIDTH . HEIGHT))
  841. The `posn-' functions access elements of such lists.
  842. For more information, see Info node `(elisp)Click Events'.
  843. If EVENT is a mouse or key press or a mouse click, this is the
  844. position of the event. If EVENT is a drag, this is the starting
  845. position of the drag."
  846. (if (consp event) (nth 1 event)
  847. (list (selected-window) (point) '(0 . 0) 0)))
  848. (defsubst event-end (event)
  849. "Return the ending location of EVENT.
  850. EVENT should be a click, drag, or key press event.
  851. If EVENT is a key press event, the return value has the form
  852. (WINDOW POS (0 . 0) 0)
  853. If EVENT is a click event, this function is the same as
  854. `event-start'. For click and drag events, the return value has
  855. the form
  856. (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
  857. IMAGE (DX . DY) (WIDTH . HEIGHT))
  858. The `posn-' functions access elements of such lists.
  859. For more information, see Info node `(elisp)Click Events'.
  860. If EVENT is a mouse or key press or a mouse click, this is the
  861. position of the event. If EVENT is a drag, this is the starting
  862. position of the drag."
  863. (if (consp event) (nth (if (consp (nth 2 event)) 2 1) event)
  864. (list (selected-window) (point) '(0 . 0) 0)))
  865. (defsubst event-click-count (event)
  866. "Return the multi-click count of EVENT, a click or drag event.
  867. The return value is a positive integer."
  868. (if (and (consp event) (integerp (nth 2 event))) (nth 2 event) 1))
  869. ;;;; Extracting fields of the positions in an event.
  870. (defsubst posn-window (position)
  871. "Return the window in POSITION.
  872. POSITION should be a list of the form returned by the `event-start'
  873. and `event-end' functions."
  874. (nth 0 position))
  875. (defsubst posn-area (position)
  876. "Return the window area recorded in POSITION, or nil for the text area.
  877. POSITION should be a list of the form returned by the `event-start'
  878. and `event-end' functions."
  879. (let ((area (if (consp (nth 1 position))
  880. (car (nth 1 position))
  881. (nth 1 position))))
  882. (and (symbolp area) area)))
  883. (defsubst posn-point (position)
  884. "Return the buffer location in POSITION.
  885. POSITION should be a list of the form returned by the `event-start'
  886. and `event-end' functions."
  887. (or (nth 5 position)
  888. (if (consp (nth 1 position))
  889. (car (nth 1 position))
  890. (nth 1 position))))
  891. (defun posn-set-point (position)
  892. "Move point to POSITION.
  893. Select the corresponding window as well."
  894. (if (not (windowp (posn-window position)))
  895. (error "Position not in text area of window"))
  896. (select-window (posn-window position))
  897. (if (numberp (posn-point position))
  898. (goto-char (posn-point position))))
  899. (defsubst posn-x-y (position)
  900. "Return the x and y coordinates in POSITION.
  901. The return value has the form (X . Y), where X and Y are given in
  902. pixels. POSITION should be a list of the form returned by
  903. `event-start' and `event-end'."
  904. (nth 2 position))
  905. (declare-function scroll-bar-scale "scroll-bar" (num-denom whole))
  906. (defun posn-col-row (position)
  907. "Return the nominal column and row in POSITION, measured in characters.
  908. The column and row values are approximations calculated from the x
  909. and y coordinates in POSITION and the frame's default character width
  910. and height.
  911. For a scroll-bar event, the result column is 0, and the row
  912. corresponds to the vertical position of the click in the scroll bar.
  913. POSITION should be a list of the form returned by the `event-start'
  914. and `event-end' functions."
  915. (let* ((pair (posn-x-y position))
  916. (window (posn-window position))
  917. (area (posn-area position)))
  918. (cond
  919. ((null window)
  920. '(0 . 0))
  921. ((eq area 'vertical-scroll-bar)
  922. (cons 0 (scroll-bar-scale pair (1- (window-height window)))))
  923. ((eq area 'horizontal-scroll-bar)
  924. (cons (scroll-bar-scale pair (window-width window)) 0))
  925. (t
  926. (let* ((frame (if (framep window) window (window-frame window)))
  927. ;; FIXME: This should take line-spacing properties on
  928. ;; newlines into account.
  929. (spacing (when (display-graphic-p frame)
  930. (or (with-current-buffer (window-buffer window)
  931. line-spacing)
  932. (frame-parameter frame 'line-spacing)))))
  933. (cond ((floatp spacing)
  934. (setq spacing (truncate (* spacing
  935. (frame-char-height frame)))))
  936. ((null spacing)
  937. (setq spacing 0)))
  938. (cons (/ (car pair) (frame-char-width frame))
  939. (- (/ (cdr pair) (+ (frame-char-height frame) spacing))
  940. (if (null (with-current-buffer (window-buffer window)
  941. header-line-format))
  942. 0 1))))))))
  943. (defun posn-actual-col-row (position)
  944. "Return the actual column and row in POSITION, measured in characters.
  945. These are the actual row number in the window and character number in that row.
  946. Return nil if POSITION does not contain the actual position; in that case
  947. `posn-col-row' can be used to get approximate values.
  948. POSITION should be a list of the form returned by the `event-start'
  949. and `event-end' functions."
  950. (nth 6 position))
  951. (defsubst posn-timestamp (position)
  952. "Return the timestamp of POSITION.
  953. POSITION should be a list of the form returned by the `event-start'
  954. and `event-end' functions."
  955. (nth 3 position))
  956. (defsubst posn-string (position)
  957. "Return the string object of POSITION.
  958. Value is a cons (STRING . STRING-POS), or nil if not a string.
  959. POSITION should be a list of the form returned by the `event-start'
  960. and `event-end' functions."
  961. (nth 4 position))
  962. (defsubst posn-image (position)
  963. "Return the image object of POSITION.
  964. Value is a list (image ...), or nil if not an image.
  965. POSITION should be a list of the form returned by the `event-start'
  966. and `event-end' functions."
  967. (nth 7 position))
  968. (defsubst posn-object (position)
  969. "Return the object (image or string) of POSITION.
  970. Value is a list (image ...) for an image object, a cons cell
  971. \(STRING . STRING-POS) for a string object, and nil for a buffer position.
  972. POSITION should be a list of the form returned by the `event-start'
  973. and `event-end' functions."
  974. (or (posn-image position) (posn-string position)))
  975. (defsubst posn-object-x-y (position)
  976. "Return the x and y coordinates relative to the object of POSITION.
  977. The return value has the form (DX . DY), where DX and DY are
  978. given in pixels. POSITION should be a list of the form returned
  979. by `event-start' and `event-end'."
  980. (nth 8 position))
  981. (defsubst posn-object-width-height (position)
  982. "Return the pixel width and height of the object of POSITION.
  983. The return value has the form (WIDTH . HEIGHT). POSITION should
  984. be a list of the form returned by `event-start' and `event-end'."
  985. (nth 9 position))
  986. ;;;; Obsolescent names for functions.
  987. (define-obsolete-function-alias 'window-dot 'window-point "22.1")
  988. (define-obsolete-function-alias 'set-window-dot 'set-window-point "22.1")
  989. (define-obsolete-function-alias 'read-input 'read-string "22.1")
  990. (define-obsolete-function-alias 'show-buffer 'set-window-buffer "22.1")
  991. (define-obsolete-function-alias 'eval-current-buffer 'eval-buffer "22.1")
  992. (define-obsolete-function-alias 'string-to-int 'string-to-number "22.1")
  993. (make-obsolete 'forward-point "use (+ (point) N) instead." "23.1")
  994. (defun insert-string (&rest args)
  995. "Mocklisp-compatibility insert function.
  996. Like the function `insert' except that any argument that is a number
  997. is converted into a string by expressing it in decimal."
  998. (dolist (el args)
  999. (insert (if (integerp el) (number-to-string el) el))))
  1000. (make-obsolete 'insert-string 'insert "22.1")
  1001. (defun makehash (&optional test) (make-hash-table :test (or test 'eql)))
  1002. (make-obsolete 'makehash 'make-hash-table "22.1")
  1003. ;; These are used by VM and some old programs
  1004. (defalias 'focus-frame 'ignore "")
  1005. (make-obsolete 'focus-frame "it does nothing." "22.1")
  1006. (defalias 'unfocus-frame 'ignore "")
  1007. (make-obsolete 'unfocus-frame "it does nothing." "22.1")
  1008. (make-obsolete 'make-variable-frame-local
  1009. "explicitly check for a frame-parameter instead." "22.2")
  1010. (make-obsolete 'interactive-p 'called-interactively-p "23.2")
  1011. (set-advertised-calling-convention 'called-interactively-p '(kind) "23.1")
  1012. (set-advertised-calling-convention
  1013. 'all-completions '(string collection &optional predicate) "23.1")
  1014. (set-advertised-calling-convention 'unintern '(name obarray) "23.3")
  1015. ;;;; Obsolescence declarations for variables, and aliases.
  1016. ;; Special "default-FOO" variables which contain the default value of
  1017. ;; the "FOO" variable are nasty. Their implementation is brittle, and
  1018. ;; slows down several unrelated variable operations; furthermore, they
  1019. ;; can lead to really odd behavior if you decide to make them
  1020. ;; buffer-local.
  1021. ;; Not used at all in Emacs, last time I checked:
  1022. (make-obsolete-variable 'default-mode-line-format 'mode-line-format "23.2")
  1023. (make-obsolete-variable 'default-header-line-format 'header-line-format "23.2")
  1024. (make-obsolete-variable 'default-line-spacing 'line-spacing "23.2")
  1025. (make-obsolete-variable 'default-abbrev-mode 'abbrev-mode "23.2")
  1026. (make-obsolete-variable 'default-ctl-arrow 'ctl-arrow "23.2")
  1027. (make-obsolete-variable 'default-truncate-lines 'truncate-lines "23.2")
  1028. (make-obsolete-variable 'default-left-margin 'left-margin "23.2")
  1029. (make-obsolete-variable 'default-tab-width 'tab-width "23.2")
  1030. (make-obsolete-variable 'default-case-fold-search 'case-fold-search "23.2")
  1031. (make-obsolete-variable 'default-left-margin-width 'left-margin-width "23.2")
  1032. (make-obsolete-variable 'default-right-margin-width 'right-margin-width "23.2")
  1033. (make-obsolete-variable 'default-left-fringe-width 'left-fringe-width "23.2")
  1034. (make-obsolete-variable 'default-right-fringe-width 'right-fringe-width "23.2")
  1035. (make-obsolete-variable 'default-fringes-outside-margins 'fringes-outside-margins "23.2")
  1036. (make-obsolete-variable 'default-scroll-bar-width 'scroll-bar-width "23.2")
  1037. (make-obsolete-variable 'default-vertical-scroll-bar 'vertical-scroll-bar "23.2")
  1038. (make-obsolete-variable 'default-indicate-empty-lines 'indicate-empty-lines "23.2")
  1039. (make-obsolete-variable 'default-indicate-buffer-boundaries 'indicate-buffer-boundaries "23.2")
  1040. (make-obsolete-variable 'default-fringe-indicator-alist 'fringe-indicator-alist "23.2")
  1041. (make-obsolete-variable 'default-fringe-cursor-alist 'fringe-cursor-alist "23.2")
  1042. (make-obsolete-variable 'default-scroll-up-aggressively 'scroll-up-aggressively "23.2")
  1043. (make-obsolete-variable 'default-scroll-down-aggressively 'scroll-down-aggressively "23.2")
  1044. (make-obsolete-variable 'default-fill-column 'fill-column "23.2")
  1045. (make-obsolete-variable 'default-cursor-type 'cursor-type "23.2")
  1046. (make-obsolete-variable 'default-buffer-file-type 'buffer-file-type "23.2")
  1047. (make-obsolete-variable 'default-cursor-in-non-selected-windows 'cursor-in-non-selected-windows "23.2")
  1048. (make-obsolete-variable 'default-buffer-file-coding-system 'buffer-file-coding-system "23.2")
  1049. (make-obsolete-variable 'default-major-mode 'major-mode "23.2")
  1050. (make-obsolete-variable 'default-enable-multibyte-characters
  1051. "use enable-multibyte-characters or set-buffer-multibyte instead" "23.2")
  1052. (make-obsolete-variable 'define-key-rebound-commands nil "23.2")
  1053. (make-obsolete-variable 'redisplay-end-trigger-functions 'jit-lock-register "23.1")
  1054. (make-obsolete-variable 'deferred-action-list 'post-command-hook "24.1")
  1055. (make-obsolete-variable 'deferred-action-function 'post-command-hook "24.1")
  1056. (make-obsolete 'window-redisplay-end-trigger nil "23.1")
  1057. (make-obsolete 'set-window-redisplay-end-trigger nil "23.1")
  1058. (make-obsolete 'process-filter-multibyte-p nil "23.1")
  1059. (make-obsolete 'set-process-filter-multibyte nil "23.1")
  1060. (make-obsolete-variable
  1061. 'mode-line-inverse-video
  1062. "use the appropriate faces instead."
  1063. "21.1")
  1064. (make-obsolete-variable
  1065. 'unread-command-char
  1066. "use `unread-command-events' instead. That variable is a list of events
  1067. to reread, so it now uses nil to mean `no event', instead of -1."
  1068. "before 19.15")
  1069. ;; Lisp manual only updated in 22.1.
  1070. (define-obsolete-variable-alias 'executing-macro 'executing-kbd-macro
  1071. "before 19.34")
  1072. (defvaralias 'x-lost-selection-hooks 'x-lost-selection-functions)
  1073. (make-obsolete-variable 'x-lost-selection-hooks
  1074. 'x-lost-selection-functions "22.1")
  1075. (defvaralias 'x-sent-selection-hooks 'x-sent-selection-functions)
  1076. (make-obsolete-variable 'x-sent-selection-hooks
  1077. 'x-sent-selection-functions "22.1")
  1078. ;; This was introduced in 21.4 for pre-unicode unification. That
  1079. ;; usage was rendered obsolete in 23.1 which uses Unicode internally.
  1080. ;; Other uses are possible, so this variable is not _really_ obsolete,
  1081. ;; but Stefan insists to mark it so.
  1082. (make-obsolete-variable 'translation-table-for-input nil "23.1")
  1083. (defvaralias 'messages-buffer-max-lines 'message-log-max)
  1084. ;; These aliases exist in Emacs 19.34, and probably before, but were
  1085. ;; only marked as obsolete in 23.1.
  1086. ;; The lisp manual (since at least Emacs 21) describes them as
  1087. ;; existing "for compatibility with Emacs version 18".
  1088. (define-obsolete-variable-alias 'last-input-char 'last-input-event
  1089. "at least 19.34")
  1090. (define-obsolete-variable-alias 'last-command-char 'last-command-event
  1091. "at least 19.34")
  1092. ;;;; Alternate names for functions - these are not being phased out.
  1093. (defalias 'send-string 'process-send-string)
  1094. (defalias 'send-region 'process-send-region)
  1095. (defalias 'string= 'string-equal)
  1096. (defalias 'string< 'string-lessp)
  1097. (defalias 'move-marker 'set-marker)
  1098. (defalias 'rplaca 'setcar)
  1099. (defalias 'rplacd 'setcdr)
  1100. (defalias 'beep 'ding) ;preserve lingual purity
  1101. (defalias 'indent-to-column 'indent-to)
  1102. (defalias 'backward-delete-char 'delete-backward-char)
  1103. (defalias 'search-forward-regexp (symbol-function 're-search-forward))
  1104. (defalias 'search-backward-regexp (symbol-function 're-search-backward))
  1105. (defalias 'int-to-string 'number-to-string)
  1106. (defalias 'store-match-data 'set-match-data)
  1107. (defalias 'chmod 'set-file-modes)
  1108. (defalias 'mkdir 'make-directory)
  1109. ;; These are the XEmacs names:
  1110. (defalias 'point-at-eol 'line-end-position)
  1111. (defalias 'point-at-bol 'line-beginning-position)
  1112. (defalias 'user-original-login-name 'user-login-name)
  1113. ;;;; Hook manipulation functions.
  1114. (defun add-hook (hook function &optional append local)
  1115. "Add to the value of HOOK the function FUNCTION.
  1116. FUNCTION is not added if already present.
  1117. FUNCTION is added (if necessary) at the beginning of the hook list
  1118. unless the optional argument APPEND is non-nil, in which case
  1119. FUNCTION is added at the end.
  1120. The optional fourth argument, LOCAL, if non-nil, says to modify
  1121. the hook's buffer-local value rather than its global value.
  1122. This makes the hook buffer-local, and it makes t a member of the
  1123. buffer-local value. That acts as a flag to run the hook
  1124. functions of the global value as well as in the local value.
  1125. HOOK should be a symbol, and FUNCTION may be any valid function. If
  1126. HOOK is void, it is first set to nil. If HOOK's value is a single
  1127. function, it is changed to a list of functions."
  1128. (or (boundp hook) (set hook nil))
  1129. (or (default-boundp hook) (set-default hook nil))
  1130. (if local (unless (local-variable-if-set-p hook)
  1131. (set (make-local-variable hook) (list t)))
  1132. ;; Detect the case where make-local-variable was used on a hook
  1133. ;; and do what we used to do.
  1134. (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
  1135. (setq local t)))
  1136. (let ((hook-value (if local (symbol-value hook) (default-value hook))))
  1137. ;; If the hook value is a single function, turn it into a list.
  1138. (when (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
  1139. (setq hook-value (list hook-value)))
  1140. ;; Do the actual addition if necessary
  1141. (unless (member function hook-value)
  1142. (when (stringp function)
  1143. (setq function (purecopy function)))
  1144. (setq hook-value
  1145. (if append
  1146. (append hook-value (list function))
  1147. (cons function hook-value))))
  1148. ;; Set the actual variable
  1149. (if local
  1150. (progn
  1151. ;; If HOOK isn't a permanent local,
  1152. ;; but FUNCTION wants to survive a change of modes,
  1153. ;; mark HOOK as partially permanent.
  1154. (and (symbolp function)
  1155. (get function 'permanent-local-hook)
  1156. (not (get hook 'permanent-local))
  1157. (put hook 'permanent-local 'permanent-local-hook))
  1158. (set hook hook-value))
  1159. (set-default hook hook-value))))
  1160. (defun remove-hook (hook function &optional local)
  1161. "Remove from the value of HOOK the function FUNCTION.
  1162. HOOK should be a symbol, and FUNCTION may be any valid function. If
  1163. FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
  1164. list of hooks to run in HOOK, then nothing is done. See `add-hook'.
  1165. The optional third argument, LOCAL, if non-nil, says to modify
  1166. the hook's buffer-local value rather than its default value."
  1167. (or (boundp hook) (set hook nil))
  1168. (or (default-boundp hook) (set-default hook nil))
  1169. ;; Do nothing if LOCAL is t but this hook has no local binding.
  1170. (unless (and local (not (local-variable-p hook)))
  1171. ;; Detect the case where make-local-variable was used on a hook
  1172. ;; and do what we used to do.
  1173. (when (and (local-variable-p hook)
  1174. (not (and (consp (symbol-value hook))
  1175. (memq t (symbol-value hook)))))
  1176. (setq local t))
  1177. (let ((hook-value (if local (symbol-value hook) (default-value hook))))
  1178. ;; Remove the function, for both the list and the non-list cases.
  1179. (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
  1180. (if (equal hook-value function) (setq hook-value nil))
  1181. (setq hook-value (delete function (copy-sequence hook-value))))
  1182. ;; If the function is on the global hook, we need to shadow it locally
  1183. ;;(when (and local (member function (default-value hook))
  1184. ;; (not (member (cons 'not function) hook-value)))
  1185. ;; (push (cons 'not function) hook-value))
  1186. ;; Set the actual variable
  1187. (if (not local)
  1188. (set-default hook hook-value)
  1189. (if (equal hook-value '(t))
  1190. (kill-local-variable hook)
  1191. (set hook hook-value))))))
  1192. (defmacro letrec (binders &rest body)
  1193. "Bind variables according to BINDERS then eval BODY.
  1194. The value of the last form in BODY is returned.
  1195. Each element of BINDERS is a list (SYMBOL VALUEFORM) which binds
  1196. SYMBOL to the value of VALUEFORM.
  1197. All symbols are bound before the VALUEFORMs are evalled."
  1198. ;; Only useful in lexical-binding mode.
  1199. ;; As a special-form, we could implement it more efficiently (and cleanly,
  1200. ;; making the vars actually unbound during evaluation of the binders).
  1201. (declare (debug let) (indent 1))
  1202. `(let ,(mapcar #'car binders)
  1203. ,@(mapcar (lambda (binder) `(setq ,@binder)) binders)
  1204. ,@body))
  1205. (defmacro with-wrapper-hook (hook args &rest body)
  1206. "Run BODY, using wrapper functions from HOOK with additional ARGS.
  1207. HOOK is an abnormal hook. Each hook function in HOOK \"wraps\"
  1208. around the preceding ones, like a set of nested `around' advices.
  1209. Each hook function should accept an argument list consisting of a
  1210. function FUN, followed by the additional arguments in ARGS.
  1211. The first hook function in HOOK is passed a FUN that, if it is called
  1212. with arguments ARGS, performs BODY (i.e., the default operation).
  1213. The FUN passed to each successive hook function is defined based
  1214. on the preceding hook functions; if called with arguments ARGS,
  1215. it does what the `with-wrapper-hook' call would do if the
  1216. preceding hook functions were the only ones present in HOOK.
  1217. Each hook function may call its FUN argument as many times as it wishes,
  1218. including never. In that case, such a hook function acts to replace
  1219. the default definition altogether, and any preceding hook functions.
  1220. Of course, a subsequent hook function may do the same thing.
  1221. Each hook function definition is used to construct the FUN passed
  1222. to the next hook function, if any. The last (or \"outermost\")
  1223. FUN is then called once."
  1224. (declare (indent 2) (debug (form sexp body)))
  1225. ;; We need those two gensyms because CL's lexical scoping is not available
  1226. ;; for function arguments :-(
  1227. (let ((funs (make-symbol "funs"))
  1228. (global (make-symbol "global"))
  1229. (argssym (make-symbol "args"))
  1230. (runrestofhook (make-symbol "runrestofhook")))
  1231. ;; Since the hook is a wrapper, the loop has to be done via
  1232. ;; recursion: a given hook function will call its parameter in order to
  1233. ;; continue looping.
  1234. `(letrec ((,runrestofhook
  1235. (lambda (,funs ,global ,argssym)
  1236. ;; `funs' holds the functions left on the hook and `global'
  1237. ;; holds the functions left on the global part of the hook
  1238. ;; (in case the hook is local).
  1239. (if (consp ,funs)
  1240. (if (eq t (car ,funs))
  1241. (funcall ,runrestofhook
  1242. (append ,global (cdr ,funs)) nil ,argssym)
  1243. (apply (car ,funs)
  1244. (apply-partially
  1245. (lambda (,funs ,global &rest ,argssym)
  1246. (funcall ,runrestofhook ,funs ,global ,argssym))
  1247. (cdr ,funs) ,global)
  1248. ,argssym))
  1249. ;; Once there are no more functions on the hook, run
  1250. ;; the original body.
  1251. (apply (lambda ,args ,@body) ,argssym)))))
  1252. (funcall ,runrestofhook ,hook
  1253. ;; The global part of the hook, if any.
  1254. ,(if (symbolp hook)
  1255. `(if (local-variable-p ',hook)
  1256. (default-value ',hook)))
  1257. (list ,@args)))))
  1258. (defun add-to-list (list-var element &optional append compare-fn)
  1259. "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
  1260. The test for presence of ELEMENT is done with `equal',
  1261. or with COMPARE-FN if that's non-nil.
  1262. If ELEMENT is added, it is added at the beginning of the list,
  1263. unless the optional argument APPEND is non-nil, in which case
  1264. ELEMENT is added at the end.
  1265. The return value is the new value of LIST-VAR.
  1266. If you want to use `add-to-list' on a variable that is not defined
  1267. until a certain package is loaded, you should put the call to `add-to-list'
  1268. into a hook function that will be run only after loading the package.
  1269. `eval-after-load' provides one way to do this. In some cases
  1270. other hooks, such as major mode hooks, can do the job."
  1271. (if (cond
  1272. ((null compare-fn)
  1273. (member element (symbol-value list-var)))
  1274. ((eq compare-fn 'eq)
  1275. (memq element (symbol-value list-var)))
  1276. ((eq compare-fn 'eql)
  1277. (memql element (symbol-value list-var)))
  1278. (t
  1279. (let ((lst (symbol-value list-var)))
  1280. (while (and lst
  1281. (not (funcall compare-fn element (car lst))))
  1282. (setq lst (cdr lst)))
  1283. lst)))
  1284. (symbol-value list-var)
  1285. (set list-var
  1286. (if append
  1287. (append (symbol-value list-var) (list element))
  1288. (cons element (symbol-value list-var))))))
  1289. (defun add-to-ordered-list (list-var element &optional order)
  1290. "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
  1291. The test for presence of ELEMENT is done with `eq'.
  1292. The resulting list is reordered so that the elements are in the
  1293. order given by each element's numeric list order. Elements
  1294. without a numeric list order are placed at the end of the list.
  1295. If the third optional argument ORDER is a number (integer or
  1296. float), set the element's list order to the given value. If
  1297. ORDER is nil or omitted, do not change the numeric order of
  1298. ELEMENT. If ORDER has any other value, remove the numeric order
  1299. of ELEMENT if it has one.
  1300. The list order for each element is stored in LIST-VAR's
  1301. `list-order' property.
  1302. The return value is the new value of LIST-VAR."
  1303. (let ((ordering (get list-var 'list-order)))
  1304. (unless ordering
  1305. (put list-var 'list-order
  1306. (setq ordering (make-hash-table :weakness 'key :test 'eq))))
  1307. (when order
  1308. (puthash element (and (numberp order) order) ordering))
  1309. (unless (memq element (symbol-value list-var))
  1310. (set list-var (cons element (symbol-value list-var))))
  1311. (set list-var (sort (symbol-value list-var)
  1312. (lambda (a b)
  1313. (let ((oa (gethash a ordering))
  1314. (ob (gethash b ordering)))
  1315. (if (and oa ob)
  1316. (< oa ob)
  1317. oa)))))))
  1318. (defun add-to-history (history-var newelt &optional maxelt keep-all)
  1319. "Add NEWELT to the history list stored in the variable HISTORY-VAR.
  1320. Return the new history list.
  1321. If MAXELT is non-nil, it specifies the maximum length of the history.
  1322. Otherwise, the maximum history length is the value of the `history-length'
  1323. property on symbol HISTORY-VAR, if set, or the value of the `history-length'
  1324. variable.
  1325. Remove duplicates of NEWELT if `history-delete-duplicates' is non-nil.
  1326. If optional fourth arg KEEP-ALL is non-nil, add NEWELT to history even
  1327. if it is empty or a duplicate."
  1328. (unless maxelt
  1329. (setq maxelt (or (get history-var 'history-length)
  1330. history-length)))
  1331. (let ((history (symbol-value history-var))
  1332. tail)
  1333. (when (and (listp history)
  1334. (or keep-all
  1335. (not (stringp newelt))
  1336. (> (length newelt) 0))
  1337. (or keep-all
  1338. (not (equal (car history) newelt))))
  1339. (if history-delete-duplicates
  1340. (delete newelt history))
  1341. (setq history (cons newelt history))
  1342. (when (integerp maxelt)
  1343. (if (= 0 maxelt)
  1344. (setq history nil)
  1345. (setq tail (nthcdr (1- maxelt) history))
  1346. (when (consp tail)
  1347. (setcdr tail nil)))))
  1348. (set history-var history)))
  1349. ;;;; Mode hooks.
  1350. (defvar delay-mode-hooks nil
  1351. "If non-nil, `run-mode-hooks' should delay running the hooks.")
  1352. (defvar delayed-mode-hooks nil
  1353. "List of delayed mode hooks waiting to be run.")
  1354. (make-variable-buffer-local 'delayed-mode-hooks)
  1355. (put 'delay-mode-hooks 'permanent-local t)
  1356. (defvar change-major-mode-after-body-hook nil
  1357. "Normal hook run in major mode functions, before the mode hooks.")
  1358. (defvar after-change-major-mode-hook nil
  1359. "Normal hook run at the very end of major mode functions.")
  1360. (defun run-mode-hooks (&rest hooks)
  1361. "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
  1362. If the variable `delay-mode-hooks' is non-nil, does not run any hooks,
  1363. just adds the HOOKS to the list `delayed-mode-hooks'.
  1364. Otherwise, runs hooks in the sequence: `change-major-mode-after-body-hook',
  1365. `delayed-mode-hooks' (in reverse order), HOOKS, and finally
  1366. `after-change-major-mode-hook'. Major mode functions should use
  1367. this instead of `run-hooks' when running their FOO-mode-hook."
  1368. (if delay-mode-hooks
  1369. ;; Delaying case.
  1370. (dolist (hook hooks)
  1371. (push hook delayed-mode-hooks))
  1372. ;; Normal case, just run the hook as before plus any delayed hooks.
  1373. (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
  1374. (setq delayed-mode-hooks nil)
  1375. (apply 'run-hooks (cons 'change-major-mode-after-body-hook hooks))
  1376. (run-hooks 'after-change-major-mode-hook)))
  1377. (defmacro delay-mode-hooks (&rest body)
  1378. "Execute BODY, but delay any `run-mode-hooks'.
  1379. These hooks will be executed by the first following call to
  1380. `run-mode-hooks' that occurs outside any `delayed-mode-hooks' form.
  1381. Only affects hooks run in the current buffer."
  1382. (declare (debug t) (indent 0))
  1383. `(progn
  1384. (make-local-variable 'delay-mode-hooks)
  1385. (let ((delay-mode-hooks t))
  1386. ,@body)))
  1387. ;; PUBLIC: find if the current mode derives from another.
  1388. (defun derived-mode-p (&rest modes)
  1389. "Non-nil if the current major mode is derived from one of MODES.
  1390. Uses the `derived-mode-parent' property of the symbol to trace backwards."
  1391. (let ((parent major-mode))
  1392. (while (and (not (memq parent modes))
  1393. (setq parent (get parent 'derived-mode-parent))))
  1394. parent))
  1395. ;;;; Minor modes.
  1396. ;; If a minor mode is not defined with define-minor-mode,
  1397. ;; add it here explicitly.
  1398. ;; isearch-mode is deliberately excluded, since you should
  1399. ;; not call it yourself.
  1400. (defvar minor-mode-list '(auto-save-mode auto-fill-mode abbrev-mode
  1401. overwrite-mode view-mode
  1402. hs-minor-mode)
  1403. "List of all minor mode functions.")
  1404. (defun add-minor-mode (toggle name &optional keymap after toggle-fun)
  1405. "Register a new minor mode.
  1406. This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
  1407. TOGGLE is a symbol which is the name of a buffer-local variable that
  1408. is toggled on or off to say whether the minor mode is active or not.
  1409. NAME specifies what will appear in the mode line when the minor mode
  1410. is active. NAME should be either a string starting with a space, or a
  1411. symbol whose value is such a string.
  1412. Optional KEYMAP is the keymap for the minor mode that will be added
  1413. to `minor-mode-map-alist'.
  1414. Optional AFTER specifies that TOGGLE should be added after AFTER
  1415. in `minor-mode-alist'.
  1416. Optional TOGGLE-FUN is an interactive function to toggle the mode.
  1417. It defaults to (and should by convention be) TOGGLE.
  1418. If TOGGLE has a non-nil `:included' property, an entry for the mode is
  1419. included in the mode-line minor mode menu.
  1420. If TOGGLE has a `:menu-tag', that is used for the menu item's label."
  1421. (unless (memq toggle minor-mode-list)
  1422. (push toggle minor-mode-list))
  1423. (unless toggle-fun (setq toggle-fun toggle))
  1424. (unless (eq toggle-fun toggle)
  1425. (put toggle :minor-mode-function toggle-fun))
  1426. ;; Add the name to the minor-mode-alist.
  1427. (when name
  1428. (let ((existing (assq toggle minor-mode-alist)))
  1429. (if existing
  1430. (setcdr existing (list name))
  1431. (let ((tail minor-mode-alist) found)
  1432. (while (and tail (not found))
  1433. (if (eq after (caar tail))
  1434. (setq found tail)
  1435. (setq tail (cdr tail))))
  1436. (if found
  1437. (let ((rest (cdr found)))
  1438. (setcdr found nil)
  1439. (nconc found (list (list toggle name)) rest))
  1440. (push (list toggle name) minor-mode-alist))))))
  1441. ;; Add the toggle to the minor-modes menu if requested.
  1442. (when (get toggle :included)
  1443. (define-key mode-line-mode-menu
  1444. (vector toggle)
  1445. (list 'menu-item
  1446. (concat
  1447. (or (get toggle :menu-tag)
  1448. (if (stringp name) name (symbol-name toggle)))
  1449. (let ((mode-name (if (symbolp name) (symbol-value name))))
  1450. (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
  1451. (concat " (" (match-string 0 mode-name) ")"))))
  1452. toggle-fun
  1453. :button (cons :toggle toggle))))
  1454. ;; Add the map to the minor-mode-map-alist.
  1455. (when keymap
  1456. (let ((existing (assq toggle minor-mode-map-alist)))
  1457. (if existing
  1458. (setcdr existing keymap)
  1459. (let ((tail minor-mode-map-alist) found)
  1460. (while (and tail (not found))
  1461. (if (eq after (caar tail))
  1462. (setq found tail)
  1463. (setq tail (cdr tail))))
  1464. (if found
  1465. (let ((rest (cdr found)))
  1466. (setcdr found nil)
  1467. (nconc found (list (cons toggle keymap)) rest))
  1468. (push (cons toggle keymap) minor-mode-map-alist)))))))
  1469. ;;; Load history
  1470. (defun symbol-file (symbol &optional type)
  1471. "Return the name of the file that defined SYMBOL.
  1472. The value is normally an absolute file name. It can also be nil,
  1473. if the definition is not associated with any file. If SYMBOL
  1474. specifies an autoloaded function, the value can be a relative
  1475. file name without extension.
  1476. If TYPE is nil, then any kind of definition is acceptable. If
  1477. TYPE is `defun', `defvar', or `defface', that specifies function
  1478. definition, variable definition, or face definition only."
  1479. (if (and (or (null type) (eq type 'defun))
  1480. (symbolp symbol) (fboundp symbol)
  1481. (eq 'autoload (car-safe (symbol-function symbol))))
  1482. (nth 1 (symbol-function symbol))
  1483. (let ((files load-history)
  1484. file)
  1485. (while files
  1486. (if (if type
  1487. (if (eq type 'defvar)
  1488. ;; Variables are present just as their names.
  1489. (member symbol (cdr (car files)))
  1490. ;; Other types are represented as (TYPE . NAME).
  1491. (member (cons type symbol) (cdr (car files))))
  1492. ;; We accept all types, so look for variable def
  1493. ;; and then for any other kind.
  1494. (or (member symbol (cdr (car files)))
  1495. (rassq symbol (cdr (car files)))))
  1496. (setq file (car (car files)) files nil))
  1497. (setq files (cdr files)))
  1498. file)))
  1499. (defun locate-library (library &optional nosuffix path interactive-call)
  1500. "Show the precise file name of Emacs library LIBRARY.
  1501. LIBRARY should be a relative file name of the library, a string.
  1502. It can omit the suffix (a.k.a. file-name extension) if NOSUFFIX is
  1503. nil (which is the default, see below).
  1504. This command searches the directories in `load-path' like `\\[load-library]'
  1505. to find the file that `\\[load-library] RET LIBRARY RET' would load.
  1506. Optional second arg NOSUFFIX non-nil means don't add suffixes `load-suffixes'
  1507. to the specified name LIBRARY.
  1508. If the optional third arg PATH is specified, that list of directories
  1509. is used instead of `load-path'.
  1510. When called from a program, the file name is normally returned as a
  1511. string. When run interactively, the argument INTERACTIVE-CALL is t,
  1512. and the file name is displayed in the echo area."
  1513. (interactive (list (completing-read "Locate library: "
  1514. (apply-partially
  1515. 'locate-file-completion-table
  1516. load-path (get-load-suffixes)))
  1517. nil nil
  1518. t))
  1519. (let ((file (locate-file library
  1520. (or path load-path)
  1521. (append (unless nosuffix (get-load-suffixes))
  1522. load-file-rep-suffixes))))
  1523. (if interactive-call
  1524. (if file
  1525. (message "Library is file %s" (abbreviate-file-name file))
  1526. (message "No library %s in search path" library)))
  1527. file))
  1528. ;;;; Specifying things to do later.
  1529. (defun load-history-regexp (file)
  1530. "Form a regexp to find FILE in `load-history'.
  1531. FILE, a string, is described in the function `eval-after-load'."
  1532. (if (file-name-absolute-p file)
  1533. (setq file (file-truename file)))
  1534. (concat (if (file-name-absolute-p file) "\\`" "\\(\\`\\|/\\)")
  1535. (regexp-quote file)
  1536. (if (file-name-extension file)
  1537. ""
  1538. ;; Note: regexp-opt can't be used here, since we need to call
  1539. ;; this before Emacs has been fully started. 2006-05-21
  1540. (concat "\\(" (mapconcat 'regexp-quote load-suffixes "\\|") "\\)?"))
  1541. "\\(" (mapconcat 'regexp-quote jka-compr-load-suffixes "\\|")
  1542. "\\)?\\'"))
  1543. (defun load-history-filename-element (file-regexp)
  1544. "Get the first elt of `load-history' whose car matches FILE-REGEXP.
  1545. Return nil if there isn't one."
  1546. (let* ((loads load-history)
  1547. (load-elt (and loads (car loads))))
  1548. (save-match-data
  1549. (while (and loads
  1550. (or (null (car load-elt))
  1551. (not (string-match file-regexp (car load-elt)))))
  1552. (setq loads (cdr loads)
  1553. load-elt (and loads (car loads)))))
  1554. load-elt))
  1555. (put 'eval-after-load 'lisp-indent-function 1)
  1556. (defun eval-after-load (file form)
  1557. "Arrange that if FILE is loaded, FORM will be run immediately afterwards.
  1558. If FILE is already loaded, evaluate FORM right now.
  1559. If a matching file is loaded again, FORM will be evaluated again.
  1560. If FILE is a string, it may be either an absolute or a relative file
  1561. name, and may have an extension \(e.g. \".el\") or may lack one, and
  1562. additionally may or may not have an extension denoting a compressed
  1563. format \(e.g. \".gz\").
  1564. When FILE is absolute, this first converts it to a true name by chasing
  1565. symbolic links. Only a file of this name \(see next paragraph regarding
  1566. extensions) will trigger the evaluation of FORM. When FILE is relative,
  1567. a file whose absolute true name ends in FILE will trigger evaluation.
  1568. When FILE lacks an extension, a file name with any extension will trigger
  1569. evaluation. Otherwise, its extension must match FILE's. A further
  1570. extension for a compressed format \(e.g. \".gz\") on FILE will not affect
  1571. this name matching.
  1572. Alternatively, FILE can be a feature (i.e. a symbol), in which case FORM
  1573. is evaluated at the end of any file that `provide's this feature.
  1574. If the feature is provided when evaluating code not associated with a
  1575. file, FORM is evaluated immediately after the provide statement.
  1576. Usually FILE is just a library name like \"font-lock\" or a feature name
  1577. like 'font-lock.
  1578. This function makes or adds to an entry on `after-load-alist'."
  1579. ;; Add this FORM into after-load-alist (regardless of whether we'll be
  1580. ;; evaluating it now).
  1581. (let* ((regexp-or-feature
  1582. (if (stringp file)
  1583. (setq file (purecopy (load-history-regexp file)))
  1584. file))
  1585. (elt (assoc regexp-or-feature after-load-alist)))
  1586. (unless elt
  1587. (setq elt (list regexp-or-feature))
  1588. (push elt after-load-alist))
  1589. ;; Make sure `form' is evalled in the current lexical/dynamic code.
  1590. (setq form `(funcall ',(eval `(lambda () ,form) lexical-binding)))
  1591. ;; Is there an already loaded file whose name (or `provide' name)
  1592. ;; matches FILE?
  1593. (prog1 (if (if (stringp file)
  1594. (load-history-filename-element regexp-or-feature)
  1595. (featurep file))
  1596. (eval form))
  1597. (when (symbolp regexp-or-feature)
  1598. ;; For features, the after-load-alist elements get run when `provide' is
  1599. ;; called rather than at the end of the file. So add an indirection to
  1600. ;; make sure that `form' is really run "after-load" in case the provide
  1601. ;; call happens early.
  1602. (setq form
  1603. `(if load-file-name
  1604. (let ((fun (make-symbol "eval-after-load-helper")))
  1605. (fset fun `(lambda (file)
  1606. (if (not (equal file ',load-file-name))
  1607. nil
  1608. (remove-hook 'after-load-functions ',fun)
  1609. ,',form)))
  1610. (add-hook 'after-load-functions fun))
  1611. ;; Not being provided from a file, run form right now.
  1612. ,form)))
  1613. ;; Add FORM to the element unless it's already there.
  1614. (unless (member form (cdr elt))
  1615. (nconc elt (purecopy (list form)))))))
  1616. (defvar after-load-functions nil
  1617. "Special hook run after loading a file.
  1618. Each function there is called with a single argument, the absolute
  1619. name of the file just loaded.")
  1620. (defun do-after-load-evaluation (abs-file)
  1621. "Evaluate all `eval-after-load' forms, if any, for ABS-FILE.
  1622. ABS-FILE, a string, should be the absolute true name of a file just loaded.
  1623. This function is called directly from the C code."
  1624. ;; Run the relevant eval-after-load forms.
  1625. (mapc #'(lambda (a-l-element)
  1626. (when (and (stringp (car a-l-element))
  1627. (string-match-p (car a-l-element) abs-file))
  1628. ;; discard the file name regexp
  1629. (mapc #'eval (cdr a-l-element))))
  1630. after-load-alist)
  1631. ;; Complain when the user uses obsolete files.
  1632. (when (string-match-p "/obsolete/[^/]*\\'" abs-file)
  1633. (run-with-timer 0 nil
  1634. (lambda (file)
  1635. (message "Package %s is obsolete!"
  1636. (substring file 0
  1637. (string-match "\\.elc?\\>" file))))
  1638. (file-name-nondirectory abs-file)))
  1639. ;; Finally, run any other hook.
  1640. (run-hook-with-args 'after-load-functions abs-file))
  1641. (defun eval-next-after-load (file)
  1642. "Read the following input sexp, and run it whenever FILE is loaded.
  1643. This makes or adds to an entry on `after-load-alist'.
  1644. FILE should be the name of a library, with no directory name."
  1645. (eval-after-load file (read)))
  1646. (make-obsolete 'eval-next-after-load `eval-after-load "23.2")
  1647. (defun display-delayed-warnings ()
  1648. "Display delayed warnings from `delayed-warnings-list'.
  1649. Used from `delayed-warnings-hook' (which see)."
  1650. (dolist (warning (nreverse delayed-warnings-list))
  1651. (apply 'display-warning warning))
  1652. (setq delayed-warnings-list nil))
  1653. (defun collapse-delayed-warnings ()
  1654. "Remove duplicates from `delayed-warnings-list'.
  1655. Collapse identical adjacent warnings into one (plus count).
  1656. Used from `delayed-warnings-hook' (which see)."
  1657. (let ((count 1)
  1658. collapsed warning)
  1659. (while delayed-warnings-list
  1660. (setq warning (pop delayed-warnings-list))
  1661. (if (equal warning (car delayed-warnings-list))
  1662. (setq count (1+ count))
  1663. (when (> count 1)
  1664. (setcdr warning (cons (format "%s [%d times]" (cadr warning) count)
  1665. (cddr warning)))
  1666. (setq count 1))
  1667. (push warning collapsed)))
  1668. (setq delayed-warnings-list (nreverse collapsed))))
  1669. ;; At present this is only used for Emacs internals.
  1670. ;; Ref http://lists.gnu.org/archive/html/emacs-devel/2012-02/msg00085.html
  1671. (defvar delayed-warnings-hook '(collapse-delayed-warnings
  1672. display-delayed-warnings)
  1673. "Normal hook run to process and display delayed warnings.
  1674. By default, this hook contains functions to consolidate the
  1675. warnings listed in `delayed-warnings-list', display them, and set
  1676. `delayed-warnings-list' back to nil.")
  1677. ;;;; Process stuff.
  1678. (defun process-lines (program &rest args)
  1679. "Execute PROGRAM with ARGS, returning its output as a list of lines.
  1680. Signal an error if the program returns with a non-zero exit status."
  1681. (with-temp-buffer
  1682. (let ((status (apply 'call-process program nil (current-buffer) nil args)))
  1683. (unless (eq status 0)
  1684. (error "%s exited with status %s" program status))
  1685. (goto-char (point-min))
  1686. (let (lines)
  1687. (while (not (eobp))
  1688. (setq lines (cons (buffer-substring-no-properties
  1689. (line-beginning-position)
  1690. (line-end-position))
  1691. lines))
  1692. (forward-line 1))
  1693. (nreverse lines)))))
  1694. (defun process-live-p (process)
  1695. "Returns non-nil if PROCESS is alive.
  1696. A process is considered alive if its status is `run', `open',
  1697. `listen', `connect' or `stop'."
  1698. (memq (process-status process)
  1699. '(run open listen connect stop)))
  1700. ;; compatibility
  1701. (make-obsolete
  1702. 'process-kill-without-query
  1703. "use `process-query-on-exit-flag' or `set-process-query-on-exit-flag'."
  1704. "22.1")
  1705. (defun process-kill-without-query (process &optional _flag)
  1706. "Say no query needed if PROCESS is running when Emacs is exited.
  1707. Optional second argument if non-nil says to require a query.
  1708. Value is t if a query was formerly required."
  1709. (let ((old (process-query-on-exit-flag process)))
  1710. (set-process-query-on-exit-flag process nil)
  1711. old))
  1712. (defun process-kill-buffer-query-function ()
  1713. "Ask before killing a buffer that has a running process."
  1714. (let ((process (get-buffer-process (current-buffer))))
  1715. (or (not process)
  1716. (not (memq (process-status process) '(run stop open listen)))
  1717. (not (process-query-on-exit-flag process))
  1718. (yes-or-no-p
  1719. (format "Buffer %S has a running process; kill it? "
  1720. (buffer-name (current-buffer)))))))
  1721. (add-hook 'kill-buffer-query-functions 'process-kill-buffer-query-function)
  1722. ;; process plist management
  1723. (defun process-get (process propname)
  1724. "Return the value of PROCESS' PROPNAME property.
  1725. This is the last value stored with `(process-put PROCESS PROPNAME VALUE)'."
  1726. (plist-get (process-plist process) propname))
  1727. (defun process-put (process propname value)
  1728. "Change PROCESS' PROPNAME property to VALUE.
  1729. It can be retrieved with `(process-get PROCESS PROPNAME)'."
  1730. (set-process-plist process
  1731. (plist-put (process-plist process) propname value)))
  1732. ;;;; Input and display facilities.
  1733. (defvar read-quoted-char-radix 8
  1734. "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
  1735. Legitimate radix values are 8, 10 and 16.")
  1736. (custom-declare-variable-early
  1737. 'read-quoted-char-radix 8
  1738. "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
  1739. Legitimate radix values are 8, 10 and 16."
  1740. :type '(choice (const 8) (const 10) (const 16))
  1741. :group 'editing-basics)
  1742. (defconst read-key-empty-map (make-sparse-keymap))
  1743. (defvar read-key-delay 0.01) ;Fast enough for 100Hz repeat rate, hopefully.
  1744. (defun read-key (&optional prompt)
  1745. "Read a key from the keyboard.
  1746. Contrary to `read-event' this will not return a raw event but instead will
  1747. obey the input decoding and translations usually done by `read-key-sequence'.
  1748. So escape sequences and keyboard encoding are taken into account.
  1749. When there's an ambiguity because the key looks like the prefix of
  1750. some sort of escape sequence, the ambiguity is resolved via `read-key-delay'."
  1751. (let ((overriding-terminal-local-map read-key-empty-map)
  1752. (overriding-local-map nil)
  1753. (echo-keystrokes 0)
  1754. (old-global-map (current-global-map))
  1755. (timer (run-with-idle-timer
  1756. ;; Wait long enough that Emacs has the time to receive and
  1757. ;; process all the raw events associated with the single-key.
  1758. ;; But don't wait too long, or the user may find the delay
  1759. ;; annoying (or keep hitting more keys which may then get
  1760. ;; lost or misinterpreted).
  1761. ;; This is only relevant for keys which Emacs perceives as
  1762. ;; "prefixes", such as C-x (because of the C-x 8 map in
  1763. ;; key-translate-table and the C-x @ map in function-key-map)
  1764. ;; or ESC (because of terminal escape sequences in
  1765. ;; input-decode-map).
  1766. read-key-delay t
  1767. (lambda ()
  1768. (let ((keys (this-command-keys-vector)))
  1769. (unless (zerop (length keys))
  1770. ;; `keys' is non-empty, so the user has hit at least
  1771. ;; one key; there's no point waiting any longer, even
  1772. ;; though read-key-sequence thinks we should wait
  1773. ;; for more input to decide how to interpret the
  1774. ;; current input.
  1775. (throw 'read-key keys)))))))
  1776. (unwind-protect
  1777. (progn
  1778. (use-global-map
  1779. (let ((map (make-sparse-keymap)))
  1780. ;; Don't hide the menu-bar and tool-bar entries.
  1781. (define-key map [menu-bar] (lookup-key global-map [menu-bar]))
  1782. (define-key map [tool-bar]
  1783. ;; This hack avoids evaluating the :filter (Bug#9922).
  1784. (or (cdr (assq 'tool-bar global-map))
  1785. (lookup-key global-map [tool-bar])))
  1786. map))
  1787. (aref (catch 'read-key (read-key-sequence-vector prompt nil t)) 0))
  1788. (cancel-timer timer)
  1789. (use-global-map old-global-map))))
  1790. (defun read-quoted-char (&optional prompt)
  1791. "Like `read-char', but do not allow quitting.
  1792. Also, if the first character read is an octal digit,
  1793. we read any number of octal digits and return the
  1794. specified character code. Any nondigit terminates the sequence.
  1795. If the terminator is RET, it is discarded;
  1796. any other terminator is used itself as input.
  1797. The optional argument PROMPT specifies a string to use to prompt the user.
  1798. The variable `read-quoted-char-radix' controls which radix to use
  1799. for numeric input."
  1800. (let ((message-log-max nil) done (first t) (code 0) char translated)
  1801. (while (not done)
  1802. (let ((inhibit-quit first)
  1803. ;; Don't let C-h get the help message--only help function keys.
  1804. (help-char nil)
  1805. (help-form
  1806. "Type the special character you want to use,
  1807. or the octal character code.
  1808. RET terminates the character code and is discarded;
  1809. any other non-digit terminates the character code and is then used as input."))
  1810. (setq char (read-event (and prompt (format "%s-" prompt)) t))
  1811. (if inhibit-quit (setq quit-flag nil)))
  1812. ;; Translate TAB key into control-I ASCII character, and so on.
  1813. ;; Note: `read-char' does it using the `ascii-character' property.
  1814. ;; We should try and use read-key instead.
  1815. (let ((translation (lookup-key local-function-key-map (vector char))))
  1816. (setq translated (if (arrayp translation)
  1817. (aref translation 0)
  1818. char)))
  1819. (if (integerp translated)
  1820. (setq translated (char-resolve-modifiers translated)))
  1821. (cond ((null translated))
  1822. ((not (integerp translated))
  1823. (setq unread-command-events (list char)
  1824. done t))
  1825. ((/= (logand translated ?\M-\^@) 0)
  1826. ;; Turn a meta-character into a character with the 0200 bit set.
  1827. (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
  1828. done t))
  1829. ((and (<= ?0 translated)
  1830. (< translated (+ ?0 (min 10 read-quoted-char-radix))))
  1831. (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
  1832. (and prompt (setq prompt (message "%s %c" prompt translated))))
  1833. ((and (<= ?a (downcase translated))
  1834. (< (downcase translated)
  1835. (+ ?a -10 (min 36 read-quoted-char-radix))))
  1836. (setq code (+ (* code read-quoted-char-radix)
  1837. (+ 10 (- (downcase translated) ?a))))
  1838. (and prompt (setq prompt (message "%s %c" prompt translated))))
  1839. ((and (not first) (eq translated ?\C-m))
  1840. (setq done t))
  1841. ((not first)
  1842. (setq unread-command-events (list char)
  1843. done t))
  1844. (t (setq code translated
  1845. done t)))
  1846. (setq first nil))
  1847. code))
  1848. (defun read-passwd (prompt &optional confirm default)
  1849. "Read a password, prompting with PROMPT, and return it.
  1850. If optional CONFIRM is non-nil, read the password twice to make sure.
  1851. Optional DEFAULT is a default password to use instead of empty input.
  1852. This function echoes `.' for each character that the user types.
  1853. The user ends with RET, LFD, or ESC. DEL or C-h rubs out.
  1854. C-y yanks the current kill. C-u kills line.
  1855. C-g quits; if `inhibit-quit' was non-nil around this function,
  1856. then it returns nil if the user types C-g, but `quit-flag' remains set.
  1857. Once the caller uses the password, it can erase the password
  1858. by doing (clear-string STRING)."
  1859. (with-local-quit
  1860. (if confirm
  1861. (let (success)
  1862. (while (not success)
  1863. (let ((first (read-passwd prompt nil default))
  1864. (second (read-passwd "Confirm password: " nil default)))
  1865. (if (equal first second)
  1866. (progn
  1867. (and (arrayp second) (clear-string second))
  1868. (setq success first))
  1869. (and (arrayp first) (clear-string first))
  1870. (and (arrayp second) (clear-string second))
  1871. (message "Password not repeated accurately; please start over")
  1872. (sit-for 1))))
  1873. success)
  1874. (let ((pass nil)
  1875. ;; Copy it so that add-text-properties won't modify
  1876. ;; the object that was passed in by the caller.
  1877. (prompt (copy-sequence prompt))
  1878. (c 0)
  1879. (echo-keystrokes 0)
  1880. (cursor-in-echo-area t)
  1881. (message-log-max nil)
  1882. (stop-keys (list 'return ?\r ?\n ?\e))
  1883. (rubout-keys (list 'backspace ?\b ?\177)))
  1884. (add-text-properties 0 (length prompt)
  1885. minibuffer-prompt-properties prompt)
  1886. (while (progn (message "%s%s"
  1887. prompt
  1888. (make-string (length pass) ?.))
  1889. (setq c (read-key))
  1890. (not (memq c stop-keys)))
  1891. (clear-this-command-keys)
  1892. (cond ((memq c rubout-keys) ; rubout
  1893. (when (> (length pass) 0)
  1894. (let ((new-pass (substring pass 0 -1)))
  1895. (and (arrayp pass) (clear-string pass))
  1896. (setq pass new-pass))))
  1897. ((eq c ?\C-g) (keyboard-quit))
  1898. ((not (numberp c)))
  1899. ((= c ?\C-u) ; kill line
  1900. (and (arrayp pass) (clear-string pass))
  1901. (setq pass ""))
  1902. ((= c ?\C-y) ; yank
  1903. (let* ((str (condition-case nil
  1904. (current-kill 0)
  1905. (error nil)))
  1906. new-pass)
  1907. (when str
  1908. (setq new-pass
  1909. (concat pass
  1910. (substring-no-properties str)))
  1911. (and (arrayp pass) (clear-string pass))
  1912. (setq c ?\0)
  1913. (setq pass new-pass))))
  1914. ((characterp c) ; insert char
  1915. (let* ((new-char (char-to-string c))
  1916. (new-pass (concat pass new-char)))
  1917. (and (arrayp pass) (clear-string pass))
  1918. (clear-string new-char)
  1919. (setq c ?\0)
  1920. (setq pass new-pass)))))
  1921. (message nil)
  1922. (or pass default "")))))
  1923. ;; This should be used by `call-interactively' for `n' specs.
  1924. (defun read-number (prompt &optional default)
  1925. "Read a numeric value in the minibuffer, prompting with PROMPT.
  1926. DEFAULT specifies a default value to return if the user just types RET.
  1927. The value of DEFAULT is inserted into PROMPT."
  1928. (let ((n nil))
  1929. (when default
  1930. (setq prompt
  1931. (if (string-match "\\(\\):[ \t]*\\'" prompt)
  1932. (replace-match (format " (default %s)" default) t t prompt 1)
  1933. (replace-regexp-in-string "[ \t]*\\'"
  1934. (format " (default %s) " default)
  1935. prompt t t))))
  1936. (while
  1937. (progn
  1938. (let ((str (read-from-minibuffer prompt nil nil nil nil
  1939. (and default
  1940. (number-to-string default)))))
  1941. (condition-case nil
  1942. (setq n (cond
  1943. ((zerop (length str)) default)
  1944. ((stringp str) (read str))))
  1945. (error nil)))
  1946. (unless (numberp n)
  1947. (message "Please enter a number.")
  1948. (sit-for 1)
  1949. t)))
  1950. n))
  1951. (defun read-char-choice (prompt chars &optional inhibit-keyboard-quit)
  1952. "Read and return one of CHARS, prompting for PROMPT.
  1953. Any input that is not one of CHARS is ignored.
  1954. If optional argument INHIBIT-KEYBOARD-QUIT is non-nil, ignore
  1955. keyboard-quit events while waiting for a valid input."
  1956. (unless (consp chars)
  1957. (error "Called `read-char-choice' without valid char choices"))
  1958. (let (char done show-help (helpbuf " *Char Help*"))
  1959. (let ((cursor-in-echo-area t)
  1960. (executing-kbd-macro executing-kbd-macro))
  1961. (save-window-excursion ; in case we call help-form-show
  1962. (while (not done)
  1963. (unless (get-text-property 0 'face prompt)
  1964. (setq prompt (propertize prompt 'face 'minibuffer-prompt)))
  1965. (setq char (let ((inhibit-quit inhibit-keyboard-quit))
  1966. (read-key prompt)))
  1967. (and show-help (buffer-live-p (get-buffer helpbuf))
  1968. (kill-buffer helpbuf))
  1969. (cond
  1970. ((not (numberp char)))
  1971. ;; If caller has set help-form, that's enough.
  1972. ;; They don't explicitly have to add help-char to chars.
  1973. ((and help-form
  1974. (eq char help-char)
  1975. (setq show-help t)
  1976. (help-form-show)))
  1977. ((memq char chars)
  1978. (setq done t))
  1979. ((and executing-kbd-macro (= char -1))
  1980. ;; read-event returns -1 if we are in a kbd macro and
  1981. ;; there are no more events in the macro. Attempt to
  1982. ;; get an event interactively.
  1983. (setq executing-kbd-macro nil))
  1984. ((and (not inhibit-keyboard-quit) (eq char ?\C-g))
  1985. (keyboard-quit))))))
  1986. ;; Display the question with the answer. But without cursor-in-echo-area.
  1987. (message "%s%s" prompt (char-to-string char))
  1988. char))
  1989. (defun sit-for (seconds &optional nodisp obsolete)
  1990. "Perform redisplay, then wait for SECONDS seconds or until input is available.
  1991. SECONDS may be a floating-point value.
  1992. \(On operating systems that do not support waiting for fractions of a
  1993. second, floating-point values are rounded down to the nearest integer.)
  1994. If optional arg NODISP is t, don't redisplay, just wait for input.
  1995. Redisplay does not happen if input is available before it starts.
  1996. Value is t if waited the full time with no input arriving, and nil otherwise.
  1997. An obsolete, but still supported form is
  1998. \(sit-for SECONDS &optional MILLISECONDS NODISP)
  1999. where the optional arg MILLISECONDS specifies an additional wait period,
  2000. in milliseconds; this was useful when Emacs was built without
  2001. floating point support."
  2002. (if (numberp nodisp)
  2003. (setq seconds (+ seconds (* 1e-3 nodisp))
  2004. nodisp obsolete)
  2005. (if obsolete (setq nodisp obsolete)))
  2006. (cond
  2007. (noninteractive
  2008. (sleep-for seconds)
  2009. t)
  2010. ((input-pending-p)
  2011. nil)
  2012. ((<= seconds 0)
  2013. (or nodisp (redisplay)))
  2014. (t
  2015. (or nodisp (redisplay))
  2016. (let ((read (read-event nil nil seconds)))
  2017. (or (null read)
  2018. (progn
  2019. ;; If last command was a prefix arg, e.g. C-u, push this event onto
  2020. ;; unread-command-events as (t . EVENT) so it will be added to
  2021. ;; this-command-keys by read-key-sequence.
  2022. (if (eq overriding-terminal-local-map universal-argument-map)
  2023. (setq read (cons t read)))
  2024. (push read unread-command-events)
  2025. nil))))))
  2026. (set-advertised-calling-convention 'sit-for '(seconds &optional nodisp) "22.1")
  2027. (defun y-or-n-p (prompt)
  2028. "Ask user a \"y or n\" question. Return t if answer is \"y\".
  2029. PROMPT is the string to display to ask the question. It should
  2030. end in a space; `y-or-n-p' adds \"(y or n) \" to it.
  2031. No confirmation of the answer is requested; a single character is enough.
  2032. Also accepts Space to mean yes, or Delete to mean no. \(Actually, it uses
  2033. the bindings in `query-replace-map'; see the documentation of that variable
  2034. for more information. In this case, the useful bindings are `act', `skip',
  2035. `recenter', and `quit'.\)
  2036. Under a windowing system a dialog box will be used if `last-nonmenu-event'
  2037. is nil and `use-dialog-box' is non-nil."
  2038. ;; ¡Beware! when I tried to edebug this code, Emacs got into a weird state
  2039. ;; where all the keys were unbound (i.e. it somehow got triggered
  2040. ;; within read-key, apparently). I had to kill it.
  2041. (let ((answer 'recenter))
  2042. (cond
  2043. (noninteractive
  2044. (setq prompt (concat prompt
  2045. (if (eq ?\s (aref prompt (1- (length prompt))))
  2046. "" " ")
  2047. "(y or n) "))
  2048. (let ((temp-prompt prompt))
  2049. (while (not (memq answer '(act skip)))
  2050. (let ((str (read-string temp-prompt)))
  2051. (cond ((member str '("y" "Y")) (setq answer 'act))
  2052. ((member str '("n" "N")) (setq answer 'skip))
  2053. (t (setq temp-prompt (concat "Please answer y or n. "
  2054. prompt))))))))
  2055. ((and (display-popup-menus-p)
  2056. (listp last-nonmenu-event)
  2057. use-dialog-box)
  2058. (setq answer
  2059. (x-popup-dialog t `(,prompt ("Yes" . act) ("No" . skip)))))
  2060. (t
  2061. (setq prompt (concat prompt
  2062. (if (eq ?\s (aref prompt (1- (length prompt))))
  2063. "" " ")
  2064. "(y or n) "))
  2065. (while
  2066. (let* ((key
  2067. (let ((cursor-in-echo-area t))
  2068. (when minibuffer-auto-raise
  2069. (raise-frame (window-frame (minibuffer-window))))
  2070. (read-key (propertize (if (eq answer 'recenter)
  2071. prompt
  2072. (concat "Please answer y or n. "
  2073. prompt))
  2074. 'face 'minibuffer-prompt)))))
  2075. (setq answer (lookup-key query-replace-map (vector key) t))
  2076. (cond
  2077. ((memq answer '(skip act)) nil)
  2078. ((eq answer 'recenter) (recenter) t)
  2079. ((memq answer '(exit-prefix quit)) (signal 'quit nil) t)
  2080. (t t)))
  2081. (ding)
  2082. (discard-input))))
  2083. (let ((ret (eq answer 'act)))
  2084. (unless noninteractive
  2085. ;; FIXME this prints one too many spaces, since prompt
  2086. ;; already ends in a space. Eg "... (y or n) y".
  2087. (message "%s %s" prompt (if ret "y" "n")))
  2088. ret)))
  2089. ;;; Atomic change groups.
  2090. (defmacro atomic-change-group (&rest body)
  2091. "Perform BODY as an atomic change group.
  2092. This means that if BODY exits abnormally,
  2093. all of its changes to the current buffer are undone.
  2094. This works regardless of whether undo is enabled in the buffer.
  2095. This mechanism is transparent to ordinary use of undo;
  2096. if undo is enabled in the buffer and BODY succeeds, the
  2097. user can undo the change normally."
  2098. (declare (indent 0) (debug t))
  2099. (let ((handle (make-symbol "--change-group-handle--"))
  2100. (success (make-symbol "--change-group-success--")))
  2101. `(let ((,handle (prepare-change-group))
  2102. ;; Don't truncate any undo data in the middle of this.
  2103. (undo-outer-limit nil)
  2104. (undo-limit most-positive-fixnum)
  2105. (undo-strong-limit most-positive-fixnum)
  2106. (,success nil))
  2107. (unwind-protect
  2108. (progn
  2109. ;; This is inside the unwind-protect because
  2110. ;; it enables undo if that was disabled; we need
  2111. ;; to make sure that it gets disabled again.
  2112. (activate-change-group ,handle)
  2113. ,@body
  2114. (setq ,success t))
  2115. ;; Either of these functions will disable undo
  2116. ;; if it was disabled before.
  2117. (if ,success
  2118. (accept-change-group ,handle)
  2119. (cancel-change-group ,handle))))))
  2120. (defun prepare-change-group (&optional buffer)
  2121. "Return a handle for the current buffer's state, for a change group.
  2122. If you specify BUFFER, make a handle for BUFFER's state instead.
  2123. Pass the handle to `activate-change-group' afterward to initiate
  2124. the actual changes of the change group.
  2125. To finish the change group, call either `accept-change-group' or
  2126. `cancel-change-group' passing the same handle as argument. Call
  2127. `accept-change-group' to accept the changes in the group as final;
  2128. call `cancel-change-group' to undo them all. You should use
  2129. `unwind-protect' to make sure the group is always finished. The call
  2130. to `activate-change-group' should be inside the `unwind-protect'.
  2131. Once you finish the group, don't use the handle again--don't try to
  2132. finish the same group twice. For a simple example of correct use, see
  2133. the source code of `atomic-change-group'.
  2134. The handle records only the specified buffer. To make a multibuffer
  2135. change group, call this function once for each buffer you want to
  2136. cover, then use `nconc' to combine the returned values, like this:
  2137. (nconc (prepare-change-group buffer-1)
  2138. (prepare-change-group buffer-2))
  2139. You can then activate that multibuffer change group with a single
  2140. call to `activate-change-group' and finish it with a single call
  2141. to `accept-change-group' or `cancel-change-group'."
  2142. (if buffer
  2143. (list (cons buffer (with-current-buffer buffer buffer-undo-list)))
  2144. (list (cons (current-buffer) buffer-undo-list))))
  2145. (defun activate-change-group (handle)
  2146. "Activate a change group made with `prepare-change-group' (which see)."
  2147. (dolist (elt handle)
  2148. (with-current-buffer (car elt)
  2149. (if (eq buffer-undo-list t)
  2150. (setq buffer-undo-list nil)))))
  2151. (defun accept-change-group (handle)
  2152. "Finish a change group made with `prepare-change-group' (which see).
  2153. This finishes the change group by accepting its changes as final."
  2154. (dolist (elt handle)
  2155. (with-current-buffer (car elt)
  2156. (if (eq elt t)
  2157. (setq buffer-undo-list t)))))
  2158. (defun cancel-change-group (handle)
  2159. "Finish a change group made with `prepare-change-group' (which see).
  2160. This finishes the change group by reverting all of its changes."
  2161. (dolist (elt handle)
  2162. (with-current-buffer (car elt)
  2163. (setq elt (cdr elt))
  2164. (save-restriction
  2165. ;; Widen buffer temporarily so if the buffer was narrowed within
  2166. ;; the body of `atomic-change-group' all changes can be undone.
  2167. (widen)
  2168. (let ((old-car
  2169. (if (consp elt) (car elt)))
  2170. (old-cdr
  2171. (if (consp elt) (cdr elt))))
  2172. ;; Temporarily truncate the undo log at ELT.
  2173. (when (consp elt)
  2174. (setcar elt nil) (setcdr elt nil))
  2175. (unless (eq last-command 'undo) (undo-start))
  2176. ;; Make sure there's no confusion.
  2177. (when (and (consp elt) (not (eq elt (last pending-undo-list))))
  2178. (error "Undoing to some unrelated state"))
  2179. ;; Undo it all.
  2180. (save-excursion
  2181. (while (listp pending-undo-list) (undo-more 1)))
  2182. ;; Reset the modified cons cell ELT to its original content.
  2183. (when (consp elt)
  2184. (setcar elt old-car)
  2185. (setcdr elt old-cdr))
  2186. ;; Revert the undo info to what it was when we grabbed the state.
  2187. (setq buffer-undo-list elt))))))
  2188. ;;;; Display-related functions.
  2189. ;; For compatibility.
  2190. (defalias 'redraw-modeline 'force-mode-line-update)
  2191. (defun force-mode-line-update (&optional all)
  2192. "Force redisplay of the current buffer's mode line and header line.
  2193. With optional non-nil ALL, force redisplay of all mode lines and
  2194. header lines. This function also forces recomputation of the
  2195. menu bar menus and the frame title."
  2196. (if all (with-current-buffer (other-buffer)))
  2197. (set-buffer-modified-p (buffer-modified-p)))
  2198. (defun momentary-string-display (string pos &optional exit-char message)
  2199. "Momentarily display STRING in the buffer at POS.
  2200. Display remains until next event is input.
  2201. If POS is a marker, only its position is used; its buffer is ignored.
  2202. Optional third arg EXIT-CHAR can be a character, event or event
  2203. description list. EXIT-CHAR defaults to SPC. If the input is
  2204. EXIT-CHAR it is swallowed; otherwise it is then available as
  2205. input (as a command if nothing else).
  2206. Display MESSAGE (optional fourth arg) in the echo area.
  2207. If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
  2208. (or exit-char (setq exit-char ?\s))
  2209. (let ((ol (make-overlay pos pos))
  2210. (str (copy-sequence string)))
  2211. (unwind-protect
  2212. (progn
  2213. (save-excursion
  2214. (overlay-put ol 'after-string str)
  2215. (goto-char pos)
  2216. ;; To avoid trouble with out-of-bounds position
  2217. (setq pos (point))
  2218. ;; If the string end is off screen, recenter now.
  2219. (if (<= (window-end nil t) pos)
  2220. (recenter (/ (window-height) 2))))
  2221. (message (or message "Type %s to continue editing.")
  2222. (single-key-description exit-char))
  2223. (let ((event (read-event)))
  2224. ;; `exit-char' can be an event, or an event description list.
  2225. (or (eq event exit-char)
  2226. (eq event (event-convert-list exit-char))
  2227. (setq unread-command-events (list event)))))
  2228. (delete-overlay ol))))
  2229. ;;;; Overlay operations
  2230. (defun copy-overlay (o)
  2231. "Return a copy of overlay O."
  2232. (let ((o1 (if (overlay-buffer o)
  2233. (make-overlay (overlay-start o) (overlay-end o)
  2234. ;; FIXME: there's no easy way to find the
  2235. ;; insertion-type of the two markers.
  2236. (overlay-buffer o))
  2237. (let ((o1 (make-overlay (point-min) (point-min))))
  2238. (delete-overlay o1)
  2239. o1)))
  2240. (props (overlay-properties o)))
  2241. (while props
  2242. (overlay-put o1 (pop props) (pop props)))
  2243. o1))
  2244. (defun remove-overlays (&optional beg end name val)
  2245. "Clear BEG and END of overlays whose property NAME has value VAL.
  2246. Overlays might be moved and/or split.
  2247. BEG and END default respectively to the beginning and end of buffer."
  2248. ;; This speeds up the loops over overlays.
  2249. (unless beg (setq beg (point-min)))
  2250. (unless end (setq end (point-max)))
  2251. (overlay-recenter end)
  2252. (if (< end beg)
  2253. (setq beg (prog1 end (setq end beg))))
  2254. (save-excursion
  2255. (dolist (o (overlays-in beg end))
  2256. (when (eq (overlay-get o name) val)
  2257. ;; Either push this overlay outside beg...end
  2258. ;; or split it to exclude beg...end
  2259. ;; or delete it entirely (if it is contained in beg...end).
  2260. (if (< (overlay-start o) beg)
  2261. (if (> (overlay-end o) end)
  2262. (progn
  2263. (move-overlay (copy-overlay o)
  2264. (overlay-start o) beg)
  2265. (move-overlay o end (overlay-end o)))
  2266. (move-overlay o (overlay-start o) beg))
  2267. (if (> (overlay-end o) end)
  2268. (move-overlay o end (overlay-end o))
  2269. (delete-overlay o)))))))
  2270. ;;;; Miscellanea.
  2271. (defvar suspend-hook nil
  2272. "Normal hook run by `suspend-emacs', before suspending.")
  2273. (defvar suspend-resume-hook nil
  2274. "Normal hook run by `suspend-emacs', after Emacs is continued.")
  2275. (defvar temp-buffer-show-hook nil
  2276. "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
  2277. When the hook runs, the temporary buffer is current, and the window it
  2278. was displayed in is selected.")
  2279. (defvar temp-buffer-setup-hook nil
  2280. "Normal hook run by `with-output-to-temp-buffer' at the start.
  2281. When the hook runs, the temporary buffer is current.
  2282. This hook is normally set up with a function to put the buffer in Help
  2283. mode.")
  2284. ;; Avoid compiler warnings about this variable,
  2285. ;; which has a special meaning on certain system types.
  2286. (defvar buffer-file-type nil
  2287. "Non-nil if the visited file is a binary file.
  2288. This variable is meaningful on MS-DOG and Windows NT.
  2289. On those systems, it is automatically local in every buffer.
  2290. On other systems, this variable is normally always nil.")
  2291. ;; The `assert' macro from the cl package signals
  2292. ;; `cl-assertion-failed' at runtime so always define it.
  2293. (put 'cl-assertion-failed 'error-conditions '(error))
  2294. (put 'cl-assertion-failed 'error-message (purecopy "Assertion failed"))
  2295. (defconst user-emacs-directory
  2296. (if (eq system-type 'ms-dos)
  2297. ;; MS-DOS cannot have initial dot.
  2298. "~/_emacs.d/"
  2299. "~/.emacs.d/")
  2300. "Directory beneath which additional per-user Emacs-specific files are placed.
  2301. Various programs in Emacs store information in this directory.
  2302. Note that this should end with a directory separator.
  2303. See also `locate-user-emacs-file'.")
  2304. (defun locate-user-emacs-file (new-name &optional old-name)
  2305. "Return an absolute per-user Emacs-specific file name.
  2306. If OLD-NAME is non-nil and ~/OLD-NAME exists, return ~/OLD-NAME.
  2307. Else return NEW-NAME in `user-emacs-directory', creating the
  2308. directory if it does not exist."
  2309. (convert-standard-filename
  2310. (let* ((home (concat "~" (or init-file-user "")))
  2311. (at-home (and old-name (expand-file-name old-name home))))
  2312. (if (and at-home (file-readable-p at-home))
  2313. at-home
  2314. ;; Make sure `user-emacs-directory' exists,
  2315. ;; unless we're in batch mode or dumping Emacs
  2316. (or noninteractive
  2317. purify-flag
  2318. (file-accessible-directory-p
  2319. (directory-file-name user-emacs-directory))
  2320. (let ((umask (default-file-modes)))
  2321. (unwind-protect
  2322. (progn
  2323. (set-default-file-modes ?\700)
  2324. (make-directory user-emacs-directory))
  2325. (set-default-file-modes umask))))
  2326. (abbreviate-file-name
  2327. (expand-file-name new-name user-emacs-directory))))))
  2328. ;;;; Misc. useful functions.
  2329. (defun find-tag-default ()
  2330. "Determine default tag to search for, based on text at point.
  2331. If there is no plausible default, return nil."
  2332. (let (from to bound)
  2333. (when (or (progn
  2334. ;; Look at text around `point'.
  2335. (save-excursion
  2336. (skip-syntax-backward "w_") (setq from (point)))
  2337. (save-excursion
  2338. (skip-syntax-forward "w_") (setq to (point)))
  2339. (> to from))
  2340. ;; Look between `line-beginning-position' and `point'.
  2341. (save-excursion
  2342. (and (setq bound (line-beginning-position))
  2343. (skip-syntax-backward "^w_" bound)
  2344. (> (setq to (point)) bound)
  2345. (skip-syntax-backward "w_")
  2346. (setq from (point))))
  2347. ;; Look between `point' and `line-end-position'.
  2348. (save-excursion
  2349. (and (setq bound (line-end-position))
  2350. (skip-syntax-forward "^w_" bound)
  2351. (< (setq from (point)) bound)
  2352. (skip-syntax-forward "w_")
  2353. (setq to (point)))))
  2354. (buffer-substring-no-properties from to))))
  2355. (defun play-sound (sound)
  2356. "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
  2357. The following keywords are recognized:
  2358. :file FILE - read sound data from FILE. If FILE isn't an
  2359. absolute file name, it is searched in `data-directory'.
  2360. :data DATA - read sound data from string DATA.
  2361. Exactly one of :file or :data must be present.
  2362. :volume VOL - set volume to VOL. VOL must an integer in the
  2363. range 0..100 or a float in the range 0..1.0. If not specified,
  2364. don't change the volume setting of the sound device.
  2365. :device DEVICE - play sound on DEVICE. If not specified,
  2366. a system-dependent default device name is used.
  2367. Note: :data and :device are currently not supported on Windows."
  2368. (if (fboundp 'play-sound-internal)
  2369. (play-sound-internal sound)
  2370. (error "This Emacs binary lacks sound support")))
  2371. (declare-function w32-shell-dos-semantics "w32-fns" nil)
  2372. (defun shell-quote-argument (argument)
  2373. "Quote ARGUMENT for passing as argument to an inferior shell."
  2374. (cond
  2375. ((eq system-type 'ms-dos)
  2376. ;; Quote using double quotes, but escape any existing quotes in
  2377. ;; the argument with backslashes.
  2378. (let ((result "")
  2379. (start 0)
  2380. end)
  2381. (if (or (null (string-match "[^\"]" argument))
  2382. (< (match-end 0) (length argument)))
  2383. (while (string-match "[\"]" argument start)
  2384. (setq end (match-beginning 0)
  2385. result (concat result (substring argument start end)
  2386. "\\" (substring argument end (1+ end)))
  2387. start (1+ end))))
  2388. (concat "\"" result (substring argument start) "\"")))
  2389. ((and (eq system-type 'windows-nt) (w32-shell-dos-semantics))
  2390. ;; First, quote argument so that CommandLineToArgvW will
  2391. ;; understand it. See
  2392. ;; http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
  2393. ;; After we perform that level of quoting, escape shell
  2394. ;; metacharacters so that cmd won't mangle our argument. If the
  2395. ;; argument contains no double quote characters, we can just
  2396. ;; surround it with double quotes. Otherwise, we need to prefix
  2397. ;; each shell metacharacter with a caret.
  2398. (setq argument
  2399. ;; escape backslashes at end of string
  2400. (replace-regexp-in-string
  2401. "\\(\\\\*\\)$"
  2402. "\\1\\1"
  2403. ;; escape backslashes and quotes in string body
  2404. (replace-regexp-in-string
  2405. "\\(\\\\*\\)\""
  2406. "\\1\\1\\\\\""
  2407. argument)))
  2408. (if (string-match "[%!\"]" argument)
  2409. (concat
  2410. "^\""
  2411. (replace-regexp-in-string
  2412. "\\([%!()\"<>&|^]\\)"
  2413. "^\\1"
  2414. argument)
  2415. "^\"")
  2416. (concat "\"" argument "\"")))
  2417. (t
  2418. (if (equal argument "")
  2419. "''"
  2420. ;; Quote everything except POSIX filename characters.
  2421. ;; This should be safe enough even for really weird shells.
  2422. (replace-regexp-in-string
  2423. "\n" "'\n'"
  2424. (replace-regexp-in-string "[^-0-9a-zA-Z_./\n]" "\\\\\\&" argument))))
  2425. ))
  2426. (defun string-or-null-p (object)
  2427. "Return t if OBJECT is a string or nil.
  2428. Otherwise, return nil."
  2429. (or (stringp object) (null object)))
  2430. (defun booleanp (object)
  2431. "Return t if OBJECT is one of the two canonical boolean values: t or nil.
  2432. Otherwise, return nil."
  2433. (and (memq object '(nil t)) t))
  2434. (defun field-at-pos (pos)
  2435. "Return the field at position POS, taking stickiness etc into account."
  2436. (let ((raw-field (get-char-property (field-beginning pos) 'field)))
  2437. (if (eq raw-field 'boundary)
  2438. (get-char-property (1- (field-end pos)) 'field)
  2439. raw-field)))
  2440. (defun sha1 (object &optional start end binary)
  2441. "Return the SHA1 (Secure Hash Algorithm) of an OBJECT.
  2442. OBJECT is either a string or a buffer. Optional arguments START and
  2443. END are character positions specifying which portion of OBJECT for
  2444. computing the hash. If BINARY is non-nil, return a string in binary
  2445. form."
  2446. (secure-hash 'sha1 object start end binary))
  2447. ;;;; Support for yanking and text properties.
  2448. (defvar yank-excluded-properties)
  2449. (defun remove-yank-excluded-properties (start end)
  2450. "Remove `yank-excluded-properties' between START and END positions.
  2451. Replaces `category' properties with their defined properties."
  2452. (let ((inhibit-read-only t))
  2453. ;; Replace any `category' property with the properties it stands
  2454. ;; for. This is to remove `mouse-face' properties that are placed
  2455. ;; on categories in *Help* buffers' buttons. See
  2456. ;; http://lists.gnu.org/archive/html/emacs-devel/2002-04/msg00648.html
  2457. ;; for the details.
  2458. (unless (memq yank-excluded-properties '(t nil))
  2459. (save-excursion
  2460. (goto-char start)
  2461. (while (< (point) end)
  2462. (let ((cat (get-text-property (point) 'category))
  2463. run-end)
  2464. (setq run-end
  2465. (next-single-property-change (point) 'category nil end))
  2466. (when cat
  2467. (let (run-end2 original)
  2468. (remove-list-of-text-properties (point) run-end '(category))
  2469. (while (< (point) run-end)
  2470. (setq run-end2 (next-property-change (point) nil run-end))
  2471. (setq original (text-properties-at (point)))
  2472. (set-text-properties (point) run-end2 (symbol-plist cat))
  2473. (add-text-properties (point) run-end2 original)
  2474. (goto-char run-end2))))
  2475. (goto-char run-end)))))
  2476. (if (eq yank-excluded-properties t)
  2477. (set-text-properties start end nil)
  2478. (remove-list-of-text-properties start end yank-excluded-properties))))
  2479. (defvar yank-undo-function)
  2480. (defun insert-for-yank (string)
  2481. "Call `insert-for-yank-1' repetitively for each `yank-handler' segment.
  2482. See `insert-for-yank-1' for more details."
  2483. (let (to)
  2484. (while (setq to (next-single-property-change 0 'yank-handler string))
  2485. (insert-for-yank-1 (substring string 0 to))
  2486. (setq string (substring string to))))
  2487. (insert-for-yank-1 string))
  2488. (defun insert-for-yank-1 (string)
  2489. "Insert STRING at point, stripping some text properties.
  2490. Strip text properties from the inserted text according to
  2491. `yank-excluded-properties'. Otherwise just like (insert STRING).
  2492. If STRING has a non-nil `yank-handler' property on the first character,
  2493. the normal insert behavior is modified in various ways. The value of
  2494. the yank-handler property must be a list with one to four elements
  2495. with the following format: (FUNCTION PARAM NOEXCLUDE UNDO).
  2496. When FUNCTION is present and non-nil, it is called instead of `insert'
  2497. to insert the string. FUNCTION takes one argument--the object to insert.
  2498. If PARAM is present and non-nil, it replaces STRING as the object
  2499. passed to FUNCTION (or `insert'); for example, if FUNCTION is
  2500. `yank-rectangle', PARAM may be a list of strings to insert as a
  2501. rectangle.
  2502. If NOEXCLUDE is present and non-nil, the normal removal of the
  2503. `yank-excluded-properties' is not performed; instead FUNCTION is
  2504. responsible for removing those properties. This may be necessary
  2505. if FUNCTION adjusts point before or after inserting the object.
  2506. If UNDO is present and non-nil, it is a function that will be called
  2507. by `yank-pop' to undo the insertion of the current object. It is
  2508. called with two arguments, the start and end of the current region.
  2509. FUNCTION may set `yank-undo-function' to override the UNDO value."
  2510. (let* ((handler (and (stringp string)
  2511. (get-text-property 0 'yank-handler string)))
  2512. (param (or (nth 1 handler) string))
  2513. (opoint (point))
  2514. (inhibit-read-only inhibit-read-only)
  2515. end)
  2516. (setq yank-undo-function t)
  2517. (if (nth 0 handler) ;; FUNCTION
  2518. (funcall (car handler) param)
  2519. (insert param))
  2520. (setq end (point))
  2521. ;; Prevent read-only properties from interfering with the
  2522. ;; following text property changes.
  2523. (setq inhibit-read-only t)
  2524. ;; What should we do with `font-lock-face' properties?
  2525. (if font-lock-defaults
  2526. ;; No, just wipe them.
  2527. (remove-list-of-text-properties opoint end '(font-lock-face))
  2528. ;; Convert them to `face'.
  2529. (save-excursion
  2530. (goto-char opoint)
  2531. (while (< (point) end)
  2532. (let ((face (get-text-property (point) 'font-lock-face))
  2533. run-end)
  2534. (setq run-end
  2535. (next-single-property-change (point) 'font-lock-face nil end))
  2536. (when face
  2537. (remove-text-properties (point) run-end '(font-lock-face nil))
  2538. (put-text-property (point) run-end 'face face))
  2539. (goto-char run-end)))))
  2540. (unless (nth 2 handler) ;; NOEXCLUDE
  2541. (remove-yank-excluded-properties opoint (point)))
  2542. ;; If last inserted char has properties, mark them as rear-nonsticky.
  2543. (if (and (> end opoint)
  2544. (text-properties-at (1- end)))
  2545. (put-text-property (1- end) end 'rear-nonsticky t))
  2546. (if (eq yank-undo-function t) ;; not set by FUNCTION
  2547. (setq yank-undo-function (nth 3 handler))) ;; UNDO
  2548. (if (nth 4 handler) ;; COMMAND
  2549. (setq this-command (nth 4 handler)))))
  2550. (defun insert-buffer-substring-no-properties (buffer &optional start end)
  2551. "Insert before point a substring of BUFFER, without text properties.
  2552. BUFFER may be a buffer or a buffer name.
  2553. Arguments START and END are character positions specifying the substring.
  2554. They default to the values of (point-min) and (point-max) in BUFFER."
  2555. (let ((opoint (point)))
  2556. (insert-buffer-substring buffer start end)
  2557. (let ((inhibit-read-only t))
  2558. (set-text-properties opoint (point) nil))))
  2559. (defun insert-buffer-substring-as-yank (buffer &optional start end)
  2560. "Insert before point a part of BUFFER, stripping some text properties.
  2561. BUFFER may be a buffer or a buffer name.
  2562. Arguments START and END are character positions specifying the substring.
  2563. They default to the values of (point-min) and (point-max) in BUFFER.
  2564. Strip text properties from the inserted text according to
  2565. `yank-excluded-properties'."
  2566. ;; Since the buffer text should not normally have yank-handler properties,
  2567. ;; there is no need to handle them here.
  2568. (let ((opoint (point)))
  2569. (insert-buffer-substring buffer start end)
  2570. (remove-yank-excluded-properties opoint (point))))
  2571. ;;;; Synchronous shell commands.
  2572. (defun start-process-shell-command (name buffer &rest args)
  2573. "Start a program in a subprocess. Return the process object for it.
  2574. NAME is name for process. It is modified if necessary to make it unique.
  2575. BUFFER is the buffer (or buffer name) to associate with the process.
  2576. Process output goes at end of that buffer, unless you specify
  2577. an output stream or filter function to handle the output.
  2578. BUFFER may be also nil, meaning that this process is not associated
  2579. with any buffer
  2580. COMMAND is the shell command to run.
  2581. An old calling convention accepted any number of arguments after COMMAND,
  2582. which were just concatenated to COMMAND. This is still supported but strongly
  2583. discouraged."
  2584. ;; We used to use `exec' to replace the shell with the command,
  2585. ;; but that failed to handle (...) and semicolon, etc.
  2586. (start-process name buffer shell-file-name shell-command-switch
  2587. (mapconcat 'identity args " ")))
  2588. (set-advertised-calling-convention 'start-process-shell-command
  2589. '(name buffer command) "23.1")
  2590. (defun start-file-process-shell-command (name buffer &rest args)
  2591. "Start a program in a subprocess. Return the process object for it.
  2592. Similar to `start-process-shell-command', but calls `start-file-process'."
  2593. (start-file-process
  2594. name buffer
  2595. (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
  2596. (if (file-remote-p default-directory) "-c" shell-command-switch)
  2597. (mapconcat 'identity args " ")))
  2598. (set-advertised-calling-convention 'start-file-process-shell-command
  2599. '(name buffer command) "23.1")
  2600. (defun call-process-shell-command (command &optional infile buffer display
  2601. &rest args)
  2602. "Execute the shell command COMMAND synchronously in separate process.
  2603. The remaining arguments are optional.
  2604. The program's input comes from file INFILE (nil means `/dev/null').
  2605. Insert output in BUFFER before point; t means current buffer;
  2606. nil for BUFFER means discard it; 0 means discard and don't wait.
  2607. BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
  2608. REAL-BUFFER says what to do with standard output, as above,
  2609. while STDERR-FILE says what to do with standard error in the child.
  2610. STDERR-FILE may be nil (discard standard error output),
  2611. t (mix it with ordinary output), or a file name string.
  2612. Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
  2613. Remaining arguments are strings passed as additional arguments for COMMAND.
  2614. Wildcards and redirection are handled as usual in the shell.
  2615. If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
  2616. Otherwise it waits for COMMAND to terminate and returns a numeric exit
  2617. status or a signal description string.
  2618. If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
  2619. ;; We used to use `exec' to replace the shell with the command,
  2620. ;; but that failed to handle (...) and semicolon, etc.
  2621. (call-process shell-file-name
  2622. infile buffer display
  2623. shell-command-switch
  2624. (mapconcat 'identity (cons command args) " ")))
  2625. (defun process-file-shell-command (command &optional infile buffer display
  2626. &rest args)
  2627. "Process files synchronously in a separate process.
  2628. Similar to `call-process-shell-command', but calls `process-file'."
  2629. (process-file
  2630. (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
  2631. infile buffer display
  2632. (if (file-remote-p default-directory) "-c" shell-command-switch)
  2633. (mapconcat 'identity (cons command args) " ")))
  2634. ;;;; Lisp macros to do various things temporarily.
  2635. (defmacro with-current-buffer (buffer-or-name &rest body)
  2636. "Execute the forms in BODY with BUFFER-OR-NAME temporarily current.
  2637. BUFFER-OR-NAME must be a buffer or the name of an existing buffer.
  2638. The value returned is the value of the last form in BODY. See
  2639. also `with-temp-buffer'."
  2640. (declare (indent 1) (debug t))
  2641. `(save-current-buffer
  2642. (set-buffer ,buffer-or-name)
  2643. ,@body))
  2644. (defmacro with-selected-window (window &rest body)
  2645. "Execute the forms in BODY with WINDOW as the selected window.
  2646. The value returned is the value of the last form in BODY.
  2647. This macro saves and restores the selected window, as well as the
  2648. selected window of each frame. It does not change the order of
  2649. recently selected windows. If the previously selected window of
  2650. some frame is no longer live at the end of BODY, that frame's
  2651. selected window is left alone. If the selected window is no
  2652. longer live, then whatever window is selected at the end of BODY
  2653. remains selected.
  2654. This macro uses `save-current-buffer' to save and restore the
  2655. current buffer, since otherwise its normal operation could
  2656. potentially make a different buffer current. It does not alter
  2657. the buffer list ordering."
  2658. (declare (indent 1) (debug t))
  2659. ;; Most of this code is a copy of save-selected-window.
  2660. `(let ((save-selected-window-window (selected-window))
  2661. ;; It is necessary to save all of these, because calling
  2662. ;; select-window changes frame-selected-window for whatever
  2663. ;; frame that window is in.
  2664. (save-selected-window-alist
  2665. (mapcar (lambda (frame) (list frame (frame-selected-window frame)))
  2666. (frame-list))))
  2667. (save-current-buffer
  2668. (unwind-protect
  2669. (progn (select-window ,window 'norecord)
  2670. ,@body)
  2671. (dolist (elt save-selected-window-alist)
  2672. (and (frame-live-p (car elt))
  2673. (window-live-p (cadr elt))
  2674. (set-frame-selected-window (car elt) (cadr elt) 'norecord)))
  2675. (when (window-live-p save-selected-window-window)
  2676. (select-window save-selected-window-window 'norecord))))))
  2677. (defmacro with-selected-frame (frame &rest body)
  2678. "Execute the forms in BODY with FRAME as the selected frame.
  2679. The value returned is the value of the last form in BODY.
  2680. This macro saves and restores the selected frame, and changes the
  2681. order of neither the recently selected windows nor the buffers in
  2682. the buffer list."
  2683. (declare (indent 1) (debug t))
  2684. (let ((old-frame (make-symbol "old-frame"))
  2685. (old-buffer (make-symbol "old-buffer")))
  2686. `(let ((,old-frame (selected-frame))
  2687. (,old-buffer (current-buffer)))
  2688. (unwind-protect
  2689. (progn (select-frame ,frame 'norecord)
  2690. ,@body)
  2691. (when (frame-live-p ,old-frame)
  2692. (select-frame ,old-frame 'norecord))
  2693. (when (buffer-live-p ,old-buffer)
  2694. (set-buffer ,old-buffer))))))
  2695. (defmacro save-window-excursion (&rest body)
  2696. "Execute BODY, then restore previous window configuration.
  2697. This macro saves the window configuration on the selected frame,
  2698. executes BODY, then calls `set-window-configuration' to restore
  2699. the saved window configuration. The return value is the last
  2700. form in BODY. The window configuration is also restored if BODY
  2701. exits nonlocally.
  2702. BEWARE: Most uses of this macro introduce bugs.
  2703. E.g. it should not be used to try and prevent some code from opening
  2704. a new window, since that window may sometimes appear in another frame,
  2705. in which case `save-window-excursion' cannot help."
  2706. (declare (indent 0) (debug t))
  2707. (let ((c (make-symbol "wconfig")))
  2708. `(let ((,c (current-window-configuration)))
  2709. (unwind-protect (progn ,@body)
  2710. (set-window-configuration ,c)))))
  2711. (defmacro with-output-to-temp-buffer (bufname &rest body)
  2712. "Bind `standard-output' to buffer BUFNAME, eval BODY, then show that buffer.
  2713. This construct makes buffer BUFNAME empty before running BODY.
  2714. It does not make the buffer current for BODY.
  2715. Instead it binds `standard-output' to that buffer, so that output
  2716. generated with `prin1' and similar functions in BODY goes into
  2717. the buffer.
  2718. At the end of BODY, this marks buffer BUFNAME unmodified and displays
  2719. it in a window, but does not select it. The normal way to do this is
  2720. by calling `display-buffer', then running `temp-buffer-show-hook'.
  2721. However, if `temp-buffer-show-function' is non-nil, it calls that
  2722. function instead (and does not run `temp-buffer-show-hook'). The
  2723. function gets one argument, the buffer to display.
  2724. The return value of `with-output-to-temp-buffer' is the value of the
  2725. last form in BODY. If BODY does not finish normally, the buffer
  2726. BUFNAME is not displayed.
  2727. This runs the hook `temp-buffer-setup-hook' before BODY,
  2728. with the buffer BUFNAME temporarily current. It runs the hook
  2729. `temp-buffer-show-hook' after displaying buffer BUFNAME, with that
  2730. buffer temporarily current, and the window that was used to display it
  2731. temporarily selected. But it doesn't run `temp-buffer-show-hook'
  2732. if it uses `temp-buffer-show-function'."
  2733. (declare (debug t))
  2734. (let ((old-dir (make-symbol "old-dir"))
  2735. (buf (make-symbol "buf")))
  2736. `(let* ((,old-dir default-directory)
  2737. (,buf
  2738. (with-current-buffer (get-buffer-create ,bufname)
  2739. (prog1 (current-buffer)
  2740. (kill-all-local-variables)
  2741. ;; FIXME: delete_all_overlays
  2742. (setq default-directory ,old-dir)
  2743. (setq buffer-read-only nil)
  2744. (setq buffer-file-name nil)
  2745. (setq buffer-undo-list t)
  2746. (let ((inhibit-read-only t)
  2747. (inhibit-modification-hooks t))
  2748. (erase-buffer)
  2749. (run-hooks 'temp-buffer-setup-hook)))))
  2750. (standard-output ,buf))
  2751. (prog1 (progn ,@body)
  2752. (internal-temp-output-buffer-show ,buf)))))
  2753. (defmacro with-temp-file (file &rest body)
  2754. "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
  2755. The value returned is the value of the last form in BODY.
  2756. See also `with-temp-buffer'."
  2757. (declare (indent 1) (debug t))
  2758. (let ((temp-file (make-symbol "temp-file"))
  2759. (temp-buffer (make-symbol "temp-buffer")))
  2760. `(let ((,temp-file ,file)
  2761. (,temp-buffer
  2762. (get-buffer-create (generate-new-buffer-name " *temp file*"))))
  2763. (unwind-protect
  2764. (prog1
  2765. (with-current-buffer ,temp-buffer
  2766. ,@body)
  2767. (with-current-buffer ,temp-buffer
  2768. (write-region nil nil ,temp-file nil 0)))
  2769. (and (buffer-name ,temp-buffer)
  2770. (kill-buffer ,temp-buffer))))))
  2771. (defmacro with-temp-message (message &rest body)
  2772. "Display MESSAGE temporarily if non-nil while BODY is evaluated.
  2773. The original message is restored to the echo area after BODY has finished.
  2774. The value returned is the value of the last form in BODY.
  2775. MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
  2776. If MESSAGE is nil, the echo area and message log buffer are unchanged.
  2777. Use a MESSAGE of \"\" to temporarily clear the echo area."
  2778. (declare (debug t) (indent 1))
  2779. (let ((current-message (make-symbol "current-message"))
  2780. (temp-message (make-symbol "with-temp-message")))
  2781. `(let ((,temp-message ,message)
  2782. (,current-message))
  2783. (unwind-protect
  2784. (progn
  2785. (when ,temp-message
  2786. (setq ,current-message (current-message))
  2787. (message "%s" ,temp-message))
  2788. ,@body)
  2789. (and ,temp-message
  2790. (if ,current-message
  2791. (message "%s" ,current-message)
  2792. (message nil)))))))
  2793. (defmacro with-temp-buffer (&rest body)
  2794. "Create a temporary buffer, and evaluate BODY there like `progn'.
  2795. See also `with-temp-file' and `with-output-to-string'."
  2796. (declare (indent 0) (debug t))
  2797. (let ((temp-buffer (make-symbol "temp-buffer")))
  2798. `(let ((,temp-buffer (generate-new-buffer " *temp*")))
  2799. ;; FIXME: kill-buffer can change current-buffer in some odd cases.
  2800. (with-current-buffer ,temp-buffer
  2801. (unwind-protect
  2802. (progn ,@body)
  2803. (and (buffer-name ,temp-buffer)
  2804. (kill-buffer ,temp-buffer)))))))
  2805. (defmacro with-silent-modifications (&rest body)
  2806. "Execute BODY, pretending it does not modify the buffer.
  2807. If BODY performs real modifications to the buffer's text, other
  2808. than cosmetic ones, undo data may become corrupted.
  2809. This macro will run BODY normally, but doesn't count its buffer
  2810. modifications as being buffer modifications. This affects things
  2811. like buffer-modified-p, checking whether the file is locked by
  2812. someone else, running buffer modification hooks, and other things
  2813. of that nature.
  2814. Typically used around modifications of text-properties which do
  2815. not really affect the buffer's content."
  2816. (declare (debug t) (indent 0))
  2817. (let ((modified (make-symbol "modified")))
  2818. `(let* ((,modified (buffer-modified-p))
  2819. (buffer-undo-list t)
  2820. (inhibit-read-only t)
  2821. (inhibit-modification-hooks t)
  2822. deactivate-mark
  2823. ;; Avoid setting and removing file locks and checking
  2824. ;; buffer's uptodate-ness w.r.t the underlying file.
  2825. buffer-file-name
  2826. buffer-file-truename)
  2827. (unwind-protect
  2828. (progn
  2829. ,@body)
  2830. (unless ,modified
  2831. (restore-buffer-modified-p nil))))))
  2832. (defmacro with-output-to-string (&rest body)
  2833. "Execute BODY, return the text it sent to `standard-output', as a string."
  2834. (declare (indent 0) (debug t))
  2835. `(let ((standard-output
  2836. (get-buffer-create (generate-new-buffer-name " *string-output*"))))
  2837. (unwind-protect
  2838. (progn
  2839. (let ((standard-output standard-output))
  2840. ,@body)
  2841. (with-current-buffer standard-output
  2842. (buffer-string)))
  2843. (kill-buffer standard-output))))
  2844. (defmacro with-local-quit (&rest body)
  2845. "Execute BODY, allowing quits to terminate BODY but not escape further.
  2846. When a quit terminates BODY, `with-local-quit' returns nil but
  2847. requests another quit. That quit will be processed as soon as quitting
  2848. is allowed once again. (Immediately, if `inhibit-quit' is nil.)"
  2849. (declare (debug t) (indent 0))
  2850. `(condition-case nil
  2851. (let ((inhibit-quit nil))
  2852. ,@body)
  2853. (quit (setq quit-flag t)
  2854. ;; This call is to give a chance to handle quit-flag
  2855. ;; in case inhibit-quit is nil.
  2856. ;; Without this, it will not be handled until the next function
  2857. ;; call, and that might allow it to exit thru a condition-case
  2858. ;; that intends to handle the quit signal next time.
  2859. (eval '(ignore nil)))))
  2860. (defmacro while-no-input (&rest body)
  2861. "Execute BODY only as long as there's no pending input.
  2862. If input arrives, that ends the execution of BODY,
  2863. and `while-no-input' returns t. Quitting makes it return nil.
  2864. If BODY finishes, `while-no-input' returns whatever value BODY produced."
  2865. (declare (debug t) (indent 0))
  2866. (let ((catch-sym (make-symbol "input")))
  2867. `(with-local-quit
  2868. (catch ',catch-sym
  2869. (let ((throw-on-input ',catch-sym))
  2870. (or (input-pending-p)
  2871. (progn ,@body)))))))
  2872. (defmacro condition-case-unless-debug (var bodyform &rest handlers)
  2873. "Like `condition-case' except that it does not catch anything when debugging.
  2874. More specifically if `debug-on-error' is set, then it does not catch any signal."
  2875. (declare (debug condition-case) (indent 2))
  2876. (let ((bodysym (make-symbol "body")))
  2877. `(let ((,bodysym (lambda () ,bodyform)))
  2878. (if debug-on-error
  2879. (funcall ,bodysym)
  2880. (condition-case ,var
  2881. (funcall ,bodysym)
  2882. ,@handlers)))))
  2883. (define-obsolete-function-alias 'condition-case-no-debug
  2884. 'condition-case-unless-debug "24.1")
  2885. (defmacro with-demoted-errors (&rest body)
  2886. "Run BODY and demote any errors to simple messages.
  2887. If `debug-on-error' is non-nil, run BODY without catching its errors.
  2888. This is to be used around code which is not expected to signal an error
  2889. but which should be robust in the unexpected case that an error is signaled."
  2890. (declare (debug t) (indent 0))
  2891. (let ((err (make-symbol "err")))
  2892. `(condition-case-unless-debug ,err
  2893. (progn ,@body)
  2894. (error (message "Error: %S" ,err) nil))))
  2895. (defmacro combine-after-change-calls (&rest body)
  2896. "Execute BODY, but don't call the after-change functions till the end.
  2897. If BODY makes changes in the buffer, they are recorded
  2898. and the functions on `after-change-functions' are called several times
  2899. when BODY is finished.
  2900. The return value is the value of the last form in BODY.
  2901. If `before-change-functions' is non-nil, then calls to the after-change
  2902. functions can't be deferred, so in that case this macro has no effect.
  2903. Do not alter `after-change-functions' or `before-change-functions'
  2904. in BODY."
  2905. (declare (indent 0) (debug t))
  2906. `(unwind-protect
  2907. (let ((combine-after-change-calls t))
  2908. . ,body)
  2909. (combine-after-change-execute)))
  2910. (defmacro with-case-table (table &rest body)
  2911. "Execute the forms in BODY with TABLE as the current case table.
  2912. The value returned is the value of the last form in BODY."
  2913. (declare (indent 1) (debug t))
  2914. (let ((old-case-table (make-symbol "table"))
  2915. (old-buffer (make-symbol "buffer")))
  2916. `(let ((,old-case-table (current-case-table))
  2917. (,old-buffer (current-buffer)))
  2918. (unwind-protect
  2919. (progn (set-case-table ,table)
  2920. ,@body)
  2921. (with-current-buffer ,old-buffer
  2922. (set-case-table ,old-case-table))))))
  2923. ;;; Matching and match data.
  2924. (defvar save-match-data-internal)
  2925. ;; We use save-match-data-internal as the local variable because
  2926. ;; that works ok in practice (people should not use that variable elsewhere).
  2927. ;; We used to use an uninterned symbol; the compiler handles that properly
  2928. ;; now, but it generates slower code.
  2929. (defmacro save-match-data (&rest body)
  2930. "Execute the BODY forms, restoring the global value of the match data.
  2931. The value returned is the value of the last form in BODY."
  2932. ;; It is better not to use backquote here,
  2933. ;; because that makes a bootstrapping problem
  2934. ;; if you need to recompile all the Lisp files using interpreted code.
  2935. (declare (indent 0) (debug t))
  2936. (list 'let
  2937. '((save-match-data-internal (match-data)))
  2938. (list 'unwind-protect
  2939. (cons 'progn body)
  2940. ;; It is safe to free (evaporate) markers immediately here,
  2941. ;; as Lisp programs should not copy from save-match-data-internal.
  2942. '(set-match-data save-match-data-internal 'evaporate))))
  2943. (defun match-string (num &optional string)
  2944. "Return string of text matched by last search.
  2945. NUM specifies which parenthesized expression in the last regexp.
  2946. Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
  2947. Zero means the entire text matched by the whole regexp or whole string.
  2948. STRING should be given if the last search was by `string-match' on STRING.
  2949. If STRING is nil, the current buffer should be the same buffer
  2950. the search/match was performed in."
  2951. (if (match-beginning num)
  2952. (if string
  2953. (substring string (match-beginning num) (match-end num))
  2954. (buffer-substring (match-beginning num) (match-end num)))))
  2955. (defun match-string-no-properties (num &optional string)
  2956. "Return string of text matched by last search, without text properties.
  2957. NUM specifies which parenthesized expression in the last regexp.
  2958. Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
  2959. Zero means the entire text matched by the whole regexp or whole string.
  2960. STRING should be given if the last search was by `string-match' on STRING.
  2961. If STRING is nil, the current buffer should be the same buffer
  2962. the search/match was performed in."
  2963. (if (match-beginning num)
  2964. (if string
  2965. (substring-no-properties string (match-beginning num)
  2966. (match-end num))
  2967. (buffer-substring-no-properties (match-beginning num)
  2968. (match-end num)))))
  2969. (defun match-substitute-replacement (replacement
  2970. &optional fixedcase literal string subexp)
  2971. "Return REPLACEMENT as it will be inserted by `replace-match'.
  2972. In other words, all back-references in the form `\\&' and `\\N'
  2973. are substituted with actual strings matched by the last search.
  2974. Optional FIXEDCASE, LITERAL, STRING and SUBEXP have the same
  2975. meaning as for `replace-match'."
  2976. (let ((match (match-string 0 string)))
  2977. (save-match-data
  2978. (set-match-data (mapcar (lambda (x)
  2979. (if (numberp x)
  2980. (- x (match-beginning 0))
  2981. x))
  2982. (match-data t)))
  2983. (replace-match replacement fixedcase literal match subexp))))
  2984. (defun looking-back (regexp &optional limit greedy)
  2985. "Return non-nil if text before point matches regular expression REGEXP.
  2986. Like `looking-at' except matches before point, and is slower.
  2987. LIMIT if non-nil speeds up the search by specifying a minimum
  2988. starting position, to avoid checking matches that would start
  2989. before LIMIT.
  2990. If GREEDY is non-nil, extend the match backwards as far as
  2991. possible, stopping when a single additional previous character
  2992. cannot be part of a match for REGEXP. When the match is
  2993. extended, its starting position is allowed to occur before
  2994. LIMIT."
  2995. (let ((start (point))
  2996. (pos
  2997. (save-excursion
  2998. (and (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t)
  2999. (point)))))
  3000. (if (and greedy pos)
  3001. (save-restriction
  3002. (narrow-to-region (point-min) start)
  3003. (while (and (> pos (point-min))
  3004. (save-excursion
  3005. (goto-char pos)
  3006. (backward-char 1)
  3007. (looking-at (concat "\\(?:" regexp "\\)\\'"))))
  3008. (setq pos (1- pos)))
  3009. (save-excursion
  3010. (goto-char pos)
  3011. (looking-at (concat "\\(?:" regexp "\\)\\'")))))
  3012. (not (null pos))))
  3013. (defsubst looking-at-p (regexp)
  3014. "\
  3015. Same as `looking-at' except this function does not change the match data."
  3016. (let ((inhibit-changing-match-data t))
  3017. (looking-at regexp)))
  3018. (defsubst string-match-p (regexp string &optional start)
  3019. "\
  3020. Same as `string-match' except this function does not change the match data."
  3021. (let ((inhibit-changing-match-data t))
  3022. (string-match regexp string start)))
  3023. (defun subregexp-context-p (regexp pos &optional start)
  3024. "Return non-nil if POS is in a normal subregexp context in REGEXP.
  3025. A subregexp context is one where a sub-regexp can appear.
  3026. A non-subregexp context is for example within brackets, or within a
  3027. repetition bounds operator `\\=\\{...\\}', or right after a `\\'.
  3028. If START is non-nil, it should be a position in REGEXP, smaller
  3029. than POS, and known to be in a subregexp context."
  3030. ;; Here's one possible implementation, with the great benefit that it
  3031. ;; reuses the regexp-matcher's own parser, so it understands all the
  3032. ;; details of the syntax. A disadvantage is that it needs to match the
  3033. ;; error string.
  3034. (condition-case err
  3035. (progn
  3036. (string-match (substring regexp (or start 0) pos) "")
  3037. t)
  3038. (invalid-regexp
  3039. (not (member (cadr err) '("Unmatched [ or [^"
  3040. "Unmatched \\{"
  3041. "Trailing backslash")))))
  3042. ;; An alternative implementation:
  3043. ;; (defconst re-context-re
  3044. ;; (let* ((harmless-ch "[^\\[]")
  3045. ;; (harmless-esc "\\\\[^{]")
  3046. ;; (class-harmless-ch "[^][]")
  3047. ;; (class-lb-harmless "[^]:]")
  3048. ;; (class-lb-colon-maybe-charclass ":\\([a-z]+:]\\)?")
  3049. ;; (class-lb (concat "\\[\\(" class-lb-harmless
  3050. ;; "\\|" class-lb-colon-maybe-charclass "\\)"))
  3051. ;; (class
  3052. ;; (concat "\\[^?]?"
  3053. ;; "\\(" class-harmless-ch
  3054. ;; "\\|" class-lb "\\)*"
  3055. ;; "\\[?]")) ; special handling for bare [ at end of re
  3056. ;; (braces "\\\\{[0-9,]+\\\\}"))
  3057. ;; (concat "\\`\\(" harmless-ch "\\|" harmless-esc
  3058. ;; "\\|" class "\\|" braces "\\)*\\'"))
  3059. ;; "Matches any prefix that corresponds to a normal subregexp context.")
  3060. ;; (string-match re-context-re (substring regexp (or start 0) pos))
  3061. )
  3062. ;;;; split-string
  3063. (defconst split-string-default-separators "[ \f\t\n\r\v]+"
  3064. "The default value of separators for `split-string'.
  3065. A regexp matching strings of whitespace. May be locale-dependent
  3066. \(as yet unimplemented). Should not match non-breaking spaces.
  3067. Warning: binding this to a different value and using it as default is
  3068. likely to have undesired semantics.")
  3069. ;; The specification says that if both SEPARATORS and OMIT-NULLS are
  3070. ;; defaulted, OMIT-NULLS should be treated as t. Simplifying the logical
  3071. ;; expression leads to the equivalent implementation that if SEPARATORS
  3072. ;; is defaulted, OMIT-NULLS is treated as t.
  3073. (defun split-string (string &optional separators omit-nulls)
  3074. "Split STRING into substrings bounded by matches for SEPARATORS.
  3075. The beginning and end of STRING, and each match for SEPARATORS, are
  3076. splitting points. The substrings matching SEPARATORS are removed, and
  3077. the substrings between the splitting points are collected as a list,
  3078. which is returned.
  3079. If SEPARATORS is non-nil, it should be a regular expression matching text
  3080. which separates, but is not part of, the substrings. If nil it defaults to
  3081. `split-string-default-separators', normally \"[ \\f\\t\\n\\r\\v]+\", and
  3082. OMIT-NULLS is forced to t.
  3083. If OMIT-NULLS is t, zero-length substrings are omitted from the list \(so
  3084. that for the default value of SEPARATORS leading and trailing whitespace
  3085. are effectively trimmed). If nil, all zero-length substrings are retained,
  3086. which correctly parses CSV format, for example.
  3087. Note that the effect of `(split-string STRING)' is the same as
  3088. `(split-string STRING split-string-default-separators t)'. In the rare
  3089. case that you wish to retain zero-length substrings when splitting on
  3090. whitespace, use `(split-string STRING split-string-default-separators)'.
  3091. Modifies the match data; use `save-match-data' if necessary."
  3092. (let ((keep-nulls (not (if separators omit-nulls t)))
  3093. (rexp (or separators split-string-default-separators))
  3094. (start 0)
  3095. notfirst
  3096. (list nil))
  3097. (while (and (string-match rexp string
  3098. (if (and notfirst
  3099. (= start (match-beginning 0))
  3100. (< start (length string)))
  3101. (1+ start) start))
  3102. (< start (length string)))
  3103. (setq notfirst t)
  3104. (if (or keep-nulls (< start (match-beginning 0)))
  3105. (setq list
  3106. (cons (substring string start (match-beginning 0))
  3107. list)))
  3108. (setq start (match-end 0)))
  3109. (if (or keep-nulls (< start (length string)))
  3110. (setq list
  3111. (cons (substring string start)
  3112. list)))
  3113. (nreverse list)))
  3114. (defun combine-and-quote-strings (strings &optional separator)
  3115. "Concatenate the STRINGS, adding the SEPARATOR (default \" \").
  3116. This tries to quote the strings to avoid ambiguity such that
  3117. (split-string-and-unquote (combine-and-quote-strings strs)) == strs
  3118. Only some SEPARATORs will work properly."
  3119. (let* ((sep (or separator " "))
  3120. (re (concat "[\\\"]" "\\|" (regexp-quote sep))))
  3121. (mapconcat
  3122. (lambda (str)
  3123. (if (string-match re str)
  3124. (concat "\"" (replace-regexp-in-string "[\\\"]" "\\\\\\&" str) "\"")
  3125. str))
  3126. strings sep)))
  3127. (defun split-string-and-unquote (string &optional separator)
  3128. "Split the STRING into a list of strings.
  3129. It understands Emacs Lisp quoting within STRING, such that
  3130. (split-string-and-unquote (combine-and-quote-strings strs)) == strs
  3131. The SEPARATOR regexp defaults to \"\\s-+\"."
  3132. (let ((sep (or separator "\\s-+"))
  3133. (i (string-match "\"" string)))
  3134. (if (null i)
  3135. (split-string string sep t) ; no quoting: easy
  3136. (append (unless (eq i 0) (split-string (substring string 0 i) sep t))
  3137. (let ((rfs (read-from-string string i)))
  3138. (cons (car rfs)
  3139. (split-string-and-unquote (substring string (cdr rfs))
  3140. sep)))))))
  3141. ;;;; Replacement in strings.
  3142. (defun subst-char-in-string (fromchar tochar string &optional inplace)
  3143. "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
  3144. Unless optional argument INPLACE is non-nil, return a new string."
  3145. (let ((i (length string))
  3146. (newstr (if inplace string (copy-sequence string))))
  3147. (while (> i 0)
  3148. (setq i (1- i))
  3149. (if (eq (aref newstr i) fromchar)
  3150. (aset newstr i tochar)))
  3151. newstr))
  3152. (defun replace-regexp-in-string (regexp rep string &optional
  3153. fixedcase literal subexp start)
  3154. "Replace all matches for REGEXP with REP in STRING.
  3155. Return a new string containing the replacements.
  3156. Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
  3157. arguments with the same names of function `replace-match'. If START
  3158. is non-nil, start replacements at that index in STRING.
  3159. REP is either a string used as the NEWTEXT arg of `replace-match' or a
  3160. function. If it is a function, it is called with the actual text of each
  3161. match, and its value is used as the replacement text. When REP is called,
  3162. the match data are the result of matching REGEXP against a substring
  3163. of STRING.
  3164. To replace only the first match (if any), make REGEXP match up to \\'
  3165. and replace a sub-expression, e.g.
  3166. (replace-regexp-in-string \"\\\\(foo\\\\).*\\\\'\" \"bar\" \" foo foo\" nil nil 1)
  3167. => \" bar foo\"
  3168. "
  3169. ;; To avoid excessive consing from multiple matches in long strings,
  3170. ;; don't just call `replace-match' continually. Walk down the
  3171. ;; string looking for matches of REGEXP and building up a (reversed)
  3172. ;; list MATCHES. This comprises segments of STRING which weren't
  3173. ;; matched interspersed with replacements for segments that were.
  3174. ;; [For a `large' number of replacements it's more efficient to
  3175. ;; operate in a temporary buffer; we can't tell from the function's
  3176. ;; args whether to choose the buffer-based implementation, though it
  3177. ;; might be reasonable to do so for long enough STRING.]
  3178. (let ((l (length string))
  3179. (start (or start 0))
  3180. matches str mb me)
  3181. (save-match-data
  3182. (while (and (< start l) (string-match regexp string start))
  3183. (setq mb (match-beginning 0)
  3184. me (match-end 0))
  3185. ;; If we matched the empty string, make sure we advance by one char
  3186. (when (= me mb) (setq me (min l (1+ mb))))
  3187. ;; Generate a replacement for the matched substring.
  3188. ;; Operate only on the substring to minimize string consing.
  3189. ;; Set up match data for the substring for replacement;
  3190. ;; presumably this is likely to be faster than munging the
  3191. ;; match data directly in Lisp.
  3192. (string-match regexp (setq str (substring string mb me)))
  3193. (setq matches
  3194. (cons (replace-match (if (stringp rep)
  3195. rep
  3196. (funcall rep (match-string 0 str)))
  3197. fixedcase literal str subexp)
  3198. (cons (substring string start mb) ; unmatched prefix
  3199. matches)))
  3200. (setq start me))
  3201. ;; Reconstruct a string from the pieces.
  3202. (setq matches (cons (substring string start l) matches)) ; leftover
  3203. (apply #'concat (nreverse matches)))))
  3204. (defun string-prefix-p (str1 str2 &optional ignore-case)
  3205. "Return non-nil if STR1 is a prefix of STR2.
  3206. If IGNORE-CASE is non-nil, the comparison is done without paying attention
  3207. to case differences."
  3208. (eq t (compare-strings str1 nil nil
  3209. str2 0 (length str1) ignore-case)))
  3210. (defun bidi-string-mark-left-to-right (str)
  3211. "Return a string that can be safely inserted in left-to-right text.
  3212. Normally, inserting a string with right-to-left (RTL) script into
  3213. a buffer may cause some subsequent text to be displayed as part
  3214. of the RTL segment (usually this affects punctuation characters).
  3215. This function returns a string which displays as STR but forces
  3216. subsequent text to be displayed as left-to-right.
  3217. If STR contains any RTL character, this function returns a string
  3218. consisting of STR followed by an invisible left-to-right mark
  3219. \(LRM) character. Otherwise, it returns STR."
  3220. (unless (stringp str)
  3221. (signal 'wrong-type-argument (list 'stringp str)))
  3222. (if (string-match "\\cR" str)
  3223. (concat str (propertize (string ?\x200e) 'invisible t))
  3224. str))
  3225. ;;;; invisibility specs
  3226. (defun add-to-invisibility-spec (element)
  3227. "Add ELEMENT to `buffer-invisibility-spec'.
  3228. See documentation for `buffer-invisibility-spec' for the kind of elements
  3229. that can be added."
  3230. (if (eq buffer-invisibility-spec t)
  3231. (setq buffer-invisibility-spec (list t)))
  3232. (setq buffer-invisibility-spec
  3233. (cons element buffer-invisibility-spec)))
  3234. (defun remove-from-invisibility-spec (element)
  3235. "Remove ELEMENT from `buffer-invisibility-spec'."
  3236. (if (consp buffer-invisibility-spec)
  3237. (setq buffer-invisibility-spec
  3238. (delete element buffer-invisibility-spec))))
  3239. ;;;; Syntax tables.
  3240. (defmacro with-syntax-table (table &rest body)
  3241. "Evaluate BODY with syntax table of current buffer set to TABLE.
  3242. The syntax table of the current buffer is saved, BODY is evaluated, and the
  3243. saved table is restored, even in case of an abnormal exit.
  3244. Value is what BODY returns."
  3245. (declare (debug t) (indent 1))
  3246. (let ((old-table (make-symbol "table"))
  3247. (old-buffer (make-symbol "buffer")))
  3248. `(let ((,old-table (syntax-table))
  3249. (,old-buffer (current-buffer)))
  3250. (unwind-protect
  3251. (progn
  3252. (set-syntax-table ,table)
  3253. ,@body)
  3254. (save-current-buffer
  3255. (set-buffer ,old-buffer)
  3256. (set-syntax-table ,old-table))))))
  3257. (defun make-syntax-table (&optional oldtable)
  3258. "Return a new syntax table.
  3259. Create a syntax table which inherits from OLDTABLE (if non-nil) or
  3260. from `standard-syntax-table' otherwise."
  3261. (let ((table (make-char-table 'syntax-table nil)))
  3262. (set-char-table-parent table (or oldtable (standard-syntax-table)))
  3263. table))
  3264. (defun syntax-after (pos)
  3265. "Return the raw syntax of the char after POS.
  3266. If POS is outside the buffer's accessible portion, return nil."
  3267. (unless (or (< pos (point-min)) (>= pos (point-max)))
  3268. (let ((st (if parse-sexp-lookup-properties
  3269. (get-char-property pos 'syntax-table))))
  3270. (if (consp st) st
  3271. (aref (or st (syntax-table)) (char-after pos))))))
  3272. (defun syntax-class (syntax)
  3273. "Return the syntax class part of the syntax descriptor SYNTAX.
  3274. If SYNTAX is nil, return nil."
  3275. (and syntax (logand (car syntax) 65535)))
  3276. ;;;; Text clones
  3277. (defun text-clone-maintain (ol1 after beg end &optional _len)
  3278. "Propagate the changes made under the overlay OL1 to the other clones.
  3279. This is used on the `modification-hooks' property of text clones."
  3280. (when (and after (not undo-in-progress) (overlay-start ol1))
  3281. (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
  3282. (setq beg (max beg (+ (overlay-start ol1) margin)))
  3283. (setq end (min end (- (overlay-end ol1) margin)))
  3284. (when (<= beg end)
  3285. (save-excursion
  3286. (when (overlay-get ol1 'text-clone-syntax)
  3287. ;; Check content of the clone's text.
  3288. (let ((cbeg (+ (overlay-start ol1) margin))
  3289. (cend (- (overlay-end ol1) margin)))
  3290. (goto-char cbeg)
  3291. (save-match-data
  3292. (if (not (re-search-forward
  3293. (overlay-get ol1 'text-clone-syntax) cend t))
  3294. ;; Mark the overlay for deletion.
  3295. (overlay-put ol1 'text-clones nil)
  3296. (when (< (match-end 0) cend)
  3297. ;; Shrink the clone at its end.
  3298. (setq end (min end (match-end 0)))
  3299. (move-overlay ol1 (overlay-start ol1)
  3300. (+ (match-end 0) margin)))
  3301. (when (> (match-beginning 0) cbeg)
  3302. ;; Shrink the clone at its beginning.
  3303. (setq beg (max (match-beginning 0) beg))
  3304. (move-overlay ol1 (- (match-beginning 0) margin)
  3305. (overlay-end ol1)))))))
  3306. ;; Now go ahead and update the clones.
  3307. (let ((head (- beg (overlay-start ol1)))
  3308. (tail (- (overlay-end ol1) end))
  3309. (str (buffer-substring beg end))
  3310. (nothing-left t)
  3311. (inhibit-modification-hooks t))
  3312. (dolist (ol2 (overlay-get ol1 'text-clones))
  3313. (let ((oe (overlay-end ol2)))
  3314. (unless (or (eq ol1 ol2) (null oe))
  3315. (setq nothing-left nil)
  3316. (let ((mod-beg (+ (overlay-start ol2) head)))
  3317. ;;(overlay-put ol2 'modification-hooks nil)
  3318. (goto-char (- (overlay-end ol2) tail))
  3319. (unless (> mod-beg (point))
  3320. (save-excursion (insert str))
  3321. (delete-region mod-beg (point)))
  3322. ;;(overlay-put ol2 'modification-hooks '(text-clone-maintain))
  3323. ))))
  3324. (if nothing-left (delete-overlay ol1))))))))
  3325. (defun text-clone-create (start end &optional spreadp syntax)
  3326. "Create a text clone of START...END at point.
  3327. Text clones are chunks of text that are automatically kept identical:
  3328. changes done to one of the clones will be immediately propagated to the other.
  3329. The buffer's content at point is assumed to be already identical to
  3330. the one between START and END.
  3331. If SYNTAX is provided it's a regexp that describes the possible text of
  3332. the clones; the clone will be shrunk or killed if necessary to ensure that
  3333. its text matches the regexp.
  3334. If SPREADP is non-nil it indicates that text inserted before/after the
  3335. clone should be incorporated in the clone."
  3336. ;; To deal with SPREADP we can either use an overlay with `nil t' along
  3337. ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
  3338. ;; (with a one-char margin at each end) with `t nil'.
  3339. ;; We opted for a larger overlay because it behaves better in the case
  3340. ;; where the clone is reduced to the empty string (we want the overlay to
  3341. ;; stay when the clone's content is the empty string and we want to use
  3342. ;; `evaporate' to make sure those overlays get deleted when needed).
  3343. ;;
  3344. (let* ((pt-end (+ (point) (- end start)))
  3345. (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
  3346. 0 1))
  3347. (end-margin (if (or (not spreadp)
  3348. (>= pt-end (point-max))
  3349. (>= start (point-max)))
  3350. 0 1))
  3351. (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
  3352. (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
  3353. (dups (list ol1 ol2)))
  3354. (overlay-put ol1 'modification-hooks '(text-clone-maintain))
  3355. (when spreadp (overlay-put ol1 'text-clone-spreadp t))
  3356. (when syntax (overlay-put ol1 'text-clone-syntax syntax))
  3357. ;;(overlay-put ol1 'face 'underline)
  3358. (overlay-put ol1 'evaporate t)
  3359. (overlay-put ol1 'text-clones dups)
  3360. ;;
  3361. (overlay-put ol2 'modification-hooks '(text-clone-maintain))
  3362. (when spreadp (overlay-put ol2 'text-clone-spreadp t))
  3363. (when syntax (overlay-put ol2 'text-clone-syntax syntax))
  3364. ;;(overlay-put ol2 'face 'underline)
  3365. (overlay-put ol2 'evaporate t)
  3366. (overlay-put ol2 'text-clones dups)))
  3367. ;;;; Mail user agents.
  3368. ;; Here we include just enough for other packages to be able
  3369. ;; to define them.
  3370. (defun define-mail-user-agent (symbol composefunc sendfunc
  3371. &optional abortfunc hookvar)
  3372. "Define a symbol to identify a mail-sending package for `mail-user-agent'.
  3373. SYMBOL can be any Lisp symbol. Its function definition and/or
  3374. value as a variable do not matter for this usage; we use only certain
  3375. properties on its property list, to encode the rest of the arguments.
  3376. COMPOSEFUNC is program callable function that composes an outgoing
  3377. mail message buffer. This function should set up the basics of the
  3378. buffer without requiring user interaction. It should populate the
  3379. standard mail headers, leaving the `to:' and `subject:' headers blank
  3380. by default.
  3381. COMPOSEFUNC should accept several optional arguments--the same
  3382. arguments that `compose-mail' takes. See that function's documentation.
  3383. SENDFUNC is the command a user would run to send the message.
  3384. Optional ABORTFUNC is the command a user would run to abort the
  3385. message. For mail packages that don't have a separate abort function,
  3386. this can be `kill-buffer' (the equivalent of omitting this argument).
  3387. Optional HOOKVAR is a hook variable that gets run before the message
  3388. is actually sent. Callers that use the `mail-user-agent' may
  3389. install a hook function temporarily on this hook variable.
  3390. If HOOKVAR is nil, `mail-send-hook' is used.
  3391. The properties used on SYMBOL are `composefunc', `sendfunc',
  3392. `abortfunc', and `hookvar'."
  3393. (put symbol 'composefunc composefunc)
  3394. (put symbol 'sendfunc sendfunc)
  3395. (put symbol 'abortfunc (or abortfunc 'kill-buffer))
  3396. (put symbol 'hookvar (or hookvar 'mail-send-hook)))
  3397. ;;;; Progress reporters.
  3398. ;; Progress reporter has the following structure:
  3399. ;;
  3400. ;; (NEXT-UPDATE-VALUE . [NEXT-UPDATE-TIME
  3401. ;; MIN-VALUE
  3402. ;; MAX-VALUE
  3403. ;; MESSAGE
  3404. ;; MIN-CHANGE
  3405. ;; MIN-TIME])
  3406. ;;
  3407. ;; This weirdness is for optimization reasons: we want
  3408. ;; `progress-reporter-update' to be as fast as possible, so
  3409. ;; `(car reporter)' is better than `(aref reporter 0)'.
  3410. ;;
  3411. ;; NEXT-UPDATE-TIME is a float. While `float-time' loses a couple
  3412. ;; digits of precision, it doesn't really matter here. On the other
  3413. ;; hand, it greatly simplifies the code.
  3414. (defsubst progress-reporter-update (reporter &optional value)
  3415. "Report progress of an operation in the echo area.
  3416. REPORTER should be the result of a call to `make-progress-reporter'.
  3417. If REPORTER is a numerical progress reporter---i.e. if it was
  3418. made using non-nil MIN-VALUE and MAX-VALUE arguments to
  3419. `make-progress-reporter'---then VALUE should be a number between
  3420. MIN-VALUE and MAX-VALUE.
  3421. If REPORTER is a non-numerical reporter, VALUE should be nil.
  3422. This function is relatively inexpensive. If the change since
  3423. last update is too small or insufficient time has passed, it does
  3424. nothing."
  3425. (when (or (not (numberp value)) ; For pulsing reporter
  3426. (>= value (car reporter))) ; For numerical reporter
  3427. (progress-reporter-do-update reporter value)))
  3428. (defun make-progress-reporter (message &optional min-value max-value
  3429. current-value min-change min-time)
  3430. "Return progress reporter object for use with `progress-reporter-update'.
  3431. MESSAGE is shown in the echo area, with a status indicator
  3432. appended to the end. When you call `progress-reporter-done', the
  3433. word \"done\" is printed after the MESSAGE. You can change the
  3434. MESSAGE of an existing progress reporter by calling
  3435. `progress-reporter-force-update'.
  3436. MIN-VALUE and MAX-VALUE, if non-nil, are starting (0% complete)
  3437. and final (100% complete) states of operation; the latter should
  3438. be larger. In this case, the status message shows the percentage
  3439. progress.
  3440. If MIN-VALUE and/or MAX-VALUE is omitted or nil, the status
  3441. message shows a \"spinning\", non-numeric indicator.
  3442. Optional CURRENT-VALUE is the initial progress; the default is
  3443. MIN-VALUE.
  3444. Optional MIN-CHANGE is the minimal change in percents to report;
  3445. the default is 1%.
  3446. CURRENT-VALUE and MIN-CHANGE do not have any effect if MIN-VALUE
  3447. and/or MAX-VALUE are nil.
  3448. Optional MIN-TIME specifies the minimum interval time between
  3449. echo area updates (default is 0.2 seconds.) If the function
  3450. `float-time' is not present, time is not tracked at all. If the
  3451. OS is not capable of measuring fractions of seconds, this
  3452. parameter is effectively rounded up."
  3453. (when (string-match "[[:alnum:]]\\'" message)
  3454. (setq message (concat message "...")))
  3455. (unless min-time
  3456. (setq min-time 0.2))
  3457. (let ((reporter
  3458. ;; Force a call to `message' now
  3459. (cons (or min-value 0)
  3460. (vector (if (and (fboundp 'float-time)
  3461. (>= min-time 0.02))
  3462. (float-time) nil)
  3463. min-value
  3464. max-value
  3465. message
  3466. (if min-change (max (min min-change 50) 1) 1)
  3467. min-time))))
  3468. (progress-reporter-update reporter (or current-value min-value))
  3469. reporter))
  3470. (defun progress-reporter-force-update (reporter &optional value new-message)
  3471. "Report progress of an operation in the echo area unconditionally.
  3472. The first two arguments are the same as in `progress-reporter-update'.
  3473. NEW-MESSAGE, if non-nil, sets a new message for the reporter."
  3474. (let ((parameters (cdr reporter)))
  3475. (when new-message
  3476. (aset parameters 3 new-message))
  3477. (when (aref parameters 0)
  3478. (aset parameters 0 (float-time)))
  3479. (progress-reporter-do-update reporter value)))
  3480. (defvar progress-reporter--pulse-characters ["-" "\\" "|" "/"]
  3481. "Characters to use for pulsing progress reporters.")
  3482. (defun progress-reporter-do-update (reporter value)
  3483. (let* ((parameters (cdr reporter))
  3484. (update-time (aref parameters 0))
  3485. (min-value (aref parameters 1))
  3486. (max-value (aref parameters 2))
  3487. (text (aref parameters 3))
  3488. (current-time (float-time))
  3489. (enough-time-passed
  3490. ;; See if enough time has passed since the last update.
  3491. (or (not update-time)
  3492. (when (>= current-time update-time)
  3493. ;; Calculate time for the next update
  3494. (aset parameters 0 (+ update-time (aref parameters 5)))))))
  3495. (cond ((and min-value max-value)
  3496. ;; Numerical indicator
  3497. (let* ((one-percent (/ (- max-value min-value) 100.0))
  3498. (percentage (if (= max-value min-value)
  3499. 0
  3500. (truncate (/ (- value min-value)
  3501. one-percent)))))
  3502. ;; Calculate NEXT-UPDATE-VALUE. If we are not printing
  3503. ;; message because not enough time has passed, use 1
  3504. ;; instead of MIN-CHANGE. This makes delays between echo
  3505. ;; area updates closer to MIN-TIME.
  3506. (setcar reporter
  3507. (min (+ min-value (* (+ percentage
  3508. (if enough-time-passed
  3509. ;; MIN-CHANGE
  3510. (aref parameters 4)
  3511. 1))
  3512. one-percent))
  3513. max-value))
  3514. (when (integerp value)
  3515. (setcar reporter (ceiling (car reporter))))
  3516. ;; Only print message if enough time has passed
  3517. (when enough-time-passed
  3518. (if (> percentage 0)
  3519. (message "%s%d%%" text percentage)
  3520. (message "%s" text)))))
  3521. ;; Pulsing indicator
  3522. (enough-time-passed
  3523. (let ((index (mod (1+ (car reporter)) 4))
  3524. (message-log-max nil))
  3525. (setcar reporter index)
  3526. (message "%s %s"
  3527. text
  3528. (aref progress-reporter--pulse-characters
  3529. index)))))))
  3530. (defun progress-reporter-done (reporter)
  3531. "Print reporter's message followed by word \"done\" in echo area."
  3532. (message "%sdone" (aref (cdr reporter) 3)))
  3533. (defmacro dotimes-with-progress-reporter (spec message &rest body)
  3534. "Loop a certain number of times and report progress in the echo area.
  3535. Evaluate BODY with VAR bound to successive integers running from
  3536. 0, inclusive, to COUNT, exclusive. Then evaluate RESULT to get
  3537. the return value (nil if RESULT is omitted).
  3538. At each iteration MESSAGE followed by progress percentage is
  3539. printed in the echo area. After the loop is finished, MESSAGE
  3540. followed by word \"done\" is printed. This macro is a
  3541. convenience wrapper around `make-progress-reporter' and friends.
  3542. \(fn (VAR COUNT [RESULT]) MESSAGE BODY...)"
  3543. (declare (indent 2) (debug ((symbolp form &optional form) form body)))
  3544. (let ((temp (make-symbol "--dotimes-temp--"))
  3545. (temp2 (make-symbol "--dotimes-temp2--"))
  3546. (start 0)
  3547. (end (nth 1 spec)))
  3548. `(let ((,temp ,end)
  3549. (,(car spec) ,start)
  3550. (,temp2 (make-progress-reporter ,message ,start ,end)))
  3551. (while (< ,(car spec) ,temp)
  3552. ,@body
  3553. (progress-reporter-update ,temp2
  3554. (setq ,(car spec) (1+ ,(car spec)))))
  3555. (progress-reporter-done ,temp2)
  3556. nil ,@(cdr (cdr spec)))))
  3557. ;;;; Comparing version strings.
  3558. (defconst version-separator "."
  3559. "Specify the string used to separate the version elements.
  3560. Usually the separator is \".\", but it can be any other string.")
  3561. (defconst version-regexp-alist
  3562. '(("^[-_+ ]?alpha$" . -3)
  3563. ("^[-_+]$" . -3) ; treat "1.2.3-20050920" and "1.2-3" as alpha releases
  3564. ("^[-_+ ]cvs$" . -3) ; treat "1.2.3-CVS" as alpha release
  3565. ("^[-_+ ]?beta$" . -2)
  3566. ("^[-_+ ]?\\(pre\\|rcc\\)$" . -1))
  3567. "Specify association between non-numeric version and its priority.
  3568. This association is used to handle version string like \"1.0pre2\",
  3569. \"0.9alpha1\", etc. It's used by `version-to-list' (which see) to convert the
  3570. non-numeric part of a version string to an integer. For example:
  3571. String Version Integer List Version
  3572. \"1.0pre2\" (1 0 -1 2)
  3573. \"1.0PRE2\" (1 0 -1 2)
  3574. \"22.8beta3\" (22 8 -2 3)
  3575. \"22.8 Beta3\" (22 8 -2 3)
  3576. \"0.9alpha1\" (0 9 -3 1)
  3577. \"0.9AlphA1\" (0 9 -3 1)
  3578. \"0.9 alpha\" (0 9 -3)
  3579. Each element has the following form:
  3580. (REGEXP . PRIORITY)
  3581. Where:
  3582. REGEXP regexp used to match non-numeric part of a version string.
  3583. It should begin with the `^' anchor and end with a `$' to
  3584. prevent false hits. Letter-case is ignored while matching
  3585. REGEXP.
  3586. PRIORITY a negative integer specifying non-numeric priority of REGEXP.")
  3587. (defun version-to-list (ver)
  3588. "Convert version string VER into a list of integers.
  3589. The version syntax is given by the following EBNF:
  3590. VERSION ::= NUMBER ( SEPARATOR NUMBER )*.
  3591. NUMBER ::= (0|1|2|3|4|5|6|7|8|9)+.
  3592. SEPARATOR ::= `version-separator' (which see)
  3593. | `version-regexp-alist' (which see).
  3594. The NUMBER part is optional if SEPARATOR is a match for an element
  3595. in `version-regexp-alist'.
  3596. Examples of valid version syntax:
  3597. 1.0pre2 1.0.7.5 22.8beta3 0.9alpha1 6.9.30Beta
  3598. Examples of invalid version syntax:
  3599. 1.0prepre2 1.0..7.5 22.8X3 alpha3.2 .5
  3600. Examples of version conversion:
  3601. Version String Version as a List of Integers
  3602. \"1.0.7.5\" (1 0 7 5)
  3603. \"1.0pre2\" (1 0 -1 2)
  3604. \"1.0PRE2\" (1 0 -1 2)
  3605. \"22.8beta3\" (22 8 -2 3)
  3606. \"22.8Beta3\" (22 8 -2 3)
  3607. \"0.9alpha1\" (0 9 -3 1)
  3608. \"0.9AlphA1\" (0 9 -3 1)
  3609. \"0.9alpha\" (0 9 -3)
  3610. See documentation for `version-separator' and `version-regexp-alist'."
  3611. (or (and (stringp ver) (> (length ver) 0))
  3612. (error "Invalid version string: '%s'" ver))
  3613. ;; Change .x.y to 0.x.y
  3614. (if (and (>= (length ver) (length version-separator))
  3615. (string-equal (substring ver 0 (length version-separator))
  3616. version-separator))
  3617. (setq ver (concat "0" ver)))
  3618. (save-match-data
  3619. (let ((i 0)
  3620. (case-fold-search t) ; ignore case in matching
  3621. lst s al)
  3622. (while (and (setq s (string-match "[0-9]+" ver i))
  3623. (= s i))
  3624. ;; handle numeric part
  3625. (setq lst (cons (string-to-number (substring ver i (match-end 0)))
  3626. lst)
  3627. i (match-end 0))
  3628. ;; handle non-numeric part
  3629. (when (and (setq s (string-match "[^0-9]+" ver i))
  3630. (= s i))
  3631. (setq s (substring ver i (match-end 0))
  3632. i (match-end 0))
  3633. ;; handle alpha, beta, pre, etc. separator
  3634. (unless (string= s version-separator)
  3635. (setq al version-regexp-alist)
  3636. (while (and al (not (string-match (caar al) s)))
  3637. (setq al (cdr al)))
  3638. (cond (al
  3639. (push (cdar al) lst))
  3640. ;; Convert 22.3a to 22.3.1, 22.3b to 22.3.2, etc.
  3641. ((string-match "^[-_+ ]?\\([a-zA-Z]\\)$" s)
  3642. (push (- (aref (downcase (match-string 1 s)) 0) ?a -1)
  3643. lst))
  3644. (t (error "Invalid version syntax: '%s'" ver))))))
  3645. (if (null lst)
  3646. (error "Invalid version syntax: '%s'" ver)
  3647. (nreverse lst)))))
  3648. (defun version-list-< (l1 l2)
  3649. "Return t if L1, a list specification of a version, is lower than L2.
  3650. Note that a version specified by the list (1) is equal to (1 0),
  3651. \(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant.
  3652. Also, a version given by the list (1) is higher than (1 -1), which in
  3653. turn is higher than (1 -2), which is higher than (1 -3)."
  3654. (while (and l1 l2 (= (car l1) (car l2)))
  3655. (setq l1 (cdr l1)
  3656. l2 (cdr l2)))
  3657. (cond
  3658. ;; l1 not null and l2 not null
  3659. ((and l1 l2) (< (car l1) (car l2)))
  3660. ;; l1 null and l2 null ==> l1 length = l2 length
  3661. ((and (null l1) (null l2)) nil)
  3662. ;; l1 not null and l2 null ==> l1 length > l2 length
  3663. (l1 (< (version-list-not-zero l1) 0))
  3664. ;; l1 null and l2 not null ==> l2 length > l1 length
  3665. (t (< 0 (version-list-not-zero l2)))))
  3666. (defun version-list-= (l1 l2)
  3667. "Return t if L1, a list specification of a version, is equal to L2.
  3668. Note that a version specified by the list (1) is equal to (1 0),
  3669. \(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant.
  3670. Also, a version given by the list (1) is higher than (1 -1), which in
  3671. turn is higher than (1 -2), which is higher than (1 -3)."
  3672. (while (and l1 l2 (= (car l1) (car l2)))
  3673. (setq l1 (cdr l1)
  3674. l2 (cdr l2)))
  3675. (cond
  3676. ;; l1 not null and l2 not null
  3677. ((and l1 l2) nil)
  3678. ;; l1 null and l2 null ==> l1 length = l2 length
  3679. ((and (null l1) (null l2)))
  3680. ;; l1 not null and l2 null ==> l1 length > l2 length
  3681. (l1 (zerop (version-list-not-zero l1)))
  3682. ;; l1 null and l2 not null ==> l2 length > l1 length
  3683. (t (zerop (version-list-not-zero l2)))))
  3684. (defun version-list-<= (l1 l2)
  3685. "Return t if L1, a list specification of a version, is lower or equal to L2.
  3686. Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0),
  3687. etc. That is, the trailing zeroes are insignificant. Also, integer
  3688. list (1) is greater than (1 -1) which is greater than (1 -2)
  3689. which is greater than (1 -3)."
  3690. (while (and l1 l2 (= (car l1) (car l2)))
  3691. (setq l1 (cdr l1)
  3692. l2 (cdr l2)))
  3693. (cond
  3694. ;; l1 not null and l2 not null
  3695. ((and l1 l2) (< (car l1) (car l2)))
  3696. ;; l1 null and l2 null ==> l1 length = l2 length
  3697. ((and (null l1) (null l2)))
  3698. ;; l1 not null and l2 null ==> l1 length > l2 length
  3699. (l1 (<= (version-list-not-zero l1) 0))
  3700. ;; l1 null and l2 not null ==> l2 length > l1 length
  3701. (t (<= 0 (version-list-not-zero l2)))))
  3702. (defun version-list-not-zero (lst)
  3703. "Return the first non-zero element of LST, which is a list of integers.
  3704. If all LST elements are zeros or LST is nil, return zero."
  3705. (while (and lst (zerop (car lst)))
  3706. (setq lst (cdr lst)))
  3707. (if lst
  3708. (car lst)
  3709. ;; there is no element different of zero
  3710. 0))
  3711. (defun version< (v1 v2)
  3712. "Return t if version V1 is lower (older) than V2.
  3713. Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
  3714. etc. That is, the trailing \".0\"s are insignificant. Also, version
  3715. string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
  3716. which is higher than \"1alpha\". Also, \"-CVS\" and \"-NNN\" are treated
  3717. as alpha versions."
  3718. (version-list-< (version-to-list v1) (version-to-list v2)))
  3719. (defun version<= (v1 v2)
  3720. "Return t if version V1 is lower (older) than or equal to V2.
  3721. Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
  3722. etc. That is, the trailing \".0\"s are insignificant. Also, version
  3723. string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
  3724. which is higher than \"1alpha\". Also, \"-CVS\" and \"-NNN\" are treated
  3725. as alpha versions."
  3726. (version-list-<= (version-to-list v1) (version-to-list v2)))
  3727. (defun version= (v1 v2)
  3728. "Return t if version V1 is equal to V2.
  3729. Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
  3730. etc. That is, the trailing \".0\"s are insignificant. Also, version
  3731. string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
  3732. which is higher than \"1alpha\". Also, \"-CVS\" and \"-NNN\" are treated
  3733. as alpha versions."
  3734. (version-list-= (version-to-list v1) (version-to-list v2)))
  3735. ;;; Misc.
  3736. (defconst menu-bar-separator '("--")
  3737. "Separator for menus.")
  3738. ;; The following statement ought to be in print.c, but `provide' can't
  3739. ;; be used there.
  3740. ;; http://lists.gnu.org/archive/html/emacs-devel/2009-08/msg00236.html
  3741. (when (hash-table-p (car (read-from-string
  3742. (prin1-to-string (make-hash-table)))))
  3743. (provide 'hashtable-print-readable))
  3744. ;;; subr.el ends here