subr.el 208 KB

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