simple.el 343 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610
  1. ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
  2. ;; Copyright (C) 1985-1987, 1993-2015 Free Software Foundation, Inc.
  3. ;; Maintainer: emacs-devel@gnu.org
  4. ;; Keywords: internal
  5. ;; Package: emacs
  6. ;; This file is part of GNU Emacs.
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;; A grab-bag of basic Emacs commands not specifically related to some
  19. ;; major mode or to file-handling.
  20. ;;; Code:
  21. (eval-when-compile (require 'cl-lib))
  22. (declare-function widget-convert "wid-edit" (type &rest args))
  23. (declare-function shell-mode "shell" ())
  24. ;;; From compile.el
  25. (defvar compilation-current-error)
  26. (defvar compilation-context-lines)
  27. (defcustom idle-update-delay 0.5
  28. "Idle time delay before updating various things on the screen.
  29. Various Emacs features that update auxiliary information when point moves
  30. wait this many seconds after Emacs becomes idle before doing an update."
  31. :type 'number
  32. :group 'display
  33. :version "22.1")
  34. (defgroup killing nil
  35. "Killing and yanking commands."
  36. :group 'editing)
  37. (defgroup paren-matching nil
  38. "Highlight (un)matching of parens and expressions."
  39. :group 'matching)
  40. ;;; next-error support framework
  41. (defgroup next-error nil
  42. "`next-error' support framework."
  43. :group 'compilation
  44. :version "22.1")
  45. (defface next-error
  46. '((t (:inherit region)))
  47. "Face used to highlight next error locus."
  48. :group 'next-error
  49. :version "22.1")
  50. (defcustom next-error-highlight 0.5
  51. "Highlighting of locations in selected source buffers.
  52. If a number, highlight the locus in `next-error' face for the given time
  53. in seconds, or until the next command is executed.
  54. If t, highlight the locus until the next command is executed, or until
  55. some other locus replaces it.
  56. If nil, don't highlight the locus in the source buffer.
  57. If `fringe-arrow', indicate the locus by the fringe arrow
  58. indefinitely until some other locus replaces it."
  59. :type '(choice (number :tag "Highlight for specified time")
  60. (const :tag "Semipermanent highlighting" t)
  61. (const :tag "No highlighting" nil)
  62. (const :tag "Fringe arrow" fringe-arrow))
  63. :group 'next-error
  64. :version "22.1")
  65. (defcustom next-error-highlight-no-select 0.5
  66. "Highlighting of locations in `next-error-no-select'.
  67. If number, highlight the locus in `next-error' face for given time in seconds.
  68. If t, highlight the locus indefinitely until some other locus replaces it.
  69. If nil, don't highlight the locus in the source buffer.
  70. If `fringe-arrow', indicate the locus by the fringe arrow
  71. indefinitely until some other locus replaces it."
  72. :type '(choice (number :tag "Highlight for specified time")
  73. (const :tag "Semipermanent highlighting" t)
  74. (const :tag "No highlighting" nil)
  75. (const :tag "Fringe arrow" fringe-arrow))
  76. :group 'next-error
  77. :version "22.1")
  78. (defcustom next-error-recenter nil
  79. "Display the line in the visited source file recentered as specified.
  80. If non-nil, the value is passed directly to `recenter'."
  81. :type '(choice (integer :tag "Line to recenter to")
  82. (const :tag "Center of window" (4))
  83. (const :tag "No recentering" nil))
  84. :group 'next-error
  85. :version "23.1")
  86. (defcustom next-error-hook nil
  87. "List of hook functions run by `next-error' after visiting source file."
  88. :type 'hook
  89. :group 'next-error)
  90. (defvar next-error-highlight-timer nil)
  91. (defvar next-error-overlay-arrow-position nil)
  92. (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
  93. (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
  94. (defvar next-error-last-buffer nil
  95. "The most recent `next-error' buffer.
  96. A buffer becomes most recent when its compilation, grep, or
  97. similar mode is started, or when it is used with \\[next-error]
  98. or \\[compile-goto-error].")
  99. (defvar next-error-function nil
  100. "Function to use to find the next error in the current buffer.
  101. The function is called with 2 parameters:
  102. ARG is an integer specifying by how many errors to move.
  103. RESET is a boolean which, if non-nil, says to go back to the beginning
  104. of the errors before moving.
  105. Major modes providing compile-like functionality should set this variable
  106. to indicate to `next-error' that this is a candidate buffer and how
  107. to navigate in it.")
  108. (make-variable-buffer-local 'next-error-function)
  109. (defvar next-error-move-function nil
  110. "Function to use to move to an error locus.
  111. It takes two arguments, a buffer position in the error buffer
  112. and a buffer position in the error locus buffer.
  113. The buffer for the error locus should already be current.
  114. nil means use goto-char using the second argument position.")
  115. (make-variable-buffer-local 'next-error-move-function)
  116. (defsubst next-error-buffer-p (buffer
  117. &optional avoid-current
  118. extra-test-inclusive
  119. extra-test-exclusive)
  120. "Test if BUFFER is a `next-error' capable buffer.
  121. If AVOID-CURRENT is non-nil, treat the current buffer
  122. as an absolute last resort only.
  123. The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
  124. that normally would not qualify. If it returns t, the buffer
  125. in question is treated as usable.
  126. The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
  127. that would normally be considered usable. If it returns nil,
  128. that buffer is rejected."
  129. (and (buffer-name buffer) ;First make sure it's live.
  130. (not (and avoid-current (eq buffer (current-buffer))))
  131. (with-current-buffer buffer
  132. (if next-error-function ; This is the normal test.
  133. ;; Optionally reject some buffers.
  134. (if extra-test-exclusive
  135. (funcall extra-test-exclusive)
  136. t)
  137. ;; Optionally accept some other buffers.
  138. (and extra-test-inclusive
  139. (funcall extra-test-inclusive))))))
  140. (defun next-error-find-buffer (&optional avoid-current
  141. extra-test-inclusive
  142. extra-test-exclusive)
  143. "Return a `next-error' capable buffer.
  144. If AVOID-CURRENT is non-nil, treat the current buffer
  145. as an absolute last resort only.
  146. The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
  147. that normally would not qualify. If it returns t, the buffer
  148. in question is treated as usable.
  149. The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
  150. that would normally be considered usable. If it returns nil,
  151. that buffer is rejected."
  152. (or
  153. ;; 1. If one window on the selected frame displays such buffer, return it.
  154. (let ((window-buffers
  155. (delete-dups
  156. (delq nil (mapcar (lambda (w)
  157. (if (next-error-buffer-p
  158. (window-buffer w)
  159. avoid-current
  160. extra-test-inclusive extra-test-exclusive)
  161. (window-buffer w)))
  162. (window-list))))))
  163. (if (eq (length window-buffers) 1)
  164. (car window-buffers)))
  165. ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
  166. (if (and next-error-last-buffer
  167. (next-error-buffer-p next-error-last-buffer avoid-current
  168. extra-test-inclusive extra-test-exclusive))
  169. next-error-last-buffer)
  170. ;; 3. If the current buffer is acceptable, choose it.
  171. (if (next-error-buffer-p (current-buffer) avoid-current
  172. extra-test-inclusive extra-test-exclusive)
  173. (current-buffer))
  174. ;; 4. Look for any acceptable buffer.
  175. (let ((buffers (buffer-list)))
  176. (while (and buffers
  177. (not (next-error-buffer-p
  178. (car buffers) avoid-current
  179. extra-test-inclusive extra-test-exclusive)))
  180. (setq buffers (cdr buffers)))
  181. (car buffers))
  182. ;; 5. Use the current buffer as a last resort if it qualifies,
  183. ;; even despite AVOID-CURRENT.
  184. (and avoid-current
  185. (next-error-buffer-p (current-buffer) nil
  186. extra-test-inclusive extra-test-exclusive)
  187. (progn
  188. (message "This is the only buffer with error message locations")
  189. (current-buffer)))
  190. ;; 6. Give up.
  191. (error "No buffers contain error message locations")))
  192. (defun next-error (&optional arg reset)
  193. "Visit next `next-error' message and corresponding source code.
  194. If all the error messages parsed so far have been processed already,
  195. the message buffer is checked for new ones.
  196. A prefix ARG specifies how many error messages to move;
  197. negative means move back to previous error messages.
  198. Just \\[universal-argument] as a prefix means reparse the error message buffer
  199. and start at the first error.
  200. The RESET argument specifies that we should restart from the beginning.
  201. \\[next-error] normally uses the most recently started
  202. compilation, grep, or occur buffer. It can also operate on any
  203. buffer with output from the \\[compile], \\[grep] commands, or,
  204. more generally, on any buffer in Compilation mode or with
  205. Compilation Minor mode enabled, or any buffer in which
  206. `next-error-function' is bound to an appropriate function.
  207. To specify use of a particular buffer for error messages, type
  208. \\[next-error] in that buffer when it is the only one displayed
  209. in the current frame.
  210. Once \\[next-error] has chosen the buffer for error messages, it
  211. runs `next-error-hook' with `run-hooks', and stays with that buffer
  212. until you use it in some other buffer which uses Compilation mode
  213. or Compilation Minor mode.
  214. To control which errors are matched, customize the variable
  215. `compilation-error-regexp-alist'."
  216. (interactive "P")
  217. (if (consp arg) (setq reset t arg nil))
  218. (when (setq next-error-last-buffer (next-error-find-buffer))
  219. ;; we know here that next-error-function is a valid symbol we can funcall
  220. (with-current-buffer next-error-last-buffer
  221. (funcall next-error-function (prefix-numeric-value arg) reset)
  222. (when next-error-recenter
  223. (recenter next-error-recenter))
  224. (run-hooks 'next-error-hook))))
  225. (defun next-error-internal ()
  226. "Visit the source code corresponding to the `next-error' message at point."
  227. (setq next-error-last-buffer (current-buffer))
  228. ;; we know here that next-error-function is a valid symbol we can funcall
  229. (with-current-buffer next-error-last-buffer
  230. (funcall next-error-function 0 nil)
  231. (when next-error-recenter
  232. (recenter next-error-recenter))
  233. (run-hooks 'next-error-hook)))
  234. (defalias 'goto-next-locus 'next-error)
  235. (defalias 'next-match 'next-error)
  236. (defun previous-error (&optional n)
  237. "Visit previous `next-error' message and corresponding source code.
  238. Prefix arg N says how many error messages to move backwards (or
  239. forwards, if negative).
  240. This operates on the output from the \\[compile] and \\[grep] commands."
  241. (interactive "p")
  242. (next-error (- (or n 1))))
  243. (defun first-error (&optional n)
  244. "Restart at the first error.
  245. Visit corresponding source code.
  246. With prefix arg N, visit the source code of the Nth error.
  247. This operates on the output from the \\[compile] command, for instance."
  248. (interactive "p")
  249. (next-error n t))
  250. (defun next-error-no-select (&optional n)
  251. "Move point to the next error in the `next-error' buffer and highlight match.
  252. Prefix arg N says how many error messages to move forwards (or
  253. backwards, if negative).
  254. Finds and highlights the source line like \\[next-error], but does not
  255. select the source buffer."
  256. (interactive "p")
  257. (let ((next-error-highlight next-error-highlight-no-select))
  258. (next-error n))
  259. (pop-to-buffer next-error-last-buffer))
  260. (defun previous-error-no-select (&optional n)
  261. "Move point to the previous error in the `next-error' buffer and highlight match.
  262. Prefix arg N says how many error messages to move backwards (or
  263. forwards, if negative).
  264. Finds and highlights the source line like \\[previous-error], but does not
  265. select the source buffer."
  266. (interactive "p")
  267. (next-error-no-select (- (or n 1))))
  268. ;; Internal variable for `next-error-follow-mode-post-command-hook'.
  269. (defvar next-error-follow-last-line nil)
  270. (define-minor-mode next-error-follow-minor-mode
  271. "Minor mode for compilation, occur and diff modes.
  272. With a prefix argument ARG, enable mode if ARG is positive, and
  273. disable it otherwise. If called from Lisp, enable mode if ARG is
  274. omitted or nil.
  275. When turned on, cursor motion in the compilation, grep, occur or diff
  276. buffer causes automatic display of the corresponding source code location."
  277. :group 'next-error :init-value nil :lighter " Fol"
  278. (if (not next-error-follow-minor-mode)
  279. (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
  280. (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
  281. (make-local-variable 'next-error-follow-last-line)))
  282. ;; Used as a `post-command-hook' by `next-error-follow-mode'
  283. ;; for the *Compilation* *grep* and *Occur* buffers.
  284. (defun next-error-follow-mode-post-command-hook ()
  285. (unless (equal next-error-follow-last-line (line-number-at-pos))
  286. (setq next-error-follow-last-line (line-number-at-pos))
  287. (condition-case nil
  288. (let ((compilation-context-lines nil))
  289. (setq compilation-current-error (point))
  290. (next-error-no-select 0))
  291. (error t))))
  292. ;;;
  293. (defun fundamental-mode ()
  294. "Major mode not specialized for anything in particular.
  295. Other major modes are defined by comparison with this one."
  296. (interactive)
  297. (kill-all-local-variables)
  298. (run-mode-hooks))
  299. ;; Special major modes to view specially formatted data rather than files.
  300. (defvar special-mode-map
  301. (let ((map (make-sparse-keymap)))
  302. (suppress-keymap map)
  303. (define-key map "q" 'quit-window)
  304. (define-key map " " 'scroll-up-command)
  305. (define-key map [?\S-\ ] 'scroll-down-command)
  306. (define-key map "\C-?" 'scroll-down-command)
  307. (define-key map "?" 'describe-mode)
  308. (define-key map "h" 'describe-mode)
  309. (define-key map ">" 'end-of-buffer)
  310. (define-key map "<" 'beginning-of-buffer)
  311. (define-key map "g" 'revert-buffer)
  312. map))
  313. (put 'special-mode 'mode-class 'special)
  314. (define-derived-mode special-mode nil "Special"
  315. "Parent major mode from which special major modes should inherit."
  316. (setq buffer-read-only t))
  317. ;; Making and deleting lines.
  318. (defvar self-insert-uses-region-functions nil
  319. "Special hook to tell if `self-insert-command' will use the region.
  320. It must be called via `run-hook-with-args-until-success' with no arguments.
  321. Any `post-self-insert-command' which consumes the region should
  322. register a function on this hook so that things like `delete-selection-mode'
  323. can refrain from consuming the region.")
  324. (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
  325. "Propertized string representing a hard newline character.")
  326. (defun newline (&optional arg interactive)
  327. "Insert a newline, and move to left margin of the new line if it's blank.
  328. If option `use-hard-newlines' is non-nil, the newline is marked with the
  329. text-property `hard'.
  330. With ARG, insert that many newlines.
  331. If `electric-indent-mode' is enabled, this indents the final new line
  332. that it adds, and reindents the preceding line. To just insert
  333. a newline, use \\[electric-indent-just-newline].
  334. Calls `auto-fill-function' if the current column number is greater
  335. than the value of `fill-column' and ARG is nil.
  336. A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
  337. (interactive "*P\np")
  338. (barf-if-buffer-read-only)
  339. ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
  340. ;; Set last-command-event to tell self-insert what to insert.
  341. (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
  342. (beforepos (point))
  343. (last-command-event ?\n)
  344. ;; Don't auto-fill if we have a numeric argument.
  345. (auto-fill-function (if arg nil auto-fill-function))
  346. (postproc
  347. ;; Do the rest in post-self-insert-hook, because we want to do it
  348. ;; *before* other functions on that hook.
  349. (lambda ()
  350. (cl-assert (eq ?\n (char-before)))
  351. ;; Mark the newline(s) `hard'.
  352. (if use-hard-newlines
  353. (set-hard-newline-properties
  354. (- (point) (prefix-numeric-value arg)) (point)))
  355. ;; If the newline leaves the previous line blank, and we
  356. ;; have a left margin, delete that from the blank line.
  357. (save-excursion
  358. (goto-char beforepos)
  359. (beginning-of-line)
  360. (and (looking-at "[ \t]$")
  361. (> (current-left-margin) 0)
  362. (delete-region (point)
  363. (line-end-position))))
  364. ;; Indent the line after the newline, except in one case:
  365. ;; when we added the newline at the beginning of a line which
  366. ;; starts a page.
  367. (or was-page-start
  368. (move-to-left-margin nil t)))))
  369. (unwind-protect
  370. (if (not interactive)
  371. ;; FIXME: For non-interactive uses, many calls actually just want
  372. ;; (insert "\n"), so maybe we should do just that, so as to avoid
  373. ;; the risk of filling or running abbrevs unexpectedly.
  374. (let ((post-self-insert-hook (list postproc)))
  375. (self-insert-command (prefix-numeric-value arg)))
  376. (unwind-protect
  377. (progn
  378. (add-hook 'post-self-insert-hook postproc nil t)
  379. (self-insert-command (prefix-numeric-value arg)))
  380. ;; We first used let-binding to protect the hook, but that was naive
  381. ;; since add-hook affects the symbol-default value of the variable,
  382. ;; whereas the let-binding might only protect the buffer-local value.
  383. (remove-hook 'post-self-insert-hook postproc t)))
  384. (cl-assert (not (member postproc post-self-insert-hook)))
  385. (cl-assert (not (member postproc (default-value 'post-self-insert-hook))))))
  386. nil)
  387. (defun set-hard-newline-properties (from to)
  388. (let ((sticky (get-text-property from 'rear-nonsticky)))
  389. (put-text-property from to 'hard 't)
  390. ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
  391. (if (and (listp sticky) (not (memq 'hard sticky)))
  392. (put-text-property from (point) 'rear-nonsticky
  393. (cons 'hard sticky)))))
  394. (declare-function electric-indent-just-newline "electric")
  395. (defun open-line (n &optional interactive)
  396. "Insert a newline and leave point before it.
  397. If `electric-indent-mode' is enabled, indent the new line if it's
  398. not empty.
  399. If there is a fill prefix and/or a `left-margin', insert them on
  400. the new line. If the old line would have been blank, insert them
  401. on the old line as well.
  402. With arg N, insert N newlines.
  403. A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
  404. (interactive "*p\np")
  405. (let* ((do-fill-prefix (and fill-prefix (bolp)))
  406. (do-left-margin (and (bolp) (> (current-left-margin) 0)))
  407. (loc (point-marker))
  408. ;; Don't expand an abbrev before point.
  409. (abbrev-mode nil))
  410. (if (and interactive
  411. (looking-at-p "[[:space:]]*$"))
  412. (electric-indent-just-newline n)
  413. (newline n interactive))
  414. (goto-char loc)
  415. (while (> n 0)
  416. (cond ((bolp)
  417. (if do-left-margin (indent-to (current-left-margin)))
  418. (if do-fill-prefix (insert-and-inherit fill-prefix))))
  419. (forward-line 1)
  420. (setq n (1- n)))
  421. (goto-char loc)
  422. ;; Necessary in case a margin or prefix was inserted.
  423. (end-of-line)))
  424. (defun split-line (&optional arg)
  425. "Split current line, moving portion beyond point vertically down.
  426. If the current line starts with `fill-prefix', insert it on the new
  427. line as well. With prefix ARG, don't insert `fill-prefix' on new line.
  428. When called from Lisp code, ARG may be a prefix string to copy."
  429. (interactive "*P")
  430. (skip-chars-forward " \t")
  431. (let* ((col (current-column))
  432. (pos (point))
  433. ;; What prefix should we check for (nil means don't).
  434. (prefix (cond ((stringp arg) arg)
  435. (arg nil)
  436. (t fill-prefix)))
  437. ;; Does this line start with it?
  438. (have-prfx (and prefix
  439. (save-excursion
  440. (beginning-of-line)
  441. (looking-at (regexp-quote prefix))))))
  442. (newline 1)
  443. (if have-prfx (insert-and-inherit prefix))
  444. (indent-to col 0)
  445. (goto-char pos)))
  446. (defun delete-indentation (&optional arg)
  447. "Join this line to previous and fix up whitespace at join.
  448. If there is a fill prefix, delete it from the beginning of this line.
  449. With argument, join this line to following line."
  450. (interactive "*P")
  451. (beginning-of-line)
  452. (if arg (forward-line 1))
  453. (if (eq (preceding-char) ?\n)
  454. (progn
  455. (delete-region (point) (1- (point)))
  456. ;; If the second line started with the fill prefix,
  457. ;; delete the prefix.
  458. (if (and fill-prefix
  459. (<= (+ (point) (length fill-prefix)) (point-max))
  460. (string= fill-prefix
  461. (buffer-substring (point)
  462. (+ (point) (length fill-prefix)))))
  463. (delete-region (point) (+ (point) (length fill-prefix))))
  464. (fixup-whitespace))))
  465. (defalias 'join-line #'delete-indentation) ; easier to find
  466. (defun delete-blank-lines ()
  467. "On blank line, delete all surrounding blank lines, leaving just one.
  468. On isolated blank line, delete that one.
  469. On nonblank line, delete any immediately following blank lines."
  470. (interactive "*")
  471. (let (thisblank singleblank)
  472. (save-excursion
  473. (beginning-of-line)
  474. (setq thisblank (looking-at "[ \t]*$"))
  475. ;; Set singleblank if there is just one blank line here.
  476. (setq singleblank
  477. (and thisblank
  478. (not (looking-at "[ \t]*\n[ \t]*$"))
  479. (or (bobp)
  480. (progn (forward-line -1)
  481. (not (looking-at "[ \t]*$")))))))
  482. ;; Delete preceding blank lines, and this one too if it's the only one.
  483. (if thisblank
  484. (progn
  485. (beginning-of-line)
  486. (if singleblank (forward-line 1))
  487. (delete-region (point)
  488. (if (re-search-backward "[^ \t\n]" nil t)
  489. (progn (forward-line 1) (point))
  490. (point-min)))))
  491. ;; Delete following blank lines, unless the current line is blank
  492. ;; and there are no following blank lines.
  493. (if (not (and thisblank singleblank))
  494. (save-excursion
  495. (end-of-line)
  496. (forward-line 1)
  497. (delete-region (point)
  498. (if (re-search-forward "[^ \t\n]" nil t)
  499. (progn (beginning-of-line) (point))
  500. (point-max)))))
  501. ;; Handle the special case where point is followed by newline and eob.
  502. ;; Delete the line, leaving point at eob.
  503. (if (looking-at "^[ \t]*\n\\'")
  504. (delete-region (point) (point-max)))))
  505. (defcustom delete-trailing-lines t
  506. "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
  507. Trailing lines are deleted only if `delete-trailing-whitespace'
  508. is called on the entire buffer (rather than an active region)."
  509. :type 'boolean
  510. :group 'editing
  511. :version "24.3")
  512. (defun delete-trailing-whitespace (&optional start end)
  513. "Delete trailing whitespace between START and END.
  514. If called interactively, START and END are the start/end of the
  515. region if the mark is active, or of the buffer's accessible
  516. portion if the mark is inactive.
  517. This command deletes whitespace characters after the last
  518. non-whitespace character in each line between START and END. It
  519. does not consider formfeed characters to be whitespace.
  520. If this command acts on the entire buffer (i.e. if called
  521. interactively with the mark inactive, or called from Lisp with
  522. END nil), it also deletes all trailing lines at the end of the
  523. buffer if the variable `delete-trailing-lines' is non-nil."
  524. (interactive (progn
  525. (barf-if-buffer-read-only)
  526. (if (use-region-p)
  527. (list (region-beginning) (region-end))
  528. (list nil nil))))
  529. (save-match-data
  530. (save-excursion
  531. (let ((end-marker (copy-marker (or end (point-max))))
  532. (start (or start (point-min))))
  533. (goto-char start)
  534. (while (re-search-forward "\\s-$" end-marker t)
  535. (skip-syntax-backward "-" (line-beginning-position))
  536. ;; Don't delete formfeeds, even if they are considered whitespace.
  537. (if (looking-at-p ".*\f")
  538. (goto-char (match-end 0)))
  539. (delete-region (point) (match-end 0)))
  540. ;; Delete trailing empty lines.
  541. (goto-char end-marker)
  542. (when (and (not end)
  543. delete-trailing-lines
  544. ;; Really the end of buffer.
  545. (= (point-max) (1+ (buffer-size)))
  546. (<= (skip-chars-backward "\n") -2))
  547. (delete-region (1+ (point)) end-marker))
  548. (set-marker end-marker nil))))
  549. ;; Return nil for the benefit of `write-file-functions'.
  550. nil)
  551. (defun newline-and-indent ()
  552. "Insert a newline, then indent according to major mode.
  553. Indentation is done using the value of `indent-line-function'.
  554. In programming language modes, this is the same as TAB.
  555. In some text modes, where TAB inserts a tab, this command indents to the
  556. column specified by the function `current-left-margin'."
  557. (interactive "*")
  558. (delete-horizontal-space t)
  559. (newline nil t)
  560. (indent-according-to-mode))
  561. (defun reindent-then-newline-and-indent ()
  562. "Reindent current line, insert newline, then indent the new line.
  563. Indentation of both lines is done according to the current major mode,
  564. which means calling the current value of `indent-line-function'.
  565. In programming language modes, this is the same as TAB.
  566. In some text modes, where TAB inserts a tab, this indents to the
  567. column specified by the function `current-left-margin'."
  568. (interactive "*")
  569. (let ((pos (point)))
  570. ;; Be careful to insert the newline before indenting the line.
  571. ;; Otherwise, the indentation might be wrong.
  572. (newline)
  573. (save-excursion
  574. (goto-char pos)
  575. ;; We are at EOL before the call to indent-according-to-mode, and
  576. ;; after it we usually are as well, but not always. We tried to
  577. ;; address it with `save-excursion' but that uses a normal marker
  578. ;; whereas we need `move after insertion', so we do the save/restore
  579. ;; by hand.
  580. (setq pos (copy-marker pos t))
  581. (indent-according-to-mode)
  582. (goto-char pos)
  583. ;; Remove the trailing white-space after indentation because
  584. ;; indentation may introduce the whitespace.
  585. (delete-horizontal-space t))
  586. (indent-according-to-mode)))
  587. (defcustom read-quoted-char-radix 8
  588. "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
  589. Legitimate radix values are 8, 10 and 16."
  590. :type '(choice (const 8) (const 10) (const 16))
  591. :group 'editing-basics)
  592. (defun read-quoted-char (&optional prompt)
  593. "Like `read-char', but do not allow quitting.
  594. Also, if the first character read is an octal digit,
  595. we read any number of octal digits and return the
  596. specified character code. Any nondigit terminates the sequence.
  597. If the terminator is RET, it is discarded;
  598. any other terminator is used itself as input.
  599. The optional argument PROMPT specifies a string to use to prompt the user.
  600. The variable `read-quoted-char-radix' controls which radix to use
  601. for numeric input."
  602. (let ((message-log-max nil)
  603. (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
  604. help-event-list)))
  605. done (first t) (code 0) translated)
  606. (while (not done)
  607. (let ((inhibit-quit first)
  608. ;; Don't let C-h or other help chars get the help
  609. ;; message--only help function keys. See bug#16617.
  610. (help-char nil)
  611. (help-event-list help-events)
  612. (help-form
  613. "Type the special character you want to use,
  614. or the octal character code.
  615. RET terminates the character code and is discarded;
  616. any other non-digit terminates the character code and is then used as input."))
  617. (setq translated (read-key (and prompt (format "%s-" prompt))))
  618. (if inhibit-quit (setq quit-flag nil)))
  619. (if (integerp translated)
  620. (setq translated (char-resolve-modifiers translated)))
  621. (cond ((null translated))
  622. ((not (integerp translated))
  623. (setq unread-command-events
  624. (nconc (listify-key-sequence (this-single-command-raw-keys))
  625. unread-command-events)
  626. done t))
  627. ((/= (logand translated ?\M-\^@) 0)
  628. ;; Turn a meta-character into a character with the 0200 bit set.
  629. (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
  630. done t))
  631. ((and (<= ?0 translated)
  632. (< translated (+ ?0 (min 10 read-quoted-char-radix))))
  633. (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
  634. (and prompt (setq prompt (message "%s %c" prompt translated))))
  635. ((and (<= ?a (downcase translated))
  636. (< (downcase translated)
  637. (+ ?a -10 (min 36 read-quoted-char-radix))))
  638. (setq code (+ (* code read-quoted-char-radix)
  639. (+ 10 (- (downcase translated) ?a))))
  640. (and prompt (setq prompt (message "%s %c" prompt translated))))
  641. ((and (not first) (eq translated ?\C-m))
  642. (setq done t))
  643. ((not first)
  644. (setq unread-command-events
  645. (nconc (listify-key-sequence (this-single-command-raw-keys))
  646. unread-command-events)
  647. done t))
  648. (t (setq code translated
  649. done t)))
  650. (setq first nil))
  651. code))
  652. (defun quoted-insert (arg)
  653. "Read next input character and insert it.
  654. This is useful for inserting control characters.
  655. With argument, insert ARG copies of the character.
  656. If the first character you type after this command is an octal digit,
  657. you should type a sequence of octal digits which specify a character code.
  658. Any nondigit terminates the sequence. If the terminator is a RET,
  659. it is discarded; any other terminator is used itself as input.
  660. The variable `read-quoted-char-radix' specifies the radix for this feature;
  661. set it to 10 or 16 to use decimal or hex instead of octal.
  662. In overwrite mode, this function inserts the character anyway, and
  663. does not handle octal digits specially. This means that if you use
  664. overwrite as your normal editing mode, you can use this function to
  665. insert characters when necessary.
  666. In binary overwrite mode, this function does overwrite, and octal
  667. digits are interpreted as a character code. This is intended to be
  668. useful for editing binary files."
  669. (interactive "*p")
  670. (let* ((char
  671. ;; Avoid "obsolete" warnings for translation-table-for-input.
  672. (with-no-warnings
  673. (let (translation-table-for-input input-method-function)
  674. (if (or (not overwrite-mode)
  675. (eq overwrite-mode 'overwrite-mode-binary))
  676. (read-quoted-char)
  677. (read-char))))))
  678. ;; This used to assume character codes 0240 - 0377 stand for
  679. ;; characters in some single-byte character set, and converted them
  680. ;; to Emacs characters. But in 23.1 this feature is deprecated
  681. ;; in favor of inserting the corresponding Unicode characters.
  682. ;; (if (and enable-multibyte-characters
  683. ;; (>= char ?\240)
  684. ;; (<= char ?\377))
  685. ;; (setq char (unibyte-char-to-multibyte char)))
  686. (unless (characterp char)
  687. (user-error "%s is not a valid character"
  688. (key-description (vector char))))
  689. (if (> arg 0)
  690. (if (eq overwrite-mode 'overwrite-mode-binary)
  691. (delete-char arg)))
  692. (while (> arg 0)
  693. (insert-and-inherit char)
  694. (setq arg (1- arg)))))
  695. (defun forward-to-indentation (&optional arg)
  696. "Move forward ARG lines and position at first nonblank character."
  697. (interactive "^p")
  698. (forward-line (or arg 1))
  699. (skip-chars-forward " \t"))
  700. (defun backward-to-indentation (&optional arg)
  701. "Move backward ARG lines and position at first nonblank character."
  702. (interactive "^p")
  703. (forward-line (- (or arg 1)))
  704. (skip-chars-forward " \t"))
  705. (defun back-to-indentation ()
  706. "Move point to the first non-whitespace character on this line."
  707. (interactive "^")
  708. (beginning-of-line 1)
  709. (skip-syntax-forward " " (line-end-position))
  710. ;; Move back over chars that have whitespace syntax but have the p flag.
  711. (backward-prefix-chars))
  712. (defun fixup-whitespace ()
  713. "Fixup white space between objects around point.
  714. Leave one space or none, according to the context."
  715. (interactive "*")
  716. (save-excursion
  717. (delete-horizontal-space)
  718. (if (or (looking-at "^\\|\\s)")
  719. (save-excursion (forward-char -1)
  720. (looking-at "$\\|\\s(\\|\\s'")))
  721. nil
  722. (insert ?\s))))
  723. (defun delete-horizontal-space (&optional backward-only)
  724. "Delete all spaces and tabs around point.
  725. If BACKWARD-ONLY is non-nil, only delete them before point."
  726. (interactive "*P")
  727. (let ((orig-pos (point)))
  728. (delete-region
  729. (if backward-only
  730. orig-pos
  731. (progn
  732. (skip-chars-forward " \t")
  733. (constrain-to-field nil orig-pos t)))
  734. (progn
  735. (skip-chars-backward " \t")
  736. (constrain-to-field nil orig-pos)))))
  737. (defun just-one-space (&optional n)
  738. "Delete all spaces and tabs around point, leaving one space (or N spaces).
  739. If N is negative, delete newlines as well, leaving -N spaces.
  740. See also `cycle-spacing'."
  741. (interactive "*p")
  742. (cycle-spacing n nil 'single-shot))
  743. (defvar cycle-spacing--context nil
  744. "Store context used in consecutive calls to `cycle-spacing' command.
  745. The first time `cycle-spacing' runs, it saves in this variable:
  746. its N argument, the original point position, and the original spacing
  747. around point.")
  748. (defun cycle-spacing (&optional n preserve-nl-back mode)
  749. "Manipulate whitespace around point in a smart way.
  750. In interactive use, this function behaves differently in successive
  751. consecutive calls.
  752. The first call in a sequence acts like `just-one-space'.
  753. It deletes all spaces and tabs around point, leaving one space
  754. \(or N spaces). N is the prefix argument. If N is negative,
  755. it deletes newlines as well, leaving -N spaces.
  756. \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
  757. The second call in a sequence deletes all spaces.
  758. The third call in a sequence restores the original whitespace (and point).
  759. If MODE is `single-shot', it only performs the first step in the sequence.
  760. If MODE is `fast' and the first step would not result in any change
  761. \(i.e., there are exactly (abs N) spaces around point),
  762. the function goes straight to the second step.
  763. Repeatedly calling the function with different values of N starts a
  764. new sequence each time."
  765. (interactive "*p")
  766. (let ((orig-pos (point))
  767. (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
  768. (num (abs (or n 1))))
  769. (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
  770. (constrain-to-field nil orig-pos)
  771. (cond
  772. ;; Command run for the first time, single-shot mode or different argument
  773. ((or (eq 'single-shot mode)
  774. (not (equal last-command this-command))
  775. (not cycle-spacing--context)
  776. (not (eq (car cycle-spacing--context) n)))
  777. (let* ((start (point))
  778. (num (- num (skip-chars-forward " " (+ num (point)))))
  779. (mid (point))
  780. (end (progn
  781. (skip-chars-forward skip-characters)
  782. (constrain-to-field nil orig-pos t))))
  783. (setq cycle-spacing--context ;; Save for later.
  784. ;; Special handling for case where there was no space at all.
  785. (unless (= start end)
  786. (cons n (cons orig-pos (buffer-substring start (point))))))
  787. ;; If this run causes no change in buffer content, delete all spaces,
  788. ;; otherwise delete all excess spaces.
  789. (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
  790. start mid) end)
  791. (insert (make-string num ?\s))))
  792. ;; Command run for the second time.
  793. ((not (equal orig-pos (point)))
  794. (delete-region (point) orig-pos))
  795. ;; Command run for the third time.
  796. (t
  797. (insert (cddr cycle-spacing--context))
  798. (goto-char (cadr cycle-spacing--context))
  799. (setq cycle-spacing--context nil)))))
  800. (defun beginning-of-buffer (&optional arg)
  801. "Move point to the beginning of the buffer.
  802. With numeric arg N, put point N/10 of the way from the beginning.
  803. If the buffer is narrowed, this command uses the beginning of the
  804. accessible part of the buffer.
  805. Push mark at previous position, unless either a \\[universal-argument] prefix
  806. is supplied, or Transient Mark mode is enabled and the mark is active."
  807. (declare (interactive-only "use `(goto-char (point-min))' instead."))
  808. (interactive "^P")
  809. (or (consp arg)
  810. (region-active-p)
  811. (push-mark))
  812. (let ((size (- (point-max) (point-min))))
  813. (goto-char (if (and arg (not (consp arg)))
  814. (+ (point-min)
  815. (if (> size 10000)
  816. ;; Avoid overflow for large buffer sizes!
  817. (* (prefix-numeric-value arg)
  818. (/ size 10))
  819. (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
  820. (point-min))))
  821. (if (and arg (not (consp arg))) (forward-line 1)))
  822. (defun end-of-buffer (&optional arg)
  823. "Move point to the end of the buffer.
  824. With numeric arg N, put point N/10 of the way from the end.
  825. If the buffer is narrowed, this command uses the end of the
  826. accessible part of the buffer.
  827. Push mark at previous position, unless either a \\[universal-argument] prefix
  828. is supplied, or Transient Mark mode is enabled and the mark is active."
  829. (declare (interactive-only "use `(goto-char (point-max))' instead."))
  830. (interactive "^P")
  831. (or (consp arg) (region-active-p) (push-mark))
  832. (let ((size (- (point-max) (point-min))))
  833. (goto-char (if (and arg (not (consp arg)))
  834. (- (point-max)
  835. (if (> size 10000)
  836. ;; Avoid overflow for large buffer sizes!
  837. (* (prefix-numeric-value arg)
  838. (/ size 10))
  839. (/ (* size (prefix-numeric-value arg)) 10)))
  840. (point-max))))
  841. ;; If we went to a place in the middle of the buffer,
  842. ;; adjust it to the beginning of a line.
  843. (cond ((and arg (not (consp arg))) (forward-line 1))
  844. ((and (eq (current-buffer) (window-buffer))
  845. (> (point) (window-end nil t)))
  846. ;; If the end of the buffer is not already on the screen,
  847. ;; then scroll specially to put it near, but not at, the bottom.
  848. (overlay-recenter (point))
  849. (recenter -3))))
  850. (defcustom delete-active-region t
  851. "Whether single-char deletion commands delete an active region.
  852. This has an effect only if Transient Mark mode is enabled, and
  853. affects `delete-forward-char' and `delete-backward-char', though
  854. not `delete-char'.
  855. If the value is the symbol `kill', the active region is killed
  856. instead of deleted."
  857. :type '(choice (const :tag "Delete active region" t)
  858. (const :tag "Kill active region" kill)
  859. (const :tag "Do ordinary deletion" nil))
  860. :group 'killing
  861. :version "24.1")
  862. (defvar region-extract-function
  863. (lambda (delete)
  864. (when (region-beginning)
  865. (if (eq delete 'delete-only)
  866. (delete-region (region-beginning) (region-end))
  867. (filter-buffer-substring (region-beginning) (region-end) delete))))
  868. "Function to get the region's content.
  869. Called with one argument DELETE.
  870. If DELETE is `delete-only', then only delete the region and the return value
  871. is undefined. If DELETE is nil, just return the content as a string.
  872. If anything else, delete the region and return its content as a string.")
  873. (defun delete-backward-char (n &optional killflag)
  874. "Delete the previous N characters (following if N is negative).
  875. If Transient Mark mode is enabled, the mark is active, and N is 1,
  876. delete the text in the region and deactivate the mark instead.
  877. To disable this, set option `delete-active-region' to nil.
  878. Optional second arg KILLFLAG, if non-nil, means to kill (save in
  879. kill ring) instead of delete. Interactively, N is the prefix
  880. arg, and KILLFLAG is set if N is explicitly specified.
  881. In Overwrite mode, single character backward deletion may replace
  882. tabs with spaces so as to back over columns, unless point is at
  883. the end of the line."
  884. (declare (interactive-only delete-char))
  885. (interactive "p\nP")
  886. (unless (integerp n)
  887. (signal 'wrong-type-argument (list 'integerp n)))
  888. (cond ((and (use-region-p)
  889. delete-active-region
  890. (= n 1))
  891. ;; If a region is active, kill or delete it.
  892. (if (eq delete-active-region 'kill)
  893. (kill-region (region-beginning) (region-end) 'region)
  894. (funcall region-extract-function 'delete-only)))
  895. ;; In Overwrite mode, maybe untabify while deleting
  896. ((null (or (null overwrite-mode)
  897. (<= n 0)
  898. (memq (char-before) '(?\t ?\n))
  899. (eobp)
  900. (eq (char-after) ?\n)))
  901. (let ((ocol (current-column)))
  902. (delete-char (- n) killflag)
  903. (save-excursion
  904. (insert-char ?\s (- ocol (current-column)) nil))))
  905. ;; Otherwise, do simple deletion.
  906. (t (delete-char (- n) killflag))))
  907. (defun delete-forward-char (n &optional killflag)
  908. "Delete the following N characters (previous if N is negative).
  909. If Transient Mark mode is enabled, the mark is active, and N is 1,
  910. delete the text in the region and deactivate the mark instead.
  911. To disable this, set variable `delete-active-region' to nil.
  912. Optional second arg KILLFLAG non-nil means to kill (save in kill
  913. ring) instead of delete. Interactively, N is the prefix arg, and
  914. KILLFLAG is set if N was explicitly specified."
  915. (declare (interactive-only delete-char))
  916. (interactive "p\nP")
  917. (unless (integerp n)
  918. (signal 'wrong-type-argument (list 'integerp n)))
  919. (cond ((and (use-region-p)
  920. delete-active-region
  921. (= n 1))
  922. ;; If a region is active, kill or delete it.
  923. (if (eq delete-active-region 'kill)
  924. (kill-region (region-beginning) (region-end) 'region)
  925. (funcall region-extract-function 'delete-only)))
  926. ;; Otherwise, do simple deletion.
  927. (t (delete-char n killflag))))
  928. (defun mark-whole-buffer ()
  929. "Put point at beginning and mark at end of buffer.
  930. If narrowing is in effect, only uses the accessible part of the buffer.
  931. You probably should not use this function in Lisp programs;
  932. it is usually a mistake for a Lisp function to use any subroutine
  933. that uses or sets the mark."
  934. (declare (interactive-only t))
  935. (interactive)
  936. (push-mark (point))
  937. (push-mark (point-max) nil t)
  938. (goto-char (point-min)))
  939. ;; Counting lines, one way or another.
  940. (defun goto-line (line &optional buffer)
  941. "Go to LINE, counting from line 1 at beginning of buffer.
  942. If called interactively, a numeric prefix argument specifies
  943. LINE; without a numeric prefix argument, read LINE from the
  944. minibuffer.
  945. If optional argument BUFFER is non-nil, switch to that buffer and
  946. move to line LINE there. If called interactively with \\[universal-argument]
  947. as argument, BUFFER is the most recently selected other buffer.
  948. Prior to moving point, this function sets the mark (without
  949. activating it), unless Transient Mark mode is enabled and the
  950. mark is already active.
  951. This function is usually the wrong thing to use in a Lisp program.
  952. What you probably want instead is something like:
  953. (goto-char (point-min))
  954. (forward-line (1- N))
  955. If at all possible, an even better solution is to use char counts
  956. rather than line counts."
  957. (declare (interactive-only forward-line))
  958. (interactive
  959. (if (and current-prefix-arg (not (consp current-prefix-arg)))
  960. (list (prefix-numeric-value current-prefix-arg))
  961. ;; Look for a default, a number in the buffer at point.
  962. (let* ((default
  963. (save-excursion
  964. (skip-chars-backward "0-9")
  965. (if (looking-at "[0-9]")
  966. (string-to-number
  967. (buffer-substring-no-properties
  968. (point)
  969. (progn (skip-chars-forward "0-9")
  970. (point)))))))
  971. ;; Decide if we're switching buffers.
  972. (buffer
  973. (if (consp current-prefix-arg)
  974. (other-buffer (current-buffer) t)))
  975. (buffer-prompt
  976. (if buffer
  977. (concat " in " (buffer-name buffer))
  978. "")))
  979. ;; Read the argument, offering that number (if any) as default.
  980. (list (read-number (format "Goto line%s: " buffer-prompt)
  981. (list default (line-number-at-pos)))
  982. buffer))))
  983. ;; Switch to the desired buffer, one way or another.
  984. (if buffer
  985. (let ((window (get-buffer-window buffer)))
  986. (if window (select-window window)
  987. (switch-to-buffer-other-window buffer))))
  988. ;; Leave mark at previous position
  989. (or (region-active-p) (push-mark))
  990. ;; Move to the specified line number in that buffer.
  991. (save-restriction
  992. (widen)
  993. (goto-char (point-min))
  994. (if (eq selective-display t)
  995. (re-search-forward "[\n\C-m]" nil 'end (1- line))
  996. (forward-line (1- line)))))
  997. (defun count-words-region (start end &optional arg)
  998. "Count the number of words in the region.
  999. If called interactively, print a message reporting the number of
  1000. lines, words, and characters in the region (whether or not the
  1001. region is active); with prefix ARG, report for the entire buffer
  1002. rather than the region.
  1003. If called from Lisp, return the number of words between positions
  1004. START and END."
  1005. (interactive (if current-prefix-arg
  1006. (list nil nil current-prefix-arg)
  1007. (list (region-beginning) (region-end) nil)))
  1008. (cond ((not (called-interactively-p 'any))
  1009. (count-words start end))
  1010. (arg
  1011. (count-words--buffer-message))
  1012. (t
  1013. (count-words--message "Region" start end))))
  1014. (defun count-words (start end)
  1015. "Count words between START and END.
  1016. If called interactively, START and END are normally the start and
  1017. end of the buffer; but if the region is active, START and END are
  1018. the start and end of the region. Print a message reporting the
  1019. number of lines, words, and chars.
  1020. If called from Lisp, return the number of words between START and
  1021. END, without printing any message."
  1022. (interactive (list nil nil))
  1023. (cond ((not (called-interactively-p 'any))
  1024. (let ((words 0))
  1025. (save-excursion
  1026. (save-restriction
  1027. (narrow-to-region start end)
  1028. (goto-char (point-min))
  1029. (while (forward-word 1)
  1030. (setq words (1+ words)))))
  1031. words))
  1032. ((use-region-p)
  1033. (call-interactively 'count-words-region))
  1034. (t
  1035. (count-words--buffer-message))))
  1036. (defun count-words--buffer-message ()
  1037. (count-words--message
  1038. (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
  1039. (point-min) (point-max)))
  1040. (defun count-words--message (str start end)
  1041. (let ((lines (count-lines start end))
  1042. (words (count-words start end))
  1043. (chars (- end start)))
  1044. (message "%s has %d line%s, %d word%s, and %d character%s."
  1045. str
  1046. lines (if (= lines 1) "" "s")
  1047. words (if (= words 1) "" "s")
  1048. chars (if (= chars 1) "" "s"))))
  1049. (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
  1050. (defun what-line ()
  1051. "Print the current buffer line number and narrowed line number of point."
  1052. (interactive)
  1053. (let ((start (point-min))
  1054. (n (line-number-at-pos)))
  1055. (if (= start 1)
  1056. (message "Line %d" n)
  1057. (save-excursion
  1058. (save-restriction
  1059. (widen)
  1060. (message "line %d (narrowed line %d)"
  1061. (+ n (line-number-at-pos start) -1) n))))))
  1062. (defun count-lines (start end)
  1063. "Return number of lines between START and END.
  1064. This is usually the number of newlines between them,
  1065. but can be one more if START is not equal to END
  1066. and the greater of them is not at the start of a line."
  1067. (save-excursion
  1068. (save-restriction
  1069. (narrow-to-region start end)
  1070. (goto-char (point-min))
  1071. (if (eq selective-display t)
  1072. (save-match-data
  1073. (let ((done 0))
  1074. (while (re-search-forward "[\n\C-m]" nil t 40)
  1075. (setq done (+ 40 done)))
  1076. (while (re-search-forward "[\n\C-m]" nil t 1)
  1077. (setq done (+ 1 done)))
  1078. (goto-char (point-max))
  1079. (if (and (/= start end)
  1080. (not (bolp)))
  1081. (1+ done)
  1082. done)))
  1083. (- (buffer-size) (forward-line (buffer-size)))))))
  1084. (defun line-number-at-pos (&optional pos)
  1085. "Return (narrowed) buffer line number at position POS.
  1086. If POS is nil, use current buffer location.
  1087. Counting starts at (point-min), so the value refers
  1088. to the contents of the accessible portion of the buffer."
  1089. (let ((opoint (or pos (point))) start)
  1090. (save-excursion
  1091. (goto-char (point-min))
  1092. (setq start (point))
  1093. (goto-char opoint)
  1094. (forward-line 0)
  1095. (1+ (count-lines start (point))))))
  1096. (defun what-cursor-position (&optional detail)
  1097. "Print info on cursor position (on screen and within buffer).
  1098. Also describe the character after point, and give its character code
  1099. in octal, decimal and hex.
  1100. For a non-ASCII multibyte character, also give its encoding in the
  1101. buffer's selected coding system if the coding system encodes the
  1102. character safely. If the character is encoded into one byte, that
  1103. code is shown in hex. If the character is encoded into more than one
  1104. byte, just \"...\" is shown.
  1105. In addition, with prefix argument, show details about that character
  1106. in *Help* buffer. See also the command `describe-char'."
  1107. (interactive "P")
  1108. (let* ((char (following-char))
  1109. (bidi-fixer
  1110. ;; If the character is one of LRE, LRO, RLE, RLO, it will
  1111. ;; start a directional embedding, which could completely
  1112. ;; disrupt the rest of the line (e.g., RLO will display the
  1113. ;; rest of the line right-to-left). So we put an invisible
  1114. ;; PDF character after these characters, to end the
  1115. ;; embedding, which eliminates any effects on the rest of
  1116. ;; the line. For RLE and RLO we also append an invisible
  1117. ;; LRM, to avoid reordering the following numerical
  1118. ;; characters. For LRI/RLI/FSI we append a PDI.
  1119. (cond ((memq char '(?\x202a ?\x202d))
  1120. (propertize (string ?\x202c) 'invisible t))
  1121. ((memq char '(?\x202b ?\x202e))
  1122. (propertize (string ?\x202c ?\x200e) 'invisible t))
  1123. ((memq char '(?\x2066 ?\x2067 ?\x2068))
  1124. (propertize (string ?\x2069) 'invisible t))
  1125. ;; Strong right-to-left characters cause reordering of
  1126. ;; the following numerical characters which show the
  1127. ;; codepoint, so append LRM to countermand that.
  1128. ((memq (get-char-code-property char 'bidi-class) '(R AL))
  1129. (propertize (string ?\x200e) 'invisible t))
  1130. (t
  1131. "")))
  1132. (beg (point-min))
  1133. (end (point-max))
  1134. (pos (point))
  1135. (total (buffer-size))
  1136. (percent (round (* 100.0 (1- pos)) (max 1 total)))
  1137. (hscroll (if (= (window-hscroll) 0)
  1138. ""
  1139. (format " Hscroll=%d" (window-hscroll))))
  1140. (col (current-column)))
  1141. (if (= pos end)
  1142. (if (or (/= beg 1) (/= end (1+ total)))
  1143. (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
  1144. pos total percent beg end col hscroll)
  1145. (message "point=%d of %d (EOB) column=%d%s"
  1146. pos total col hscroll))
  1147. (let ((coding buffer-file-coding-system)
  1148. encoded encoding-msg display-prop under-display)
  1149. (if (or (not coding)
  1150. (eq (coding-system-type coding) t))
  1151. (setq coding (default-value 'buffer-file-coding-system)))
  1152. (if (eq (char-charset char) 'eight-bit)
  1153. (setq encoding-msg
  1154. (format "(%d, #o%o, #x%x, raw-byte)" char char char))
  1155. ;; Check if the character is displayed with some `display'
  1156. ;; text property. In that case, set under-display to the
  1157. ;; buffer substring covered by that property.
  1158. (setq display-prop (get-char-property pos 'display))
  1159. (if display-prop
  1160. (let ((to (or (next-single-char-property-change pos 'display)
  1161. (point-max))))
  1162. (if (< to (+ pos 4))
  1163. (setq under-display "")
  1164. (setq under-display "..."
  1165. to (+ pos 4)))
  1166. (setq under-display
  1167. (concat (buffer-substring-no-properties pos to)
  1168. under-display)))
  1169. (setq encoded (and (>= char 128) (encode-coding-char char coding))))
  1170. (setq encoding-msg
  1171. (if display-prop
  1172. (if (not (stringp display-prop))
  1173. (format "(%d, #o%o, #x%x, part of display \"%s\")"
  1174. char char char under-display)
  1175. (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
  1176. char char char under-display display-prop))
  1177. (if encoded
  1178. (format "(%d, #o%o, #x%x, file %s)"
  1179. char char char
  1180. (if (> (length encoded) 1)
  1181. "..."
  1182. (encoded-string-description encoded coding)))
  1183. (format "(%d, #o%o, #x%x)" char char char)))))
  1184. (if detail
  1185. ;; We show the detailed information about CHAR.
  1186. (describe-char (point)))
  1187. (if (or (/= beg 1) (/= end (1+ total)))
  1188. (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
  1189. (if (< char 256)
  1190. (single-key-description char)
  1191. (buffer-substring-no-properties (point) (1+ (point))))
  1192. bidi-fixer
  1193. encoding-msg pos total percent beg end col hscroll)
  1194. (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
  1195. (if enable-multibyte-characters
  1196. (if (< char 128)
  1197. (single-key-description char)
  1198. (buffer-substring-no-properties (point) (1+ (point))))
  1199. (single-key-description char))
  1200. bidi-fixer encoding-msg pos total percent col hscroll))))))
  1201. ;; Initialize read-expression-map. It is defined at C level.
  1202. (defvar read-expression-map
  1203. (let ((m (make-sparse-keymap)))
  1204. (define-key m "\M-\t" 'completion-at-point)
  1205. ;; Might as well bind TAB to completion, since inserting a TAB char is
  1206. ;; much too rarely useful.
  1207. (define-key m "\t" 'completion-at-point)
  1208. (set-keymap-parent m minibuffer-local-map)
  1209. m))
  1210. (defun read-minibuffer (prompt &optional initial-contents)
  1211. "Return a Lisp object read using the minibuffer, unevaluated.
  1212. Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
  1213. is a string to insert in the minibuffer before reading.
  1214. \(INITIAL-CONTENTS can also be a cons of a string and an integer.
  1215. Such arguments are used as in `read-from-minibuffer'.)"
  1216. ;; Used for interactive spec `x'.
  1217. (read-from-minibuffer prompt initial-contents minibuffer-local-map
  1218. t 'minibuffer-history))
  1219. (defun eval-minibuffer (prompt &optional initial-contents)
  1220. "Return value of Lisp expression read using the minibuffer.
  1221. Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
  1222. is a string to insert in the minibuffer before reading.
  1223. \(INITIAL-CONTENTS can also be a cons of a string and an integer.
  1224. Such arguments are used as in `read-from-minibuffer'.)"
  1225. ;; Used for interactive spec `X'.
  1226. (eval (read--expression prompt initial-contents)))
  1227. (defvar minibuffer-completing-symbol nil
  1228. "Non-nil means completing a Lisp symbol in the minibuffer.")
  1229. (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
  1230. (defvar minibuffer-default nil
  1231. "The current default value or list of default values in the minibuffer.
  1232. The functions `read-from-minibuffer' and `completing-read' bind
  1233. this variable locally.")
  1234. (defcustom eval-expression-print-level 4
  1235. "Value for `print-level' while printing value in `eval-expression'.
  1236. A value of nil means no limit."
  1237. :group 'lisp
  1238. :type '(choice (const :tag "No Limit" nil) integer)
  1239. :version "21.1")
  1240. (defcustom eval-expression-print-length 12
  1241. "Value for `print-length' while printing value in `eval-expression'.
  1242. A value of nil means no limit."
  1243. :group 'lisp
  1244. :type '(choice (const :tag "No Limit" nil) integer)
  1245. :version "21.1")
  1246. (defcustom eval-expression-debug-on-error t
  1247. "If non-nil set `debug-on-error' to t in `eval-expression'.
  1248. If nil, don't change the value of `debug-on-error'."
  1249. :group 'lisp
  1250. :type 'boolean
  1251. :version "21.1")
  1252. (defun eval-expression-print-format (value)
  1253. "Format VALUE as a result of evaluated expression.
  1254. Return a formatted string which is displayed in the echo area
  1255. in addition to the value printed by prin1 in functions which
  1256. display the result of expression evaluation."
  1257. (if (and (integerp value)
  1258. (or (eq standard-output t)
  1259. (zerop (prefix-numeric-value current-prefix-arg))))
  1260. (let ((char-string
  1261. (if (and (characterp value)
  1262. (char-displayable-p value))
  1263. (prin1-char value))))
  1264. (if char-string
  1265. (format " (#o%o, #x%x, %s)" value value char-string)
  1266. (format " (#o%o, #x%x)" value value)))))
  1267. (defvar eval-expression-minibuffer-setup-hook nil
  1268. "Hook run by `eval-expression' when entering the minibuffer.")
  1269. (defun read--expression (prompt &optional initial-contents)
  1270. (let ((minibuffer-completing-symbol t))
  1271. (minibuffer-with-setup-hook
  1272. (lambda ()
  1273. ;; FIXME: call emacs-lisp-mode?
  1274. (add-function :before-until (local 'eldoc-documentation-function)
  1275. #'elisp-eldoc-documentation-function)
  1276. (add-hook 'completion-at-point-functions
  1277. #'elisp-completion-at-point nil t)
  1278. (run-hooks 'eval-expression-minibuffer-setup-hook))
  1279. (read-from-minibuffer prompt initial-contents
  1280. read-expression-map t
  1281. 'read-expression-history))))
  1282. ;; We define this, rather than making `eval' interactive,
  1283. ;; for the sake of completion of names like eval-region, eval-buffer.
  1284. (defun eval-expression (exp &optional insert-value)
  1285. "Evaluate EXP and print value in the echo area.
  1286. When called interactively, read an Emacs Lisp expression and evaluate it.
  1287. Value is also consed on to front of the variable `values'.
  1288. Optional argument INSERT-VALUE non-nil (interactively, with prefix
  1289. argument) means insert the result into the current buffer instead of
  1290. printing it in the echo area.
  1291. Normally, this function truncates long output according to the value
  1292. of the variables `eval-expression-print-length' and
  1293. `eval-expression-print-level'. With a prefix argument of zero,
  1294. however, there is no such truncation. Such a prefix argument
  1295. also causes integers to be printed in several additional formats
  1296. \(octal, hexadecimal, and character).
  1297. Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
  1298. minibuffer.
  1299. If `eval-expression-debug-on-error' is non-nil, which is the default,
  1300. this command arranges for all errors to enter the debugger."
  1301. (interactive
  1302. (list (read--expression "Eval: ")
  1303. current-prefix-arg))
  1304. (if (null eval-expression-debug-on-error)
  1305. (push (eval exp lexical-binding) values)
  1306. (let ((old-value (make-symbol "t")) new-value)
  1307. ;; Bind debug-on-error to something unique so that we can
  1308. ;; detect when evalled code changes it.
  1309. (let ((debug-on-error old-value))
  1310. (push (eval (macroexpand-all exp) lexical-binding) values)
  1311. (setq new-value debug-on-error))
  1312. ;; If evalled code has changed the value of debug-on-error,
  1313. ;; propagate that change to the global binding.
  1314. (unless (eq old-value new-value)
  1315. (setq debug-on-error new-value))))
  1316. (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
  1317. eval-expression-print-length))
  1318. (print-level (and (not (zerop (prefix-numeric-value insert-value)))
  1319. eval-expression-print-level))
  1320. (deactivate-mark))
  1321. (if insert-value
  1322. (with-no-warnings
  1323. (let ((standard-output (current-buffer)))
  1324. (prog1
  1325. (prin1 (car values))
  1326. (when (zerop (prefix-numeric-value insert-value))
  1327. (let ((str (eval-expression-print-format (car values))))
  1328. (if str (princ str)))))))
  1329. (prog1
  1330. (prin1 (car values) t)
  1331. (let ((str (eval-expression-print-format (car values))))
  1332. (if str (princ str t)))))))
  1333. (defun edit-and-eval-command (prompt command)
  1334. "Prompting with PROMPT, let user edit COMMAND and eval result.
  1335. COMMAND is a Lisp expression. Let user edit that expression in
  1336. the minibuffer, then read and evaluate the result."
  1337. (let ((command
  1338. (let ((print-level nil)
  1339. (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
  1340. (unwind-protect
  1341. (read-from-minibuffer prompt
  1342. (prin1-to-string command)
  1343. read-expression-map t
  1344. 'command-history)
  1345. ;; If command was added to command-history as a string,
  1346. ;; get rid of that. We want only evaluable expressions there.
  1347. (if (stringp (car command-history))
  1348. (setq command-history (cdr command-history)))))))
  1349. ;; If command to be redone does not match front of history,
  1350. ;; add it to the history.
  1351. (or (equal command (car command-history))
  1352. (setq command-history (cons command command-history)))
  1353. (eval command)))
  1354. (defun repeat-complex-command (arg)
  1355. "Edit and re-evaluate last complex command, or ARGth from last.
  1356. A complex command is one which used the minibuffer.
  1357. The command is placed in the minibuffer as a Lisp form for editing.
  1358. The result is executed, repeating the command as changed.
  1359. If the command has been changed or is not the most recent previous
  1360. command it is added to the front of the command history.
  1361. You can use the minibuffer history commands \
  1362. \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
  1363. to get different commands to edit and resubmit."
  1364. (interactive "p")
  1365. (let ((elt (nth (1- arg) command-history))
  1366. newcmd)
  1367. (if elt
  1368. (progn
  1369. (setq newcmd
  1370. (let ((print-level nil)
  1371. (minibuffer-history-position arg)
  1372. (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
  1373. (unwind-protect
  1374. (read-from-minibuffer
  1375. "Redo: " (prin1-to-string elt) read-expression-map t
  1376. (cons 'command-history arg))
  1377. ;; If command was added to command-history as a
  1378. ;; string, get rid of that. We want only
  1379. ;; evaluable expressions there.
  1380. (if (stringp (car command-history))
  1381. (setq command-history (cdr command-history))))))
  1382. ;; If command to be redone does not match front of history,
  1383. ;; add it to the history.
  1384. (or (equal newcmd (car command-history))
  1385. (setq command-history (cons newcmd command-history)))
  1386. (apply #'funcall-interactively
  1387. (car newcmd)
  1388. (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
  1389. (if command-history
  1390. (error "Argument %d is beyond length of command history" arg)
  1391. (error "There are no previous complex commands to repeat")))))
  1392. (defvar extended-command-history nil)
  1393. (defvar execute-extended-command--last-typed nil)
  1394. (defun read-extended-command ()
  1395. "Read command name to invoke in `execute-extended-command'."
  1396. (minibuffer-with-setup-hook
  1397. (lambda ()
  1398. (add-hook 'post-self-insert-hook
  1399. (lambda ()
  1400. (setq execute-extended-command--last-typed
  1401. (minibuffer-contents)))
  1402. nil 'local)
  1403. (set (make-local-variable 'minibuffer-default-add-function)
  1404. (lambda ()
  1405. ;; Get a command name at point in the original buffer
  1406. ;; to propose it after M-n.
  1407. (with-current-buffer (window-buffer (minibuffer-selected-window))
  1408. (and (commandp (function-called-at-point))
  1409. (format "%S" (function-called-at-point)))))))
  1410. ;; Read a string, completing from and restricting to the set of
  1411. ;; all defined commands. Don't provide any initial input.
  1412. ;; Save the command read on the extended-command history list.
  1413. (completing-read
  1414. (concat (cond
  1415. ((eq current-prefix-arg '-) "- ")
  1416. ((and (consp current-prefix-arg)
  1417. (eq (car current-prefix-arg) 4)) "C-u ")
  1418. ((and (consp current-prefix-arg)
  1419. (integerp (car current-prefix-arg)))
  1420. (format "%d " (car current-prefix-arg)))
  1421. ((integerp current-prefix-arg)
  1422. (format "%d " current-prefix-arg)))
  1423. ;; This isn't strictly correct if `execute-extended-command'
  1424. ;; is bound to anything else (e.g. [menu]).
  1425. ;; It could use (key-description (this-single-command-keys)),
  1426. ;; but actually a prompt other than "M-x" would be confusing,
  1427. ;; because "M-x" is a well-known prompt to read a command
  1428. ;; and it serves as a shorthand for "Extended command: ".
  1429. "M-x ")
  1430. (lambda (string pred action)
  1431. (let ((pred
  1432. (if (memq action '(nil t))
  1433. ;; Exclude obsolete commands from completions.
  1434. (lambda (sym)
  1435. (and (funcall pred sym)
  1436. (or (equal string (symbol-name sym))
  1437. (not (get sym 'byte-obsolete-info)))))
  1438. pred)))
  1439. (complete-with-action action obarray string pred)))
  1440. #'commandp t nil 'extended-command-history)))
  1441. (defcustom suggest-key-bindings t
  1442. "Non-nil means show the equivalent key-binding when M-x command has one.
  1443. The value can be a length of time to show the message for.
  1444. If the value is non-nil and not a number, we wait 2 seconds."
  1445. :group 'keyboard
  1446. :type '(choice (const :tag "off" nil)
  1447. (integer :tag "time" 2)
  1448. (other :tag "on")))
  1449. (defun execute-extended-command--shorter-1 (name length)
  1450. (cond
  1451. ((zerop length) (list ""))
  1452. ((equal name "") nil)
  1453. (t
  1454. (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
  1455. (execute-extended-command--shorter-1
  1456. (substring name 1) (1- length)))
  1457. (when (string-match "\\`\\(-\\)?[^-]*" name)
  1458. (execute-extended-command--shorter-1
  1459. (substring name (match-end 0)) length))))))
  1460. (defun execute-extended-command--shorter (name typed)
  1461. (let ((candidates '())
  1462. (max (length typed))
  1463. (len 1)
  1464. binding)
  1465. (while (and (not binding)
  1466. (progn
  1467. (unless candidates
  1468. (setq len (1+ len))
  1469. (setq candidates (execute-extended-command--shorter-1
  1470. name len)))
  1471. ;; Don't show the help message if the binding isn't
  1472. ;; significantly shorter than the M-x command the user typed.
  1473. (< len (- max 5))))
  1474. (let ((candidate (pop candidates)))
  1475. (when (equal name
  1476. (car-safe (completion-try-completion
  1477. candidate obarray 'commandp len)))
  1478. (setq binding candidate))))
  1479. binding))
  1480. (defun execute-extended-command (prefixarg &optional command-name typed)
  1481. ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
  1482. ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
  1483. "Read a command name, then read the arguments and call the command.
  1484. To pass a prefix argument to the command you are
  1485. invoking, give a prefix argument to `execute-extended-command'."
  1486. (declare (interactive-only command-execute))
  1487. ;; FIXME: Remember the actual text typed by the user before completion,
  1488. ;; so that we don't later on suggest the same shortening.
  1489. (interactive
  1490. (let ((execute-extended-command--last-typed nil))
  1491. (list current-prefix-arg
  1492. (read-extended-command)
  1493. execute-extended-command--last-typed)))
  1494. ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
  1495. (unless command-name
  1496. (let ((current-prefix-arg prefixarg) ; for prompt
  1497. (execute-extended-command--last-typed nil))
  1498. (setq command-name (read-extended-command))
  1499. (setq typed execute-extended-command--last-typed)))
  1500. (let* ((function (and (stringp command-name) (intern-soft command-name)))
  1501. (binding (and suggest-key-bindings
  1502. (not executing-kbd-macro)
  1503. (where-is-internal function overriding-local-map t))))
  1504. (unless (commandp function)
  1505. (error "`%s' is not a valid command name" command-name))
  1506. (setq this-command function)
  1507. ;; Normally `real-this-command' should never be changed, but here we really
  1508. ;; want to pretend that M-x <cmd> RET is nothing more than a "key
  1509. ;; binding" for <cmd>, so the command the user really wanted to run is
  1510. ;; `function' and not `execute-extended-command'. The difference is
  1511. ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
  1512. (setq real-this-command function)
  1513. (let ((prefix-arg prefixarg))
  1514. (command-execute function 'record))
  1515. ;; If enabled, show which key runs this command.
  1516. ;; But first wait, and skip the message if there is input.
  1517. (let* ((waited
  1518. ;; If this command displayed something in the echo area;
  1519. ;; wait a few seconds, then display our suggestion message.
  1520. ;; FIXME: Wait *after* running post-command-hook!
  1521. ;; FIXME: Don't wait if execute-extended-command--shorter won't
  1522. ;; find a better answer anyway!
  1523. (when suggest-key-bindings
  1524. (sit-for (cond
  1525. ((zerop (length (current-message))) 0)
  1526. ((numberp suggest-key-bindings) suggest-key-bindings)
  1527. (t 2))))))
  1528. (when (and waited (not (consp unread-command-events)))
  1529. (unless (or binding executing-kbd-macro (not (symbolp function))
  1530. (<= (length (symbol-name function)) 2))
  1531. ;; There's no binding for CMD. Let's try and find the shortest
  1532. ;; string to use in M-x.
  1533. ;; FIXME: Can be slow. Cache it maybe?
  1534. (while-no-input
  1535. (setq binding (execute-extended-command--shorter
  1536. (symbol-name function) typed))))
  1537. (when binding
  1538. (with-temp-message
  1539. (format-message "You can run the command `%s' with %s"
  1540. function
  1541. (if (stringp binding)
  1542. (concat "M-x " binding " RET")
  1543. (key-description binding)))
  1544. (sit-for (if (numberp suggest-key-bindings)
  1545. suggest-key-bindings
  1546. 2))))))))
  1547. (defun command-execute (cmd &optional record-flag keys special)
  1548. ;; BEWARE: Called directly from the C code.
  1549. "Execute CMD as an editor command.
  1550. CMD must be a symbol that satisfies the `commandp' predicate.
  1551. Optional second arg RECORD-FLAG non-nil
  1552. means unconditionally put this command in the variable `command-history'.
  1553. Otherwise, that is done only if an arg is read using the minibuffer.
  1554. The argument KEYS specifies the value to use instead of (this-command-keys)
  1555. when reading the arguments; if it is nil, (this-command-keys) is used.
  1556. The argument SPECIAL, if non-nil, means that this command is executing
  1557. a special event, so ignore the prefix argument and don't clear it."
  1558. (setq debug-on-next-call nil)
  1559. (let ((prefixarg (unless special
  1560. ;; FIXME: This should probably be done around
  1561. ;; pre-command-hook rather than here!
  1562. (prog1 prefix-arg
  1563. (setq current-prefix-arg prefix-arg)
  1564. (setq prefix-arg nil)
  1565. (when current-prefix-arg
  1566. (prefix-command-update))))))
  1567. (if (and (symbolp cmd)
  1568. (get cmd 'disabled)
  1569. disabled-command-function)
  1570. ;; FIXME: Weird calling convention!
  1571. (run-hooks 'disabled-command-function)
  1572. (let ((final cmd))
  1573. (while
  1574. (progn
  1575. (setq final (indirect-function final))
  1576. (if (autoloadp final)
  1577. (setq final (autoload-do-load final cmd)))))
  1578. (cond
  1579. ((arrayp final)
  1580. ;; If requested, place the macro in the command history. For
  1581. ;; other sorts of commands, call-interactively takes care of this.
  1582. (when record-flag
  1583. (push `(execute-kbd-macro ,final ,prefixarg) command-history)
  1584. ;; Don't keep command history around forever.
  1585. (when (and (numberp history-length) (> history-length 0))
  1586. (let ((cell (nthcdr history-length command-history)))
  1587. (if (consp cell) (setcdr cell nil)))))
  1588. (execute-kbd-macro final prefixarg))
  1589. (t
  1590. ;; Pass `cmd' rather than `final', for the backtrace's sake.
  1591. (prog1 (call-interactively cmd record-flag keys)
  1592. (when (and (symbolp cmd)
  1593. (get cmd 'byte-obsolete-info)
  1594. (not (get cmd 'command-execute-obsolete-warned)))
  1595. (put cmd 'command-execute-obsolete-warned t)
  1596. (message "%s" (macroexp--obsolete-warning
  1597. cmd (get cmd 'byte-obsolete-info) "command"))))))))))
  1598. (defvar minibuffer-history nil
  1599. "Default minibuffer history list.
  1600. This is used for all minibuffer input
  1601. except when an alternate history list is specified.
  1602. Maximum length of the history list is determined by the value
  1603. of `history-length', which see.")
  1604. (defvar minibuffer-history-sexp-flag nil
  1605. "Control whether history list elements are expressions or strings.
  1606. If the value of this variable equals current minibuffer depth,
  1607. they are expressions; otherwise they are strings.
  1608. \(That convention is designed to do the right thing for
  1609. recursive uses of the minibuffer.)")
  1610. (setq minibuffer-history-variable 'minibuffer-history)
  1611. (setq minibuffer-history-position nil) ;; Defvar is in C code.
  1612. (defvar minibuffer-history-search-history nil)
  1613. (defvar minibuffer-text-before-history nil
  1614. "Text that was in this minibuffer before any history commands.
  1615. This is nil if there have not yet been any history commands
  1616. in this use of the minibuffer.")
  1617. (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
  1618. (defun minibuffer-history-initialize ()
  1619. (setq minibuffer-text-before-history nil))
  1620. (defun minibuffer-avoid-prompt (_new _old)
  1621. "A point-motion hook for the minibuffer, that moves point out of the prompt."
  1622. (declare (obsolete cursor-intangible-mode "25.1"))
  1623. (constrain-to-field nil (point-max)))
  1624. (defcustom minibuffer-history-case-insensitive-variables nil
  1625. "Minibuffer history variables for which matching should ignore case.
  1626. If a history variable is a member of this list, then the
  1627. \\[previous-matching-history-element] and \\[next-matching-history-element]\
  1628. commands ignore case when searching it, regardless of `case-fold-search'."
  1629. :type '(repeat variable)
  1630. :group 'minibuffer)
  1631. (defun previous-matching-history-element (regexp n)
  1632. "Find the previous history element that matches REGEXP.
  1633. \(Previous history elements refer to earlier actions.)
  1634. With prefix argument N, search for Nth previous match.
  1635. If N is negative, find the next or Nth next match.
  1636. Normally, history elements are matched case-insensitively if
  1637. `case-fold-search' is non-nil, but an uppercase letter in REGEXP
  1638. makes the search case-sensitive.
  1639. See also `minibuffer-history-case-insensitive-variables'."
  1640. (interactive
  1641. (let* ((enable-recursive-minibuffers t)
  1642. (regexp (read-from-minibuffer "Previous element matching (regexp): "
  1643. nil
  1644. minibuffer-local-map
  1645. nil
  1646. 'minibuffer-history-search-history
  1647. (car minibuffer-history-search-history))))
  1648. ;; Use the last regexp specified, by default, if input is empty.
  1649. (list (if (string= regexp "")
  1650. (if minibuffer-history-search-history
  1651. (car minibuffer-history-search-history)
  1652. (user-error "No previous history search regexp"))
  1653. regexp)
  1654. (prefix-numeric-value current-prefix-arg))))
  1655. (unless (zerop n)
  1656. (if (and (zerop minibuffer-history-position)
  1657. (null minibuffer-text-before-history))
  1658. (setq minibuffer-text-before-history
  1659. (minibuffer-contents-no-properties)))
  1660. (let ((history (symbol-value minibuffer-history-variable))
  1661. (case-fold-search
  1662. (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
  1663. ;; On some systems, ignore case for file names.
  1664. (if (memq minibuffer-history-variable
  1665. minibuffer-history-case-insensitive-variables)
  1666. t
  1667. ;; Respect the user's setting for case-fold-search:
  1668. case-fold-search)
  1669. nil))
  1670. prevpos
  1671. match-string
  1672. match-offset
  1673. (pos minibuffer-history-position))
  1674. (while (/= n 0)
  1675. (setq prevpos pos)
  1676. (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
  1677. (when (= pos prevpos)
  1678. (user-error (if (= pos 1)
  1679. "No later matching history item"
  1680. "No earlier matching history item")))
  1681. (setq match-string
  1682. (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
  1683. (let ((print-level nil))
  1684. (prin1-to-string (nth (1- pos) history)))
  1685. (nth (1- pos) history)))
  1686. (setq match-offset
  1687. (if (< n 0)
  1688. (and (string-match regexp match-string)
  1689. (match-end 0))
  1690. (and (string-match (concat ".*\\(" regexp "\\)") match-string)
  1691. (match-beginning 1))))
  1692. (when match-offset
  1693. (setq n (+ n (if (< n 0) 1 -1)))))
  1694. (setq minibuffer-history-position pos)
  1695. (goto-char (point-max))
  1696. (delete-minibuffer-contents)
  1697. (insert match-string)
  1698. (goto-char (+ (minibuffer-prompt-end) match-offset))))
  1699. (if (memq (car (car command-history)) '(previous-matching-history-element
  1700. next-matching-history-element))
  1701. (setq command-history (cdr command-history))))
  1702. (defun next-matching-history-element (regexp n)
  1703. "Find the next history element that matches REGEXP.
  1704. \(The next history element refers to a more recent action.)
  1705. With prefix argument N, search for Nth next match.
  1706. If N is negative, find the previous or Nth previous match.
  1707. Normally, history elements are matched case-insensitively if
  1708. `case-fold-search' is non-nil, but an uppercase letter in REGEXP
  1709. makes the search case-sensitive."
  1710. (interactive
  1711. (let* ((enable-recursive-minibuffers t)
  1712. (regexp (read-from-minibuffer "Next element matching (regexp): "
  1713. nil
  1714. minibuffer-local-map
  1715. nil
  1716. 'minibuffer-history-search-history
  1717. (car minibuffer-history-search-history))))
  1718. ;; Use the last regexp specified, by default, if input is empty.
  1719. (list (if (string= regexp "")
  1720. (if minibuffer-history-search-history
  1721. (car minibuffer-history-search-history)
  1722. (user-error "No previous history search regexp"))
  1723. regexp)
  1724. (prefix-numeric-value current-prefix-arg))))
  1725. (previous-matching-history-element regexp (- n)))
  1726. (defvar minibuffer-temporary-goal-position nil)
  1727. (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
  1728. "Function run by `goto-history-element' before consuming default values.
  1729. This is useful to dynamically add more elements to the list of default values
  1730. when `goto-history-element' reaches the end of this list.
  1731. Before calling this function `goto-history-element' sets the variable
  1732. `minibuffer-default-add-done' to t, so it will call this function only
  1733. once. In special cases, when this function needs to be called more
  1734. than once, it can set `minibuffer-default-add-done' to nil explicitly,
  1735. overriding the setting of this variable to t in `goto-history-element'.")
  1736. (defvar minibuffer-default-add-done nil
  1737. "When nil, add more elements to the end of the list of default values.
  1738. The value nil causes `goto-history-element' to add more elements to
  1739. the list of defaults when it reaches the end of this list. It does
  1740. this by calling a function defined by `minibuffer-default-add-function'.")
  1741. (make-variable-buffer-local 'minibuffer-default-add-done)
  1742. (defun minibuffer-default-add-completions ()
  1743. "Return a list of all completions without the default value.
  1744. This function is used to add all elements of the completion table to
  1745. the end of the list of defaults just after the default value."
  1746. (let ((def minibuffer-default)
  1747. (all (all-completions ""
  1748. minibuffer-completion-table
  1749. minibuffer-completion-predicate)))
  1750. (if (listp def)
  1751. (append def all)
  1752. (cons def (delete def all)))))
  1753. (defun goto-history-element (nabs)
  1754. "Puts element of the minibuffer history in the minibuffer.
  1755. The argument NABS specifies the absolute history position."
  1756. (interactive "p")
  1757. (when (and (not minibuffer-default-add-done)
  1758. (functionp minibuffer-default-add-function)
  1759. (< nabs (- (if (listp minibuffer-default)
  1760. (length minibuffer-default)
  1761. 1))))
  1762. (setq minibuffer-default-add-done t
  1763. minibuffer-default (funcall minibuffer-default-add-function)))
  1764. (let ((minimum (if minibuffer-default
  1765. (- (if (listp minibuffer-default)
  1766. (length minibuffer-default)
  1767. 1))
  1768. 0))
  1769. elt minibuffer-returned-to-present)
  1770. (if (and (zerop minibuffer-history-position)
  1771. (null minibuffer-text-before-history))
  1772. (setq minibuffer-text-before-history
  1773. (minibuffer-contents-no-properties)))
  1774. (if (< nabs minimum)
  1775. (user-error (if minibuffer-default
  1776. "End of defaults; no next item"
  1777. "End of history; no default available")))
  1778. (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
  1779. (length (symbol-value minibuffer-history-variable))
  1780. 0))
  1781. (user-error "Beginning of history; no preceding item"))
  1782. (unless (memq last-command '(next-history-element
  1783. previous-history-element))
  1784. (let ((prompt-end (minibuffer-prompt-end)))
  1785. (set (make-local-variable 'minibuffer-temporary-goal-position)
  1786. (cond ((<= (point) prompt-end) prompt-end)
  1787. ((eobp) nil)
  1788. (t (point))))))
  1789. (goto-char (point-max))
  1790. (delete-minibuffer-contents)
  1791. (setq minibuffer-history-position nabs)
  1792. (cond ((< nabs 0)
  1793. (setq elt (if (listp minibuffer-default)
  1794. (nth (1- (abs nabs)) minibuffer-default)
  1795. minibuffer-default)))
  1796. ((= nabs 0)
  1797. (setq elt (or minibuffer-text-before-history ""))
  1798. (setq minibuffer-returned-to-present t)
  1799. (setq minibuffer-text-before-history nil))
  1800. (t (setq elt (nth (1- minibuffer-history-position)
  1801. (symbol-value minibuffer-history-variable)))))
  1802. (insert
  1803. (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
  1804. (not minibuffer-returned-to-present))
  1805. (let ((print-level nil))
  1806. (prin1-to-string elt))
  1807. elt))
  1808. (goto-char (or minibuffer-temporary-goal-position (point-max)))))
  1809. (defun next-history-element (n)
  1810. "Puts next element of the minibuffer history in the minibuffer.
  1811. With argument N, it uses the Nth following element."
  1812. (interactive "p")
  1813. (or (zerop n)
  1814. (goto-history-element (- minibuffer-history-position n))))
  1815. (defun previous-history-element (n)
  1816. "Puts previous element of the minibuffer history in the minibuffer.
  1817. With argument N, it uses the Nth previous element."
  1818. (interactive "p")
  1819. (or (zerop n)
  1820. (goto-history-element (+ minibuffer-history-position n))))
  1821. (defun next-line-or-history-element (&optional arg)
  1822. "Move cursor vertically down ARG lines, or to the next history element.
  1823. When point moves over the bottom line of multi-line minibuffer, puts ARGth
  1824. next element of the minibuffer history in the minibuffer."
  1825. (interactive "^p")
  1826. (or arg (setq arg 1))
  1827. (let* ((old-point (point))
  1828. ;; Remember the original goal column of possibly multi-line input
  1829. ;; excluding the length of the prompt on the first line.
  1830. (prompt-end (minibuffer-prompt-end))
  1831. (old-column (unless (and (eolp) (> (point) prompt-end))
  1832. (if (= (line-number-at-pos) 1)
  1833. (max (- (current-column) (1- prompt-end)) 0)
  1834. (current-column)))))
  1835. (condition-case nil
  1836. (with-no-warnings
  1837. (next-line arg))
  1838. (end-of-buffer
  1839. ;; Restore old position since `line-move-visual' moves point to
  1840. ;; the end of the line when it fails to go to the next line.
  1841. (goto-char old-point)
  1842. (next-history-element arg)
  1843. ;; Restore the original goal column on the last line
  1844. ;; of possibly multi-line input.
  1845. (goto-char (point-max))
  1846. (when old-column
  1847. (if (= (line-number-at-pos) 1)
  1848. (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
  1849. (move-to-column old-column)))))))
  1850. (defun previous-line-or-history-element (&optional arg)
  1851. "Move cursor vertically up ARG lines, or to the previous history element.
  1852. When point moves over the top line of multi-line minibuffer, puts ARGth
  1853. previous element of the minibuffer history in the minibuffer."
  1854. (interactive "^p")
  1855. (or arg (setq arg 1))
  1856. (let* ((old-point (point))
  1857. ;; Remember the original goal column of possibly multi-line input
  1858. ;; excluding the length of the prompt on the first line.
  1859. (prompt-end (minibuffer-prompt-end))
  1860. (old-column (unless (and (eolp) (> (point) prompt-end))
  1861. (if (= (line-number-at-pos) 1)
  1862. (max (- (current-column) (1- prompt-end)) 0)
  1863. (current-column)))))
  1864. (condition-case nil
  1865. (with-no-warnings
  1866. (previous-line arg))
  1867. (beginning-of-buffer
  1868. ;; Restore old position since `line-move-visual' moves point to
  1869. ;; the beginning of the line when it fails to go to the previous line.
  1870. (goto-char old-point)
  1871. (previous-history-element arg)
  1872. ;; Restore the original goal column on the first line
  1873. ;; of possibly multi-line input.
  1874. (goto-char (minibuffer-prompt-end))
  1875. (if old-column
  1876. (if (= (line-number-at-pos) 1)
  1877. (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
  1878. (move-to-column old-column))
  1879. (goto-char (line-end-position)))))))
  1880. (defun next-complete-history-element (n)
  1881. "Get next history element which completes the minibuffer before the point.
  1882. The contents of the minibuffer after the point are deleted, and replaced
  1883. by the new completion."
  1884. (interactive "p")
  1885. (let ((point-at-start (point)))
  1886. (next-matching-history-element
  1887. (concat
  1888. "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
  1889. n)
  1890. ;; next-matching-history-element always puts us at (point-min).
  1891. ;; Move to the position we were at before changing the buffer contents.
  1892. ;; This is still sensible, because the text before point has not changed.
  1893. (goto-char point-at-start)))
  1894. (defun previous-complete-history-element (n)
  1895. "\
  1896. Get previous history element which completes the minibuffer before the point.
  1897. The contents of the minibuffer after the point are deleted, and replaced
  1898. by the new completion."
  1899. (interactive "p")
  1900. (next-complete-history-element (- n)))
  1901. ;; For compatibility with the old subr of the same name.
  1902. (defun minibuffer-prompt-width ()
  1903. "Return the display width of the minibuffer prompt.
  1904. Return 0 if current buffer is not a minibuffer."
  1905. ;; Return the width of everything before the field at the end of
  1906. ;; the buffer; this should be 0 for normal buffers.
  1907. (1- (minibuffer-prompt-end)))
  1908. ;; isearch minibuffer history
  1909. (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
  1910. (defvar minibuffer-history-isearch-message-overlay)
  1911. (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
  1912. (defun minibuffer-history-isearch-setup ()
  1913. "Set up a minibuffer for using isearch to search the minibuffer history.
  1914. Intended to be added to `minibuffer-setup-hook'."
  1915. (set (make-local-variable 'isearch-search-fun-function)
  1916. 'minibuffer-history-isearch-search)
  1917. (set (make-local-variable 'isearch-message-function)
  1918. 'minibuffer-history-isearch-message)
  1919. (set (make-local-variable 'isearch-wrap-function)
  1920. 'minibuffer-history-isearch-wrap)
  1921. (set (make-local-variable 'isearch-push-state-function)
  1922. 'minibuffer-history-isearch-push-state)
  1923. (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
  1924. (defun minibuffer-history-isearch-end ()
  1925. "Clean up the minibuffer after terminating isearch in the minibuffer."
  1926. (if minibuffer-history-isearch-message-overlay
  1927. (delete-overlay minibuffer-history-isearch-message-overlay)))
  1928. (defun minibuffer-history-isearch-search ()
  1929. "Return the proper search function, for isearch in minibuffer history."
  1930. (lambda (string bound noerror)
  1931. (let ((search-fun
  1932. ;; Use standard functions to search within minibuffer text
  1933. (isearch-search-fun-default))
  1934. found)
  1935. ;; Avoid lazy-highlighting matches in the minibuffer prompt when
  1936. ;; searching forward. Lazy-highlight calls this lambda with the
  1937. ;; bound arg, so skip the minibuffer prompt.
  1938. (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
  1939. (goto-char (minibuffer-prompt-end)))
  1940. (or
  1941. ;; 1. First try searching in the initial minibuffer text
  1942. (funcall search-fun string
  1943. (if isearch-forward bound (minibuffer-prompt-end))
  1944. noerror)
  1945. ;; 2. If the above search fails, start putting next/prev history
  1946. ;; elements in the minibuffer successively, and search the string
  1947. ;; in them. Do this only when bound is nil (i.e. not while
  1948. ;; lazy-highlighting search strings in the current minibuffer text).
  1949. (unless bound
  1950. (condition-case nil
  1951. (progn
  1952. (while (not found)
  1953. (cond (isearch-forward
  1954. (next-history-element 1)
  1955. (goto-char (minibuffer-prompt-end)))
  1956. (t
  1957. (previous-history-element 1)
  1958. (goto-char (point-max))))
  1959. (setq isearch-barrier (point) isearch-opoint (point))
  1960. ;; After putting the next/prev history element, search
  1961. ;; the string in them again, until next-history-element
  1962. ;; or previous-history-element raises an error at the
  1963. ;; beginning/end of history.
  1964. (setq found (funcall search-fun string
  1965. (unless isearch-forward
  1966. ;; For backward search, don't search
  1967. ;; in the minibuffer prompt
  1968. (minibuffer-prompt-end))
  1969. noerror)))
  1970. ;; Return point of the new search result
  1971. (point))
  1972. ;; Return nil when next(prev)-history-element fails
  1973. (error nil)))))))
  1974. (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
  1975. "Display the minibuffer history search prompt.
  1976. If there are no search errors, this function displays an overlay with
  1977. the isearch prompt which replaces the original minibuffer prompt.
  1978. Otherwise, it displays the standard isearch message returned from
  1979. the function `isearch-message'."
  1980. (if (not (and (minibufferp) isearch-success (not isearch-error)))
  1981. ;; Use standard function `isearch-message' when not in the minibuffer,
  1982. ;; or search fails, or has an error (like incomplete regexp).
  1983. ;; This function overwrites minibuffer text with isearch message,
  1984. ;; so it's possible to see what is wrong in the search string.
  1985. (isearch-message c-q-hack ellipsis)
  1986. ;; Otherwise, put the overlay with the standard isearch prompt over
  1987. ;; the initial minibuffer prompt.
  1988. (if (overlayp minibuffer-history-isearch-message-overlay)
  1989. (move-overlay minibuffer-history-isearch-message-overlay
  1990. (point-min) (minibuffer-prompt-end))
  1991. (setq minibuffer-history-isearch-message-overlay
  1992. (make-overlay (point-min) (minibuffer-prompt-end)))
  1993. (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
  1994. (overlay-put minibuffer-history-isearch-message-overlay
  1995. 'display (isearch-message-prefix c-q-hack ellipsis))
  1996. ;; And clear any previous isearch message.
  1997. (message "")))
  1998. (defun minibuffer-history-isearch-wrap ()
  1999. "Wrap the minibuffer history search when search fails.
  2000. Move point to the first history element for a forward search,
  2001. or to the last history element for a backward search."
  2002. ;; When `minibuffer-history-isearch-search' fails on reaching the
  2003. ;; beginning/end of the history, wrap the search to the first/last
  2004. ;; minibuffer history element.
  2005. (if isearch-forward
  2006. (goto-history-element (length (symbol-value minibuffer-history-variable)))
  2007. (goto-history-element 0))
  2008. (setq isearch-success t)
  2009. (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
  2010. (defun minibuffer-history-isearch-push-state ()
  2011. "Save a function restoring the state of minibuffer history search.
  2012. Save `minibuffer-history-position' to the additional state parameter
  2013. in the search status stack."
  2014. (let ((pos minibuffer-history-position))
  2015. (lambda (cmd)
  2016. (minibuffer-history-isearch-pop-state cmd pos))))
  2017. (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
  2018. "Restore the minibuffer history search state.
  2019. Go to the history element by the absolute history position HIST-POS."
  2020. (goto-history-element hist-pos))
  2021. ;Put this on C-x u, so we can force that rather than C-_ into startup msg
  2022. (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
  2023. (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
  2024. "Table mapping redo records to the corresponding undo one.
  2025. A redo record for undo-in-region maps to t.
  2026. A redo record for ordinary undo maps to the following (earlier) undo.")
  2027. (defvar undo-in-region nil
  2028. "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
  2029. (defvar undo-no-redo nil
  2030. "If t, `undo' doesn't go through redo entries.")
  2031. (defvar pending-undo-list nil
  2032. "Within a run of consecutive undo commands, list remaining to be undone.
  2033. If t, we undid all the way to the end of it.")
  2034. (defun undo (&optional arg)
  2035. "Undo some previous changes.
  2036. Repeat this command to undo more changes.
  2037. A numeric ARG serves as a repeat count.
  2038. In Transient Mark mode when the mark is active, only undo changes within
  2039. the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
  2040. as an argument limits undo to changes within the current region."
  2041. (interactive "*P")
  2042. ;; Make last-command indicate for the next command that this was an undo.
  2043. ;; That way, another undo will undo more.
  2044. ;; If we get to the end of the undo history and get an error,
  2045. ;; another undo command will find the undo history empty
  2046. ;; and will get another error. To begin undoing the undos,
  2047. ;; you must type some other command.
  2048. (let* ((modified (buffer-modified-p))
  2049. ;; For an indirect buffer, look in the base buffer for the
  2050. ;; auto-save data.
  2051. (base-buffer (or (buffer-base-buffer) (current-buffer)))
  2052. (recent-save (with-current-buffer base-buffer
  2053. (recent-auto-save-p)))
  2054. message)
  2055. ;; If we get an error in undo-start,
  2056. ;; the next command should not be a "consecutive undo".
  2057. ;; So set `this-command' to something other than `undo'.
  2058. (setq this-command 'undo-start)
  2059. (unless (and (eq last-command 'undo)
  2060. (or (eq pending-undo-list t)
  2061. ;; If something (a timer or filter?) changed the buffer
  2062. ;; since the previous command, don't continue the undo seq.
  2063. (let ((list buffer-undo-list))
  2064. (while (eq (car list) nil)
  2065. (setq list (cdr list)))
  2066. ;; If the last undo record made was made by undo
  2067. ;; it shows nothing else happened in between.
  2068. (gethash list undo-equiv-table))))
  2069. (setq undo-in-region
  2070. (or (region-active-p) (and arg (not (numberp arg)))))
  2071. (if undo-in-region
  2072. (undo-start (region-beginning) (region-end))
  2073. (undo-start))
  2074. ;; get rid of initial undo boundary
  2075. (undo-more 1))
  2076. ;; If we got this far, the next command should be a consecutive undo.
  2077. (setq this-command 'undo)
  2078. ;; Check to see whether we're hitting a redo record, and if
  2079. ;; so, ask the user whether she wants to skip the redo/undo pair.
  2080. (let ((equiv (gethash pending-undo-list undo-equiv-table)))
  2081. (or (eq (selected-window) (minibuffer-window))
  2082. (setq message (format "%s%s!"
  2083. (if (or undo-no-redo (not equiv))
  2084. "Undo" "Redo")
  2085. (if undo-in-region " in region" ""))))
  2086. (when (and (consp equiv) undo-no-redo)
  2087. ;; The equiv entry might point to another redo record if we have done
  2088. ;; undo-redo-undo-redo-... so skip to the very last equiv.
  2089. (while (let ((next (gethash equiv undo-equiv-table)))
  2090. (if next (setq equiv next))))
  2091. (setq pending-undo-list equiv)))
  2092. (undo-more
  2093. (if (numberp arg)
  2094. (prefix-numeric-value arg)
  2095. 1))
  2096. ;; Record the fact that the just-generated undo records come from an
  2097. ;; undo operation--that is, they are redo records.
  2098. ;; In the ordinary case (not within a region), map the redo
  2099. ;; record to the following undos.
  2100. ;; I don't know how to do that in the undo-in-region case.
  2101. (let ((list buffer-undo-list))
  2102. ;; Strip any leading undo boundaries there might be, like we do
  2103. ;; above when checking.
  2104. (while (eq (car list) nil)
  2105. (setq list (cdr list)))
  2106. (puthash list
  2107. ;; Prevent identity mapping. This can happen if
  2108. ;; consecutive nils are erroneously in undo list.
  2109. (if (or undo-in-region (eq list pending-undo-list))
  2110. t
  2111. pending-undo-list)
  2112. undo-equiv-table))
  2113. ;; Don't specify a position in the undo record for the undo command.
  2114. ;; Instead, undoing this should move point to where the change is.
  2115. (let ((tail buffer-undo-list)
  2116. (prev nil))
  2117. (while (car tail)
  2118. (when (integerp (car tail))
  2119. (let ((pos (car tail)))
  2120. (if prev
  2121. (setcdr prev (cdr tail))
  2122. (setq buffer-undo-list (cdr tail)))
  2123. (setq tail (cdr tail))
  2124. (while (car tail)
  2125. (if (eq pos (car tail))
  2126. (if prev
  2127. (setcdr prev (cdr tail))
  2128. (setq buffer-undo-list (cdr tail)))
  2129. (setq prev tail))
  2130. (setq tail (cdr tail)))
  2131. (setq tail nil)))
  2132. (setq prev tail tail (cdr tail))))
  2133. ;; Record what the current undo list says,
  2134. ;; so the next command can tell if the buffer was modified in between.
  2135. (and modified (not (buffer-modified-p))
  2136. (with-current-buffer base-buffer
  2137. (delete-auto-save-file-if-necessary recent-save)))
  2138. ;; Display a message announcing success.
  2139. (if message
  2140. (message "%s" message))))
  2141. (defun buffer-disable-undo (&optional buffer)
  2142. "Make BUFFER stop keeping undo information.
  2143. No argument or nil as argument means do this for the current buffer."
  2144. (interactive)
  2145. (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
  2146. (setq buffer-undo-list t)))
  2147. (defun undo-only (&optional arg)
  2148. "Undo some previous changes.
  2149. Repeat this command to undo more changes.
  2150. A numeric ARG serves as a repeat count.
  2151. Contrary to `undo', this will not redo a previous undo."
  2152. (interactive "*p")
  2153. (let ((undo-no-redo t)) (undo arg)))
  2154. (defvar undo-in-progress nil
  2155. "Non-nil while performing an undo.
  2156. Some change-hooks test this variable to do something different.")
  2157. (defun undo-more (n)
  2158. "Undo back N undo-boundaries beyond what was already undone recently.
  2159. Call `undo-start' to get ready to undo recent changes,
  2160. then call `undo-more' one or more times to undo them."
  2161. (or (listp pending-undo-list)
  2162. (user-error (concat "No further undo information"
  2163. (and undo-in-region " for region"))))
  2164. (let ((undo-in-progress t))
  2165. ;; Note: The following, while pulling elements off
  2166. ;; `pending-undo-list' will call primitive change functions which
  2167. ;; will push more elements onto `buffer-undo-list'.
  2168. (setq pending-undo-list (primitive-undo n pending-undo-list))
  2169. (if (null pending-undo-list)
  2170. (setq pending-undo-list t))))
  2171. (defun primitive-undo (n list)
  2172. "Undo N records from the front of the list LIST.
  2173. Return what remains of the list."
  2174. ;; This is a good feature, but would make undo-start
  2175. ;; unable to do what is expected.
  2176. ;;(when (null (car (list)))
  2177. ;; ;; If the head of the list is a boundary, it is the boundary
  2178. ;; ;; preceding this command. Get rid of it and don't count it.
  2179. ;; (setq list (cdr list))))
  2180. (let ((arg n)
  2181. ;; In a writable buffer, enable undoing read-only text that is
  2182. ;; so because of text properties.
  2183. (inhibit-read-only t)
  2184. ;; Don't let `intangible' properties interfere with undo.
  2185. (inhibit-point-motion-hooks t)
  2186. ;; We use oldlist only to check for EQ. ++kfs
  2187. (oldlist buffer-undo-list)
  2188. (did-apply nil)
  2189. (next nil))
  2190. (while (> arg 0)
  2191. (while (setq next (pop list)) ;Exit inner loop at undo boundary.
  2192. ;; Handle an integer by setting point to that value.
  2193. (pcase next
  2194. ((pred integerp) (goto-char next))
  2195. ;; Element (t . TIME) records previous modtime.
  2196. ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
  2197. ;; UNKNOWN_MODTIME_NSECS.
  2198. (`(t . ,time)
  2199. ;; If this records an obsolete save
  2200. ;; (not matching the actual disk file)
  2201. ;; then don't mark unmodified.
  2202. (when (or (equal time (visited-file-modtime))
  2203. (and (consp time)
  2204. (equal (list (car time) (cdr time))
  2205. (visited-file-modtime))))
  2206. (when (fboundp 'unlock-buffer)
  2207. (unlock-buffer))
  2208. (set-buffer-modified-p nil)))
  2209. ;; Element (nil PROP VAL BEG . END) is property change.
  2210. (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
  2211. (when (or (> (point-min) beg) (< (point-max) end))
  2212. (error "Changes to be undone are outside visible portion of buffer"))
  2213. (put-text-property beg end prop val))
  2214. ;; Element (BEG . END) means range was inserted.
  2215. (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
  2216. ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
  2217. ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
  2218. (when (or (> (point-min) beg) (< (point-max) end))
  2219. (error "Changes to be undone are outside visible portion of buffer"))
  2220. ;; Set point first thing, so that undoing this undo
  2221. ;; does not send point back to where it is now.
  2222. (goto-char beg)
  2223. (delete-region beg end))
  2224. ;; Element (apply FUN . ARGS) means call FUN to undo.
  2225. (`(apply . ,fun-args)
  2226. (let ((currbuff (current-buffer)))
  2227. (if (integerp (car fun-args))
  2228. ;; Long format: (apply DELTA START END FUN . ARGS).
  2229. (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
  2230. (start-mark (copy-marker start nil))
  2231. (end-mark (copy-marker end t)))
  2232. (when (or (> (point-min) start) (< (point-max) end))
  2233. (error "Changes to be undone are outside visible portion of buffer"))
  2234. (apply fun args) ;; Use `save-current-buffer'?
  2235. ;; Check that the function did what the entry
  2236. ;; said it would do.
  2237. (unless (and (= start start-mark)
  2238. (= (+ delta end) end-mark))
  2239. (error "Changes to be undone by function different than announced"))
  2240. (set-marker start-mark nil)
  2241. (set-marker end-mark nil))
  2242. (apply fun-args))
  2243. (unless (eq currbuff (current-buffer))
  2244. (error "Undo function switched buffer"))
  2245. (setq did-apply t)))
  2246. ;; Element (STRING . POS) means STRING was deleted.
  2247. (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
  2248. (when (let ((apos (abs pos)))
  2249. (or (< apos (point-min)) (> apos (point-max))))
  2250. (error "Changes to be undone are outside visible portion of buffer"))
  2251. (let (valid-marker-adjustments)
  2252. ;; Check that marker adjustments which were recorded
  2253. ;; with the (STRING . POS) record are still valid, ie
  2254. ;; the markers haven't moved. We check their validity
  2255. ;; before reinserting the string so as we don't need to
  2256. ;; mind marker insertion-type.
  2257. (while (and (markerp (car-safe (car list)))
  2258. (integerp (cdr-safe (car list))))
  2259. (let* ((marker-adj (pop list))
  2260. (m (car marker-adj)))
  2261. (and (eq (marker-buffer m) (current-buffer))
  2262. (= pos m)
  2263. (push marker-adj valid-marker-adjustments))))
  2264. ;; Insert string and adjust point
  2265. (if (< pos 0)
  2266. (progn
  2267. (goto-char (- pos))
  2268. (insert string))
  2269. (goto-char pos)
  2270. (insert string)
  2271. (goto-char pos))
  2272. ;; Adjust the valid marker adjustments
  2273. (dolist (adj valid-marker-adjustments)
  2274. (set-marker (car adj)
  2275. (- (car adj) (cdr adj))))))
  2276. ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
  2277. (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
  2278. (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
  2279. next)
  2280. ;; Even though these elements are not expected in the undo
  2281. ;; list, adjust them to be conservative for the 24.4
  2282. ;; release. (Bug#16818)
  2283. (when (marker-buffer marker)
  2284. (set-marker marker
  2285. (- marker offset)
  2286. (marker-buffer marker))))
  2287. (_ (error "Unrecognized entry in undo list %S" next))))
  2288. (setq arg (1- arg)))
  2289. ;; Make sure an apply entry produces at least one undo entry,
  2290. ;; so the test in `undo' for continuing an undo series
  2291. ;; will work right.
  2292. (if (and did-apply
  2293. (eq oldlist buffer-undo-list))
  2294. (setq buffer-undo-list
  2295. (cons (list 'apply 'cdr nil) buffer-undo-list))))
  2296. list)
  2297. ;; Deep copy of a list
  2298. (defun undo-copy-list (list)
  2299. "Make a copy of undo list LIST."
  2300. (mapcar 'undo-copy-list-1 list))
  2301. (defun undo-copy-list-1 (elt)
  2302. (if (consp elt)
  2303. (cons (car elt) (undo-copy-list-1 (cdr elt)))
  2304. elt))
  2305. (defun undo-start (&optional beg end)
  2306. "Set `pending-undo-list' to the front of the undo list.
  2307. The next call to `undo-more' will undo the most recently made change.
  2308. If BEG and END are specified, then only undo elements
  2309. that apply to text between BEG and END are used; other undo elements
  2310. are ignored. If BEG and END are nil, all undo elements are used."
  2311. (if (eq buffer-undo-list t)
  2312. (user-error "No undo information in this buffer"))
  2313. (setq pending-undo-list
  2314. (if (and beg end (not (= beg end)))
  2315. (undo-make-selective-list (min beg end) (max beg end))
  2316. buffer-undo-list)))
  2317. ;; The positions given in elements of the undo list are the positions
  2318. ;; as of the time that element was recorded to undo history. In
  2319. ;; general, subsequent buffer edits render those positions invalid in
  2320. ;; the current buffer, unless adjusted according to the intervening
  2321. ;; undo elements.
  2322. ;;
  2323. ;; Undo in region is a use case that requires adjustments to undo
  2324. ;; elements. It must adjust positions of elements in the region based
  2325. ;; on newer elements not in the region so as they may be correctly
  2326. ;; applied in the current buffer. undo-make-selective-list
  2327. ;; accomplishes this with its undo-deltas list of adjustments. An
  2328. ;; example undo history from oldest to newest:
  2329. ;;
  2330. ;; buf pos:
  2331. ;; 123456789 buffer-undo-list undo-deltas
  2332. ;; --------- ---------------- -----------
  2333. ;; aaa (1 . 4) (1 . -3)
  2334. ;; aaba (3 . 4) N/A (in region)
  2335. ;; ccaaba (1 . 3) (1 . -2)
  2336. ;; ccaabaddd (7 . 10) (7 . -3)
  2337. ;; ccaabdd ("ad" . 6) (6 . 2)
  2338. ;; ccaabaddd (6 . 8) (6 . -2)
  2339. ;; | |<-- region: "caab", from 2 to 6
  2340. ;;
  2341. ;; When the user starts a run of undos in region,
  2342. ;; undo-make-selective-list is called to create the full list of in
  2343. ;; region elements. Each element is adjusted forward chronologically
  2344. ;; through undo-deltas to determine if it is in the region.
  2345. ;;
  2346. ;; In the above example, the insertion of "b" is (3 . 4) in the
  2347. ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
  2348. ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
  2349. ;; . 6) is assessed as in the region and placed in the selective list.
  2350. ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
  2351. ;; due to the selected element. The "b" insertion is the only element
  2352. ;; fully in the region, so in this example undo-make-selective-list
  2353. ;; returns (nil (5 . 6)).
  2354. ;;
  2355. ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
  2356. ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
  2357. ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
  2358. ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
  2359. ;; . 10) adjusts to (6 . 8) due to the first undo delta.
  2360. ;;
  2361. ;; More interesting is how to adjust the "ddd" insertion due to the
  2362. ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
  2363. ;; If the reinsertion was a manual retyping of "ad", then the total
  2364. ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
  2365. ;; the reinsertion was due to undo, one might expect the first "d"
  2366. ;; character would again be a part of the "ddd" text, meaning its
  2367. ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
  2368. ;;
  2369. ;; undo-make-selective-list assumes in this situation that "ad" was a
  2370. ;; new edit, even if it was inserted because of an undo.
  2371. ;; Consequently, if the user undos in region "8 to 10" of the
  2372. ;; "ccaabaddd" buffer, they could be surprised that it becomes
  2373. ;; "ccaabad", as though the first "d" became detached from the
  2374. ;; original "ddd" insertion. This quirk is a FIXME.
  2375. (defun undo-make-selective-list (start end)
  2376. "Return a list of undo elements for the region START to END.
  2377. The elements come from `buffer-undo-list', but we keep only the
  2378. elements inside this region, and discard those outside this
  2379. region. The elements' positions are adjusted so as the returned
  2380. list can be applied to the current buffer."
  2381. (let ((ulist buffer-undo-list)
  2382. ;; A list of position adjusted undo elements in the region.
  2383. (selective-list (list nil))
  2384. ;; A list of undo-deltas for out of region undo elements.
  2385. undo-deltas
  2386. undo-elt)
  2387. (while ulist
  2388. (when undo-no-redo
  2389. (while (gethash ulist undo-equiv-table)
  2390. (setq ulist (gethash ulist undo-equiv-table))))
  2391. (setq undo-elt (car ulist))
  2392. (cond
  2393. ((null undo-elt)
  2394. ;; Don't put two nils together in the list
  2395. (when (car selective-list)
  2396. (push nil selective-list)))
  2397. ((and (consp undo-elt) (eq (car undo-elt) t))
  2398. ;; This is a "was unmodified" element. Keep it
  2399. ;; if we have kept everything thus far.
  2400. (when (not undo-deltas)
  2401. (push undo-elt selective-list)))
  2402. ;; Skip over marker adjustments, instead relying
  2403. ;; on finding them after (TEXT . POS) elements
  2404. ((markerp (car-safe undo-elt))
  2405. nil)
  2406. (t
  2407. (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
  2408. undo-deltas)))
  2409. (if (undo-elt-in-region adjusted-undo-elt start end)
  2410. (progn
  2411. (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
  2412. (push adjusted-undo-elt selective-list)
  2413. ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
  2414. ;; kept. primitive-undo may discard them later.
  2415. (when (and (stringp (car-safe adjusted-undo-elt))
  2416. (integerp (cdr-safe adjusted-undo-elt)))
  2417. (let ((list-i (cdr ulist)))
  2418. (while (markerp (car-safe (car list-i)))
  2419. (push (pop list-i) selective-list)))))
  2420. (let ((delta (undo-delta undo-elt)))
  2421. (when (/= 0 (cdr delta))
  2422. (push delta undo-deltas)))))))
  2423. (pop ulist))
  2424. (nreverse selective-list)))
  2425. (defun undo-elt-in-region (undo-elt start end)
  2426. "Determine whether UNDO-ELT falls inside the region START ... END.
  2427. If it crosses the edge, we return nil.
  2428. Generally this function is not useful for determining
  2429. whether (MARKER . ADJUSTMENT) undo elements are in the region,
  2430. because markers can be arbitrarily relocated. Instead, pass the
  2431. marker adjustment's corresponding (TEXT . POS) element."
  2432. (cond ((integerp undo-elt)
  2433. (and (>= undo-elt start)
  2434. (<= undo-elt end)))
  2435. ((eq undo-elt nil)
  2436. t)
  2437. ((atom undo-elt)
  2438. nil)
  2439. ((stringp (car undo-elt))
  2440. ;; (TEXT . POSITION)
  2441. (and (>= (abs (cdr undo-elt)) start)
  2442. (<= (abs (cdr undo-elt)) end)))
  2443. ((and (consp undo-elt) (markerp (car undo-elt)))
  2444. ;; (MARKER . ADJUSTMENT)
  2445. (<= start (car undo-elt) end))
  2446. ((null (car undo-elt))
  2447. ;; (nil PROPERTY VALUE BEG . END)
  2448. (let ((tail (nthcdr 3 undo-elt)))
  2449. (and (>= (car tail) start)
  2450. (<= (cdr tail) end))))
  2451. ((integerp (car undo-elt))
  2452. ;; (BEGIN . END)
  2453. (and (>= (car undo-elt) start)
  2454. (<= (cdr undo-elt) end)))))
  2455. (defun undo-elt-crosses-region (undo-elt start end)
  2456. "Test whether UNDO-ELT crosses one edge of that region START ... END.
  2457. This assumes we have already decided that UNDO-ELT
  2458. is not *inside* the region START...END."
  2459. (declare (obsolete nil "25.1"))
  2460. (cond ((atom undo-elt) nil)
  2461. ((null (car undo-elt))
  2462. ;; (nil PROPERTY VALUE BEG . END)
  2463. (let ((tail (nthcdr 3 undo-elt)))
  2464. (and (< (car tail) end)
  2465. (> (cdr tail) start))))
  2466. ((integerp (car undo-elt))
  2467. ;; (BEGIN . END)
  2468. (and (< (car undo-elt) end)
  2469. (> (cdr undo-elt) start)))))
  2470. (defun undo-adjust-elt (elt deltas)
  2471. "Return adjustment of undo element ELT by the undo DELTAS
  2472. list."
  2473. (pcase elt
  2474. ;; POSITION
  2475. ((pred integerp)
  2476. (undo-adjust-pos elt deltas))
  2477. ;; (BEG . END)
  2478. (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
  2479. (undo-adjust-beg-end beg end deltas))
  2480. ;; (TEXT . POSITION)
  2481. (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
  2482. (cons text (* (if (< pos 0) -1 1)
  2483. (undo-adjust-pos (abs pos) deltas))))
  2484. ;; (nil PROPERTY VALUE BEG . END)
  2485. (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
  2486. `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
  2487. ;; (apply DELTA START END FUN . ARGS)
  2488. ;; FIXME
  2489. ;; All others return same elt
  2490. (_ elt)))
  2491. ;; (BEG . END) can adjust to the same positions, commonly when an
  2492. ;; insertion was undone and they are out of region, for example:
  2493. ;;
  2494. ;; buf pos:
  2495. ;; 123456789 buffer-undo-list undo-deltas
  2496. ;; --------- ---------------- -----------
  2497. ;; [...]
  2498. ;; abbaa (2 . 4) (2 . -2)
  2499. ;; aaa ("bb" . 2) (2 . 2)
  2500. ;; [...]
  2501. ;;
  2502. ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
  2503. ;; undo. Further adjustments to such an element should be the same as
  2504. ;; for (TEXT . POSITION) elements. The options are:
  2505. ;;
  2506. ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
  2507. ;; analogous to marker insertion-type t.
  2508. ;;
  2509. ;; 2: POSITION adjusts using <, resulting in behavior analogous to
  2510. ;; marker insertion-type nil.
  2511. ;;
  2512. ;; There was no strong reason to prefer one or the other, except that
  2513. ;; the first is more consistent with prior undo in region behavior.
  2514. (defun undo-adjust-beg-end (beg end deltas)
  2515. "Return cons of adjustments to BEG and END by the undo DELTAS
  2516. list."
  2517. (let ((adj-beg (undo-adjust-pos beg deltas)))
  2518. ;; Note: option 2 above would be like (cons (min ...) adj-end)
  2519. (cons adj-beg
  2520. (max adj-beg (undo-adjust-pos end deltas t)))))
  2521. (defun undo-adjust-pos (pos deltas &optional use-<)
  2522. "Return adjustment of POS by the undo DELTAS list, comparing
  2523. with < or <= based on USE-<."
  2524. (dolist (d deltas pos)
  2525. (when (if use-<
  2526. (< (car d) pos)
  2527. (<= (car d) pos))
  2528. (setq pos
  2529. ;; Don't allow pos to become less than the undo-delta
  2530. ;; position. This edge case is described in the overview
  2531. ;; comments.
  2532. (max (car d) (- pos (cdr d)))))))
  2533. ;; Return the first affected buffer position and the delta for an undo element
  2534. ;; delta is defined as the change in subsequent buffer positions if we *did*
  2535. ;; the undo.
  2536. (defun undo-delta (undo-elt)
  2537. (if (consp undo-elt)
  2538. (cond ((stringp (car undo-elt))
  2539. ;; (TEXT . POSITION)
  2540. (cons (abs (cdr undo-elt)) (length (car undo-elt))))
  2541. ((integerp (car undo-elt))
  2542. ;; (BEGIN . END)
  2543. (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
  2544. (t
  2545. '(0 . 0)))
  2546. '(0 . 0)))
  2547. ;;; Default undo-boundary addition
  2548. ;;
  2549. ;; This section adds a new undo-boundary at either after a command is
  2550. ;; called or in some cases on a timer called after a change is made in
  2551. ;; any buffer.
  2552. (defvar-local undo-auto--last-boundary-cause nil
  2553. "Describe the cause of the last undo-boundary.
  2554. If `explicit', the last boundary was caused by an explicit call to
  2555. `undo-boundary', that is one not called by the code in this
  2556. section.
  2557. If it is equal to `timer', then the last boundary was inserted
  2558. by `undo-auto--boundary-timer'.
  2559. If it is equal to `command', then the last boundary was inserted
  2560. automatically after a command, that is by the code defined in
  2561. this section.
  2562. If it is equal to a list, then the last boundary was inserted by
  2563. an amalgamating command. The car of the list is the number of
  2564. times an amalgamating command has been called, and the cdr are the
  2565. buffers that were changed during the last command.")
  2566. (defvar undo-auto--current-boundary-timer nil
  2567. "Current timer which will run `undo-auto--boundary-timer' or nil.
  2568. If set to non-nil, this will effectively disable the timer.")
  2569. (defvar undo-auto--this-command-amalgamating nil
  2570. "Non-nil if `this-command' should be amalgamated.
  2571. This variable is set to nil by `undo-auto--boundaries' and is set
  2572. by `undo-auto--amalgamate'." )
  2573. (defun undo-auto--needs-boundary-p ()
  2574. "Return non-nil if `buffer-undo-list' needs a boundary at the start."
  2575. (car-safe buffer-undo-list))
  2576. (defun undo-auto--last-boundary-amalgamating-number ()
  2577. "Return the number of amalgamating last commands or nil.
  2578. Amalgamating commands are, by default, either
  2579. `self-insert-command' and `delete-char', but can be any command
  2580. that calls `undo-auto--amalgamate'."
  2581. (car-safe undo-auto--last-boundary-cause))
  2582. (defun undo-auto--ensure-boundary (cause)
  2583. "Add an `undo-boundary' to the current buffer if needed.
  2584. REASON describes the reason that the boundary is being added; see
  2585. `undo-auto--last-boundary' for more information."
  2586. (when (and
  2587. (undo-auto--needs-boundary-p))
  2588. (let ((last-amalgamating
  2589. (undo-auto--last-boundary-amalgamating-number)))
  2590. (undo-boundary)
  2591. (setq undo-auto--last-boundary-cause
  2592. (if (eq 'amalgamate cause)
  2593. (cons
  2594. (if last-amalgamating (1+ last-amalgamating) 0)
  2595. undo-auto--undoably-changed-buffers)
  2596. cause)))))
  2597. (defun undo-auto--boundaries (cause)
  2598. "Check recently changed buffers and add a boundary if necessary.
  2599. REASON describes the reason that the boundary is being added; see
  2600. `undo-last-boundary' for more information."
  2601. (dolist (b undo-auto--undoably-changed-buffers)
  2602. (when (buffer-live-p b)
  2603. (with-current-buffer b
  2604. (undo-auto--ensure-boundary cause))))
  2605. (setq undo-auto--undoably-changed-buffers nil))
  2606. (defun undo-auto--boundary-timer ()
  2607. "Timer which will run `undo--auto-boundary-timer'."
  2608. (setq undo-auto--current-boundary-timer nil)
  2609. (undo-auto--boundaries 'timer))
  2610. (defun undo-auto--boundary-ensure-timer ()
  2611. "Ensure that the `undo-auto-boundary-timer' is set."
  2612. (unless undo-auto--current-boundary-timer
  2613. (setq undo-auto--current-boundary-timer
  2614. (run-at-time 10 nil #'undo-auto--boundary-timer))))
  2615. (defvar undo-auto--undoably-changed-buffers nil
  2616. "List of buffers that have changed recently.
  2617. This list is maintained by `undo-auto--undoable-change' and
  2618. `undo-auto--boundaries' and can be affected by changes to their
  2619. default values.
  2620. See also `undo-auto--buffer-undoably-changed'.")
  2621. (defun undo-auto--add-boundary ()
  2622. "Add an `undo-boundary' in appropriate buffers."
  2623. (undo-auto--boundaries
  2624. (if undo-auto--this-command-amalgamating
  2625. 'amalgamate
  2626. 'command))
  2627. (setq undo-auto--this-command-amalgamating nil))
  2628. (defun undo-auto--amalgamate ()
  2629. "Amalgamate undo if necessary.
  2630. This function can be called after an amalgamating command. It
  2631. removes the previous `undo-boundary' if a series of such calls
  2632. have been made. By default `self-insert-command' and
  2633. `delete-char' are the only amalgamating commands, although this
  2634. function could be called by any command wishing to have this
  2635. behaviour."
  2636. (let ((last-amalgamating-count
  2637. (undo-auto--last-boundary-amalgamating-number)))
  2638. (setq undo-auto--this-command-amalgamating t)
  2639. (when
  2640. last-amalgamating-count
  2641. (if
  2642. (and
  2643. (< last-amalgamating-count 20)
  2644. (eq this-command last-command))
  2645. ;; Amalgamate all buffers that have changed.
  2646. (dolist (b (cdr undo-auto--last-boundary-cause))
  2647. (when (buffer-live-p b)
  2648. (with-current-buffer
  2649. b
  2650. (when
  2651. ;; The head of `buffer-undo-list' is nil.
  2652. ;; `car-safe' doesn't work because
  2653. ;; `buffer-undo-list' need not be a list!
  2654. (and (listp buffer-undo-list)
  2655. (not (car buffer-undo-list)))
  2656. (setq buffer-undo-list
  2657. (cdr buffer-undo-list))))))
  2658. (setq undo-auto--last-boundary-cause 0)))))
  2659. (defun undo-auto--undoable-change ()
  2660. "Called after every undoable buffer change."
  2661. (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
  2662. (undo-auto--boundary-ensure-timer))
  2663. ;; End auto-boundary section
  2664. (defcustom undo-ask-before-discard nil
  2665. "If non-nil ask about discarding undo info for the current command.
  2666. Normally, Emacs discards the undo info for the current command if
  2667. it exceeds `undo-outer-limit'. But if you set this option
  2668. non-nil, it asks in the echo area whether to discard the info.
  2669. If you answer no, there is a slight risk that Emacs might crash, so
  2670. only do it if you really want to undo the command.
  2671. This option is mainly intended for debugging. You have to be
  2672. careful if you use it for other purposes. Garbage collection is
  2673. inhibited while the question is asked, meaning that Emacs might
  2674. leak memory. So you should make sure that you do not wait
  2675. excessively long before answering the question."
  2676. :type 'boolean
  2677. :group 'undo
  2678. :version "22.1")
  2679. (defvar undo-extra-outer-limit nil
  2680. "If non-nil, an extra level of size that's ok in an undo item.
  2681. We don't ask the user about truncating the undo list until the
  2682. current item gets bigger than this amount.
  2683. This variable only matters if `undo-ask-before-discard' is non-nil.")
  2684. (make-variable-buffer-local 'undo-extra-outer-limit)
  2685. ;; When the first undo batch in an undo list is longer than
  2686. ;; undo-outer-limit, this function gets called to warn the user that
  2687. ;; the undo info for the current command was discarded. Garbage
  2688. ;; collection is inhibited around the call, so it had better not do a
  2689. ;; lot of consing.
  2690. (setq undo-outer-limit-function 'undo-outer-limit-truncate)
  2691. (defun undo-outer-limit-truncate (size)
  2692. (if undo-ask-before-discard
  2693. (when (or (null undo-extra-outer-limit)
  2694. (> size undo-extra-outer-limit))
  2695. ;; Don't ask the question again unless it gets even bigger.
  2696. ;; This applies, in particular, if the user quits from the question.
  2697. ;; Such a quit quits out of GC, but something else will call GC
  2698. ;; again momentarily. It will call this function again,
  2699. ;; but we don't want to ask the question again.
  2700. (setq undo-extra-outer-limit (+ size 50000))
  2701. (if (let (use-dialog-box track-mouse executing-kbd-macro )
  2702. (yes-or-no-p (format-message
  2703. "Buffer `%s' undo info is %d bytes long; discard it? "
  2704. (buffer-name) size)))
  2705. (progn (setq buffer-undo-list nil)
  2706. (setq undo-extra-outer-limit nil)
  2707. t)
  2708. nil))
  2709. (display-warning '(undo discard-info)
  2710. (concat
  2711. (format-message
  2712. "Buffer `%s' undo info was %d bytes long.\n"
  2713. (buffer-name) size)
  2714. "The undo info was discarded because it exceeded \
  2715. `undo-outer-limit'.
  2716. This is normal if you executed a command that made a huge change
  2717. to the buffer. In that case, to prevent similar problems in the
  2718. future, set `undo-outer-limit' to a value that is large enough to
  2719. cover the maximum size of normal changes you expect a single
  2720. command to make, but not so large that it might exceed the
  2721. maximum memory allotted to Emacs.
  2722. If you did not execute any such command, the situation is
  2723. probably due to a bug and you should report it.
  2724. You can disable the popping up of this buffer by adding the entry
  2725. \(undo discard-info) to the user option `warning-suppress-types',
  2726. which is defined in the `warnings' library.\n")
  2727. :warning)
  2728. (setq buffer-undo-list nil)
  2729. t))
  2730. (defcustom password-word-equivalents
  2731. '("password" "passcode" "passphrase" "pass phrase"
  2732. ; These are sorted according to the GNU en_US locale.
  2733. "암호" ; ko
  2734. "パスワード" ; ja
  2735. "ପ୍ରବେଶ ସଙ୍କେତ" ; or
  2736. "ពាក្យសម្ងាត់" ; km
  2737. "adgangskode" ; da
  2738. "contraseña" ; es
  2739. "contrasenya" ; ca
  2740. "geslo" ; sl
  2741. "hasło" ; pl
  2742. "heslo" ; cs, sk
  2743. "iphasiwedi" ; zu
  2744. "jelszó" ; hu
  2745. "lösenord" ; sv
  2746. "lozinka" ; hr, sr
  2747. "mật khẩu" ; vi
  2748. "mot de passe" ; fr
  2749. "parola" ; tr
  2750. "pasahitza" ; eu
  2751. "passord" ; nb
  2752. "passwort" ; de
  2753. "pasvorto" ; eo
  2754. "salasana" ; fi
  2755. "senha" ; pt
  2756. "slaptažodis" ; lt
  2757. "wachtwoord" ; nl
  2758. "كلمة السر" ; ar
  2759. "ססמה" ; he
  2760. "лозинка" ; sr
  2761. "пароль" ; kk, ru, uk
  2762. "गुप्तशब्द" ; mr
  2763. "शब्दकूट" ; hi
  2764. "પાસવર્ડ" ; gu
  2765. "సంకేతపదము" ; te
  2766. "ਪਾਸਵਰਡ" ; pa
  2767. "ಗುಪ್ತಪದ" ; kn
  2768. "கடவுச்சொல்" ; ta
  2769. "അടയാളവാക്ക്" ; ml
  2770. "গুপ্তশব্দ" ; as
  2771. "পাসওয়ার্ড" ; bn_IN
  2772. "රහස්පදය" ; si
  2773. "密码" ; zh_CN
  2774. "密碼" ; zh_TW
  2775. )
  2776. "List of words equivalent to \"password\".
  2777. This is used by Shell mode and other parts of Emacs to recognize
  2778. password prompts, including prompts in languages other than
  2779. English. Different case choices should not be assumed to be
  2780. included; callers should bind `case-fold-search' to t."
  2781. :type '(repeat string)
  2782. :version "24.4"
  2783. :group 'processes)
  2784. (defvar shell-command-history nil
  2785. "History list for some commands that read shell commands.
  2786. Maximum length of the history list is determined by the value
  2787. of `history-length', which see.")
  2788. (defvar shell-command-switch (purecopy "-c")
  2789. "Switch used to have the shell execute its command line argument.")
  2790. (defvar shell-command-default-error-buffer nil
  2791. "Buffer name for `shell-command' and `shell-command-on-region' error output.
  2792. This buffer is used when `shell-command' or `shell-command-on-region'
  2793. is run interactively. A value of nil means that output to stderr and
  2794. stdout will be intermixed in the output stream.")
  2795. (declare-function mailcap-file-default-commands "mailcap" (files))
  2796. (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
  2797. (defun minibuffer-default-add-shell-commands ()
  2798. "Return a list of all commands associated with the current file.
  2799. This function is used to add all related commands retrieved by `mailcap'
  2800. to the end of the list of defaults just after the default value."
  2801. (interactive)
  2802. (let* ((filename (if (listp minibuffer-default)
  2803. (car minibuffer-default)
  2804. minibuffer-default))
  2805. (commands (and filename (require 'mailcap nil t)
  2806. (mailcap-file-default-commands (list filename)))))
  2807. (setq commands (mapcar (lambda (command)
  2808. (concat command " " filename))
  2809. commands))
  2810. (if (listp minibuffer-default)
  2811. (append minibuffer-default commands)
  2812. (cons minibuffer-default commands))))
  2813. (declare-function shell-completion-vars "shell" ())
  2814. (defvar minibuffer-local-shell-command-map
  2815. (let ((map (make-sparse-keymap)))
  2816. (set-keymap-parent map minibuffer-local-map)
  2817. (define-key map "\t" 'completion-at-point)
  2818. map)
  2819. "Keymap used for completing shell commands in minibuffer.")
  2820. (defun read-shell-command (prompt &optional initial-contents hist &rest args)
  2821. "Read a shell command from the minibuffer.
  2822. The arguments are the same as the ones of `read-from-minibuffer',
  2823. except READ and KEYMAP are missing and HIST defaults
  2824. to `shell-command-history'."
  2825. (require 'shell)
  2826. (minibuffer-with-setup-hook
  2827. (lambda ()
  2828. (shell-completion-vars)
  2829. (set (make-local-variable 'minibuffer-default-add-function)
  2830. 'minibuffer-default-add-shell-commands))
  2831. (apply 'read-from-minibuffer prompt initial-contents
  2832. minibuffer-local-shell-command-map
  2833. nil
  2834. (or hist 'shell-command-history)
  2835. args)))
  2836. (defcustom async-shell-command-buffer 'confirm-new-buffer
  2837. "What to do when the output buffer is used by another shell command.
  2838. This option specifies how to resolve the conflict where a new command
  2839. wants to direct its output to the buffer `*Async Shell Command*',
  2840. but this buffer is already taken by another running shell command.
  2841. The value `confirm-kill-process' is used to ask for confirmation before
  2842. killing the already running process and running a new process
  2843. in the same buffer, `confirm-new-buffer' for confirmation before running
  2844. the command in a new buffer with a name other than the default buffer name,
  2845. `new-buffer' for doing the same without confirmation,
  2846. `confirm-rename-buffer' for confirmation before renaming the existing
  2847. output buffer and running a new command in the default buffer,
  2848. `rename-buffer' for doing the same without confirmation."
  2849. :type '(choice (const :tag "Confirm killing of running command"
  2850. confirm-kill-process)
  2851. (const :tag "Confirm creation of a new buffer"
  2852. confirm-new-buffer)
  2853. (const :tag "Create a new buffer"
  2854. new-buffer)
  2855. (const :tag "Confirm renaming of existing buffer"
  2856. confirm-rename-buffer)
  2857. (const :tag "Rename the existing buffer"
  2858. rename-buffer))
  2859. :group 'shell
  2860. :version "24.3")
  2861. (defun async-shell-command (command &optional output-buffer error-buffer)
  2862. "Execute string COMMAND asynchronously in background.
  2863. Like `shell-command', but adds `&' at the end of COMMAND
  2864. to execute it asynchronously.
  2865. The output appears in the buffer `*Async Shell Command*'.
  2866. That buffer is in shell mode.
  2867. You can configure `async-shell-command-buffer' to specify what to do in
  2868. case when `*Async Shell Command*' buffer is already taken by another
  2869. running shell command. To run COMMAND without displaying the output
  2870. in a window you can configure `display-buffer-alist' to use the action
  2871. `display-buffer-no-window' for the buffer `*Async Shell Command*'.
  2872. In Elisp, you will often be better served by calling `start-process'
  2873. directly, since it offers more control and does not impose the use of a
  2874. shell (with its need to quote arguments)."
  2875. (interactive
  2876. (list
  2877. (read-shell-command "Async shell command: " nil nil
  2878. (let ((filename
  2879. (cond
  2880. (buffer-file-name)
  2881. ((eq major-mode 'dired-mode)
  2882. (dired-get-filename nil t)))))
  2883. (and filename (file-relative-name filename))))
  2884. current-prefix-arg
  2885. shell-command-default-error-buffer))
  2886. (unless (string-match "&[ \t]*\\'" command)
  2887. (setq command (concat command " &")))
  2888. (shell-command command output-buffer error-buffer))
  2889. (defun shell-command (command &optional output-buffer error-buffer)
  2890. "Execute string COMMAND in inferior shell; display output, if any.
  2891. With prefix argument, insert the COMMAND's output at point.
  2892. If COMMAND ends in `&', execute it asynchronously.
  2893. The output appears in the buffer `*Async Shell Command*'.
  2894. That buffer is in shell mode. You can also use
  2895. `async-shell-command' that automatically adds `&'.
  2896. Otherwise, COMMAND is executed synchronously. The output appears in
  2897. the buffer `*Shell Command Output*'. If the output is short enough to
  2898. display in the echo area (which is determined by the variables
  2899. `resize-mini-windows' and `max-mini-window-height'), it is shown
  2900. there, but it is nonetheless available in buffer `*Shell Command
  2901. Output*' even though that buffer is not automatically displayed.
  2902. To specify a coding system for converting non-ASCII characters
  2903. in the shell command output, use \\[universal-coding-system-argument] \
  2904. before this command.
  2905. Noninteractive callers can specify coding systems by binding
  2906. `coding-system-for-read' and `coding-system-for-write'.
  2907. The optional second argument OUTPUT-BUFFER, if non-nil,
  2908. says to put the output in some other buffer.
  2909. If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
  2910. If OUTPUT-BUFFER is not a buffer and not nil,
  2911. insert output in current buffer. (This cannot be done asynchronously.)
  2912. In either case, the buffer is first erased, and the output is
  2913. inserted after point (leaving mark after it).
  2914. If the command terminates without error, but generates output,
  2915. and you did not specify \"insert it in the current buffer\",
  2916. the output can be displayed in the echo area or in its buffer.
  2917. If the output is short enough to display in the echo area
  2918. \(determined by the variable `max-mini-window-height' if
  2919. `resize-mini-windows' is non-nil), it is shown there.
  2920. Otherwise,the buffer containing the output is displayed.
  2921. If there is output and an error, and you did not specify \"insert it
  2922. in the current buffer\", a message about the error goes at the end
  2923. of the output.
  2924. If there is no output, or if output is inserted in the current buffer,
  2925. then `*Shell Command Output*' is deleted.
  2926. If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
  2927. or buffer name to which to direct the command's standard error output.
  2928. If it is nil, error output is mingled with regular output.
  2929. In an interactive call, the variable `shell-command-default-error-buffer'
  2930. specifies the value of ERROR-BUFFER.
  2931. In Elisp, you will often be better served by calling `call-process' or
  2932. `start-process' directly, since it offers more control and does not impose
  2933. the use of a shell (with its need to quote arguments)."
  2934. (interactive
  2935. (list
  2936. (read-shell-command "Shell command: " nil nil
  2937. (let ((filename
  2938. (cond
  2939. (buffer-file-name)
  2940. ((eq major-mode 'dired-mode)
  2941. (dired-get-filename nil t)))))
  2942. (and filename (file-relative-name filename))))
  2943. current-prefix-arg
  2944. shell-command-default-error-buffer))
  2945. ;; Look for a handler in case default-directory is a remote file name.
  2946. (let ((handler
  2947. (find-file-name-handler (directory-file-name default-directory)
  2948. 'shell-command)))
  2949. (if handler
  2950. (funcall handler 'shell-command command output-buffer error-buffer)
  2951. (if (and output-buffer
  2952. (not (or (bufferp output-buffer) (stringp output-buffer))))
  2953. ;; Output goes in current buffer.
  2954. (let ((error-file
  2955. (if error-buffer
  2956. (make-temp-file
  2957. (expand-file-name "scor"
  2958. (or small-temporary-file-directory
  2959. temporary-file-directory)))
  2960. nil)))
  2961. (barf-if-buffer-read-only)
  2962. (push-mark nil t)
  2963. ;; We do not use -f for csh; we will not support broken use of
  2964. ;; .cshrcs. Even the BSD csh manual says to use
  2965. ;; "if ($?prompt) exit" before things which are not useful
  2966. ;; non-interactively. Besides, if someone wants their other
  2967. ;; aliases for shell commands then they can still have them.
  2968. (call-process shell-file-name nil
  2969. (if error-file
  2970. (list t error-file)
  2971. t)
  2972. nil shell-command-switch command)
  2973. (when (and error-file (file-exists-p error-file))
  2974. (if (< 0 (nth 7 (file-attributes error-file)))
  2975. (with-current-buffer (get-buffer-create error-buffer)
  2976. (let ((pos-from-end (- (point-max) (point))))
  2977. (or (bobp)
  2978. (insert "\f\n"))
  2979. ;; Do no formatting while reading error file,
  2980. ;; because that can run a shell command, and we
  2981. ;; don't want that to cause an infinite recursion.
  2982. (format-insert-file error-file nil)
  2983. ;; Put point after the inserted errors.
  2984. (goto-char (- (point-max) pos-from-end)))
  2985. (display-buffer (current-buffer))))
  2986. (delete-file error-file))
  2987. ;; This is like exchange-point-and-mark, but doesn't
  2988. ;; activate the mark. It is cleaner to avoid activation,
  2989. ;; even though the command loop would deactivate the mark
  2990. ;; because we inserted text.
  2991. (goto-char (prog1 (mark t)
  2992. (set-marker (mark-marker) (point)
  2993. (current-buffer)))))
  2994. ;; Output goes in a separate buffer.
  2995. ;; Preserve the match data in case called from a program.
  2996. (save-match-data
  2997. (if (string-match "[ \t]*&[ \t]*\\'" command)
  2998. ;; Command ending with ampersand means asynchronous.
  2999. (let ((buffer (get-buffer-create
  3000. (or output-buffer "*Async Shell Command*")))
  3001. (directory default-directory)
  3002. proc)
  3003. ;; Remove the ampersand.
  3004. (setq command (substring command 0 (match-beginning 0)))
  3005. ;; Ask the user what to do with already running process.
  3006. (setq proc (get-buffer-process buffer))
  3007. (when proc
  3008. (cond
  3009. ((eq async-shell-command-buffer 'confirm-kill-process)
  3010. ;; If will kill a process, query first.
  3011. (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
  3012. (kill-process proc)
  3013. (error "Shell command in progress")))
  3014. ((eq async-shell-command-buffer 'confirm-new-buffer)
  3015. ;; If will create a new buffer, query first.
  3016. (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
  3017. (setq buffer (generate-new-buffer
  3018. (or (and (bufferp output-buffer) (buffer-name output-buffer))
  3019. output-buffer "*Async Shell Command*")))
  3020. (error "Shell command in progress")))
  3021. ((eq async-shell-command-buffer 'new-buffer)
  3022. ;; It will create a new buffer.
  3023. (setq buffer (generate-new-buffer
  3024. (or (and (bufferp output-buffer) (buffer-name output-buffer))
  3025. output-buffer "*Async Shell Command*"))))
  3026. ((eq async-shell-command-buffer 'confirm-rename-buffer)
  3027. ;; If will rename the buffer, query first.
  3028. (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
  3029. (progn
  3030. (with-current-buffer buffer
  3031. (rename-uniquely))
  3032. (setq buffer (get-buffer-create
  3033. (or output-buffer "*Async Shell Command*"))))
  3034. (error "Shell command in progress")))
  3035. ((eq async-shell-command-buffer 'rename-buffer)
  3036. ;; It will rename the buffer.
  3037. (with-current-buffer buffer
  3038. (rename-uniquely))
  3039. (setq buffer (get-buffer-create
  3040. (or output-buffer "*Async Shell Command*"))))))
  3041. (with-current-buffer buffer
  3042. (setq buffer-read-only nil)
  3043. ;; Setting buffer-read-only to nil doesn't suffice
  3044. ;; if some text has a non-nil read-only property,
  3045. ;; which comint sometimes adds for prompts.
  3046. (let ((inhibit-read-only t))
  3047. (erase-buffer))
  3048. (display-buffer buffer '(nil (allow-no-window . t)))
  3049. (setq default-directory directory)
  3050. (setq proc (start-process "Shell" buffer shell-file-name
  3051. shell-command-switch command))
  3052. (setq mode-line-process '(":%s"))
  3053. (require 'shell) (shell-mode)
  3054. (set-process-sentinel proc 'shell-command-sentinel)
  3055. ;; Use the comint filter for proper handling of carriage motion
  3056. ;; (see `comint-inhibit-carriage-motion'),.
  3057. (set-process-filter proc 'comint-output-filter)
  3058. ))
  3059. ;; Otherwise, command is executed synchronously.
  3060. (shell-command-on-region (point) (point) command
  3061. output-buffer nil error-buffer)))))))
  3062. (defun display-message-or-buffer (message
  3063. &optional buffer-name not-this-window frame)
  3064. "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
  3065. MESSAGE may be either a string or a buffer.
  3066. A buffer is displayed using `display-buffer' if MESSAGE is too long for
  3067. the maximum height of the echo area, as defined by `max-mini-window-height'
  3068. if `resize-mini-windows' is non-nil.
  3069. Returns either the string shown in the echo area, or when a pop-up
  3070. buffer is used, the window used to display it.
  3071. If MESSAGE is a string, then the optional argument BUFFER-NAME is the
  3072. name of the buffer used to display it in the case where a pop-up buffer
  3073. is used, defaulting to `*Message*'. In the case where MESSAGE is a
  3074. string and it is displayed in the echo area, it is not specified whether
  3075. the contents are inserted into the buffer anyway.
  3076. Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
  3077. and only used if a buffer is displayed."
  3078. (cond ((and (stringp message) (not (string-match "\n" message)))
  3079. ;; Trivial case where we can use the echo area
  3080. (message "%s" message))
  3081. ((and (stringp message)
  3082. (= (string-match "\n" message) (1- (length message))))
  3083. ;; Trivial case where we can just remove single trailing newline
  3084. (message "%s" (substring message 0 (1- (length message)))))
  3085. (t
  3086. ;; General case
  3087. (with-current-buffer
  3088. (if (bufferp message)
  3089. message
  3090. (get-buffer-create (or buffer-name "*Message*")))
  3091. (unless (bufferp message)
  3092. (erase-buffer)
  3093. (insert message))
  3094. (let ((lines
  3095. (if (= (buffer-size) 0)
  3096. 0
  3097. (count-screen-lines nil nil nil (minibuffer-window)))))
  3098. (cond ((= lines 0))
  3099. ((and (or (<= lines 1)
  3100. (<= lines
  3101. (if resize-mini-windows
  3102. (cond ((floatp max-mini-window-height)
  3103. (* (frame-height)
  3104. max-mini-window-height))
  3105. ((integerp max-mini-window-height)
  3106. max-mini-window-height)
  3107. (t
  3108. 1))
  3109. 1)))
  3110. ;; Don't use the echo area if the output buffer is
  3111. ;; already displayed in the selected frame.
  3112. (not (get-buffer-window (current-buffer))))
  3113. ;; Echo area
  3114. (goto-char (point-max))
  3115. (when (bolp)
  3116. (backward-char 1))
  3117. (message "%s" (buffer-substring (point-min) (point))))
  3118. (t
  3119. ;; Buffer
  3120. (goto-char (point-min))
  3121. (display-buffer (current-buffer)
  3122. not-this-window frame))))))))
  3123. ;; We have a sentinel to prevent insertion of a termination message
  3124. ;; in the buffer itself.
  3125. (defun shell-command-sentinel (process signal)
  3126. (if (memq (process-status process) '(exit signal))
  3127. (message "%s: %s."
  3128. (car (cdr (cdr (process-command process))))
  3129. (substring signal 0 -1))))
  3130. (defun shell-command-on-region (start end command
  3131. &optional output-buffer replace
  3132. error-buffer display-error-buffer)
  3133. "Execute string COMMAND in inferior shell with region as input.
  3134. Normally display output (if any) in temp buffer `*Shell Command Output*';
  3135. Prefix arg means replace the region with it. Return the exit code of
  3136. COMMAND.
  3137. To specify a coding system for converting non-ASCII characters
  3138. in the input and output to the shell command, use \\[universal-coding-system-argument]
  3139. before this command. By default, the input (from the current buffer)
  3140. is encoded using coding-system specified by `process-coding-system-alist',
  3141. falling back to `default-process-coding-system' if no match for COMMAND
  3142. is found in `process-coding-system-alist'.
  3143. Noninteractive callers can specify coding systems by binding
  3144. `coding-system-for-read' and `coding-system-for-write'.
  3145. If the command generates output, the output may be displayed
  3146. in the echo area or in a buffer.
  3147. If the output is short enough to display in the echo area
  3148. \(determined by the variable `max-mini-window-height' if
  3149. `resize-mini-windows' is non-nil), it is shown there.
  3150. Otherwise it is displayed in the buffer `*Shell Command Output*'.
  3151. The output is available in that buffer in both cases.
  3152. If there is output and an error, a message about the error
  3153. appears at the end of the output. If there is no output, or if
  3154. output is inserted in the current buffer, the buffer `*Shell
  3155. Command Output*' is deleted.
  3156. Optional fourth arg OUTPUT-BUFFER specifies where to put the
  3157. command's output. If the value is a buffer or buffer name,
  3158. put the output there. If the value is nil, use the buffer
  3159. `*Shell Command Output*'. Any other value, excluding nil,
  3160. means to insert the output in the current buffer. In either case,
  3161. the output is inserted after point (leaving mark after it).
  3162. Optional fifth arg REPLACE, if non-nil, means to insert the
  3163. output in place of text from START to END, putting point and mark
  3164. around it.
  3165. Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
  3166. or buffer name to which to direct the command's standard error
  3167. output. If nil, error output is mingled with regular output.
  3168. When called interactively, `shell-command-default-error-buffer'
  3169. is used for ERROR-BUFFER.
  3170. Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
  3171. display the error buffer if there were any errors. When called
  3172. interactively, this is t."
  3173. (interactive (let (string)
  3174. (unless (mark)
  3175. (user-error "The mark is not set now, so there is no region"))
  3176. ;; Do this before calling region-beginning
  3177. ;; and region-end, in case subprocess output
  3178. ;; relocates them while we are in the minibuffer.
  3179. (setq string (read-shell-command "Shell command on region: "))
  3180. ;; call-interactively recognizes region-beginning and
  3181. ;; region-end specially, leaving them in the history.
  3182. (list (region-beginning) (region-end)
  3183. string
  3184. current-prefix-arg
  3185. current-prefix-arg
  3186. shell-command-default-error-buffer
  3187. t)))
  3188. (let ((error-file
  3189. (if error-buffer
  3190. (make-temp-file
  3191. (expand-file-name "scor"
  3192. (or small-temporary-file-directory
  3193. temporary-file-directory)))
  3194. nil))
  3195. exit-status)
  3196. (if (or replace
  3197. (and output-buffer
  3198. (not (or (bufferp output-buffer) (stringp output-buffer)))))
  3199. ;; Replace specified region with output from command.
  3200. (let ((swap (and replace (< start end))))
  3201. ;; Don't muck with mark unless REPLACE says we should.
  3202. (goto-char start)
  3203. (and replace (push-mark (point) 'nomsg))
  3204. (setq exit-status
  3205. (call-process-region start end shell-file-name replace
  3206. (if error-file
  3207. (list t error-file)
  3208. t)
  3209. nil shell-command-switch command))
  3210. ;; It is rude to delete a buffer which the command is not using.
  3211. ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
  3212. ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
  3213. ;; (kill-buffer shell-buffer)))
  3214. ;; Don't muck with mark unless REPLACE says we should.
  3215. (and replace swap (exchange-point-and-mark)))
  3216. ;; No prefix argument: put the output in a temp buffer,
  3217. ;; replacing its entire contents.
  3218. (let ((buffer (get-buffer-create
  3219. (or output-buffer "*Shell Command Output*"))))
  3220. (unwind-protect
  3221. (if (eq buffer (current-buffer))
  3222. ;; If the input is the same buffer as the output,
  3223. ;; delete everything but the specified region,
  3224. ;; then replace that region with the output.
  3225. (progn (setq buffer-read-only nil)
  3226. (delete-region (max start end) (point-max))
  3227. (delete-region (point-min) (min start end))
  3228. (setq exit-status
  3229. (call-process-region (point-min) (point-max)
  3230. shell-file-name t
  3231. (if error-file
  3232. (list t error-file)
  3233. t)
  3234. nil shell-command-switch
  3235. command)))
  3236. ;; Clear the output buffer, then run the command with
  3237. ;; output there.
  3238. (let ((directory default-directory))
  3239. (with-current-buffer buffer
  3240. (setq buffer-read-only nil)
  3241. (if (not output-buffer)
  3242. (setq default-directory directory))
  3243. (erase-buffer)))
  3244. (setq exit-status
  3245. (call-process-region start end shell-file-name nil
  3246. (if error-file
  3247. (list buffer error-file)
  3248. buffer)
  3249. nil shell-command-switch command)))
  3250. ;; Report the output.
  3251. (with-current-buffer buffer
  3252. (setq mode-line-process
  3253. (cond ((null exit-status)
  3254. " - Error")
  3255. ((stringp exit-status)
  3256. (format " - Signal [%s]" exit-status))
  3257. ((not (equal 0 exit-status))
  3258. (format " - Exit [%d]" exit-status)))))
  3259. (if (with-current-buffer buffer (> (point-max) (point-min)))
  3260. ;; There's some output, display it
  3261. (display-message-or-buffer buffer)
  3262. ;; No output; error?
  3263. (let ((output
  3264. (if (and error-file
  3265. (< 0 (nth 7 (file-attributes error-file))))
  3266. (format "some error output%s"
  3267. (if shell-command-default-error-buffer
  3268. (format " to the \"%s\" buffer"
  3269. shell-command-default-error-buffer)
  3270. ""))
  3271. "no output")))
  3272. (cond ((null exit-status)
  3273. (message "(Shell command failed with error)"))
  3274. ((equal 0 exit-status)
  3275. (message "(Shell command succeeded with %s)"
  3276. output))
  3277. ((stringp exit-status)
  3278. (message "(Shell command killed by signal %s)"
  3279. exit-status))
  3280. (t
  3281. (message "(Shell command failed with code %d and %s)"
  3282. exit-status output))))
  3283. ;; Don't kill: there might be useful info in the undo-log.
  3284. ;; (kill-buffer buffer)
  3285. ))))
  3286. (when (and error-file (file-exists-p error-file))
  3287. (if (< 0 (nth 7 (file-attributes error-file)))
  3288. (with-current-buffer (get-buffer-create error-buffer)
  3289. (let ((pos-from-end (- (point-max) (point))))
  3290. (or (bobp)
  3291. (insert "\f\n"))
  3292. ;; Do no formatting while reading error file,
  3293. ;; because that can run a shell command, and we
  3294. ;; don't want that to cause an infinite recursion.
  3295. (format-insert-file error-file nil)
  3296. ;; Put point after the inserted errors.
  3297. (goto-char (- (point-max) pos-from-end)))
  3298. (and display-error-buffer
  3299. (display-buffer (current-buffer)))))
  3300. (delete-file error-file))
  3301. exit-status))
  3302. (defun shell-command-to-string (command)
  3303. "Execute shell command COMMAND and return its output as a string."
  3304. (with-output-to-string
  3305. (with-current-buffer
  3306. standard-output
  3307. (process-file shell-file-name nil t nil shell-command-switch command))))
  3308. (defun process-file (program &optional infile buffer display &rest args)
  3309. "Process files synchronously in a separate process.
  3310. Similar to `call-process', but may invoke a file handler based on
  3311. `default-directory'. The current working directory of the
  3312. subprocess is `default-directory'.
  3313. File names in INFILE and BUFFER are handled normally, but file
  3314. names in ARGS should be relative to `default-directory', as they
  3315. are passed to the process verbatim. (This is a difference to
  3316. `call-process' which does not support file handlers for INFILE
  3317. and BUFFER.)
  3318. Some file handlers might not support all variants, for example
  3319. they might behave as if DISPLAY was nil, regardless of the actual
  3320. value passed."
  3321. (let ((fh (find-file-name-handler default-directory 'process-file))
  3322. lc stderr-file)
  3323. (unwind-protect
  3324. (if fh (apply fh 'process-file program infile buffer display args)
  3325. (when infile (setq lc (file-local-copy infile)))
  3326. (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
  3327. (make-temp-file "emacs")))
  3328. (prog1
  3329. (apply 'call-process program
  3330. (or lc infile)
  3331. (if stderr-file (list (car buffer) stderr-file) buffer)
  3332. display args)
  3333. (when stderr-file (copy-file stderr-file (cadr buffer) t))))
  3334. (when stderr-file (delete-file stderr-file))
  3335. (when lc (delete-file lc)))))
  3336. (defvar process-file-side-effects t
  3337. "Whether a call of `process-file' changes remote files.
  3338. By default, this variable is always set to t, meaning that a
  3339. call of `process-file' could potentially change any file on a
  3340. remote host. When set to nil, a file handler could optimize
  3341. its behavior with respect to remote file attribute caching.
  3342. You should only ever change this variable with a let-binding;
  3343. never with `setq'.")
  3344. (defun start-file-process (name buffer program &rest program-args)
  3345. "Start a program in a subprocess. Return the process object for it.
  3346. Similar to `start-process', but may invoke a file handler based on
  3347. `default-directory'. See Info node `(elisp)Magic File Names'.
  3348. This handler ought to run PROGRAM, perhaps on the local host,
  3349. perhaps on a remote host that corresponds to `default-directory'.
  3350. In the latter case, the local part of `default-directory' becomes
  3351. the working directory of the process.
  3352. PROGRAM and PROGRAM-ARGS might be file names. They are not
  3353. objects of file handler invocation. File handlers might not
  3354. support pty association, if PROGRAM is nil."
  3355. (let ((fh (find-file-name-handler default-directory 'start-file-process)))
  3356. (if fh (apply fh 'start-file-process name buffer program program-args)
  3357. (apply 'start-process name buffer program program-args))))
  3358. ;;;; Process menu
  3359. (defvar tabulated-list-format)
  3360. (defvar tabulated-list-entries)
  3361. (defvar tabulated-list-sort-key)
  3362. (declare-function tabulated-list-init-header "tabulated-list" ())
  3363. (declare-function tabulated-list-print "tabulated-list"
  3364. (&optional remember-pos update))
  3365. (defvar process-menu-query-only nil)
  3366. (defvar process-menu-mode-map
  3367. (let ((map (make-sparse-keymap)))
  3368. (define-key map [?d] 'process-menu-delete-process)
  3369. map))
  3370. (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
  3371. "Major mode for listing the processes called by Emacs."
  3372. (setq tabulated-list-format [("Process" 15 t)
  3373. ("Status" 7 t)
  3374. ("Buffer" 15 t)
  3375. ("TTY" 12 t)
  3376. ("Command" 0 t)])
  3377. (make-local-variable 'process-menu-query-only)
  3378. (setq tabulated-list-sort-key (cons "Process" nil))
  3379. (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
  3380. (tabulated-list-init-header))
  3381. (defun process-menu-delete-process ()
  3382. "Kill process at point in a `list-processes' buffer."
  3383. (interactive)
  3384. (delete-process (tabulated-list-get-id))
  3385. (revert-buffer))
  3386. (defun list-processes--refresh ()
  3387. "Recompute the list of processes for the Process List buffer.
  3388. Also, delete any process that is exited or signaled."
  3389. (setq tabulated-list-entries nil)
  3390. (dolist (p (process-list))
  3391. (cond ((memq (process-status p) '(exit signal closed))
  3392. (delete-process p))
  3393. ((or (not process-menu-query-only)
  3394. (process-query-on-exit-flag p))
  3395. (let* ((buf (process-buffer p))
  3396. (type (process-type p))
  3397. (name (process-name p))
  3398. (status (symbol-name (process-status p)))
  3399. (buf-label (if (buffer-live-p buf)
  3400. `(,(buffer-name buf)
  3401. face link
  3402. help-echo ,(format-message
  3403. "Visit buffer `%s'"
  3404. (buffer-name buf))
  3405. follow-link t
  3406. process-buffer ,buf
  3407. action process-menu-visit-buffer)
  3408. "--"))
  3409. (tty (or (process-tty-name p) "--"))
  3410. (cmd
  3411. (if (memq type '(network serial))
  3412. (let ((contact (process-contact p t)))
  3413. (if (eq type 'network)
  3414. (format "(%s %s)"
  3415. (if (plist-get contact :type)
  3416. "datagram"
  3417. "network")
  3418. (if (plist-get contact :server)
  3419. (format "server on %s"
  3420. (or
  3421. (plist-get contact :host)
  3422. (plist-get contact :local)))
  3423. (format "connection to %s"
  3424. (plist-get contact :host))))
  3425. (format "(serial port %s%s)"
  3426. (or (plist-get contact :port) "?")
  3427. (let ((speed (plist-get contact :speed)))
  3428. (if speed
  3429. (format " at %s b/s" speed)
  3430. "")))))
  3431. (mapconcat 'identity (process-command p) " "))))
  3432. (push (list p (vector name status buf-label tty cmd))
  3433. tabulated-list-entries))))))
  3434. (defun process-menu-visit-buffer (button)
  3435. (display-buffer (button-get button 'process-buffer)))
  3436. (defun list-processes (&optional query-only buffer)
  3437. "Display a list of all processes that are Emacs sub-processes.
  3438. If optional argument QUERY-ONLY is non-nil, only processes with
  3439. the query-on-exit flag set are listed.
  3440. Any process listed as exited or signaled is actually eliminated
  3441. after the listing is made.
  3442. Optional argument BUFFER specifies a buffer to use, instead of
  3443. \"*Process List*\".
  3444. The return value is always nil.
  3445. This function lists only processes that were launched by Emacs. To
  3446. see other processes running on the system, use `list-system-processes'."
  3447. (interactive)
  3448. (or (fboundp 'process-list)
  3449. (error "Asynchronous subprocesses are not supported on this system"))
  3450. (unless (bufferp buffer)
  3451. (setq buffer (get-buffer-create "*Process List*")))
  3452. (with-current-buffer buffer
  3453. (process-menu-mode)
  3454. (setq process-menu-query-only query-only)
  3455. (list-processes--refresh)
  3456. (tabulated-list-print))
  3457. (display-buffer buffer)
  3458. nil)
  3459. ;;;; Prefix commands
  3460. (setq prefix-command--needs-update nil)
  3461. (setq prefix-command--last-echo nil)
  3462. (defun internal-echo-keystrokes-prefix ()
  3463. ;; BEWARE: Called directly from the C code.
  3464. (if (not prefix-command--needs-update)
  3465. prefix-command--last-echo
  3466. (setq prefix-command--last-echo
  3467. (let ((strs nil))
  3468. (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
  3469. (lambda (fun) (push (funcall fun) strs)))
  3470. (setq strs (delq nil strs))
  3471. (when strs (mapconcat #'identity strs " "))))))
  3472. (defvar prefix-command-echo-keystrokes-functions nil
  3473. "Abnormal hook which constructs the description of the current prefix state.
  3474. Each function is called with no argument, should return a string or nil.")
  3475. (defun prefix-command-update ()
  3476. "Update state of prefix commands.
  3477. Call it whenever you change the \"prefix command state\"."
  3478. (setq prefix-command--needs-update t))
  3479. (defvar prefix-command-preserve-state-hook nil
  3480. "Normal hook run when a command needs to preserve the prefix.")
  3481. (defun prefix-command-preserve-state ()
  3482. "Pass the current prefix command state to the next command.
  3483. Should be called by all prefix commands.
  3484. Runs `prefix-command-preserve-state-hook'."
  3485. (run-hooks 'prefix-command-preserve-state-hook)
  3486. ;; If the current command is a prefix command, we don't want the next (real)
  3487. ;; command to have `last-command' set to, say, `universal-argument'.
  3488. (setq this-command last-command)
  3489. (setq real-this-command real-last-command)
  3490. (prefix-command-update))
  3491. (defun reset-this-command-lengths ()
  3492. (declare (obsolete prefix-command-preserve-state "25.1"))
  3493. nil)
  3494. ;;;;; The main prefix command.
  3495. ;; FIXME: Declaration of `prefix-arg' should be moved here!?
  3496. (add-hook 'prefix-command-echo-keystrokes-functions
  3497. #'universal-argument--description)
  3498. (defun universal-argument--description ()
  3499. (when prefix-arg
  3500. (concat "C-u"
  3501. (pcase prefix-arg
  3502. (`(-) " -")
  3503. (`(,(and (pred integerp) n))
  3504. (let ((str ""))
  3505. (while (and (> n 4) (= (mod n 4) 0))
  3506. (setq str (concat str " C-u"))
  3507. (setq n (/ n 4)))
  3508. (if (= n 4) str (format " %s" prefix-arg))))
  3509. (_ (format " %s" prefix-arg))))))
  3510. (add-hook 'prefix-command-preserve-state-hook
  3511. #'universal-argument--preserve)
  3512. (defun universal-argument--preserve ()
  3513. (setq prefix-arg current-prefix-arg))
  3514. (defvar universal-argument-map
  3515. (let ((map (make-sparse-keymap))
  3516. (universal-argument-minus
  3517. ;; For backward compatibility, minus with no modifiers is an ordinary
  3518. ;; command if digits have already been entered.
  3519. `(menu-item "" negative-argument
  3520. :filter ,(lambda (cmd)
  3521. (if (integerp prefix-arg) nil cmd)))))
  3522. (define-key map [switch-frame]
  3523. (lambda (e) (interactive "e")
  3524. (handle-switch-frame e) (universal-argument--mode)))
  3525. (define-key map [?\C-u] 'universal-argument-more)
  3526. (define-key map [?-] universal-argument-minus)
  3527. (define-key map [?0] 'digit-argument)
  3528. (define-key map [?1] 'digit-argument)
  3529. (define-key map [?2] 'digit-argument)
  3530. (define-key map [?3] 'digit-argument)
  3531. (define-key map [?4] 'digit-argument)
  3532. (define-key map [?5] 'digit-argument)
  3533. (define-key map [?6] 'digit-argument)
  3534. (define-key map [?7] 'digit-argument)
  3535. (define-key map [?8] 'digit-argument)
  3536. (define-key map [?9] 'digit-argument)
  3537. (define-key map [kp-0] 'digit-argument)
  3538. (define-key map [kp-1] 'digit-argument)
  3539. (define-key map [kp-2] 'digit-argument)
  3540. (define-key map [kp-3] 'digit-argument)
  3541. (define-key map [kp-4] 'digit-argument)
  3542. (define-key map [kp-5] 'digit-argument)
  3543. (define-key map [kp-6] 'digit-argument)
  3544. (define-key map [kp-7] 'digit-argument)
  3545. (define-key map [kp-8] 'digit-argument)
  3546. (define-key map [kp-9] 'digit-argument)
  3547. (define-key map [kp-subtract] universal-argument-minus)
  3548. map)
  3549. "Keymap used while processing \\[universal-argument].")
  3550. (defun universal-argument--mode ()
  3551. (prefix-command-update)
  3552. (set-transient-map universal-argument-map nil))
  3553. (defun universal-argument ()
  3554. "Begin a numeric argument for the following command.
  3555. Digits or minus sign following \\[universal-argument] make up the numeric argument.
  3556. \\[universal-argument] following the digits or minus sign ends the argument.
  3557. \\[universal-argument] without digits or minus sign provides 4 as argument.
  3558. Repeating \\[universal-argument] without digits or minus sign
  3559. multiplies the argument by 4 each time.
  3560. For some commands, just \\[universal-argument] by itself serves as a flag
  3561. which is different in effect from any particular numeric argument.
  3562. These commands include \\[set-mark-command] and \\[start-kbd-macro]."
  3563. (interactive)
  3564. (prefix-command-preserve-state)
  3565. (setq prefix-arg (list 4))
  3566. (universal-argument--mode))
  3567. (defun universal-argument-more (arg)
  3568. ;; A subsequent C-u means to multiply the factor by 4 if we've typed
  3569. ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
  3570. (interactive "P")
  3571. (prefix-command-preserve-state)
  3572. (setq prefix-arg (if (consp arg)
  3573. (list (* 4 (car arg)))
  3574. (if (eq arg '-)
  3575. (list -4)
  3576. arg)))
  3577. (when (consp prefix-arg) (universal-argument--mode)))
  3578. (defun negative-argument (arg)
  3579. "Begin a negative numeric argument for the next command.
  3580. \\[universal-argument] following digits or minus sign ends the argument."
  3581. (interactive "P")
  3582. (prefix-command-preserve-state)
  3583. (setq prefix-arg (cond ((integerp arg) (- arg))
  3584. ((eq arg '-) nil)
  3585. (t '-)))
  3586. (universal-argument--mode))
  3587. (defun digit-argument (arg)
  3588. "Part of the numeric argument for the next command.
  3589. \\[universal-argument] following digits or minus sign ends the argument."
  3590. (interactive "P")
  3591. (prefix-command-preserve-state)
  3592. (let* ((char (if (integerp last-command-event)
  3593. last-command-event
  3594. (get last-command-event 'ascii-character)))
  3595. (digit (- (logand char ?\177) ?0)))
  3596. (setq prefix-arg (cond ((integerp arg)
  3597. (+ (* arg 10)
  3598. (if (< arg 0) (- digit) digit)))
  3599. ((eq arg '-)
  3600. ;; Treat -0 as just -, so that -01 will work.
  3601. (if (zerop digit) '- (- digit)))
  3602. (t
  3603. digit))))
  3604. (universal-argument--mode))
  3605. (defvar filter-buffer-substring-functions nil
  3606. "This variable is a wrapper hook around `buffer-substring--filter'.")
  3607. (make-obsolete-variable 'filter-buffer-substring-functions
  3608. 'filter-buffer-substring-function "24.4")
  3609. (defvar filter-buffer-substring-function #'buffer-substring--filter
  3610. "Function to perform the filtering in `filter-buffer-substring'.
  3611. The function is called with the same 3 arguments (BEG END DELETE)
  3612. that `filter-buffer-substring' received. It should return the
  3613. buffer substring between BEG and END, after filtering. If DELETE is
  3614. non-nil, it should delete the text between BEG and END from the buffer.")
  3615. (defvar buffer-substring-filters nil
  3616. "List of filter functions for `buffer-substring--filter'.
  3617. Each function must accept a single argument, a string, and return a string.
  3618. The buffer substring is passed to the first function in the list,
  3619. and the return value of each function is passed to the next.
  3620. As a special convention, point is set to the start of the buffer text
  3621. being operated on (i.e., the first argument of `buffer-substring--filter')
  3622. before these functions are called.")
  3623. (make-obsolete-variable 'buffer-substring-filters
  3624. 'filter-buffer-substring-function "24.1")
  3625. (defun filter-buffer-substring (beg end &optional delete)
  3626. "Return the buffer substring between BEG and END, after filtering.
  3627. If DELETE is non-nil, delete the text between BEG and END from the buffer.
  3628. This calls the function that `filter-buffer-substring-function' specifies
  3629. \(passing the same three arguments that it received) to do the work,
  3630. and returns whatever it does. The default function does no filtering,
  3631. unless a hook has been set.
  3632. Use `filter-buffer-substring' instead of `buffer-substring',
  3633. `buffer-substring-no-properties', or `delete-and-extract-region' when
  3634. you want to allow filtering to take place. For example, major or minor
  3635. modes can use `filter-buffer-substring-function' to extract characters
  3636. that are special to a buffer, and should not be copied into other buffers."
  3637. (funcall filter-buffer-substring-function beg end delete))
  3638. (defun buffer-substring--filter (beg end &optional delete)
  3639. "Default function to use for `filter-buffer-substring-function'.
  3640. Its arguments and return value are as specified for `filter-buffer-substring'.
  3641. This respects the wrapper hook `filter-buffer-substring-functions',
  3642. and the abnormal hook `buffer-substring-filters'.
  3643. No filtering is done unless a hook says to."
  3644. (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
  3645. (cond
  3646. ((or delete buffer-substring-filters)
  3647. (save-excursion
  3648. (goto-char beg)
  3649. (let ((string (if delete (delete-and-extract-region beg end)
  3650. (buffer-substring beg end))))
  3651. (dolist (filter buffer-substring-filters)
  3652. (setq string (funcall filter string)))
  3653. string)))
  3654. (t
  3655. (buffer-substring beg end)))))
  3656. ;;;; Window system cut and paste hooks.
  3657. (defvar interprogram-cut-function #'gui-select-text
  3658. "Function to call to make a killed region available to other programs.
  3659. Most window systems provide a facility for cutting and pasting
  3660. text between different programs, such as the clipboard on X and
  3661. MS-Windows, or the pasteboard on Nextstep/Mac OS.
  3662. This variable holds a function that Emacs calls whenever text is
  3663. put in the kill ring, to make the new kill available to other
  3664. programs. The function takes one argument, TEXT, which is a
  3665. string containing the text which should be made available.")
  3666. (defvar interprogram-paste-function #'gui-selection-value
  3667. "Function to call to get text cut from other programs.
  3668. Most window systems provide a facility for cutting and pasting
  3669. text between different programs, such as the clipboard on X and
  3670. MS-Windows, or the pasteboard on Nextstep/Mac OS.
  3671. This variable holds a function that Emacs calls to obtain text
  3672. that other programs have provided for pasting. The function is
  3673. called with no arguments. If no other program has provided text
  3674. to paste, the function should return nil (in which case the
  3675. caller, usually `current-kill', should use the top of the Emacs
  3676. kill ring). If another program has provided text to paste, the
  3677. function should return that text as a string (in which case the
  3678. caller should put this string in the kill ring as the latest
  3679. kill).
  3680. The function may also return a list of strings if the window
  3681. system supports multiple selections. The first string will be
  3682. used as the pasted text, but the other will be placed in the kill
  3683. ring for easy access via `yank-pop'.
  3684. Note that the function should return a string only if a program
  3685. other than Emacs has provided a string for pasting; if Emacs
  3686. provided the most recent string, the function should return nil.
  3687. If it is difficult to tell whether Emacs or some other program
  3688. provided the current string, it is probably good enough to return
  3689. nil if the string is equal (according to `string=') to the last
  3690. text Emacs provided.")
  3691. ;;;; The kill ring data structure.
  3692. (defvar kill-ring nil
  3693. "List of killed text sequences.
  3694. Since the kill ring is supposed to interact nicely with cut-and-paste
  3695. facilities offered by window systems, use of this variable should
  3696. interact nicely with `interprogram-cut-function' and
  3697. `interprogram-paste-function'. The functions `kill-new',
  3698. `kill-append', and `current-kill' are supposed to implement this
  3699. interaction; you may want to use them instead of manipulating the kill
  3700. ring directly.")
  3701. (defcustom kill-ring-max 60
  3702. "Maximum length of kill ring before oldest elements are thrown away."
  3703. :type 'integer
  3704. :group 'killing)
  3705. (defvar kill-ring-yank-pointer nil
  3706. "The tail of the kill ring whose car is the last thing yanked.")
  3707. (defcustom save-interprogram-paste-before-kill nil
  3708. "Save clipboard strings into kill ring before replacing them.
  3709. When one selects something in another program to paste it into Emacs,
  3710. but kills something in Emacs before actually pasting it,
  3711. this selection is gone unless this variable is non-nil,
  3712. in which case the other program's selection is saved in the `kill-ring'
  3713. before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
  3714. :type 'boolean
  3715. :group 'killing
  3716. :version "23.2")
  3717. (defcustom kill-do-not-save-duplicates nil
  3718. "Do not add a new string to `kill-ring' if it duplicates the last one.
  3719. The comparison is done using `equal-including-properties'."
  3720. :type 'boolean
  3721. :group 'killing
  3722. :version "23.2")
  3723. (defun kill-new (string &optional replace)
  3724. "Make STRING the latest kill in the kill ring.
  3725. Set `kill-ring-yank-pointer' to point to it.
  3726. If `interprogram-cut-function' is non-nil, apply it to STRING.
  3727. Optional second argument REPLACE non-nil means that STRING will replace
  3728. the front of the kill ring, rather than being added to the list.
  3729. When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
  3730. are non-nil, saves the interprogram paste string(s) into `kill-ring' before
  3731. STRING.
  3732. When the yank handler has a non-nil PARAM element, the original STRING
  3733. argument is not used by `insert-for-yank'. However, since Lisp code
  3734. may access and use elements from the kill ring directly, the STRING
  3735. argument should still be a \"useful\" string for such uses."
  3736. (unless (and kill-do-not-save-duplicates
  3737. ;; Due to text properties such as 'yank-handler that
  3738. ;; can alter the contents to yank, comparison using
  3739. ;; `equal' is unsafe.
  3740. (equal-including-properties string (car kill-ring)))
  3741. (if (fboundp 'menu-bar-update-yank-menu)
  3742. (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
  3743. (when save-interprogram-paste-before-kill
  3744. (let ((interprogram-paste (and interprogram-paste-function
  3745. (funcall interprogram-paste-function))))
  3746. (when interprogram-paste
  3747. (dolist (s (if (listp interprogram-paste)
  3748. (nreverse interprogram-paste)
  3749. (list interprogram-paste)))
  3750. (unless (and kill-do-not-save-duplicates
  3751. (equal-including-properties s (car kill-ring)))
  3752. (push s kill-ring))))))
  3753. (unless (and kill-do-not-save-duplicates
  3754. (equal-including-properties string (car kill-ring)))
  3755. (if (and replace kill-ring)
  3756. (setcar kill-ring string)
  3757. (push string kill-ring)
  3758. (if (> (length kill-ring) kill-ring-max)
  3759. (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
  3760. (setq kill-ring-yank-pointer kill-ring)
  3761. (if interprogram-cut-function
  3762. (funcall interprogram-cut-function string)))
  3763. ;; It has been argued that this should work similar to `self-insert-command'
  3764. ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
  3765. (defcustom kill-append-merge-undo nil
  3766. "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
  3767. :type 'boolean
  3768. :group 'killing
  3769. :version "25.1")
  3770. (defun kill-append (string before-p)
  3771. "Append STRING to the end of the latest kill in the kill ring.
  3772. If BEFORE-P is non-nil, prepend STRING to the kill.
  3773. Also removes the last undo boundary in the current buffer,
  3774. depending on `kill-append-merge-undo'.
  3775. If `interprogram-cut-function' is set, pass the resulting kill to it."
  3776. (let* ((cur (car kill-ring)))
  3777. (kill-new (if before-p (concat string cur) (concat cur string))
  3778. (or (= (length cur) 0)
  3779. (equal nil (get-text-property 0 'yank-handler cur))))
  3780. (when (and kill-append-merge-undo (not buffer-read-only))
  3781. (let ((prev buffer-undo-list)
  3782. (next (cdr buffer-undo-list)))
  3783. ;; find the next undo boundary
  3784. (while (car next)
  3785. (pop next)
  3786. (pop prev))
  3787. ;; remove this undo boundary
  3788. (when prev
  3789. (setcdr prev (cdr next)))))))
  3790. (defcustom yank-pop-change-selection nil
  3791. "Whether rotating the kill ring changes the window system selection.
  3792. If non-nil, whenever the kill ring is rotated (usually via the
  3793. `yank-pop' command), Emacs also calls `interprogram-cut-function'
  3794. to copy the new kill to the window system selection."
  3795. :type 'boolean
  3796. :group 'killing
  3797. :version "23.1")
  3798. (defun current-kill (n &optional do-not-move)
  3799. "Rotate the yanking point by N places, and then return that kill.
  3800. If N is zero and `interprogram-paste-function' is set to a
  3801. function that returns a string or a list of strings, and if that
  3802. function doesn't return nil, then that string (or list) is added
  3803. to the front of the kill ring and the string (or first string in
  3804. the list) is returned as the latest kill.
  3805. If N is not zero, and if `yank-pop-change-selection' is
  3806. non-nil, use `interprogram-cut-function' to transfer the
  3807. kill at the new yank point into the window system selection.
  3808. If optional arg DO-NOT-MOVE is non-nil, then don't actually
  3809. move the yanking point; just return the Nth kill forward."
  3810. (let ((interprogram-paste (and (= n 0)
  3811. interprogram-paste-function
  3812. (funcall interprogram-paste-function))))
  3813. (if interprogram-paste
  3814. (progn
  3815. ;; Disable the interprogram cut function when we add the new
  3816. ;; text to the kill ring, so Emacs doesn't try to own the
  3817. ;; selection, with identical text.
  3818. (let ((interprogram-cut-function nil))
  3819. (if (listp interprogram-paste)
  3820. (mapc 'kill-new (nreverse interprogram-paste))
  3821. (kill-new interprogram-paste)))
  3822. (car kill-ring))
  3823. (or kill-ring (error "Kill ring is empty"))
  3824. (let ((ARGth-kill-element
  3825. (nthcdr (mod (- n (length kill-ring-yank-pointer))
  3826. (length kill-ring))
  3827. kill-ring)))
  3828. (unless do-not-move
  3829. (setq kill-ring-yank-pointer ARGth-kill-element)
  3830. (when (and yank-pop-change-selection
  3831. (> n 0)
  3832. interprogram-cut-function)
  3833. (funcall interprogram-cut-function (car ARGth-kill-element))))
  3834. (car ARGth-kill-element)))))
  3835. ;;;; Commands for manipulating the kill ring.
  3836. (defcustom kill-read-only-ok nil
  3837. "Non-nil means don't signal an error for killing read-only text."
  3838. :type 'boolean
  3839. :group 'killing)
  3840. (defun kill-region (beg end &optional region)
  3841. "Kill (\"cut\") text between point and mark.
  3842. This deletes the text from the buffer and saves it in the kill ring.
  3843. The command \\[yank] can retrieve it from there.
  3844. \(If you want to save the region without killing it, use \\[kill-ring-save].)
  3845. If you want to append the killed region to the last killed text,
  3846. use \\[append-next-kill] before \\[kill-region].
  3847. If the buffer is read-only, Emacs will beep and refrain from deleting
  3848. the text, but put the text in the kill ring anyway. This means that
  3849. you can use the killing commands to copy text from a read-only buffer.
  3850. Lisp programs should use this function for killing text.
  3851. (To delete text, use `delete-region'.)
  3852. Supply two arguments, character positions indicating the stretch of text
  3853. to be killed.
  3854. Any command that calls this function is a \"kill command\".
  3855. If the previous command was also a kill command,
  3856. the text killed this time appends to the text killed last time
  3857. to make one entry in the kill ring.
  3858. The optional argument REGION if non-nil, indicates that we're not just killing
  3859. some text between BEG and END, but we're killing the region."
  3860. ;; Pass mark first, then point, because the order matters when
  3861. ;; calling `kill-append'.
  3862. (interactive (list (mark) (point) 'region))
  3863. (unless (and beg end)
  3864. (user-error "The mark is not set now, so there is no region"))
  3865. (condition-case nil
  3866. (let ((string (if region
  3867. (funcall region-extract-function 'delete)
  3868. (filter-buffer-substring beg end 'delete))))
  3869. (when string ;STRING is nil if BEG = END
  3870. ;; Add that string to the kill ring, one way or another.
  3871. (if (eq last-command 'kill-region)
  3872. (kill-append string (< end beg))
  3873. (kill-new string)))
  3874. (when (or string (eq last-command 'kill-region))
  3875. (setq this-command 'kill-region))
  3876. (setq deactivate-mark t)
  3877. nil)
  3878. ((buffer-read-only text-read-only)
  3879. ;; The code above failed because the buffer, or some of the characters
  3880. ;; in the region, are read-only.
  3881. ;; We should beep, in case the user just isn't aware of this.
  3882. ;; However, there's no harm in putting
  3883. ;; the region's text in the kill ring, anyway.
  3884. (copy-region-as-kill beg end region)
  3885. ;; Set this-command now, so it will be set even if we get an error.
  3886. (setq this-command 'kill-region)
  3887. ;; This should barf, if appropriate, and give us the correct error.
  3888. (if kill-read-only-ok
  3889. (progn (message "Read only text copied to kill ring") nil)
  3890. ;; Signal an error if the buffer is read-only.
  3891. (barf-if-buffer-read-only)
  3892. ;; If the buffer isn't read-only, the text is.
  3893. (signal 'text-read-only (list (current-buffer)))))))
  3894. ;; copy-region-as-kill no longer sets this-command, because it's confusing
  3895. ;; to get two copies of the text when the user accidentally types M-w and
  3896. ;; then corrects it with the intended C-w.
  3897. (defun copy-region-as-kill (beg end &optional region)
  3898. "Save the region as if killed, but don't kill it.
  3899. In Transient Mark mode, deactivate the mark.
  3900. If `interprogram-cut-function' is non-nil, also save the text for a window
  3901. system cut and paste.
  3902. The optional argument REGION if non-nil, indicates that we're not just copying
  3903. some text between BEG and END, but we're copying the region.
  3904. This command's old key binding has been given to `kill-ring-save'."
  3905. ;; Pass mark first, then point, because the order matters when
  3906. ;; calling `kill-append'.
  3907. (interactive (list (mark) (point)
  3908. (prefix-numeric-value current-prefix-arg)))
  3909. (let ((str (if region
  3910. (funcall region-extract-function nil)
  3911. (filter-buffer-substring beg end))))
  3912. (if (eq last-command 'kill-region)
  3913. (kill-append str (< end beg))
  3914. (kill-new str)))
  3915. (setq deactivate-mark t)
  3916. nil)
  3917. (defun kill-ring-save (beg end &optional region)
  3918. "Save the region as if killed, but don't kill it.
  3919. In Transient Mark mode, deactivate the mark.
  3920. If `interprogram-cut-function' is non-nil, also save the text for a window
  3921. system cut and paste.
  3922. If you want to append the killed line to the last killed text,
  3923. use \\[append-next-kill] before \\[kill-ring-save].
  3924. The optional argument REGION if non-nil, indicates that we're not just copying
  3925. some text between BEG and END, but we're copying the region.
  3926. This command is similar to `copy-region-as-kill', except that it gives
  3927. visual feedback indicating the extent of the region being copied."
  3928. ;; Pass mark first, then point, because the order matters when
  3929. ;; calling `kill-append'.
  3930. (interactive (list (mark) (point)
  3931. (prefix-numeric-value current-prefix-arg)))
  3932. (copy-region-as-kill beg end region)
  3933. ;; This use of called-interactively-p is correct because the code it
  3934. ;; controls just gives the user visual feedback.
  3935. (if (called-interactively-p 'interactive)
  3936. (indicate-copied-region)))
  3937. (defun indicate-copied-region (&optional message-len)
  3938. "Indicate that the region text has been copied interactively.
  3939. If the mark is visible in the selected window, blink the cursor
  3940. between point and mark if there is currently no active region
  3941. highlighting.
  3942. If the mark lies outside the selected window, display an
  3943. informative message containing a sample of the copied text. The
  3944. optional argument MESSAGE-LEN, if non-nil, specifies the length
  3945. of this sample text; it defaults to 40."
  3946. (let ((mark (mark t))
  3947. (point (point))
  3948. ;; Inhibit quitting so we can make a quit here
  3949. ;; look like a C-g typed as a command.
  3950. (inhibit-quit t))
  3951. (if (pos-visible-in-window-p mark (selected-window))
  3952. ;; Swap point-and-mark quickly so as to show the region that
  3953. ;; was selected. Don't do it if the region is highlighted.
  3954. (unless (and (region-active-p)
  3955. (face-background 'region))
  3956. ;; Swap point and mark.
  3957. (set-marker (mark-marker) (point) (current-buffer))
  3958. (goto-char mark)
  3959. (sit-for blink-matching-delay)
  3960. ;; Swap back.
  3961. (set-marker (mark-marker) mark (current-buffer))
  3962. (goto-char point)
  3963. ;; If user quit, deactivate the mark
  3964. ;; as C-g would as a command.
  3965. (and quit-flag (region-active-p)
  3966. (deactivate-mark)))
  3967. (let ((len (min (abs (- mark point))
  3968. (or message-len 40))))
  3969. (if (< point mark)
  3970. ;; Don't say "killed"; that is misleading.
  3971. (message "Saved text until \"%s\""
  3972. (buffer-substring-no-properties (- mark len) mark))
  3973. (message "Saved text from \"%s\""
  3974. (buffer-substring-no-properties mark (+ mark len))))))))
  3975. (defun append-next-kill (&optional interactive)
  3976. "Cause following command, if it kills, to add to previous kill.
  3977. If the next command kills forward from point, the kill is
  3978. appended to the previous killed text. If the command kills
  3979. backward, the kill is prepended. Kill commands that act on the
  3980. region, such as `kill-region', are regarded as killing forward if
  3981. point is after mark, and killing backward if point is before
  3982. mark.
  3983. If the next command is not a kill command, `append-next-kill' has
  3984. no effect.
  3985. The argument is used for internal purposes; do not supply one."
  3986. (interactive "p")
  3987. ;; We don't use (interactive-p), since that breaks kbd macros.
  3988. (if interactive
  3989. (progn
  3990. (setq this-command 'kill-region)
  3991. (message "If the next command is a kill, it will append"))
  3992. (setq last-command 'kill-region)))
  3993. (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
  3994. "Character set that matches bidirectional formatting control characters.")
  3995. (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
  3996. "Character set that matches any character except bidirectional controls.")
  3997. (defun squeeze-bidi-context-1 (from to category replacement)
  3998. "A subroutine of `squeeze-bidi-context'.
  3999. FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
  4000. (let ((pt (copy-marker from))
  4001. (limit (copy-marker to))
  4002. (old-pt 0)
  4003. lim1)
  4004. (setq lim1 limit)
  4005. (goto-char pt)
  4006. (while (< pt limit)
  4007. (if (> pt old-pt)
  4008. (move-marker lim1
  4009. (save-excursion
  4010. ;; L and R categories include embedding and
  4011. ;; override controls, but we don't want to
  4012. ;; replace them, because that might change
  4013. ;; the visual order. Likewise with PDF and
  4014. ;; isolate controls.
  4015. (+ pt (skip-chars-forward
  4016. bidi-directional-non-controls-chars
  4017. limit)))))
  4018. ;; Replace any run of non-RTL characters by a single LRM.
  4019. (if (null (re-search-forward category lim1 t))
  4020. ;; No more characters of CATEGORY, we are done.
  4021. (setq pt limit)
  4022. (replace-match replacement nil t)
  4023. (move-marker pt (point)))
  4024. (setq old-pt pt)
  4025. ;; Skip directional controls, if any.
  4026. (move-marker
  4027. pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
  4028. (defun squeeze-bidi-context (from to)
  4029. "Replace characters between FROM and TO while keeping bidi context.
  4030. This function replaces the region of text with as few characters
  4031. as possible, while preserving the effect that region will have on
  4032. bidirectional display before and after the region."
  4033. (let ((start (set-marker (make-marker)
  4034. (if (> from 0) from (+ (point-max) from))))
  4035. (end (set-marker (make-marker) to))
  4036. ;; This is for when they copy text with read-only text
  4037. ;; properties.
  4038. (inhibit-read-only t))
  4039. (if (null (marker-position end))
  4040. (setq end (point-max-marker)))
  4041. ;; Replace each run of non-RTL characters with a single LRM.
  4042. (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
  4043. ;; Replace each run of non-LTR characters with a single RLM. Note
  4044. ;; that the \cR category includes both the Arabic Letter (AL) and
  4045. ;; R characters; here we ignore the distinction between them,
  4046. ;; because that distinction only affects Arabic Number (AN)
  4047. ;; characters, which are weak and don't affect the reordering.
  4048. (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
  4049. (defun line-substring-with-bidi-context (start end &optional no-properties)
  4050. "Return buffer text between START and END with its bidi context.
  4051. START and END are assumed to belong to the same physical line
  4052. of buffer text. This function prepends and appends to the text
  4053. between START and END bidi control characters that preserve the
  4054. visual order of that text when it is inserted at some other place."
  4055. (if (or (< start (point-min))
  4056. (> end (point-max)))
  4057. (signal 'args-out-of-range (list (current-buffer) start end)))
  4058. (let ((buf (current-buffer))
  4059. substr para-dir from to)
  4060. (save-excursion
  4061. (goto-char start)
  4062. (setq para-dir (current-bidi-paragraph-direction))
  4063. (setq from (line-beginning-position)
  4064. to (line-end-position))
  4065. (goto-char from)
  4066. ;; If we don't have any mixed directional characters in the
  4067. ;; entire line, we can just copy the substring without adding
  4068. ;; any context.
  4069. (if (or (looking-at-p "\\CR*$")
  4070. (looking-at-p "\\CL*$"))
  4071. (setq substr (if no-properties
  4072. (buffer-substring-no-properties start end)
  4073. (buffer-substring start end)))
  4074. (setq substr
  4075. (with-temp-buffer
  4076. (if no-properties
  4077. (insert-buffer-substring-no-properties buf from to)
  4078. (insert-buffer-substring buf from to))
  4079. (squeeze-bidi-context 1 (1+ (- start from)))
  4080. (squeeze-bidi-context (- end to) nil)
  4081. (buffer-substring 1 (point-max)))))
  4082. ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
  4083. ;; (1) force the string to have the same base embedding
  4084. ;; direction as the paragraph direction at the source, no matter
  4085. ;; what is the paragraph direction at destination; and (2) avoid
  4086. ;; affecting the visual order of the surrounding text at
  4087. ;; destination if there are characters of different
  4088. ;; directionality there.
  4089. (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
  4090. substr "\x2069"))))
  4091. (defun buffer-substring-with-bidi-context (start end &optional no-properties)
  4092. "Return portion of current buffer between START and END with bidi context.
  4093. This function works similar to `buffer-substring', but it prepends and
  4094. appends to the text bidi directional control characters necessary to
  4095. preserve the visual appearance of the text if it is inserted at another
  4096. place. This is useful when the buffer substring includes bidirectional
  4097. text and control characters that cause non-trivial reordering on display.
  4098. If copied verbatim, such text can have a very different visual appearance,
  4099. and can also change the visual appearance of the surrounding text at the
  4100. destination of the copy.
  4101. Optional argument NO-PROPERTIES, if non-nil, means copy the text without
  4102. the text properties."
  4103. (let (line-end substr)
  4104. (if (or (< start (point-min))
  4105. (> end (point-max)))
  4106. (signal 'args-out-of-range (list (current-buffer) start end)))
  4107. (save-excursion
  4108. (goto-char start)
  4109. (setq line-end (min end (line-end-position)))
  4110. (while (< start end)
  4111. (setq substr
  4112. (concat substr
  4113. (if substr "\n" "")
  4114. (line-substring-with-bidi-context start line-end
  4115. no-properties)))
  4116. (forward-line 1)
  4117. (setq start (point))
  4118. (setq line-end (min end (line-end-position))))
  4119. substr)))
  4120. ;; Yanking.
  4121. (defcustom yank-handled-properties
  4122. '((font-lock-face . yank-handle-font-lock-face-property)
  4123. (category . yank-handle-category-property))
  4124. "List of special text property handling conditions for yanking.
  4125. Each element should have the form (PROP . FUN), where PROP is a
  4126. property symbol and FUN is a function. When the `yank' command
  4127. inserts text into the buffer, it scans the inserted text for
  4128. stretches of text that have `eq' values of the text property
  4129. PROP; for each such stretch of text, FUN is called with three
  4130. arguments: the property's value in that text, and the start and
  4131. end positions of the text.
  4132. This is done prior to removing the properties specified by
  4133. `yank-excluded-properties'."
  4134. :group 'killing
  4135. :type '(repeat (cons (symbol :tag "property symbol")
  4136. function))
  4137. :version "24.3")
  4138. ;; This is actually used in subr.el but defcustom does not work there.
  4139. (defcustom yank-excluded-properties
  4140. '(category field follow-link fontified font-lock-face help-echo
  4141. intangible invisible keymap local-map mouse-face read-only
  4142. yank-handler)
  4143. "Text properties to discard when yanking.
  4144. The value should be a list of text properties to discard or t,
  4145. which means to discard all text properties.
  4146. See also `yank-handled-properties'."
  4147. :type '(choice (const :tag "All" t) (repeat symbol))
  4148. :group 'killing
  4149. :version "24.3")
  4150. (defvar yank-window-start nil)
  4151. (defvar yank-undo-function nil
  4152. "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
  4153. Function is called with two parameters, START and END corresponding to
  4154. the value of the mark and point; it is guaranteed that START <= END.
  4155. Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
  4156. (defun yank-pop (&optional arg)
  4157. "Replace just-yanked stretch of killed text with a different stretch.
  4158. This command is allowed only immediately after a `yank' or a `yank-pop'.
  4159. At such a time, the region contains a stretch of reinserted
  4160. previously-killed text. `yank-pop' deletes that text and inserts in its
  4161. place a different stretch of killed text.
  4162. With no argument, the previous kill is inserted.
  4163. With argument N, insert the Nth previous kill.
  4164. If N is negative, this is a more recent kill.
  4165. The sequence of kills wraps around, so that after the oldest one
  4166. comes the newest one.
  4167. When this command inserts killed text into the buffer, it honors
  4168. `yank-excluded-properties' and `yank-handler' as described in the
  4169. doc string for `insert-for-yank-1', which see."
  4170. (interactive "*p")
  4171. (if (not (eq last-command 'yank))
  4172. (user-error "Previous command was not a yank"))
  4173. (setq this-command 'yank)
  4174. (unless arg (setq arg 1))
  4175. (let ((inhibit-read-only t)
  4176. (before (< (point) (mark t))))
  4177. (if before
  4178. (funcall (or yank-undo-function 'delete-region) (point) (mark t))
  4179. (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
  4180. (setq yank-undo-function nil)
  4181. (set-marker (mark-marker) (point) (current-buffer))
  4182. (insert-for-yank (current-kill arg))
  4183. ;; Set the window start back where it was in the yank command,
  4184. ;; if possible.
  4185. (set-window-start (selected-window) yank-window-start t)
  4186. (if before
  4187. ;; This is like exchange-point-and-mark, but doesn't activate the mark.
  4188. ;; It is cleaner to avoid activation, even though the command
  4189. ;; loop would deactivate the mark because we inserted text.
  4190. (goto-char (prog1 (mark t)
  4191. (set-marker (mark-marker) (point) (current-buffer))))))
  4192. nil)
  4193. (defun yank (&optional arg)
  4194. "Reinsert (\"paste\") the last stretch of killed text.
  4195. More precisely, reinsert the most recent kill, which is the
  4196. stretch of killed text most recently killed OR yanked. Put point
  4197. at the end, and set mark at the beginning without activating it.
  4198. With just \\[universal-argument] as argument, put point at beginning, and mark at end.
  4199. With argument N, reinsert the Nth most recent kill.
  4200. When this command inserts text into the buffer, it honors the
  4201. `yank-handled-properties' and `yank-excluded-properties'
  4202. variables, and the `yank-handler' text property. See
  4203. `insert-for-yank-1' for details.
  4204. See also the command `yank-pop' (\\[yank-pop])."
  4205. (interactive "*P")
  4206. (setq yank-window-start (window-start))
  4207. ;; If we don't get all the way thru, make last-command indicate that
  4208. ;; for the following command.
  4209. (setq this-command t)
  4210. (push-mark (point))
  4211. (insert-for-yank (current-kill (cond
  4212. ((listp arg) 0)
  4213. ((eq arg '-) -2)
  4214. (t (1- arg)))))
  4215. (if (consp arg)
  4216. ;; This is like exchange-point-and-mark, but doesn't activate the mark.
  4217. ;; It is cleaner to avoid activation, even though the command
  4218. ;; loop would deactivate the mark because we inserted text.
  4219. (goto-char (prog1 (mark t)
  4220. (set-marker (mark-marker) (point) (current-buffer)))))
  4221. ;; If we do get all the way thru, make this-command indicate that.
  4222. (if (eq this-command t)
  4223. (setq this-command 'yank))
  4224. nil)
  4225. (defun rotate-yank-pointer (arg)
  4226. "Rotate the yanking point in the kill ring.
  4227. With ARG, rotate that many kills forward (or backward, if negative)."
  4228. (interactive "p")
  4229. (current-kill arg))
  4230. ;; Some kill commands.
  4231. ;; Internal subroutine of delete-char
  4232. (defun kill-forward-chars (arg)
  4233. (if (listp arg) (setq arg (car arg)))
  4234. (if (eq arg '-) (setq arg -1))
  4235. (kill-region (point) (+ (point) arg)))
  4236. ;; Internal subroutine of backward-delete-char
  4237. (defun kill-backward-chars (arg)
  4238. (if (listp arg) (setq arg (car arg)))
  4239. (if (eq arg '-) (setq arg -1))
  4240. (kill-region (point) (- (point) arg)))
  4241. (defcustom backward-delete-char-untabify-method 'untabify
  4242. "The method for untabifying when deleting backward.
  4243. Can be `untabify' -- turn a tab to many spaces, then delete one space;
  4244. `hungry' -- delete all whitespace, both tabs and spaces;
  4245. `all' -- delete all whitespace, including tabs, spaces and newlines;
  4246. nil -- just delete one character."
  4247. :type '(choice (const untabify) (const hungry) (const all) (const nil))
  4248. :version "20.3"
  4249. :group 'killing)
  4250. (defun backward-delete-char-untabify (arg &optional killp)
  4251. "Delete characters backward, changing tabs into spaces.
  4252. The exact behavior depends on `backward-delete-char-untabify-method'.
  4253. Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
  4254. Interactively, ARG is the prefix arg (default 1)
  4255. and KILLP is t if a prefix arg was specified."
  4256. (interactive "*p\nP")
  4257. (when (eq backward-delete-char-untabify-method 'untabify)
  4258. (let ((count arg))
  4259. (save-excursion
  4260. (while (and (> count 0) (not (bobp)))
  4261. (if (= (preceding-char) ?\t)
  4262. (let ((col (current-column)))
  4263. (forward-char -1)
  4264. (setq col (- col (current-column)))
  4265. (insert-char ?\s col)
  4266. (delete-char 1)))
  4267. (forward-char -1)
  4268. (setq count (1- count))))))
  4269. (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
  4270. ((eq backward-delete-char-untabify-method 'all)
  4271. " \t\n\r")))
  4272. (n (if skip
  4273. (let* ((oldpt (point))
  4274. (wh (- oldpt (save-excursion
  4275. (skip-chars-backward skip)
  4276. (constrain-to-field nil oldpt)))))
  4277. (+ arg (if (zerop wh) 0 (1- wh))))
  4278. arg)))
  4279. ;; Avoid warning about delete-backward-char
  4280. (with-no-warnings (delete-backward-char n killp))))
  4281. (defun zap-to-char (arg char)
  4282. "Kill up to and including ARGth occurrence of CHAR.
  4283. Case is ignored if `case-fold-search' is non-nil in the current buffer.
  4284. Goes backward if ARG is negative; error if CHAR not found."
  4285. (interactive (list (prefix-numeric-value current-prefix-arg)
  4286. (read-char "Zap to char: " t)))
  4287. ;; Avoid "obsolete" warnings for translation-table-for-input.
  4288. (with-no-warnings
  4289. (if (char-table-p translation-table-for-input)
  4290. (setq char (or (aref translation-table-for-input char) char))))
  4291. (kill-region (point) (progn
  4292. (search-forward (char-to-string char) nil nil arg)
  4293. (point))))
  4294. ;; kill-line and its subroutines.
  4295. (defcustom kill-whole-line nil
  4296. "If non-nil, `kill-line' with no arg at start of line kills the whole line."
  4297. :type 'boolean
  4298. :group 'killing)
  4299. (defun kill-line (&optional arg)
  4300. "Kill the rest of the current line; if no nonblanks there, kill thru newline.
  4301. With prefix argument ARG, kill that many lines from point.
  4302. Negative arguments kill lines backward.
  4303. With zero argument, kills the text before point on the current line.
  4304. When calling from a program, nil means \"no arg\",
  4305. a number counts as a prefix arg.
  4306. To kill a whole line, when point is not at the beginning, type \
  4307. \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
  4308. If `show-trailing-whitespace' is non-nil, this command will just
  4309. kill the rest of the current line, even if there are only
  4310. nonblanks there.
  4311. If option `kill-whole-line' is non-nil, then this command kills the whole line
  4312. including its terminating newline, when used at the beginning of a line
  4313. with no argument. As a consequence, you can always kill a whole line
  4314. by typing \\[move-beginning-of-line] \\[kill-line].
  4315. If you want to append the killed line to the last killed text,
  4316. use \\[append-next-kill] before \\[kill-line].
  4317. If the buffer is read-only, Emacs will beep and refrain from deleting
  4318. the line, but put the line in the kill ring anyway. This means that
  4319. you can use this command to copy text from a read-only buffer.
  4320. \(If the variable `kill-read-only-ok' is non-nil, then this won't
  4321. even beep.)"
  4322. (interactive "P")
  4323. (kill-region (point)
  4324. ;; It is better to move point to the other end of the kill
  4325. ;; before killing. That way, in a read-only buffer, point
  4326. ;; moves across the text that is copied to the kill ring.
  4327. ;; The choice has no effect on undo now that undo records
  4328. ;; the value of point from before the command was run.
  4329. (progn
  4330. (if arg
  4331. (forward-visible-line (prefix-numeric-value arg))
  4332. (if (eobp)
  4333. (signal 'end-of-buffer nil))
  4334. (let ((end
  4335. (save-excursion
  4336. (end-of-visible-line) (point))))
  4337. (if (or (save-excursion
  4338. ;; If trailing whitespace is visible,
  4339. ;; don't treat it as nothing.
  4340. (unless show-trailing-whitespace
  4341. (skip-chars-forward " \t" end))
  4342. (= (point) end))
  4343. (and kill-whole-line (bolp)))
  4344. (forward-visible-line 1)
  4345. (goto-char end))))
  4346. (point))))
  4347. (defun kill-whole-line (&optional arg)
  4348. "Kill current line.
  4349. With prefix ARG, kill that many lines starting from the current line.
  4350. If ARG is negative, kill backward. Also kill the preceding newline.
  4351. \(This is meant to make \\[repeat] work well with negative arguments.)
  4352. If ARG is zero, kill current line but exclude the trailing newline."
  4353. (interactive "p")
  4354. (or arg (setq arg 1))
  4355. (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
  4356. (signal 'end-of-buffer nil))
  4357. (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
  4358. (signal 'beginning-of-buffer nil))
  4359. (unless (eq last-command 'kill-region)
  4360. (kill-new "")
  4361. (setq last-command 'kill-region))
  4362. (cond ((zerop arg)
  4363. ;; We need to kill in two steps, because the previous command
  4364. ;; could have been a kill command, in which case the text
  4365. ;; before point needs to be prepended to the current kill
  4366. ;; ring entry and the text after point appended. Also, we
  4367. ;; need to use save-excursion to avoid copying the same text
  4368. ;; twice to the kill ring in read-only buffers.
  4369. (save-excursion
  4370. (kill-region (point) (progn (forward-visible-line 0) (point))))
  4371. (kill-region (point) (progn (end-of-visible-line) (point))))
  4372. ((< arg 0)
  4373. (save-excursion
  4374. (kill-region (point) (progn (end-of-visible-line) (point))))
  4375. (kill-region (point)
  4376. (progn (forward-visible-line (1+ arg))
  4377. (unless (bobp) (backward-char))
  4378. (point))))
  4379. (t
  4380. (save-excursion
  4381. (kill-region (point) (progn (forward-visible-line 0) (point))))
  4382. (kill-region (point)
  4383. (progn (forward-visible-line arg) (point))))))
  4384. (defun forward-visible-line (arg)
  4385. "Move forward by ARG lines, ignoring currently invisible newlines only.
  4386. If ARG is negative, move backward -ARG lines.
  4387. If ARG is zero, move to the beginning of the current line."
  4388. (condition-case nil
  4389. (if (> arg 0)
  4390. (progn
  4391. (while (> arg 0)
  4392. (or (zerop (forward-line 1))
  4393. (signal 'end-of-buffer nil))
  4394. ;; If the newline we just skipped is invisible,
  4395. ;; don't count it.
  4396. (let ((prop
  4397. (get-char-property (1- (point)) 'invisible)))
  4398. (if (if (eq buffer-invisibility-spec t)
  4399. prop
  4400. (or (memq prop buffer-invisibility-spec)
  4401. (assq prop buffer-invisibility-spec)))
  4402. (setq arg (1+ arg))))
  4403. (setq arg (1- arg)))
  4404. ;; If invisible text follows, and it is a number of complete lines,
  4405. ;; skip it.
  4406. (let ((opoint (point)))
  4407. (while (and (not (eobp))
  4408. (let ((prop
  4409. (get-char-property (point) 'invisible)))
  4410. (if (eq buffer-invisibility-spec t)
  4411. prop
  4412. (or (memq prop buffer-invisibility-spec)
  4413. (assq prop buffer-invisibility-spec)))))
  4414. (goto-char
  4415. (if (get-text-property (point) 'invisible)
  4416. (or (next-single-property-change (point) 'invisible)
  4417. (point-max))
  4418. (next-overlay-change (point)))))
  4419. (unless (bolp)
  4420. (goto-char opoint))))
  4421. (let ((first t))
  4422. (while (or first (<= arg 0))
  4423. (if first
  4424. (beginning-of-line)
  4425. (or (zerop (forward-line -1))
  4426. (signal 'beginning-of-buffer nil)))
  4427. ;; If the newline we just moved to is invisible,
  4428. ;; don't count it.
  4429. (unless (bobp)
  4430. (let ((prop
  4431. (get-char-property (1- (point)) 'invisible)))
  4432. (unless (if (eq buffer-invisibility-spec t)
  4433. prop
  4434. (or (memq prop buffer-invisibility-spec)
  4435. (assq prop buffer-invisibility-spec)))
  4436. (setq arg (1+ arg)))))
  4437. (setq first nil))
  4438. ;; If invisible text follows, and it is a number of complete lines,
  4439. ;; skip it.
  4440. (let ((opoint (point)))
  4441. (while (and (not (bobp))
  4442. (let ((prop
  4443. (get-char-property (1- (point)) 'invisible)))
  4444. (if (eq buffer-invisibility-spec t)
  4445. prop
  4446. (or (memq prop buffer-invisibility-spec)
  4447. (assq prop buffer-invisibility-spec)))))
  4448. (goto-char
  4449. (if (get-text-property (1- (point)) 'invisible)
  4450. (or (previous-single-property-change (point) 'invisible)
  4451. (point-min))
  4452. (previous-overlay-change (point)))))
  4453. (unless (bolp)
  4454. (goto-char opoint)))))
  4455. ((beginning-of-buffer end-of-buffer)
  4456. nil)))
  4457. (defun end-of-visible-line ()
  4458. "Move to end of current visible line."
  4459. (end-of-line)
  4460. ;; If the following character is currently invisible,
  4461. ;; skip all characters with that same `invisible' property value,
  4462. ;; then find the next newline.
  4463. (while (and (not (eobp))
  4464. (save-excursion
  4465. (skip-chars-forward "^\n")
  4466. (let ((prop
  4467. (get-char-property (point) 'invisible)))
  4468. (if (eq buffer-invisibility-spec t)
  4469. prop
  4470. (or (memq prop buffer-invisibility-spec)
  4471. (assq prop buffer-invisibility-spec))))))
  4472. (skip-chars-forward "^\n")
  4473. (if (get-text-property (point) 'invisible)
  4474. (goto-char (or (next-single-property-change (point) 'invisible)
  4475. (point-max)))
  4476. (goto-char (next-overlay-change (point))))
  4477. (end-of-line)))
  4478. (defun insert-buffer (buffer)
  4479. "Insert after point the contents of BUFFER.
  4480. Puts mark after the inserted text.
  4481. BUFFER may be a buffer or a buffer name."
  4482. (declare (interactive-only insert-buffer-substring))
  4483. (interactive
  4484. (list
  4485. (progn
  4486. (barf-if-buffer-read-only)
  4487. (read-buffer "Insert buffer: "
  4488. (if (eq (selected-window) (next-window))
  4489. (other-buffer (current-buffer))
  4490. (window-buffer (next-window)))
  4491. t))))
  4492. (push-mark
  4493. (save-excursion
  4494. (insert-buffer-substring (get-buffer buffer))
  4495. (point)))
  4496. nil)
  4497. (defun append-to-buffer (buffer start end)
  4498. "Append to specified buffer the text of the region.
  4499. It is inserted into that buffer before its point.
  4500. When calling from a program, give three arguments:
  4501. BUFFER (or buffer name), START and END.
  4502. START and END specify the portion of the current buffer to be copied."
  4503. (interactive
  4504. (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
  4505. (region-beginning) (region-end)))
  4506. (let* ((oldbuf (current-buffer))
  4507. (append-to (get-buffer-create buffer))
  4508. (windows (get-buffer-window-list append-to t t))
  4509. point)
  4510. (save-excursion
  4511. (with-current-buffer append-to
  4512. (setq point (point))
  4513. (barf-if-buffer-read-only)
  4514. (insert-buffer-substring oldbuf start end)
  4515. (dolist (window windows)
  4516. (when (= (window-point window) point)
  4517. (set-window-point window (point))))))))
  4518. (defun prepend-to-buffer (buffer start end)
  4519. "Prepend to specified buffer the text of the region.
  4520. It is inserted into that buffer after its point.
  4521. When calling from a program, give three arguments:
  4522. BUFFER (or buffer name), START and END.
  4523. START and END specify the portion of the current buffer to be copied."
  4524. (interactive "BPrepend to buffer: \nr")
  4525. (let ((oldbuf (current-buffer)))
  4526. (with-current-buffer (get-buffer-create buffer)
  4527. (barf-if-buffer-read-only)
  4528. (save-excursion
  4529. (insert-buffer-substring oldbuf start end)))))
  4530. (defun copy-to-buffer (buffer start end)
  4531. "Copy to specified buffer the text of the region.
  4532. It is inserted into that buffer, replacing existing text there.
  4533. When calling from a program, give three arguments:
  4534. BUFFER (or buffer name), START and END.
  4535. START and END specify the portion of the current buffer to be copied."
  4536. (interactive "BCopy to buffer: \nr")
  4537. (let ((oldbuf (current-buffer)))
  4538. (with-current-buffer (get-buffer-create buffer)
  4539. (barf-if-buffer-read-only)
  4540. (erase-buffer)
  4541. (save-excursion
  4542. (insert-buffer-substring oldbuf start end)))))
  4543. (define-error 'mark-inactive (purecopy "The mark is not active now"))
  4544. (defvar activate-mark-hook nil
  4545. "Hook run when the mark becomes active.
  4546. It is also run at the end of a command, if the mark is active and
  4547. it is possible that the region may have changed.")
  4548. (defvar deactivate-mark-hook nil
  4549. "Hook run when the mark becomes inactive.")
  4550. (defun mark (&optional force)
  4551. "Return this buffer's mark value as integer, or nil if never set.
  4552. In Transient Mark mode, this function signals an error if
  4553. the mark is not active. However, if `mark-even-if-inactive' is non-nil,
  4554. or the argument FORCE is non-nil, it disregards whether the mark
  4555. is active, and returns an integer or nil in the usual way.
  4556. If you are using this in an editing command, you are most likely making
  4557. a mistake; see the documentation of `set-mark'."
  4558. (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
  4559. (marker-position (mark-marker))
  4560. (signal 'mark-inactive nil)))
  4561. ;; Behind display-selections-p.
  4562. (defun deactivate-mark (&optional force)
  4563. "Deactivate the mark.
  4564. If Transient Mark mode is disabled, this function normally does
  4565. nothing; but if FORCE is non-nil, it deactivates the mark anyway.
  4566. Deactivating the mark sets `mark-active' to nil, updates the
  4567. primary selection according to `select-active-regions', and runs
  4568. `deactivate-mark-hook'.
  4569. If Transient Mark mode was temporarily enabled, reset the value
  4570. of the variable `transient-mark-mode'; if this causes Transient
  4571. Mark mode to be disabled, don't change `mark-active' to nil or
  4572. run `deactivate-mark-hook'."
  4573. (when (or (region-active-p) force)
  4574. (when (and (if (eq select-active-regions 'only)
  4575. (eq (car-safe transient-mark-mode) 'only)
  4576. select-active-regions)
  4577. (region-active-p)
  4578. (display-selections-p))
  4579. ;; The var `saved-region-selection', if non-nil, is the text in
  4580. ;; the region prior to the last command modifying the buffer.
  4581. ;; Set the selection to that, or to the current region.
  4582. (cond (saved-region-selection
  4583. (if (gui-backend-selection-owner-p 'PRIMARY)
  4584. (gui-set-selection 'PRIMARY saved-region-selection))
  4585. (setq saved-region-selection nil))
  4586. ;; If another program has acquired the selection, region
  4587. ;; deactivation should not clobber it (Bug#11772).
  4588. ((and (/= (region-beginning) (region-end))
  4589. (or (gui-backend-selection-owner-p 'PRIMARY)
  4590. (null (gui-backend-selection-exists-p 'PRIMARY))))
  4591. (gui-set-selection 'PRIMARY
  4592. (funcall region-extract-function nil)))))
  4593. (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
  4594. (cond
  4595. ((eq (car-safe transient-mark-mode) 'only)
  4596. (setq transient-mark-mode (cdr transient-mark-mode))
  4597. (if (eq transient-mark-mode (default-value 'transient-mark-mode))
  4598. (kill-local-variable 'transient-mark-mode)))
  4599. ((eq transient-mark-mode 'lambda)
  4600. (kill-local-variable 'transient-mark-mode)))
  4601. (setq mark-active nil)
  4602. (run-hooks 'deactivate-mark-hook)
  4603. (redisplay--update-region-highlight (selected-window))))
  4604. (defun activate-mark (&optional no-tmm)
  4605. "Activate the mark.
  4606. If NO-TMM is non-nil, leave `transient-mark-mode' alone."
  4607. (when (mark t)
  4608. (unless (region-active-p)
  4609. (force-mode-line-update) ;Refresh toolbar (bug#16382).
  4610. (setq mark-active t)
  4611. (unless (or transient-mark-mode no-tmm)
  4612. (setq-local transient-mark-mode 'lambda))
  4613. (run-hooks 'activate-mark-hook))))
  4614. (defun set-mark (pos)
  4615. "Set this buffer's mark to POS. Don't use this function!
  4616. That is to say, don't use this function unless you want
  4617. the user to see that the mark has moved, and you want the previous
  4618. mark position to be lost.
  4619. Normally, when a new mark is set, the old one should go on the stack.
  4620. This is why most applications should use `push-mark', not `set-mark'.
  4621. Novice Emacs Lisp programmers often try to use the mark for the wrong
  4622. purposes. The mark saves a location for the user's convenience.
  4623. Most editing commands should not alter the mark.
  4624. To remember a location for internal use in the Lisp program,
  4625. store it in a Lisp variable. Example:
  4626. (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
  4627. (if pos
  4628. (progn
  4629. (set-marker (mark-marker) pos (current-buffer))
  4630. (activate-mark 'no-tmm))
  4631. ;; Normally we never clear mark-active except in Transient Mark mode.
  4632. ;; But when we actually clear out the mark value too, we must
  4633. ;; clear mark-active in any mode.
  4634. (deactivate-mark t)
  4635. ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
  4636. ;; it should never be nil if the mark is nil.
  4637. (setq mark-active nil)
  4638. (set-marker (mark-marker) nil)))
  4639. (defun save-mark-and-excursion--save ()
  4640. (cons
  4641. (let ((mark (mark-marker)))
  4642. (and (marker-position mark) (copy-marker mark)))
  4643. mark-active))
  4644. (defun save-mark-and-excursion--restore (saved-mark-info)
  4645. (let ((saved-mark (car saved-mark-info))
  4646. (omark (marker-position (mark-marker)))
  4647. (nmark nil)
  4648. (saved-mark-active (cdr saved-mark-info)))
  4649. ;; Mark marker
  4650. (if (null saved-mark)
  4651. (set-marker (mark-marker) nil)
  4652. (setf nmark (marker-position saved-mark))
  4653. (set-marker (mark-marker) nmark)
  4654. (set-marker saved-mark nil))
  4655. ;; Mark active
  4656. (let ((cur-mark-active mark-active))
  4657. (setq mark-active saved-mark-active)
  4658. ;; If mark is active now, and either was not active or was at a
  4659. ;; different place, run the activate hook.
  4660. (if saved-mark-active
  4661. (when (or (not cur-mark-active)
  4662. (not (eq omark nmark)))
  4663. (run-hooks 'activate-mark-hook))
  4664. ;; If mark has ceased to be active, run deactivate hook.
  4665. (when cur-mark-active
  4666. (run-hooks 'deactivate-mark-hook))))))
  4667. (defmacro save-mark-and-excursion (&rest body)
  4668. "Like `save-excursion', but also save and restore the mark state.
  4669. This macro does what `save-excursion' did before Emacs 25.1."
  4670. (let ((saved-marker-sym (make-symbol "saved-marker")))
  4671. `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
  4672. (unwind-protect
  4673. (save-excursion ,@body)
  4674. (save-mark-and-excursion--restore ,saved-marker-sym)))))
  4675. (defcustom use-empty-active-region nil
  4676. "Whether \"region-aware\" commands should act on empty regions.
  4677. If nil, region-aware commands treat empty regions as inactive.
  4678. If non-nil, region-aware commands treat the region as active as
  4679. long as the mark is active, even if the region is empty.
  4680. Region-aware commands are those that act on the region if it is
  4681. active and Transient Mark mode is enabled, and on the text near
  4682. point otherwise."
  4683. :type 'boolean
  4684. :version "23.1"
  4685. :group 'editing-basics)
  4686. (defun use-region-p ()
  4687. "Return t if the region is active and it is appropriate to act on it.
  4688. This is used by commands that act specially on the region under
  4689. Transient Mark mode.
  4690. The return value is t if Transient Mark mode is enabled and the
  4691. mark is active; furthermore, if `use-empty-active-region' is nil,
  4692. the region must not be empty. Otherwise, the return value is nil.
  4693. For some commands, it may be appropriate to ignore the value of
  4694. `use-empty-active-region'; in that case, use `region-active-p'."
  4695. (and (region-active-p)
  4696. (or use-empty-active-region (> (region-end) (region-beginning)))))
  4697. (defun region-active-p ()
  4698. "Return non-nil if Transient Mark mode is enabled and the mark is active.
  4699. Some commands act specially on the region when Transient Mark
  4700. mode is enabled. Usually, such commands should use
  4701. `use-region-p' instead of this function, because `use-region-p'
  4702. also checks the value of `use-empty-active-region'."
  4703. (and transient-mark-mode mark-active
  4704. ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
  4705. ;; without the mark being set (e.g. bug#17324). We really should fix
  4706. ;; that problem, but in the mean time, let's make sure we don't say the
  4707. ;; region is active when there's no mark.
  4708. (progn (cl-assert (mark)) t)))
  4709. (defvar redisplay-unhighlight-region-function
  4710. (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
  4711. (defvar redisplay-highlight-region-function
  4712. (lambda (start end window rol)
  4713. (if (not (overlayp rol))
  4714. (let ((nrol (make-overlay start end)))
  4715. (funcall redisplay-unhighlight-region-function rol)
  4716. (overlay-put nrol 'window window)
  4717. (overlay-put nrol 'face 'region)
  4718. ;; Normal priority so that a large region doesn't hide all the
  4719. ;; overlays within it, but high secondary priority so that if it
  4720. ;; ends/starts in the middle of a small overlay, that small overlay
  4721. ;; won't hide the region's boundaries.
  4722. (overlay-put nrol 'priority '(nil . 100))
  4723. nrol)
  4724. (unless (and (eq (overlay-buffer rol) (current-buffer))
  4725. (eq (overlay-start rol) start)
  4726. (eq (overlay-end rol) end))
  4727. (move-overlay rol start end (current-buffer)))
  4728. rol)))
  4729. (defun redisplay--update-region-highlight (window)
  4730. (let ((rol (window-parameter window 'internal-region-overlay)))
  4731. (if (not (and (region-active-p)
  4732. (or highlight-nonselected-windows
  4733. (eq window (selected-window))
  4734. (and (window-minibuffer-p)
  4735. (eq window (minibuffer-selected-window))))))
  4736. (funcall redisplay-unhighlight-region-function rol)
  4737. (let* ((pt (window-point window))
  4738. (mark (mark))
  4739. (start (min pt mark))
  4740. (end (max pt mark))
  4741. (new
  4742. (funcall redisplay-highlight-region-function
  4743. start end window rol)))
  4744. (unless (equal new rol)
  4745. (set-window-parameter window 'internal-region-overlay
  4746. new))))))
  4747. (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
  4748. "Hook run just before redisplay.
  4749. It is called in each window that is to be redisplayed. It takes one argument,
  4750. which is the window that will be redisplayed. When run, the `current-buffer'
  4751. is set to the buffer displayed in that window.")
  4752. (defun redisplay--pre-redisplay-functions (windows)
  4753. (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
  4754. (if (null windows)
  4755. (with-current-buffer (window-buffer (selected-window))
  4756. (run-hook-with-args 'pre-redisplay-functions (selected-window)))
  4757. (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
  4758. (with-current-buffer (window-buffer win)
  4759. (run-hook-with-args 'pre-redisplay-functions win))))))
  4760. (add-function :before pre-redisplay-function
  4761. #'redisplay--pre-redisplay-functions)
  4762. (defvar-local mark-ring nil
  4763. "The list of former marks of the current buffer, most recent first.")
  4764. (put 'mark-ring 'permanent-local t)
  4765. (defcustom mark-ring-max 16
  4766. "Maximum size of mark ring. Start discarding off end if gets this big."
  4767. :type 'integer
  4768. :group 'editing-basics)
  4769. (defvar global-mark-ring nil
  4770. "The list of saved global marks, most recent first.")
  4771. (defcustom global-mark-ring-max 16
  4772. "Maximum size of global mark ring. \
  4773. Start discarding off end if gets this big."
  4774. :type 'integer
  4775. :group 'editing-basics)
  4776. (defun pop-to-mark-command ()
  4777. "Jump to mark, and pop a new position for mark off the ring.
  4778. \(Does not affect global mark ring)."
  4779. (interactive)
  4780. (if (null (mark t))
  4781. (user-error "No mark set in this buffer")
  4782. (if (= (point) (mark t))
  4783. (message "Mark popped"))
  4784. (goto-char (mark t))
  4785. (pop-mark)))
  4786. (defun push-mark-command (arg &optional nomsg)
  4787. "Set mark at where point is.
  4788. If no prefix ARG and mark is already set there, just activate it.
  4789. Display `Mark set' unless the optional second arg NOMSG is non-nil."
  4790. (interactive "P")
  4791. (let ((mark (mark t)))
  4792. (if (or arg (null mark) (/= mark (point)))
  4793. (push-mark nil nomsg t)
  4794. (activate-mark 'no-tmm)
  4795. (unless nomsg
  4796. (message "Mark activated")))))
  4797. (defcustom set-mark-command-repeat-pop nil
  4798. "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
  4799. That means that C-u \\[set-mark-command] \\[set-mark-command]
  4800. will pop the mark twice, and
  4801. C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
  4802. will pop the mark three times.
  4803. A value of nil means \\[set-mark-command]'s behavior does not change
  4804. after C-u \\[set-mark-command]."
  4805. :type 'boolean
  4806. :group 'editing-basics)
  4807. (defun set-mark-command (arg)
  4808. "Set the mark where point is, or jump to the mark.
  4809. Setting the mark also alters the region, which is the text
  4810. between point and mark; this is the closest equivalent in
  4811. Emacs to what some editors call the \"selection\".
  4812. With no prefix argument, set the mark at point, and push the
  4813. old mark position on local mark ring. Also push the old mark on
  4814. global mark ring, if the previous mark was set in another buffer.
  4815. When Transient Mark Mode is off, immediately repeating this
  4816. command activates `transient-mark-mode' temporarily.
  4817. With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
  4818. jump to the mark, and set the mark from
  4819. position popped off the local mark ring (this does not affect the global
  4820. mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
  4821. mark ring (see `pop-global-mark').
  4822. If `set-mark-command-repeat-pop' is non-nil, repeating
  4823. the \\[set-mark-command] command with no prefix argument pops the next position
  4824. off the local (or global) mark ring and jumps there.
  4825. With \\[universal-argument] \\[universal-argument] as prefix
  4826. argument, unconditionally set mark where point is, even if
  4827. `set-mark-command-repeat-pop' is non-nil.
  4828. Novice Emacs Lisp programmers often try to use the mark for the wrong
  4829. purposes. See the documentation of `set-mark' for more information."
  4830. (interactive "P")
  4831. (cond ((eq transient-mark-mode 'lambda)
  4832. (kill-local-variable 'transient-mark-mode))
  4833. ((eq (car-safe transient-mark-mode) 'only)
  4834. (deactivate-mark)))
  4835. (cond
  4836. ((and (consp arg) (> (prefix-numeric-value arg) 4))
  4837. (push-mark-command nil))
  4838. ((not (eq this-command 'set-mark-command))
  4839. (if arg
  4840. (pop-to-mark-command)
  4841. (push-mark-command t)))
  4842. ((and set-mark-command-repeat-pop
  4843. (eq last-command 'pop-global-mark)
  4844. (not arg))
  4845. (setq this-command 'pop-global-mark)
  4846. (pop-global-mark))
  4847. ((or (and set-mark-command-repeat-pop
  4848. (eq last-command 'pop-to-mark-command))
  4849. arg)
  4850. (setq this-command 'pop-to-mark-command)
  4851. (pop-to-mark-command))
  4852. ((eq last-command 'set-mark-command)
  4853. (if (region-active-p)
  4854. (progn
  4855. (deactivate-mark)
  4856. (message "Mark deactivated"))
  4857. (activate-mark)
  4858. (message "Mark activated")))
  4859. (t
  4860. (push-mark-command nil))))
  4861. (defun push-mark (&optional location nomsg activate)
  4862. "Set mark at LOCATION (point, by default) and push old mark on mark ring.
  4863. If the last global mark pushed was not in the current buffer,
  4864. also push LOCATION on the global mark ring.
  4865. Display `Mark set' unless the optional second arg NOMSG is non-nil.
  4866. Novice Emacs Lisp programmers often try to use the mark for the wrong
  4867. purposes. See the documentation of `set-mark' for more information.
  4868. In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
  4869. (unless (null (mark t))
  4870. (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
  4871. (when (> (length mark-ring) mark-ring-max)
  4872. (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
  4873. (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
  4874. (set-marker (mark-marker) (or location (point)) (current-buffer))
  4875. ;; Now push the mark on the global mark ring.
  4876. (if (and global-mark-ring
  4877. (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
  4878. ;; The last global mark pushed was in this same buffer.
  4879. ;; Don't push another one.
  4880. nil
  4881. (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
  4882. (when (> (length global-mark-ring) global-mark-ring-max)
  4883. (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
  4884. (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
  4885. (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
  4886. (message "Mark set"))
  4887. (if (or activate (not transient-mark-mode))
  4888. (set-mark (mark t)))
  4889. nil)
  4890. (defun pop-mark ()
  4891. "Pop off mark ring into the buffer's actual mark.
  4892. Does not set point. Does nothing if mark ring is empty."
  4893. (when mark-ring
  4894. (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
  4895. (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
  4896. (move-marker (car mark-ring) nil)
  4897. (if (null (mark t)) (ding))
  4898. (setq mark-ring (cdr mark-ring)))
  4899. (deactivate-mark))
  4900. (define-obsolete-function-alias
  4901. 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
  4902. (defun exchange-point-and-mark (&optional arg)
  4903. "Put the mark where point is now, and point where the mark is now.
  4904. This command works even when the mark is not active,
  4905. and it reactivates the mark.
  4906. If Transient Mark mode is on, a prefix ARG deactivates the mark
  4907. if it is active, and otherwise avoids reactivating it. If
  4908. Transient Mark mode is off, a prefix ARG enables Transient Mark
  4909. mode temporarily."
  4910. (interactive "P")
  4911. (let ((omark (mark t))
  4912. (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
  4913. (if (null omark)
  4914. (user-error "No mark set in this buffer"))
  4915. (set-mark (point))
  4916. (goto-char omark)
  4917. (cond (temp-highlight
  4918. (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
  4919. ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
  4920. (not (or arg (region-active-p))))
  4921. (deactivate-mark))
  4922. (t (activate-mark)))
  4923. nil))
  4924. (defcustom shift-select-mode t
  4925. "When non-nil, shifted motion keys activate the mark momentarily.
  4926. While the mark is activated in this way, any shift-translated point
  4927. motion key extends the region, and if Transient Mark mode was off, it
  4928. is temporarily turned on. Furthermore, the mark will be deactivated
  4929. by any subsequent point motion key that was not shift-translated, or
  4930. by any action that normally deactivates the mark in Transient Mark mode.
  4931. See `this-command-keys-shift-translated' for the meaning of
  4932. shift-translation."
  4933. :type 'boolean
  4934. :group 'editing-basics)
  4935. (defun handle-shift-selection ()
  4936. "Activate/deactivate mark depending on invocation thru shift translation.
  4937. This function is called by `call-interactively' when a command
  4938. with a `^' character in its `interactive' spec is invoked, before
  4939. running the command itself.
  4940. If `shift-select-mode' is enabled and the command was invoked
  4941. through shift translation, set the mark and activate the region
  4942. temporarily, unless it was already set in this way. See
  4943. `this-command-keys-shift-translated' for the meaning of shift
  4944. translation.
  4945. Otherwise, if the region has been activated temporarily,
  4946. deactivate it, and restore the variable `transient-mark-mode' to
  4947. its earlier value."
  4948. (cond ((and shift-select-mode this-command-keys-shift-translated)
  4949. (unless (and mark-active
  4950. (eq (car-safe transient-mark-mode) 'only))
  4951. (setq-local transient-mark-mode
  4952. (cons 'only
  4953. (unless (eq transient-mark-mode 'lambda)
  4954. transient-mark-mode)))
  4955. (push-mark nil nil t)))
  4956. ((eq (car-safe transient-mark-mode) 'only)
  4957. (setq transient-mark-mode (cdr transient-mark-mode))
  4958. (if (eq transient-mark-mode (default-value 'transient-mark-mode))
  4959. (kill-local-variable 'transient-mark-mode))
  4960. (deactivate-mark))))
  4961. (define-minor-mode transient-mark-mode
  4962. "Toggle Transient Mark mode.
  4963. With a prefix argument ARG, enable Transient Mark mode if ARG is
  4964. positive, and disable it otherwise. If called from Lisp, enable
  4965. Transient Mark mode if ARG is omitted or nil.
  4966. Transient Mark mode is a global minor mode. When enabled, the
  4967. region is highlighted with the `region' face whenever the mark
  4968. is active. The mark is \"deactivated\" by changing the buffer,
  4969. and after certain other operations that set the mark but whose
  4970. main purpose is something else--for example, incremental search,
  4971. \\[beginning-of-buffer], and \\[end-of-buffer].
  4972. You can also deactivate the mark by typing \\[keyboard-quit] or
  4973. \\[keyboard-escape-quit].
  4974. Many commands change their behavior when Transient Mark mode is
  4975. in effect and the mark is active, by acting on the region instead
  4976. of their usual default part of the buffer's text. Examples of
  4977. such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
  4978. \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
  4979. To see the documentation of commands which are sensitive to the
  4980. Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
  4981. or \"mark.*active\" at the prompt."
  4982. :global t
  4983. ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
  4984. :variable (default-value 'transient-mark-mode))
  4985. (defvar widen-automatically t
  4986. "Non-nil means it is ok for commands to call `widen' when they want to.
  4987. Some commands will do this in order to go to positions outside
  4988. the current accessible part of the buffer.
  4989. If `widen-automatically' is nil, these commands will do something else
  4990. as a fallback, and won't change the buffer bounds.")
  4991. (defvar non-essential nil
  4992. "Whether the currently executing code is performing an essential task.
  4993. This variable should be non-nil only when running code which should not
  4994. disturb the user. E.g. it can be used to prevent Tramp from prompting the
  4995. user for a password when we are simply scanning a set of files in the
  4996. background or displaying possible completions before the user even asked
  4997. for it.")
  4998. (defun pop-global-mark ()
  4999. "Pop off global mark ring and jump to the top location."
  5000. (interactive)
  5001. ;; Pop entries which refer to non-existent buffers.
  5002. (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
  5003. (setq global-mark-ring (cdr global-mark-ring)))
  5004. (or global-mark-ring
  5005. (error "No global mark set"))
  5006. (let* ((marker (car global-mark-ring))
  5007. (buffer (marker-buffer marker))
  5008. (position (marker-position marker)))
  5009. (setq global-mark-ring (nconc (cdr global-mark-ring)
  5010. (list (car global-mark-ring))))
  5011. (set-buffer buffer)
  5012. (or (and (>= position (point-min))
  5013. (<= position (point-max)))
  5014. (if widen-automatically
  5015. (widen)
  5016. (error "Global mark position is outside accessible part of buffer")))
  5017. (goto-char position)
  5018. (switch-to-buffer buffer)))
  5019. (defcustom next-line-add-newlines nil
  5020. "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
  5021. :type 'boolean
  5022. :version "21.1"
  5023. :group 'editing-basics)
  5024. (defun next-line (&optional arg try-vscroll)
  5025. "Move cursor vertically down ARG lines.
  5026. Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
  5027. Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
  5028. lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
  5029. function will not vscroll.
  5030. ARG defaults to 1.
  5031. If there is no character in the target line exactly under the current column,
  5032. the cursor is positioned after the character in that line which spans this
  5033. column, or at the end of the line if it is not long enough.
  5034. If there is no line in the buffer after this one, behavior depends on the
  5035. value of `next-line-add-newlines'. If non-nil, it inserts a newline character
  5036. to create a line, and moves the cursor to that line. Otherwise it moves the
  5037. cursor to the end of the buffer.
  5038. If the variable `line-move-visual' is non-nil, this command moves
  5039. by display lines. Otherwise, it moves by buffer lines, without
  5040. taking variable-width characters or continued lines into account.
  5041. The command \\[set-goal-column] can be used to create
  5042. a semipermanent goal column for this command.
  5043. Then instead of trying to move exactly vertically (or as close as possible),
  5044. this command moves to the specified goal column (or as close as possible).
  5045. The goal column is stored in the variable `goal-column', which is nil
  5046. when there is no goal column. Note that setting `goal-column'
  5047. overrides `line-move-visual' and causes this command to move by buffer
  5048. lines rather than by display lines."
  5049. (declare (interactive-only forward-line))
  5050. (interactive "^p\np")
  5051. (or arg (setq arg 1))
  5052. (if (and next-line-add-newlines (= arg 1))
  5053. (if (save-excursion (end-of-line) (eobp))
  5054. ;; When adding a newline, don't expand an abbrev.
  5055. (let ((abbrev-mode nil))
  5056. (end-of-line)
  5057. (insert (if use-hard-newlines hard-newline "\n")))
  5058. (line-move arg nil nil try-vscroll))
  5059. (if (called-interactively-p 'interactive)
  5060. (condition-case err
  5061. (line-move arg nil nil try-vscroll)
  5062. ((beginning-of-buffer end-of-buffer)
  5063. (signal (car err) (cdr err))))
  5064. (line-move arg nil nil try-vscroll)))
  5065. nil)
  5066. (defun previous-line (&optional arg try-vscroll)
  5067. "Move cursor vertically up ARG lines.
  5068. Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
  5069. Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
  5070. lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
  5071. function will not vscroll.
  5072. ARG defaults to 1.
  5073. If there is no character in the target line exactly over the current column,
  5074. the cursor is positioned after the character in that line which spans this
  5075. column, or at the end of the line if it is not long enough.
  5076. If the variable `line-move-visual' is non-nil, this command moves
  5077. by display lines. Otherwise, it moves by buffer lines, without
  5078. taking variable-width characters or continued lines into account.
  5079. The command \\[set-goal-column] can be used to create
  5080. a semipermanent goal column for this command.
  5081. Then instead of trying to move exactly vertically (or as close as possible),
  5082. this command moves to the specified goal column (or as close as possible).
  5083. The goal column is stored in the variable `goal-column', which is nil
  5084. when there is no goal column. Note that setting `goal-column'
  5085. overrides `line-move-visual' and causes this command to move by buffer
  5086. lines rather than by display lines."
  5087. (declare (interactive-only
  5088. "use `forward-line' with negative argument instead."))
  5089. (interactive "^p\np")
  5090. (or arg (setq arg 1))
  5091. (if (called-interactively-p 'interactive)
  5092. (condition-case err
  5093. (line-move (- arg) nil nil try-vscroll)
  5094. ((beginning-of-buffer end-of-buffer)
  5095. (signal (car err) (cdr err))))
  5096. (line-move (- arg) nil nil try-vscroll))
  5097. nil)
  5098. (defcustom track-eol nil
  5099. "Non-nil means vertical motion starting at end of line keeps to ends of lines.
  5100. This means moving to the end of each line moved onto.
  5101. The beginning of a blank line does not count as the end of a line.
  5102. This has no effect when the variable `line-move-visual' is non-nil."
  5103. :type 'boolean
  5104. :group 'editing-basics)
  5105. (defcustom goal-column nil
  5106. "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
  5107. A non-nil setting overrides the variable `line-move-visual', which see."
  5108. :type '(choice integer
  5109. (const :tag "None" nil))
  5110. :group 'editing-basics)
  5111. (make-variable-buffer-local 'goal-column)
  5112. (defvar temporary-goal-column 0
  5113. "Current goal column for vertical motion.
  5114. It is the column where point was at the start of the current run
  5115. of vertical motion commands.
  5116. When moving by visual lines via the function `line-move-visual', it is a cons
  5117. cell (COL . HSCROLL), where COL is the x-position, in pixels,
  5118. divided by the default column width, and HSCROLL is the number of
  5119. columns by which window is scrolled from left margin.
  5120. When the `track-eol' feature is doing its job, the value is
  5121. `most-positive-fixnum'.")
  5122. (defcustom line-move-ignore-invisible t
  5123. "Non-nil means commands that move by lines ignore invisible newlines.
  5124. When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
  5125. as if newlines that are invisible didn't exist, and count
  5126. only visible newlines. Thus, moving across across 2 newlines
  5127. one of which is invisible will be counted as a one-line move.
  5128. Also, a non-nil value causes invisible text to be ignored when
  5129. counting columns for the purposes of keeping point in the same
  5130. column by \\[next-line] and \\[previous-line].
  5131. Outline mode sets this."
  5132. :type 'boolean
  5133. :group 'editing-basics)
  5134. (defcustom line-move-visual t
  5135. "When non-nil, `line-move' moves point by visual lines.
  5136. This movement is based on where the cursor is displayed on the
  5137. screen, instead of relying on buffer contents alone. It takes
  5138. into account variable-width characters and line continuation.
  5139. If nil, `line-move' moves point by logical lines.
  5140. A non-nil setting of `goal-column' overrides the value of this variable
  5141. and forces movement by logical lines.
  5142. A window that is horizontally scrolled also forces movement by logical
  5143. lines."
  5144. :type 'boolean
  5145. :group 'editing-basics
  5146. :version "23.1")
  5147. ;; Only used if display-graphic-p.
  5148. (declare-function font-info "font.c" (name &optional frame))
  5149. (defun default-font-height ()
  5150. "Return the height in pixels of the current buffer's default face font.
  5151. If the default font is remapped (see `face-remapping-alist'), the
  5152. function returns the height of the remapped face."
  5153. (let ((default-font (face-font 'default)))
  5154. (cond
  5155. ((and (display-multi-font-p)
  5156. ;; Avoid calling font-info if the frame's default font was
  5157. ;; not changed since the frame was created. That's because
  5158. ;; font-info is expensive for some fonts, see bug #14838.
  5159. (not (string= (frame-parameter nil 'font) default-font)))
  5160. (aref (font-info default-font) 3))
  5161. (t (frame-char-height)))))
  5162. (defun default-font-width ()
  5163. "Return the width in pixels of the current buffer's default face font.
  5164. If the default font is remapped (see `face-remapping-alist'), the
  5165. function returns the width of the remapped face."
  5166. (let ((default-font (face-font 'default)))
  5167. (cond
  5168. ((and (display-multi-font-p)
  5169. ;; Avoid calling font-info if the frame's default font was
  5170. ;; not changed since the frame was created. That's because
  5171. ;; font-info is expensive for some fonts, see bug #14838.
  5172. (not (string= (frame-parameter nil 'font) default-font)))
  5173. (let* ((info (font-info (face-font 'default)))
  5174. (width (aref info 11)))
  5175. (if (> width 0)
  5176. width
  5177. (aref info 10))))
  5178. (t (frame-char-width)))))
  5179. (defun default-line-height ()
  5180. "Return the pixel height of current buffer's default-face text line.
  5181. The value includes `line-spacing', if any, defined for the buffer
  5182. or the frame."
  5183. (let ((dfh (default-font-height))
  5184. (lsp (if (display-graphic-p)
  5185. (or line-spacing
  5186. (default-value 'line-spacing)
  5187. (frame-parameter nil 'line-spacing)
  5188. 0)
  5189. 0)))
  5190. (if (floatp lsp)
  5191. (setq lsp (truncate (* (frame-char-height) lsp))))
  5192. (+ dfh lsp)))
  5193. (defun window-screen-lines ()
  5194. "Return the number of screen lines in the text area of the selected window.
  5195. This is different from `window-text-height' in that this function counts
  5196. lines in units of the height of the font used by the default face displayed
  5197. in the window, not in units of the frame's default font, and also accounts
  5198. for `line-spacing', if any, defined for the window's buffer or frame.
  5199. The value is a floating-point number."
  5200. (let ((edges (window-inside-pixel-edges))
  5201. (dlh (default-line-height)))
  5202. (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
  5203. ;; Returns non-nil if partial move was done.
  5204. (defun line-move-partial (arg noerror to-end)
  5205. (if (< arg 0)
  5206. ;; Move backward (up).
  5207. ;; If already vscrolled, reduce vscroll
  5208. (let ((vs (window-vscroll nil t))
  5209. (dlh (default-line-height)))
  5210. (when (> vs dlh)
  5211. (set-window-vscroll nil (- vs dlh) t)))
  5212. ;; Move forward (down).
  5213. (let* ((lh (window-line-height -1))
  5214. (rowh (car lh))
  5215. (vpos (nth 1 lh))
  5216. (ypos (nth 2 lh))
  5217. (rbot (nth 3 lh))
  5218. (this-lh (window-line-height))
  5219. (this-height (car this-lh))
  5220. (this-ypos (nth 2 this-lh))
  5221. (dlh (default-line-height))
  5222. (wslines (window-screen-lines))
  5223. (edges (window-inside-pixel-edges))
  5224. (winh (- (nth 3 edges) (nth 1 edges) 1))
  5225. py vs last-line)
  5226. (if (> (mod wslines 1.0) 0.0)
  5227. (setq wslines (round (+ wslines 0.5))))
  5228. (when (or (null lh)
  5229. (>= rbot dlh)
  5230. (<= ypos (- dlh))
  5231. (null this-lh)
  5232. (<= this-ypos (- dlh)))
  5233. (unless lh
  5234. (let ((wend (pos-visible-in-window-p t nil t)))
  5235. (setq rbot (nth 3 wend)
  5236. rowh (nth 4 wend)
  5237. vpos (nth 5 wend))))
  5238. (unless this-lh
  5239. (let ((wstart (pos-visible-in-window-p nil nil t)))
  5240. (setq this-ypos (nth 2 wstart)
  5241. this-height (nth 4 wstart))))
  5242. (setq py
  5243. (or (nth 1 this-lh)
  5244. (let ((ppos (posn-at-point))
  5245. col-row)
  5246. (setq col-row (posn-actual-col-row ppos))
  5247. (if col-row
  5248. (- (cdr col-row) (window-vscroll))
  5249. (cdr (posn-col-row ppos))))))
  5250. ;; VPOS > 0 means the last line is only partially visible.
  5251. ;; But if the part that is visible is at least as tall as the
  5252. ;; default font, that means the line is actually fully
  5253. ;; readable, and something like line-spacing is hidden. So in
  5254. ;; that case we accept the last line in the window as still
  5255. ;; visible, and consider the margin as starting one line
  5256. ;; later.
  5257. (if (and vpos (> vpos 0))
  5258. (if (and rowh
  5259. (>= rowh (default-font-height))
  5260. (< rowh dlh))
  5261. (setq last-line (min (- wslines scroll-margin) vpos))
  5262. (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
  5263. (cond
  5264. ;; If last line of window is fully visible, and vscrolling
  5265. ;; more would make this line invisible, move forward.
  5266. ((and (or (< (setq vs (window-vscroll nil t)) dlh)
  5267. (null this-height)
  5268. (<= this-height dlh))
  5269. (or (null rbot) (= rbot 0)))
  5270. nil)
  5271. ;; If cursor is not in the bottom scroll margin, and the
  5272. ;; current line is is not too tall, move forward.
  5273. ((and (or (null this-height) (<= this-height winh))
  5274. vpos
  5275. (> vpos 0)
  5276. (< py last-line))
  5277. nil)
  5278. ;; When already vscrolled, we vscroll some more if we can,
  5279. ;; or clear vscroll and move forward at end of tall image.
  5280. ((> vs 0)
  5281. (when (or (and rbot (> rbot 0))
  5282. (and this-height (> this-height dlh)))
  5283. (set-window-vscroll nil (+ vs dlh) t)))
  5284. ;; If cursor just entered the bottom scroll margin, move forward,
  5285. ;; but also optionally vscroll one line so redisplay won't recenter.
  5286. ((and vpos
  5287. (> vpos 0)
  5288. (= py last-line))
  5289. ;; Don't vscroll if the partially-visible line at window
  5290. ;; bottom is not too tall (a.k.a. "just one more text
  5291. ;; line"): in that case, we do want redisplay to behave
  5292. ;; normally, i.e. recenter or whatever.
  5293. ;;
  5294. ;; Note: ROWH + RBOT from the value returned by
  5295. ;; pos-visible-in-window-p give the total height of the
  5296. ;; partially-visible glyph row at the end of the window. As
  5297. ;; we are dealing with floats, we disregard sub-pixel
  5298. ;; discrepancies between that and DLH.
  5299. (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
  5300. (set-window-vscroll nil dlh t))
  5301. (line-move-1 arg noerror to-end)
  5302. t)
  5303. ;; If there are lines above the last line, scroll-up one line.
  5304. ((and vpos (> vpos 0))
  5305. (scroll-up 1)
  5306. t)
  5307. ;; Finally, start vscroll.
  5308. (t
  5309. (set-window-vscroll nil dlh t)))))))
  5310. ;; This is like line-move-1 except that it also performs
  5311. ;; vertical scrolling of tall images if appropriate.
  5312. ;; That is not really a clean thing to do, since it mixes
  5313. ;; scrolling with cursor motion. But so far we don't have
  5314. ;; a cleaner solution to the problem of making C-n do something
  5315. ;; useful given a tall image.
  5316. (defun line-move (arg &optional noerror to-end try-vscroll)
  5317. "Move forward ARG lines.
  5318. If NOERROR, don't signal an error if we can't move ARG lines.
  5319. TO-END is unused.
  5320. TRY-VSCROLL controls whether to vscroll tall lines: if either
  5321. `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
  5322. not vscroll."
  5323. (if noninteractive
  5324. (line-move-1 arg noerror to-end)
  5325. (unless (and auto-window-vscroll try-vscroll
  5326. ;; Only vscroll for single line moves
  5327. (= (abs arg) 1)
  5328. ;; Under scroll-conservatively, the display engine
  5329. ;; does this better.
  5330. (zerop scroll-conservatively)
  5331. ;; But don't vscroll in a keyboard macro.
  5332. (not defining-kbd-macro)
  5333. (not executing-kbd-macro)
  5334. (line-move-partial arg noerror to-end))
  5335. (set-window-vscroll nil 0 t)
  5336. (if (and line-move-visual
  5337. ;; Display-based column are incompatible with goal-column.
  5338. (not goal-column)
  5339. ;; When the text in the window is scrolled to the left,
  5340. ;; display-based motion doesn't make sense (because each
  5341. ;; logical line occupies exactly one screen line).
  5342. (not (> (window-hscroll) 0))
  5343. ;; Likewise when the text _was_ scrolled to the left
  5344. ;; when the current run of vertical motion commands
  5345. ;; started.
  5346. (not (and (memq last-command
  5347. `(next-line previous-line ,this-command))
  5348. auto-hscroll-mode
  5349. (numberp temporary-goal-column)
  5350. (>= temporary-goal-column
  5351. (- (window-width) hscroll-margin)))))
  5352. (prog1 (line-move-visual arg noerror)
  5353. ;; If we moved into a tall line, set vscroll to make
  5354. ;; scrolling through tall images more smooth.
  5355. (let ((lh (line-pixel-height))
  5356. (edges (window-inside-pixel-edges))
  5357. (dlh (default-line-height))
  5358. winh)
  5359. (setq winh (- (nth 3 edges) (nth 1 edges) 1))
  5360. (if (and (< arg 0)
  5361. (< (point) (window-start))
  5362. (> lh winh))
  5363. (set-window-vscroll
  5364. nil
  5365. (- lh dlh) t))))
  5366. (line-move-1 arg noerror to-end)))))
  5367. ;; Display-based alternative to line-move-1.
  5368. ;; Arg says how many lines to move. The value is t if we can move the
  5369. ;; specified number of lines.
  5370. (defun line-move-visual (arg &optional noerror)
  5371. "Move ARG lines forward.
  5372. If NOERROR, don't signal an error if we can't move that many lines."
  5373. (let ((opoint (point))
  5374. (hscroll (window-hscroll))
  5375. target-hscroll)
  5376. ;; Check if the previous command was a line-motion command, or if
  5377. ;; we were called from some other command.
  5378. (if (and (consp temporary-goal-column)
  5379. (memq last-command `(next-line previous-line ,this-command)))
  5380. ;; If so, there's no need to reset `temporary-goal-column',
  5381. ;; but we may need to hscroll.
  5382. (if (or (/= (cdr temporary-goal-column) hscroll)
  5383. (> (cdr temporary-goal-column) 0))
  5384. (setq target-hscroll (cdr temporary-goal-column)))
  5385. ;; Otherwise, we should reset `temporary-goal-column'.
  5386. (let ((posn (posn-at-point))
  5387. x-pos)
  5388. (cond
  5389. ;; Handle the `overflow-newline-into-fringe' case:
  5390. ((eq (nth 1 posn) 'right-fringe)
  5391. (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
  5392. ((car (posn-x-y posn))
  5393. (setq x-pos (car (posn-x-y posn)))
  5394. ;; In R2L lines, the X pixel coordinate is measured from the
  5395. ;; left edge of the window, but columns are still counted
  5396. ;; from the logical-order beginning of the line, i.e. from
  5397. ;; the right edge in this case. We need to adjust for that.
  5398. (if (eq (current-bidi-paragraph-direction) 'right-to-left)
  5399. (setq x-pos (- (window-body-width nil t) 1 x-pos)))
  5400. (setq temporary-goal-column
  5401. (cons (/ (float x-pos)
  5402. (frame-char-width))
  5403. hscroll))))))
  5404. (if target-hscroll
  5405. (set-window-hscroll (selected-window) target-hscroll))
  5406. ;; vertical-motion can move more than it was asked to if it moves
  5407. ;; across display strings with newlines. We don't want to ring
  5408. ;; the bell and announce beginning/end of buffer in that case.
  5409. (or (and (or (and (>= arg 0)
  5410. (>= (vertical-motion
  5411. (cons (or goal-column
  5412. (if (consp temporary-goal-column)
  5413. (car temporary-goal-column)
  5414. temporary-goal-column))
  5415. arg))
  5416. arg))
  5417. (and (< arg 0)
  5418. (<= (vertical-motion
  5419. (cons (or goal-column
  5420. (if (consp temporary-goal-column)
  5421. (car temporary-goal-column)
  5422. temporary-goal-column))
  5423. arg))
  5424. arg)))
  5425. (or (>= arg 0)
  5426. (/= (point) opoint)
  5427. ;; If the goal column lies on a display string,
  5428. ;; `vertical-motion' advances the cursor to the end
  5429. ;; of the string. For arg < 0, this can cause the
  5430. ;; cursor to get stuck. (Bug#3020).
  5431. (= (vertical-motion arg) arg)))
  5432. (unless noerror
  5433. (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
  5434. nil)))))
  5435. ;; This is the guts of next-line and previous-line.
  5436. ;; Arg says how many lines to move.
  5437. ;; The value is t if we can move the specified number of lines.
  5438. (defun line-move-1 (arg &optional noerror _to-end)
  5439. ;; Don't run any point-motion hooks, and disregard intangibility,
  5440. ;; for intermediate positions.
  5441. (let ((inhibit-point-motion-hooks t)
  5442. (opoint (point))
  5443. (orig-arg arg))
  5444. (if (consp temporary-goal-column)
  5445. (setq temporary-goal-column (+ (car temporary-goal-column)
  5446. (cdr temporary-goal-column))))
  5447. (unwind-protect
  5448. (progn
  5449. (if (not (memq last-command '(next-line previous-line)))
  5450. (setq temporary-goal-column
  5451. (if (and track-eol (eolp)
  5452. ;; Don't count beg of empty line as end of line
  5453. ;; unless we just did explicit end-of-line.
  5454. (or (not (bolp)) (eq last-command 'move-end-of-line)))
  5455. most-positive-fixnum
  5456. (current-column))))
  5457. (if (not (or (integerp selective-display)
  5458. line-move-ignore-invisible))
  5459. ;; Use just newline characters.
  5460. ;; Set ARG to 0 if we move as many lines as requested.
  5461. (or (if (> arg 0)
  5462. (progn (if (> arg 1) (forward-line (1- arg)))
  5463. ;; This way of moving forward ARG lines
  5464. ;; verifies that we have a newline after the last one.
  5465. ;; It doesn't get confused by intangible text.
  5466. (end-of-line)
  5467. (if (zerop (forward-line 1))
  5468. (setq arg 0)))
  5469. (and (zerop (forward-line arg))
  5470. (bolp)
  5471. (setq arg 0)))
  5472. (unless noerror
  5473. (signal (if (< arg 0)
  5474. 'beginning-of-buffer
  5475. 'end-of-buffer)
  5476. nil)))
  5477. ;; Move by arg lines, but ignore invisible ones.
  5478. (let (done)
  5479. (while (and (> arg 0) (not done))
  5480. ;; If the following character is currently invisible,
  5481. ;; skip all characters with that same `invisible' property value.
  5482. (while (and (not (eobp)) (invisible-p (point)))
  5483. (goto-char (next-char-property-change (point))))
  5484. ;; Move a line.
  5485. ;; We don't use `end-of-line', since we want to escape
  5486. ;; from field boundaries occurring exactly at point.
  5487. (goto-char (constrain-to-field
  5488. (let ((inhibit-field-text-motion t))
  5489. (line-end-position))
  5490. (point) t t
  5491. 'inhibit-line-move-field-capture))
  5492. ;; If there's no invisibility here, move over the newline.
  5493. (cond
  5494. ((eobp)
  5495. (if (not noerror)
  5496. (signal 'end-of-buffer nil)
  5497. (setq done t)))
  5498. ((and (> arg 1) ;; Use vertical-motion for last move
  5499. (not (integerp selective-display))
  5500. (not (invisible-p (point))))
  5501. ;; We avoid vertical-motion when possible
  5502. ;; because that has to fontify.
  5503. (forward-line 1))
  5504. ;; Otherwise move a more sophisticated way.
  5505. ((zerop (vertical-motion 1))
  5506. (if (not noerror)
  5507. (signal 'end-of-buffer nil)
  5508. (setq done t))))
  5509. (unless done
  5510. (setq arg (1- arg))))
  5511. ;; The logic of this is the same as the loop above,
  5512. ;; it just goes in the other direction.
  5513. (while (and (< arg 0) (not done))
  5514. ;; For completely consistency with the forward-motion
  5515. ;; case, we should call beginning-of-line here.
  5516. ;; However, if point is inside a field and on a
  5517. ;; continued line, the call to (vertical-motion -1)
  5518. ;; below won't move us back far enough; then we return
  5519. ;; to the same column in line-move-finish, and point
  5520. ;; gets stuck -- cyd
  5521. (forward-line 0)
  5522. (cond
  5523. ((bobp)
  5524. (if (not noerror)
  5525. (signal 'beginning-of-buffer nil)
  5526. (setq done t)))
  5527. ((and (< arg -1) ;; Use vertical-motion for last move
  5528. (not (integerp selective-display))
  5529. (not (invisible-p (1- (point)))))
  5530. (forward-line -1))
  5531. ((zerop (vertical-motion -1))
  5532. (if (not noerror)
  5533. (signal 'beginning-of-buffer nil)
  5534. (setq done t))))
  5535. (unless done
  5536. (setq arg (1+ arg))
  5537. (while (and ;; Don't move over previous invis lines
  5538. ;; if our target is the middle of this line.
  5539. (or (zerop (or goal-column temporary-goal-column))
  5540. (< arg 0))
  5541. (not (bobp)) (invisible-p (1- (point))))
  5542. (goto-char (previous-char-property-change (point))))))))
  5543. ;; This is the value the function returns.
  5544. (= arg 0))
  5545. (cond ((> arg 0)
  5546. ;; If we did not move down as far as desired, at least go
  5547. ;; to end of line. Be sure to call point-entered and
  5548. ;; point-left-hooks.
  5549. (let* ((npoint (prog1 (line-end-position)
  5550. (goto-char opoint)))
  5551. (inhibit-point-motion-hooks nil))
  5552. (goto-char npoint)))
  5553. ((< arg 0)
  5554. ;; If we did not move up as far as desired,
  5555. ;; at least go to beginning of line.
  5556. (let* ((npoint (prog1 (line-beginning-position)
  5557. (goto-char opoint)))
  5558. (inhibit-point-motion-hooks nil))
  5559. (goto-char npoint)))
  5560. (t
  5561. (line-move-finish (or goal-column temporary-goal-column)
  5562. opoint (> orig-arg 0)))))))
  5563. (defun line-move-finish (column opoint forward)
  5564. (let ((repeat t))
  5565. (while repeat
  5566. ;; Set REPEAT to t to repeat the whole thing.
  5567. (setq repeat nil)
  5568. (let (new
  5569. (old (point))
  5570. (line-beg (line-beginning-position))
  5571. (line-end
  5572. ;; Compute the end of the line
  5573. ;; ignoring effectively invisible newlines.
  5574. (save-excursion
  5575. ;; Like end-of-line but ignores fields.
  5576. (skip-chars-forward "^\n")
  5577. (while (and (not (eobp)) (invisible-p (point)))
  5578. (goto-char (next-char-property-change (point)))
  5579. (skip-chars-forward "^\n"))
  5580. (point))))
  5581. ;; Move to the desired column.
  5582. (line-move-to-column (truncate column))
  5583. ;; Corner case: suppose we start out in a field boundary in
  5584. ;; the middle of a continued line. When we get to
  5585. ;; line-move-finish, point is at the start of a new *screen*
  5586. ;; line but the same text line; then line-move-to-column would
  5587. ;; move us backwards. Test using C-n with point on the "x" in
  5588. ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
  5589. (and forward
  5590. (< (point) old)
  5591. (goto-char old))
  5592. (setq new (point))
  5593. ;; Process intangibility within a line.
  5594. ;; With inhibit-point-motion-hooks bound to nil, a call to
  5595. ;; goto-char moves point past intangible text.
  5596. ;; However, inhibit-point-motion-hooks controls both the
  5597. ;; intangibility and the point-entered/point-left hooks. The
  5598. ;; following hack avoids calling the point-* hooks
  5599. ;; unnecessarily. Note that we move *forward* past intangible
  5600. ;; text when the initial and final points are the same.
  5601. (goto-char new)
  5602. (let ((inhibit-point-motion-hooks nil))
  5603. (goto-char new)
  5604. ;; If intangibility moves us to a different (later) place
  5605. ;; in the same line, use that as the destination.
  5606. (if (<= (point) line-end)
  5607. (setq new (point))
  5608. ;; If that position is "too late",
  5609. ;; try the previous allowable position.
  5610. ;; See if it is ok.
  5611. (backward-char)
  5612. (if (if forward
  5613. ;; If going forward, don't accept the previous
  5614. ;; allowable position if it is before the target line.
  5615. (< line-beg (point))
  5616. ;; If going backward, don't accept the previous
  5617. ;; allowable position if it is still after the target line.
  5618. (<= (point) line-end))
  5619. (setq new (point))
  5620. ;; As a last resort, use the end of the line.
  5621. (setq new line-end))))
  5622. ;; Now move to the updated destination, processing fields
  5623. ;; as well as intangibility.
  5624. (goto-char opoint)
  5625. (let ((inhibit-point-motion-hooks nil))
  5626. (goto-char
  5627. ;; Ignore field boundaries if the initial and final
  5628. ;; positions have the same `field' property, even if the
  5629. ;; fields are non-contiguous. This seems to be "nicer"
  5630. ;; behavior in many situations.
  5631. (if (eq (get-char-property new 'field)
  5632. (get-char-property opoint 'field))
  5633. new
  5634. (constrain-to-field new opoint t t
  5635. 'inhibit-line-move-field-capture))))
  5636. ;; If all this moved us to a different line,
  5637. ;; retry everything within that new line.
  5638. (when (or (< (point) line-beg) (> (point) line-end))
  5639. ;; Repeat the intangibility and field processing.
  5640. (setq repeat t))))))
  5641. (defun line-move-to-column (col)
  5642. "Try to find column COL, considering invisibility.
  5643. This function works only in certain cases,
  5644. because what we really need is for `move-to-column'
  5645. and `current-column' to be able to ignore invisible text."
  5646. (if (zerop col)
  5647. (beginning-of-line)
  5648. (move-to-column col))
  5649. (when (and line-move-ignore-invisible
  5650. (not (bolp)) (invisible-p (1- (point))))
  5651. (let ((normal-location (point))
  5652. (normal-column (current-column)))
  5653. ;; If the following character is currently invisible,
  5654. ;; skip all characters with that same `invisible' property value.
  5655. (while (and (not (eobp))
  5656. (invisible-p (point)))
  5657. (goto-char (next-char-property-change (point))))
  5658. ;; Have we advanced to a larger column position?
  5659. (if (> (current-column) normal-column)
  5660. ;; We have made some progress towards the desired column.
  5661. ;; See if we can make any further progress.
  5662. (line-move-to-column (+ (current-column) (- col normal-column)))
  5663. ;; Otherwise, go to the place we originally found
  5664. ;; and move back over invisible text.
  5665. ;; that will get us to the same place on the screen
  5666. ;; but with a more reasonable buffer position.
  5667. (goto-char normal-location)
  5668. (let ((line-beg
  5669. ;; We want the real line beginning, so it's consistent
  5670. ;; with bolp below, otherwise we might infloop.
  5671. (let ((inhibit-field-text-motion t))
  5672. (line-beginning-position))))
  5673. (while (and (not (bolp)) (invisible-p (1- (point))))
  5674. (goto-char (previous-char-property-change (point) line-beg))))))))
  5675. (defun move-end-of-line (arg)
  5676. "Move point to end of current line as displayed.
  5677. With argument ARG not nil or 1, move forward ARG - 1 lines first.
  5678. If point reaches the beginning or end of buffer, it stops there.
  5679. To ignore the effects of the `intangible' text or overlay
  5680. property, bind `inhibit-point-motion-hooks' to t.
  5681. If there is an image in the current line, this function
  5682. disregards newlines that are part of the text on which the image
  5683. rests."
  5684. (interactive "^p")
  5685. (or arg (setq arg 1))
  5686. (let (done)
  5687. (while (not done)
  5688. (let ((newpos
  5689. (save-excursion
  5690. (let ((goal-column 0)
  5691. (line-move-visual nil))
  5692. (and (line-move arg t)
  5693. ;; With bidi reordering, we may not be at bol,
  5694. ;; so make sure we are.
  5695. (skip-chars-backward "^\n")
  5696. (not (bobp))
  5697. (progn
  5698. (while (and (not (bobp)) (invisible-p (1- (point))))
  5699. (goto-char (previous-single-char-property-change
  5700. (point) 'invisible)))
  5701. (backward-char 1)))
  5702. (point)))))
  5703. (goto-char newpos)
  5704. (if (and (> (point) newpos)
  5705. (eq (preceding-char) ?\n))
  5706. (backward-char 1)
  5707. (if (and (> (point) newpos) (not (eobp))
  5708. (not (eq (following-char) ?\n)))
  5709. ;; If we skipped something intangible and now we're not
  5710. ;; really at eol, keep going.
  5711. (setq arg 1)
  5712. (setq done t)))))))
  5713. (defun move-beginning-of-line (arg)
  5714. "Move point to beginning of current line as displayed.
  5715. \(If there's an image in the line, this disregards newlines
  5716. which are part of the text that the image rests on.)
  5717. With argument ARG not nil or 1, move forward ARG - 1 lines first.
  5718. If point reaches the beginning or end of buffer, it stops there.
  5719. To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
  5720. (interactive "^p")
  5721. (or arg (setq arg 1))
  5722. (let ((orig (point))
  5723. first-vis first-vis-field-value)
  5724. ;; Move by lines, if ARG is not 1 (the default).
  5725. (if (/= arg 1)
  5726. (let ((line-move-visual nil))
  5727. (line-move (1- arg) t)))
  5728. ;; Move to beginning-of-line, ignoring fields and invisible text.
  5729. (skip-chars-backward "^\n")
  5730. (while (and (not (bobp)) (invisible-p (1- (point))))
  5731. (goto-char (previous-char-property-change (point)))
  5732. (skip-chars-backward "^\n"))
  5733. ;; Now find first visible char in the line.
  5734. (while (and (< (point) orig) (invisible-p (point)))
  5735. (goto-char (next-char-property-change (point) orig)))
  5736. (setq first-vis (point))
  5737. ;; See if fields would stop us from reaching FIRST-VIS.
  5738. (setq first-vis-field-value
  5739. (constrain-to-field first-vis orig (/= arg 1) t nil))
  5740. (goto-char (if (/= first-vis-field-value first-vis)
  5741. ;; If yes, obey them.
  5742. first-vis-field-value
  5743. ;; Otherwise, move to START with attention to fields.
  5744. ;; (It is possible that fields never matter in this case.)
  5745. (constrain-to-field (point) orig
  5746. (/= arg 1) t nil)))))
  5747. ;; Many people have said they rarely use this feature, and often type
  5748. ;; it by accident. Maybe it shouldn't even be on a key.
  5749. (put 'set-goal-column 'disabled t)
  5750. (defun set-goal-column (arg)
  5751. "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
  5752. Those commands will move to this position in the line moved to
  5753. rather than trying to keep the same horizontal position.
  5754. With a non-nil argument ARG, clears out the goal column
  5755. so that \\[next-line] and \\[previous-line] resume vertical motion.
  5756. The goal column is stored in the variable `goal-column'."
  5757. (interactive "P")
  5758. (if arg
  5759. (progn
  5760. (setq goal-column nil)
  5761. (message "No goal column"))
  5762. (setq goal-column (current-column))
  5763. ;; The older method below can be erroneous if `set-goal-column' is bound
  5764. ;; to a sequence containing %
  5765. ;;(message (substitute-command-keys
  5766. ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
  5767. ;;goal-column)
  5768. (message "%s"
  5769. (concat
  5770. (format "Goal column %d " goal-column)
  5771. (substitute-command-keys
  5772. "(use \\[set-goal-column] with an arg to unset it)")))
  5773. )
  5774. nil)
  5775. ;;; Editing based on visual lines, as opposed to logical lines.
  5776. (defun end-of-visual-line (&optional n)
  5777. "Move point to end of current visual line.
  5778. With argument N not nil or 1, move forward N - 1 visual lines first.
  5779. If point reaches the beginning or end of buffer, it stops there.
  5780. To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
  5781. (interactive "^p")
  5782. (or n (setq n 1))
  5783. (if (/= n 1)
  5784. (let ((line-move-visual t))
  5785. (line-move (1- n) t)))
  5786. ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
  5787. ;; constrain to field boundaries, so we don't either.
  5788. (vertical-motion (cons (window-width) 0)))
  5789. (defun beginning-of-visual-line (&optional n)
  5790. "Move point to beginning of current visual line.
  5791. With argument N not nil or 1, move forward N - 1 visual lines first.
  5792. If point reaches the beginning or end of buffer, it stops there.
  5793. To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
  5794. (interactive "^p")
  5795. (or n (setq n 1))
  5796. (let ((opoint (point)))
  5797. (if (/= n 1)
  5798. (let ((line-move-visual t))
  5799. (line-move (1- n) t)))
  5800. (vertical-motion 0)
  5801. ;; Constrain to field boundaries, like `move-beginning-of-line'.
  5802. (goto-char (constrain-to-field (point) opoint (/= n 1)))))
  5803. (defun kill-visual-line (&optional arg)
  5804. "Kill the rest of the visual line.
  5805. With prefix argument ARG, kill that many visual lines from point.
  5806. If ARG is negative, kill visual lines backward.
  5807. If ARG is zero, kill the text before point on the current visual
  5808. line.
  5809. If you want to append the killed line to the last killed text,
  5810. use \\[append-next-kill] before \\[kill-line].
  5811. If the buffer is read-only, Emacs will beep and refrain from deleting
  5812. the line, but put the line in the kill ring anyway. This means that
  5813. you can use this command to copy text from a read-only buffer.
  5814. \(If the variable `kill-read-only-ok' is non-nil, then this won't
  5815. even beep.)"
  5816. (interactive "P")
  5817. ;; Like in `kill-line', it's better to move point to the other end
  5818. ;; of the kill before killing.
  5819. (let ((opoint (point))
  5820. (kill-whole-line (and kill-whole-line (bolp))))
  5821. (if arg
  5822. (vertical-motion (prefix-numeric-value arg))
  5823. (end-of-visual-line 1)
  5824. (if (= (point) opoint)
  5825. (vertical-motion 1)
  5826. ;; Skip any trailing whitespace at the end of the visual line.
  5827. ;; We used to do this only if `show-trailing-whitespace' is
  5828. ;; nil, but that's wrong; the correct thing would be to check
  5829. ;; whether the trailing whitespace is highlighted. But, it's
  5830. ;; OK to just do this unconditionally.
  5831. (skip-chars-forward " \t")))
  5832. (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
  5833. (1+ (point))
  5834. (point)))))
  5835. (defun next-logical-line (&optional arg try-vscroll)
  5836. "Move cursor vertically down ARG lines.
  5837. This is identical to `next-line', except that it always moves
  5838. by logical lines instead of visual lines, ignoring the value of
  5839. the variable `line-move-visual'."
  5840. (interactive "^p\np")
  5841. (let ((line-move-visual nil))
  5842. (with-no-warnings
  5843. (next-line arg try-vscroll))))
  5844. (defun previous-logical-line (&optional arg try-vscroll)
  5845. "Move cursor vertically up ARG lines.
  5846. This is identical to `previous-line', except that it always moves
  5847. by logical lines instead of visual lines, ignoring the value of
  5848. the variable `line-move-visual'."
  5849. (interactive "^p\np")
  5850. (let ((line-move-visual nil))
  5851. (with-no-warnings
  5852. (previous-line arg try-vscroll))))
  5853. (defgroup visual-line nil
  5854. "Editing based on visual lines."
  5855. :group 'convenience
  5856. :version "23.1")
  5857. (defvar visual-line-mode-map
  5858. (let ((map (make-sparse-keymap)))
  5859. (define-key map [remap kill-line] 'kill-visual-line)
  5860. (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
  5861. (define-key map [remap move-end-of-line] 'end-of-visual-line)
  5862. ;; These keybindings interfere with xterm function keys. Are
  5863. ;; there any other suitable bindings?
  5864. ;; (define-key map "\M-[" 'previous-logical-line)
  5865. ;; (define-key map "\M-]" 'next-logical-line)
  5866. map))
  5867. (defcustom visual-line-fringe-indicators '(nil nil)
  5868. "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
  5869. The value should be a list of the form (LEFT RIGHT), where LEFT
  5870. and RIGHT are symbols representing the bitmaps to display, to
  5871. indicate wrapped lines, in the left and right fringes respectively.
  5872. See also `fringe-indicator-alist'.
  5873. The default is not to display fringe indicators for wrapped lines.
  5874. This variable does not affect fringe indicators displayed for
  5875. other purposes."
  5876. :type '(list (choice (const :tag "Hide left indicator" nil)
  5877. (const :tag "Left curly arrow" left-curly-arrow)
  5878. (symbol :tag "Other bitmap"))
  5879. (choice (const :tag "Hide right indicator" nil)
  5880. (const :tag "Right curly arrow" right-curly-arrow)
  5881. (symbol :tag "Other bitmap")))
  5882. :set (lambda (symbol value)
  5883. (dolist (buf (buffer-list))
  5884. (with-current-buffer buf
  5885. (when (and (boundp 'visual-line-mode)
  5886. (symbol-value 'visual-line-mode))
  5887. (setq fringe-indicator-alist
  5888. (cons (cons 'continuation value)
  5889. (assq-delete-all
  5890. 'continuation
  5891. (copy-tree fringe-indicator-alist)))))))
  5892. (set-default symbol value)))
  5893. (defvar visual-line--saved-state nil)
  5894. (define-minor-mode visual-line-mode
  5895. "Toggle visual line based editing (Visual Line mode).
  5896. With a prefix argument ARG, enable Visual Line mode if ARG is
  5897. positive, and disable it otherwise. If called from Lisp, enable
  5898. the mode if ARG is omitted or nil.
  5899. When Visual Line mode is enabled, `word-wrap' is turned on in
  5900. this buffer, and simple editing commands are redefined to act on
  5901. visual lines, not logical lines. See Info node `Visual Line
  5902. Mode' for details."
  5903. :keymap visual-line-mode-map
  5904. :group 'visual-line
  5905. :lighter " Wrap"
  5906. (if visual-line-mode
  5907. (progn
  5908. (set (make-local-variable 'visual-line--saved-state) nil)
  5909. ;; Save the local values of some variables, to be restored if
  5910. ;; visual-line-mode is turned off.
  5911. (dolist (var '(line-move-visual truncate-lines
  5912. truncate-partial-width-windows
  5913. word-wrap fringe-indicator-alist))
  5914. (if (local-variable-p var)
  5915. (push (cons var (symbol-value var))
  5916. visual-line--saved-state)))
  5917. (set (make-local-variable 'line-move-visual) t)
  5918. (set (make-local-variable 'truncate-partial-width-windows) nil)
  5919. (setq truncate-lines nil
  5920. word-wrap t
  5921. fringe-indicator-alist
  5922. (cons (cons 'continuation visual-line-fringe-indicators)
  5923. fringe-indicator-alist)))
  5924. (kill-local-variable 'line-move-visual)
  5925. (kill-local-variable 'word-wrap)
  5926. (kill-local-variable 'truncate-lines)
  5927. (kill-local-variable 'truncate-partial-width-windows)
  5928. (kill-local-variable 'fringe-indicator-alist)
  5929. (dolist (saved visual-line--saved-state)
  5930. (set (make-local-variable (car saved)) (cdr saved)))
  5931. (kill-local-variable 'visual-line--saved-state)))
  5932. (defun turn-on-visual-line-mode ()
  5933. (visual-line-mode 1))
  5934. (define-globalized-minor-mode global-visual-line-mode
  5935. visual-line-mode turn-on-visual-line-mode)
  5936. (defun transpose-chars (arg)
  5937. "Interchange characters around point, moving forward one character.
  5938. With prefix arg ARG, effect is to take character before point
  5939. and drag it forward past ARG other characters (backward if ARG negative).
  5940. If no argument and at end of line, the previous two chars are exchanged."
  5941. (interactive "*P")
  5942. (when (and (null arg) (eolp) (not (bobp))
  5943. (not (get-text-property (1- (point)) 'read-only)))
  5944. (forward-char -1))
  5945. (transpose-subr 'forward-char (prefix-numeric-value arg)))
  5946. (defun transpose-words (arg)
  5947. "Interchange words around point, leaving point at end of them.
  5948. With prefix arg ARG, effect is to take word before or around point
  5949. and drag it forward past ARG other words (backward if ARG negative).
  5950. If ARG is zero, the words around or after point and around or after mark
  5951. are interchanged."
  5952. ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
  5953. (interactive "*p")
  5954. (transpose-subr 'forward-word arg))
  5955. (defun transpose-sexps (arg)
  5956. "Like \\[transpose-words] but applies to sexps.
  5957. Does not work on a sexp that point is in the middle of
  5958. if it is a list or string."
  5959. (interactive "*p")
  5960. (transpose-subr
  5961. (lambda (arg)
  5962. ;; Here we should try to simulate the behavior of
  5963. ;; (cons (progn (forward-sexp x) (point))
  5964. ;; (progn (forward-sexp (- x)) (point)))
  5965. ;; Except that we don't want to rely on the second forward-sexp
  5966. ;; putting us back to where we want to be, since forward-sexp-function
  5967. ;; might do funny things like infix-precedence.
  5968. (if (if (> arg 0)
  5969. (looking-at "\\sw\\|\\s_")
  5970. (and (not (bobp))
  5971. (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
  5972. ;; Jumping over a symbol. We might be inside it, mind you.
  5973. (progn (funcall (if (> arg 0)
  5974. 'skip-syntax-backward 'skip-syntax-forward)
  5975. "w_")
  5976. (cons (save-excursion (forward-sexp arg) (point)) (point)))
  5977. ;; Otherwise, we're between sexps. Take a step back before jumping
  5978. ;; to make sure we'll obey the same precedence no matter which direction
  5979. ;; we're going.
  5980. (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
  5981. (cons (save-excursion (forward-sexp arg) (point))
  5982. (progn (while (or (forward-comment (if (> arg 0) 1 -1))
  5983. (not (zerop (funcall (if (> arg 0)
  5984. 'skip-syntax-forward
  5985. 'skip-syntax-backward)
  5986. ".")))))
  5987. (point)))))
  5988. arg 'special))
  5989. (defun transpose-lines (arg)
  5990. "Exchange current line and previous line, leaving point after both.
  5991. With argument ARG, takes previous line and moves it past ARG lines.
  5992. With argument 0, interchanges line point is in with line mark is in."
  5993. (interactive "*p")
  5994. (transpose-subr (function
  5995. (lambda (arg)
  5996. (if (> arg 0)
  5997. (progn
  5998. ;; Move forward over ARG lines,
  5999. ;; but create newlines if necessary.
  6000. (setq arg (forward-line arg))
  6001. (if (/= (preceding-char) ?\n)
  6002. (setq arg (1+ arg)))
  6003. (if (> arg 0)
  6004. (newline arg)))
  6005. (forward-line arg))))
  6006. arg))
  6007. ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
  6008. ;; which seems inconsistent with the ARG /= 0 case.
  6009. ;; FIXME document SPECIAL.
  6010. (defun transpose-subr (mover arg &optional special)
  6011. "Subroutine to do the work of transposing objects.
  6012. Works for lines, sentences, paragraphs, etc. MOVER is a function that
  6013. moves forward by units of the given object (e.g. forward-sentence,
  6014. forward-paragraph). If ARG is zero, exchanges the current object
  6015. with the one containing mark. If ARG is an integer, moves the
  6016. current object past ARG following (if ARG is positive) or
  6017. preceding (if ARG is negative) objects, leaving point after the
  6018. current object."
  6019. (let ((aux (if special mover
  6020. (lambda (x)
  6021. (cons (progn (funcall mover x) (point))
  6022. (progn (funcall mover (- x)) (point))))))
  6023. pos1 pos2)
  6024. (cond
  6025. ((= arg 0)
  6026. (save-excursion
  6027. (setq pos1 (funcall aux 1))
  6028. (goto-char (or (mark) (error "No mark set in this buffer")))
  6029. (setq pos2 (funcall aux 1))
  6030. (transpose-subr-1 pos1 pos2))
  6031. (exchange-point-and-mark))
  6032. ((> arg 0)
  6033. (setq pos1 (funcall aux -1))
  6034. (setq pos2 (funcall aux arg))
  6035. (transpose-subr-1 pos1 pos2)
  6036. (goto-char (car pos2)))
  6037. (t
  6038. (setq pos1 (funcall aux -1))
  6039. (goto-char (car pos1))
  6040. (setq pos2 (funcall aux arg))
  6041. (transpose-subr-1 pos1 pos2)))))
  6042. (defun transpose-subr-1 (pos1 pos2)
  6043. (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
  6044. (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
  6045. (when (> (car pos1) (car pos2))
  6046. (let ((swap pos1))
  6047. (setq pos1 pos2 pos2 swap)))
  6048. (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
  6049. (atomic-change-group
  6050. ;; This sequence of insertions attempts to preserve marker
  6051. ;; positions at the start and end of the transposed objects.
  6052. (let* ((word (buffer-substring (car pos2) (cdr pos2)))
  6053. (len1 (- (cdr pos1) (car pos1)))
  6054. (len2 (length word))
  6055. (boundary (make-marker)))
  6056. (set-marker boundary (car pos2))
  6057. (goto-char (cdr pos1))
  6058. (insert-before-markers word)
  6059. (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
  6060. (goto-char boundary)
  6061. (insert word)
  6062. (goto-char (+ boundary len1))
  6063. (delete-region (point) (+ (point) len2))
  6064. (set-marker boundary nil))))
  6065. (defun backward-word (&optional arg)
  6066. "Move backward until encountering the beginning of a word.
  6067. With argument ARG, do this that many times.
  6068. If ARG is omitted or nil, move point backward one word."
  6069. (interactive "^p")
  6070. (forward-word (- (or arg 1))))
  6071. (defun mark-word (&optional arg allow-extend)
  6072. "Set mark ARG words away from point.
  6073. The place mark goes is the same place \\[forward-word] would
  6074. move to with the same argument.
  6075. Interactively, if this command is repeated
  6076. or (in Transient Mark mode) if the mark is active,
  6077. it marks the next ARG words after the ones already marked."
  6078. (interactive "P\np")
  6079. (cond ((and allow-extend
  6080. (or (and (eq last-command this-command) (mark t))
  6081. (region-active-p)))
  6082. (setq arg (if arg (prefix-numeric-value arg)
  6083. (if (< (mark) (point)) -1 1)))
  6084. (set-mark
  6085. (save-excursion
  6086. (goto-char (mark))
  6087. (forward-word arg)
  6088. (point))))
  6089. (t
  6090. (push-mark
  6091. (save-excursion
  6092. (forward-word (prefix-numeric-value arg))
  6093. (point))
  6094. nil t))))
  6095. (defun kill-word (arg)
  6096. "Kill characters forward until encountering the end of a word.
  6097. With argument ARG, do this that many times."
  6098. (interactive "p")
  6099. (kill-region (point) (progn (forward-word arg) (point))))
  6100. (defun backward-kill-word (arg)
  6101. "Kill characters backward until encountering the beginning of a word.
  6102. With argument ARG, do this that many times."
  6103. (interactive "p")
  6104. (kill-word (- arg)))
  6105. (defun current-word (&optional strict really-word)
  6106. "Return the symbol or word that point is on (or a nearby one) as a string.
  6107. The return value includes no text properties.
  6108. If optional arg STRICT is non-nil, return nil unless point is within
  6109. or adjacent to a symbol or word. In all cases the value can be nil
  6110. if there is no word nearby.
  6111. The function, belying its name, normally finds a symbol.
  6112. If optional arg REALLY-WORD is non-nil, it finds just a word."
  6113. (save-excursion
  6114. (let* ((oldpoint (point)) (start (point)) (end (point))
  6115. (syntaxes (if really-word "w" "w_"))
  6116. (not-syntaxes (concat "^" syntaxes)))
  6117. (skip-syntax-backward syntaxes) (setq start (point))
  6118. (goto-char oldpoint)
  6119. (skip-syntax-forward syntaxes) (setq end (point))
  6120. (when (and (eq start oldpoint) (eq end oldpoint)
  6121. ;; Point is neither within nor adjacent to a word.
  6122. (not strict))
  6123. ;; Look for preceding word in same line.
  6124. (skip-syntax-backward not-syntaxes (line-beginning-position))
  6125. (if (bolp)
  6126. ;; No preceding word in same line.
  6127. ;; Look for following word in same line.
  6128. (progn
  6129. (skip-syntax-forward not-syntaxes (line-end-position))
  6130. (setq start (point))
  6131. (skip-syntax-forward syntaxes)
  6132. (setq end (point)))
  6133. (setq end (point))
  6134. (skip-syntax-backward syntaxes)
  6135. (setq start (point))))
  6136. ;; If we found something nonempty, return it as a string.
  6137. (unless (= start end)
  6138. (buffer-substring-no-properties start end)))))
  6139. (defcustom fill-prefix nil
  6140. "String for filling to insert at front of new line, or nil for none."
  6141. :type '(choice (const :tag "None" nil)
  6142. string)
  6143. :group 'fill)
  6144. (make-variable-buffer-local 'fill-prefix)
  6145. (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
  6146. (defcustom auto-fill-inhibit-regexp nil
  6147. "Regexp to match lines which should not be auto-filled."
  6148. :type '(choice (const :tag "None" nil)
  6149. regexp)
  6150. :group 'fill)
  6151. (defun do-auto-fill ()
  6152. "The default value for `normal-auto-fill-function'.
  6153. This is the default auto-fill function, some major modes use a different one.
  6154. Returns t if it really did any work."
  6155. (let (fc justify give-up
  6156. (fill-prefix fill-prefix))
  6157. (if (or (not (setq justify (current-justification)))
  6158. (null (setq fc (current-fill-column)))
  6159. (and (eq justify 'left)
  6160. (<= (current-column) fc))
  6161. (and auto-fill-inhibit-regexp
  6162. (save-excursion (beginning-of-line)
  6163. (looking-at auto-fill-inhibit-regexp))))
  6164. nil ;; Auto-filling not required
  6165. (if (memq justify '(full center right))
  6166. (save-excursion (unjustify-current-line)))
  6167. ;; Choose a fill-prefix automatically.
  6168. (when (and adaptive-fill-mode
  6169. (or (null fill-prefix) (string= fill-prefix "")))
  6170. (let ((prefix
  6171. (fill-context-prefix
  6172. (save-excursion (fill-forward-paragraph -1) (point))
  6173. (save-excursion (fill-forward-paragraph 1) (point)))))
  6174. (and prefix (not (equal prefix ""))
  6175. ;; Use auto-indentation rather than a guessed empty prefix.
  6176. (not (and fill-indent-according-to-mode
  6177. (string-match "\\`[ \t]*\\'" prefix)))
  6178. (setq fill-prefix prefix))))
  6179. (while (and (not give-up) (> (current-column) fc))
  6180. ;; Determine where to split the line.
  6181. (let* (after-prefix
  6182. (fill-point
  6183. (save-excursion
  6184. (beginning-of-line)
  6185. (setq after-prefix (point))
  6186. (and fill-prefix
  6187. (looking-at (regexp-quote fill-prefix))
  6188. (setq after-prefix (match-end 0)))
  6189. (move-to-column (1+ fc))
  6190. (fill-move-to-break-point after-prefix)
  6191. (point))))
  6192. ;; See whether the place we found is any good.
  6193. (if (save-excursion
  6194. (goto-char fill-point)
  6195. (or (bolp)
  6196. ;; There is no use breaking at end of line.
  6197. (save-excursion (skip-chars-forward " ") (eolp))
  6198. ;; It is futile to split at the end of the prefix
  6199. ;; since we would just insert the prefix again.
  6200. (and after-prefix (<= (point) after-prefix))
  6201. ;; Don't split right after a comment starter
  6202. ;; since we would just make another comment starter.
  6203. (and comment-start-skip
  6204. (let ((limit (point)))
  6205. (beginning-of-line)
  6206. (and (re-search-forward comment-start-skip
  6207. limit t)
  6208. (eq (point) limit))))))
  6209. ;; No good place to break => stop trying.
  6210. (setq give-up t)
  6211. ;; Ok, we have a useful place to break the line. Do it.
  6212. (let ((prev-column (current-column)))
  6213. ;; If point is at the fill-point, do not `save-excursion'.
  6214. ;; Otherwise, if a comment prefix or fill-prefix is inserted,
  6215. ;; point will end up before it rather than after it.
  6216. (if (save-excursion
  6217. (skip-chars-backward " \t")
  6218. (= (point) fill-point))
  6219. (default-indent-new-line t)
  6220. (save-excursion
  6221. (goto-char fill-point)
  6222. (default-indent-new-line t)))
  6223. ;; Now do justification, if required
  6224. (if (not (eq justify 'left))
  6225. (save-excursion
  6226. (end-of-line 0)
  6227. (justify-current-line justify nil t)))
  6228. ;; If making the new line didn't reduce the hpos of
  6229. ;; the end of the line, then give up now;
  6230. ;; trying again will not help.
  6231. (if (>= (current-column) prev-column)
  6232. (setq give-up t))))))
  6233. ;; Justify last line.
  6234. (justify-current-line justify t t)
  6235. t)))
  6236. (defvar comment-line-break-function 'comment-indent-new-line
  6237. "Mode-specific function which line breaks and continues a comment.
  6238. This function is called during auto-filling when a comment syntax
  6239. is defined.
  6240. The function should take a single optional argument, which is a flag
  6241. indicating whether it should use soft newlines.")
  6242. (defun default-indent-new-line (&optional soft)
  6243. "Break line at point and indent.
  6244. If a comment syntax is defined, call `comment-indent-new-line'.
  6245. The inserted newline is marked hard if variable `use-hard-newlines' is true,
  6246. unless optional argument SOFT is non-nil."
  6247. (interactive)
  6248. (if comment-start
  6249. (funcall comment-line-break-function soft)
  6250. ;; Insert the newline before removing empty space so that markers
  6251. ;; get preserved better.
  6252. (if soft (insert-and-inherit ?\n) (newline 1))
  6253. (save-excursion (forward-char -1) (delete-horizontal-space))
  6254. (delete-horizontal-space)
  6255. (if (and fill-prefix (not adaptive-fill-mode))
  6256. ;; Blindly trust a non-adaptive fill-prefix.
  6257. (progn
  6258. (indent-to-left-margin)
  6259. (insert-before-markers-and-inherit fill-prefix))
  6260. (cond
  6261. ;; If there's an adaptive prefix, use it unless we're inside
  6262. ;; a comment and the prefix is not a comment starter.
  6263. (fill-prefix
  6264. (indent-to-left-margin)
  6265. (insert-and-inherit fill-prefix))
  6266. ;; If we're not inside a comment, just try to indent.
  6267. (t (indent-according-to-mode))))))
  6268. (defvar normal-auto-fill-function 'do-auto-fill
  6269. "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
  6270. Some major modes set this.")
  6271. (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
  6272. ;; `functions' and `hooks' are usually unsafe to set, but setting
  6273. ;; auto-fill-function to nil in a file-local setting is safe and
  6274. ;; can be useful to prevent auto-filling.
  6275. (put 'auto-fill-function 'safe-local-variable 'null)
  6276. (define-minor-mode auto-fill-mode
  6277. "Toggle automatic line breaking (Auto Fill mode).
  6278. With a prefix argument ARG, enable Auto Fill mode if ARG is
  6279. positive, and disable it otherwise. If called from Lisp, enable
  6280. the mode if ARG is omitted or nil.
  6281. When Auto Fill mode is enabled, inserting a space at a column
  6282. beyond `current-fill-column' automatically breaks the line at a
  6283. previous space.
  6284. When `auto-fill-mode' is on, the `auto-fill-function' variable is
  6285. non-nil.
  6286. The value of `normal-auto-fill-function' specifies the function to use
  6287. for `auto-fill-function' when turning Auto Fill mode on."
  6288. :variable (auto-fill-function
  6289. . (lambda (v) (setq auto-fill-function
  6290. (if v normal-auto-fill-function)))))
  6291. ;; This holds a document string used to document auto-fill-mode.
  6292. (defun auto-fill-function ()
  6293. "Automatically break line at a previous space, in insertion of text."
  6294. nil)
  6295. (defun turn-on-auto-fill ()
  6296. "Unconditionally turn on Auto Fill mode."
  6297. (auto-fill-mode 1))
  6298. (defun turn-off-auto-fill ()
  6299. "Unconditionally turn off Auto Fill mode."
  6300. (auto-fill-mode -1))
  6301. (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
  6302. (defun set-fill-column (arg)
  6303. "Set `fill-column' to specified argument.
  6304. Use \\[universal-argument] followed by a number to specify a column.
  6305. Just \\[universal-argument] as argument means to use the current column."
  6306. (interactive
  6307. (list (or current-prefix-arg
  6308. ;; We used to use current-column silently, but C-x f is too easily
  6309. ;; typed as a typo for C-x C-f, so we turned it into an error and
  6310. ;; now an interactive prompt.
  6311. (read-number "Set fill-column to: " (current-column)))))
  6312. (if (consp arg)
  6313. (setq arg (current-column)))
  6314. (if (not (integerp arg))
  6315. ;; Disallow missing argument; it's probably a typo for C-x C-f.
  6316. (error "set-fill-column requires an explicit argument")
  6317. (message "Fill column set to %d (was %d)" arg fill-column)
  6318. (setq fill-column arg)))
  6319. (defun set-selective-display (arg)
  6320. "Set `selective-display' to ARG; clear it if no arg.
  6321. When the value of `selective-display' is a number > 0,
  6322. lines whose indentation is >= that value are not displayed.
  6323. The variable `selective-display' has a separate value for each buffer."
  6324. (interactive "P")
  6325. (if (eq selective-display t)
  6326. (error "selective-display already in use for marked lines"))
  6327. (let ((current-vpos
  6328. (save-restriction
  6329. (narrow-to-region (point-min) (point))
  6330. (goto-char (window-start))
  6331. (vertical-motion (window-height)))))
  6332. (setq selective-display
  6333. (and arg (prefix-numeric-value arg)))
  6334. (recenter current-vpos))
  6335. (set-window-start (selected-window) (window-start))
  6336. (princ "selective-display set to " t)
  6337. (prin1 selective-display t)
  6338. (princ "." t))
  6339. (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
  6340. (defun toggle-truncate-lines (&optional arg)
  6341. "Toggle truncating of long lines for the current buffer.
  6342. When truncating is off, long lines are folded.
  6343. With prefix argument ARG, truncate long lines if ARG is positive,
  6344. otherwise fold them. Note that in side-by-side windows, this
  6345. command has no effect if `truncate-partial-width-windows' is
  6346. non-nil."
  6347. (interactive "P")
  6348. (setq truncate-lines
  6349. (if (null arg)
  6350. (not truncate-lines)
  6351. (> (prefix-numeric-value arg) 0)))
  6352. (force-mode-line-update)
  6353. (unless truncate-lines
  6354. (let ((buffer (current-buffer)))
  6355. (walk-windows (lambda (window)
  6356. (if (eq buffer (window-buffer window))
  6357. (set-window-hscroll window 0)))
  6358. nil t)))
  6359. (message "Truncate long lines %s"
  6360. (if truncate-lines "enabled" "disabled")))
  6361. (defun toggle-word-wrap (&optional arg)
  6362. "Toggle whether to use word-wrapping for continuation lines.
  6363. With prefix argument ARG, wrap continuation lines at word boundaries
  6364. if ARG is positive, otherwise wrap them at the right screen edge.
  6365. This command toggles the value of `word-wrap'. It has no effect
  6366. if long lines are truncated."
  6367. (interactive "P")
  6368. (setq word-wrap
  6369. (if (null arg)
  6370. (not word-wrap)
  6371. (> (prefix-numeric-value arg) 0)))
  6372. (force-mode-line-update)
  6373. (message "Word wrapping %s"
  6374. (if word-wrap "enabled" "disabled")))
  6375. (defvar overwrite-mode-textual (purecopy " Ovwrt")
  6376. "The string displayed in the mode line when in overwrite mode.")
  6377. (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
  6378. "The string displayed in the mode line when in binary overwrite mode.")
  6379. (define-minor-mode overwrite-mode
  6380. "Toggle Overwrite mode.
  6381. With a prefix argument ARG, enable Overwrite mode if ARG is
  6382. positive, and disable it otherwise. If called from Lisp, enable
  6383. the mode if ARG is omitted or nil.
  6384. When Overwrite mode is enabled, printing characters typed in
  6385. replace existing text on a one-for-one basis, rather than pushing
  6386. it to the right. At the end of a line, such characters extend
  6387. the line. Before a tab, such characters insert until the tab is
  6388. filled in. \\[quoted-insert] still inserts characters in
  6389. overwrite mode; this is supposed to make it easier to insert
  6390. characters when necessary."
  6391. :variable (overwrite-mode
  6392. . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
  6393. (define-minor-mode binary-overwrite-mode
  6394. "Toggle Binary Overwrite mode.
  6395. With a prefix argument ARG, enable Binary Overwrite mode if ARG
  6396. is positive, and disable it otherwise. If called from Lisp,
  6397. enable the mode if ARG is omitted or nil.
  6398. When Binary Overwrite mode is enabled, printing characters typed
  6399. in replace existing text. Newlines are not treated specially, so
  6400. typing at the end of a line joins the line to the next, with the
  6401. typed character between them. Typing before a tab character
  6402. simply replaces the tab with the character typed.
  6403. \\[quoted-insert] replaces the text at the cursor, just as
  6404. ordinary typing characters do.
  6405. Note that Binary Overwrite mode is not its own minor mode; it is
  6406. a specialization of overwrite mode, entered by setting the
  6407. `overwrite-mode' variable to `overwrite-mode-binary'."
  6408. :variable (overwrite-mode
  6409. . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
  6410. (define-minor-mode line-number-mode
  6411. "Toggle line number display in the mode line (Line Number mode).
  6412. With a prefix argument ARG, enable Line Number mode if ARG is
  6413. positive, and disable it otherwise. If called from Lisp, enable
  6414. the mode if ARG is omitted or nil.
  6415. Line numbers do not appear for very large buffers and buffers
  6416. with very long lines; see variables `line-number-display-limit'
  6417. and `line-number-display-limit-width'."
  6418. :init-value t :global t :group 'mode-line)
  6419. (define-minor-mode column-number-mode
  6420. "Toggle column number display in the mode line (Column Number mode).
  6421. With a prefix argument ARG, enable Column Number mode if ARG is
  6422. positive, and disable it otherwise.
  6423. If called from Lisp, enable the mode if ARG is omitted or nil."
  6424. :global t :group 'mode-line)
  6425. (define-minor-mode size-indication-mode
  6426. "Toggle buffer size display in the mode line (Size Indication mode).
  6427. With a prefix argument ARG, enable Size Indication mode if ARG is
  6428. positive, and disable it otherwise.
  6429. If called from Lisp, enable the mode if ARG is omitted or nil."
  6430. :global t :group 'mode-line)
  6431. (define-minor-mode auto-save-mode
  6432. "Toggle auto-saving in the current buffer (Auto Save mode).
  6433. With a prefix argument ARG, enable Auto Save mode if ARG is
  6434. positive, and disable it otherwise.
  6435. If called from Lisp, enable the mode if ARG is omitted or nil."
  6436. :variable ((and buffer-auto-save-file-name
  6437. ;; If auto-save is off because buffer has shrunk,
  6438. ;; then toggling should turn it on.
  6439. (>= buffer-saved-size 0))
  6440. . (lambda (val)
  6441. (setq buffer-auto-save-file-name
  6442. (cond
  6443. ((null val) nil)
  6444. ((and buffer-file-name auto-save-visited-file-name
  6445. (not buffer-read-only))
  6446. buffer-file-name)
  6447. (t (make-auto-save-file-name))))))
  6448. ;; If -1 was stored here, to temporarily turn off saving,
  6449. ;; turn it back on.
  6450. (and (< buffer-saved-size 0)
  6451. (setq buffer-saved-size 0)))
  6452. (defgroup paren-blinking nil
  6453. "Blinking matching of parens and expressions."
  6454. :prefix "blink-matching-"
  6455. :group 'paren-matching)
  6456. (defcustom blink-matching-paren t
  6457. "Non-nil means show matching open-paren when close-paren is inserted.
  6458. If t, highlight the paren. If `jump', briefly move cursor to its
  6459. position. If `jump-offscreen', move cursor there even if the
  6460. position is off screen. With any other non-nil value, the
  6461. off-screen position of the opening paren will be shown in the
  6462. echo area."
  6463. :type '(choice
  6464. (const :tag "Disable" nil)
  6465. (const :tag "Highlight" t)
  6466. (const :tag "Move cursor" jump)
  6467. (const :tag "Move cursor, even if off screen" jump-offscreen))
  6468. :group 'paren-blinking)
  6469. (defcustom blink-matching-paren-on-screen t
  6470. "Non-nil means show matching open-paren when it is on screen.
  6471. If nil, don't show it (but the open-paren can still be shown
  6472. in the echo area when it is off screen).
  6473. This variable has no effect if `blink-matching-paren' is nil.
  6474. \(In that case, the open-paren is never shown.)
  6475. It is also ignored if `show-paren-mode' is enabled."
  6476. :type 'boolean
  6477. :group 'paren-blinking)
  6478. (defcustom blink-matching-paren-distance (* 100 1024)
  6479. "If non-nil, maximum distance to search backwards for matching open-paren.
  6480. If nil, search stops at the beginning of the accessible portion of the buffer."
  6481. :version "23.2" ; 25->100k
  6482. :type '(choice (const nil) integer)
  6483. :group 'paren-blinking)
  6484. (defcustom blink-matching-delay 1
  6485. "Time in seconds to delay after showing a matching paren."
  6486. :type 'number
  6487. :group 'paren-blinking)
  6488. (defcustom blink-matching-paren-dont-ignore-comments nil
  6489. "If nil, `blink-matching-paren' ignores comments.
  6490. More precisely, when looking for the matching parenthesis,
  6491. it skips the contents of comments that end before point."
  6492. :type 'boolean
  6493. :group 'paren-blinking)
  6494. (defun blink-matching-check-mismatch (start end)
  6495. "Return whether or not START...END are matching parens.
  6496. END is the current point and START is the blink position.
  6497. START might be nil if no matching starter was found.
  6498. Returns non-nil if we find there is a mismatch."
  6499. (let* ((end-syntax (syntax-after (1- end)))
  6500. (matching-paren (and (consp end-syntax)
  6501. (eq (syntax-class end-syntax) 5)
  6502. (cdr end-syntax))))
  6503. ;; For self-matched chars like " and $, we can't know when they're
  6504. ;; mismatched or unmatched, so we can only do it for parens.
  6505. (when matching-paren
  6506. (not (and start
  6507. (or
  6508. (eq (char-after start) matching-paren)
  6509. ;; The cdr might hold a new paren-class info rather than
  6510. ;; a matching-char info, in which case the two CDRs
  6511. ;; should match.
  6512. (eq matching-paren (cdr-safe (syntax-after start)))))))))
  6513. (defvar blink-matching-check-function #'blink-matching-check-mismatch
  6514. "Function to check parentheses mismatches.
  6515. The function takes two arguments (START and END) where START is the
  6516. position just before the opening token and END is the position right after.
  6517. START can be nil, if it was not found.
  6518. The function should return non-nil if the two tokens do not match.")
  6519. (defvar blink-matching--overlay
  6520. (let ((ol (make-overlay (point) (point) nil t)))
  6521. (overlay-put ol 'face 'show-paren-match)
  6522. (delete-overlay ol)
  6523. ol)
  6524. "Overlay used to highlight the matching paren.")
  6525. (defun blink-matching-open ()
  6526. "Momentarily highlight the beginning of the sexp before point."
  6527. (interactive)
  6528. (when (and (not (bobp))
  6529. blink-matching-paren)
  6530. (let* ((oldpos (point))
  6531. (message-log-max nil) ; Don't log messages about paren matching.
  6532. (blinkpos
  6533. (save-excursion
  6534. (save-restriction
  6535. (if blink-matching-paren-distance
  6536. (narrow-to-region
  6537. (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
  6538. (- (point) blink-matching-paren-distance))
  6539. oldpos))
  6540. (let ((parse-sexp-ignore-comments
  6541. (and parse-sexp-ignore-comments
  6542. (not blink-matching-paren-dont-ignore-comments))))
  6543. (condition-case ()
  6544. (progn
  6545. (syntax-propertize (point))
  6546. (forward-sexp -1)
  6547. ;; backward-sexp skips backward over prefix chars,
  6548. ;; so move back to the matching paren.
  6549. (while (and (< (point) (1- oldpos))
  6550. (let ((code (syntax-after (point))))
  6551. (or (eq (syntax-class code) 6)
  6552. (eq (logand 1048576 (car code))
  6553. 1048576))))
  6554. (forward-char 1))
  6555. (point))
  6556. (error nil))))))
  6557. (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
  6558. (cond
  6559. (mismatch
  6560. (if blinkpos
  6561. (if (minibufferp)
  6562. (minibuffer-message "Mismatched parentheses")
  6563. (message "Mismatched parentheses"))
  6564. (if (minibufferp)
  6565. (minibuffer-message "No matching parenthesis found")
  6566. (message "No matching parenthesis found"))))
  6567. ((not blinkpos) nil)
  6568. ((or
  6569. (eq blink-matching-paren 'jump-offscreen)
  6570. (pos-visible-in-window-p blinkpos))
  6571. ;; Matching open within window, temporarily move to or highlight
  6572. ;; char after blinkpos but only if `blink-matching-paren-on-screen'
  6573. ;; is non-nil.
  6574. (and blink-matching-paren-on-screen
  6575. (not show-paren-mode)
  6576. (if (memq blink-matching-paren '(jump jump-offscreen))
  6577. (save-excursion
  6578. (goto-char blinkpos)
  6579. (sit-for blink-matching-delay))
  6580. (unwind-protect
  6581. (progn
  6582. (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
  6583. (current-buffer))
  6584. (sit-for blink-matching-delay))
  6585. (delete-overlay blink-matching--overlay)))))
  6586. (t
  6587. (let ((open-paren-line-string
  6588. (save-excursion
  6589. (goto-char blinkpos)
  6590. ;; Show what precedes the open in its line, if anything.
  6591. (cond
  6592. ((save-excursion (skip-chars-backward " \t") (not (bolp)))
  6593. (buffer-substring (line-beginning-position)
  6594. (1+ blinkpos)))
  6595. ;; Show what follows the open in its line, if anything.
  6596. ((save-excursion
  6597. (forward-char 1)
  6598. (skip-chars-forward " \t")
  6599. (not (eolp)))
  6600. (buffer-substring blinkpos
  6601. (line-end-position)))
  6602. ;; Otherwise show the previous nonblank line,
  6603. ;; if there is one.
  6604. ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
  6605. (concat
  6606. (buffer-substring (progn
  6607. (skip-chars-backward "\n \t")
  6608. (line-beginning-position))
  6609. (progn (end-of-line)
  6610. (skip-chars-backward " \t")
  6611. (point)))
  6612. ;; Replace the newline and other whitespace with `...'.
  6613. "..."
  6614. (buffer-substring blinkpos (1+ blinkpos))))
  6615. ;; There is nothing to show except the char itself.
  6616. (t (buffer-substring blinkpos (1+ blinkpos)))))))
  6617. (minibuffer-message
  6618. "Matches %s"
  6619. (substring-no-properties open-paren-line-string))))))))
  6620. (defvar blink-paren-function 'blink-matching-open
  6621. "Function called, if non-nil, whenever a close parenthesis is inserted.
  6622. More precisely, a char with closeparen syntax is self-inserted.")
  6623. (defun blink-paren-post-self-insert-function ()
  6624. (when (and (eq (char-before) last-command-event) ; Sanity check.
  6625. (memq (char-syntax last-command-event) '(?\) ?\$))
  6626. blink-paren-function
  6627. (not executing-kbd-macro)
  6628. (not noninteractive)
  6629. ;; Verify an even number of quoting characters precede the close.
  6630. ;; FIXME: Also check if this parenthesis closes a comment as
  6631. ;; can happen in Pascal and SML.
  6632. (= 1 (logand 1 (- (point)
  6633. (save-excursion
  6634. (forward-char -1)
  6635. (skip-syntax-backward "/\\")
  6636. (point))))))
  6637. (funcall blink-paren-function)))
  6638. (put 'blink-paren-post-self-insert-function 'priority 100)
  6639. (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
  6640. ;; Most likely, this hook is nil, so this arg doesn't matter,
  6641. ;; but I use it as a reminder that this function usually
  6642. ;; likes to be run after others since it does
  6643. ;; `sit-for'. That's also the reason it get a `priority' prop
  6644. ;; of 100.
  6645. 'append)
  6646. ;; This executes C-g typed while Emacs is waiting for a command.
  6647. ;; Quitting out of a program does not go through here;
  6648. ;; that happens in the QUIT macro at the C code level.
  6649. (defun keyboard-quit ()
  6650. "Signal a `quit' condition.
  6651. During execution of Lisp code, this character causes a quit directly.
  6652. At top-level, as an editor command, this simply beeps."
  6653. (interactive)
  6654. ;; Avoid adding the region to the window selection.
  6655. (setq saved-region-selection nil)
  6656. (let (select-active-regions)
  6657. (deactivate-mark))
  6658. (if (fboundp 'kmacro-keyboard-quit)
  6659. (kmacro-keyboard-quit))
  6660. (when completion-in-region-mode
  6661. (completion-in-region-mode -1))
  6662. ;; Force the next redisplay cycle to remove the "Def" indicator from
  6663. ;; all the mode lines.
  6664. (if defining-kbd-macro
  6665. (force-mode-line-update t))
  6666. (setq defining-kbd-macro nil)
  6667. (let ((debug-on-quit nil))
  6668. (signal 'quit nil)))
  6669. (defvar buffer-quit-function nil
  6670. "Function to call to \"quit\" the current buffer, or nil if none.
  6671. \\[keyboard-escape-quit] calls this function when its more local actions
  6672. \(such as canceling a prefix argument, minibuffer or region) do not apply.")
  6673. (defun keyboard-escape-quit ()
  6674. "Exit the current \"mode\" (in a generalized sense of the word).
  6675. This command can exit an interactive command such as `query-replace',
  6676. can clear out a prefix argument or a region,
  6677. can get out of the minibuffer or other recursive edit,
  6678. cancel the use of the current buffer (for special-purpose buffers),
  6679. or go back to just one window (by deleting all but the selected window)."
  6680. (interactive)
  6681. (cond ((eq last-command 'mode-exited) nil)
  6682. ((region-active-p)
  6683. (deactivate-mark))
  6684. ((> (minibuffer-depth) 0)
  6685. (abort-recursive-edit))
  6686. (current-prefix-arg
  6687. nil)
  6688. ((> (recursion-depth) 0)
  6689. (exit-recursive-edit))
  6690. (buffer-quit-function
  6691. (funcall buffer-quit-function))
  6692. ((not (one-window-p t))
  6693. (delete-other-windows))
  6694. ((string-match "^ \\*" (buffer-name (current-buffer)))
  6695. (bury-buffer))))
  6696. (defun play-sound-file (file &optional volume device)
  6697. "Play sound stored in FILE.
  6698. VOLUME and DEVICE correspond to the keywords of the sound
  6699. specification for `play-sound'."
  6700. (interactive "fPlay sound file: ")
  6701. (let ((sound (list :file file)))
  6702. (if volume
  6703. (plist-put sound :volume volume))
  6704. (if device
  6705. (plist-put sound :device device))
  6706. (push 'sound sound)
  6707. (play-sound sound)))
  6708. (defcustom read-mail-command 'rmail
  6709. "Your preference for a mail reading package.
  6710. This is used by some keybindings which support reading mail.
  6711. See also `mail-user-agent' concerning sending mail."
  6712. :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
  6713. (function-item :tag "Gnus" :format "%t\n" gnus)
  6714. (function-item :tag "Emacs interface to MH"
  6715. :format "%t\n" mh-rmail)
  6716. (function :tag "Other"))
  6717. :version "21.1"
  6718. :group 'mail)
  6719. (defcustom mail-user-agent 'message-user-agent
  6720. "Your preference for a mail composition package.
  6721. Various Emacs Lisp packages (e.g. Reporter) require you to compose an
  6722. outgoing email message. This variable lets you specify which
  6723. mail-sending package you prefer.
  6724. Valid values include:
  6725. `message-user-agent' -- use the Message package.
  6726. See Info node `(message)'.
  6727. `sendmail-user-agent' -- use the Mail package.
  6728. See Info node `(emacs)Sending Mail'.
  6729. `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
  6730. See Info node `(mh-e)'.
  6731. `gnus-user-agent' -- like `message-user-agent', but with Gnus
  6732. paraphernalia if Gnus is running, particularly
  6733. the Gcc: header for archiving.
  6734. Additional valid symbols may be available; check with the author of
  6735. your package for details. The function should return non-nil if it
  6736. succeeds.
  6737. See also `read-mail-command' concerning reading mail."
  6738. :type '(radio (function-item :tag "Message package"
  6739. :format "%t\n"
  6740. message-user-agent)
  6741. (function-item :tag "Mail package"
  6742. :format "%t\n"
  6743. sendmail-user-agent)
  6744. (function-item :tag "Emacs interface to MH"
  6745. :format "%t\n"
  6746. mh-e-user-agent)
  6747. (function-item :tag "Message with full Gnus features"
  6748. :format "%t\n"
  6749. gnus-user-agent)
  6750. (function :tag "Other"))
  6751. :version "23.2" ; sendmail->message
  6752. :group 'mail)
  6753. (defcustom compose-mail-user-agent-warnings t
  6754. "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
  6755. If the value of `mail-user-agent' is the default, and the user
  6756. appears to have customizations applying to the old default,
  6757. `compose-mail' issues a warning."
  6758. :type 'boolean
  6759. :version "23.2"
  6760. :group 'mail)
  6761. (defun rfc822-goto-eoh ()
  6762. "If the buffer starts with a mail header, move point to the header's end.
  6763. Otherwise, moves to `point-min'.
  6764. The end of the header is the start of the next line, if there is one,
  6765. else the end of the last line. This function obeys RFC822."
  6766. (goto-char (point-min))
  6767. (when (re-search-forward
  6768. "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
  6769. (goto-char (match-beginning 0))))
  6770. ;; Used by Rmail (e.g., rmail-forward).
  6771. (defvar mail-encode-mml nil
  6772. "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
  6773. the outgoing message before sending it.")
  6774. (defun compose-mail (&optional to subject other-headers continue
  6775. switch-function yank-action send-actions
  6776. return-action)
  6777. "Start composing a mail message to send.
  6778. This uses the user's chosen mail composition package
  6779. as selected with the variable `mail-user-agent'.
  6780. The optional arguments TO and SUBJECT specify recipients
  6781. and the initial Subject field, respectively.
  6782. OTHER-HEADERS is an alist specifying additional
  6783. header fields. Elements look like (HEADER . VALUE) where both
  6784. HEADER and VALUE are strings.
  6785. CONTINUE, if non-nil, says to continue editing a message already
  6786. being composed. Interactively, CONTINUE is the prefix argument.
  6787. SWITCH-FUNCTION, if non-nil, is a function to use to
  6788. switch to and display the buffer used for mail composition.
  6789. YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
  6790. to insert the raw text of the message being replied to.
  6791. It has the form (FUNCTION . ARGS). The user agent will apply
  6792. FUNCTION to ARGS, to insert the raw text of the original message.
  6793. \(The user agent will also run `mail-citation-hook', *after* the
  6794. original text has been inserted in this way.)
  6795. SEND-ACTIONS is a list of actions to call when the message is sent.
  6796. Each action has the form (FUNCTION . ARGS).
  6797. RETURN-ACTION, if non-nil, is an action for returning to the
  6798. caller. It has the form (FUNCTION . ARGS). The function is
  6799. called after the mail has been sent or put aside, and the mail
  6800. buffer buried."
  6801. (interactive
  6802. (list nil nil nil current-prefix-arg))
  6803. ;; In Emacs 23.2, the default value of `mail-user-agent' changed
  6804. ;; from sendmail-user-agent to message-user-agent. Some users may
  6805. ;; encounter incompatibilities. This hack tries to detect problems
  6806. ;; and warn about them.
  6807. (and compose-mail-user-agent-warnings
  6808. (eq mail-user-agent 'message-user-agent)
  6809. (let (warn-vars)
  6810. (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
  6811. mail-yank-hooks mail-archive-file-name
  6812. mail-default-reply-to mail-mailing-lists
  6813. mail-self-blind))
  6814. (and (boundp var)
  6815. (symbol-value var)
  6816. (push var warn-vars)))
  6817. (when warn-vars
  6818. (display-warning 'mail
  6819. (format-message "\
  6820. The default mail mode is now Message mode.
  6821. You have the following Mail mode variable%s customized:
  6822. \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
  6823. To disable this warning, set `compose-mail-user-agent-warnings' to nil."
  6824. (if (> (length warn-vars) 1) "s" "")
  6825. (mapconcat 'symbol-name
  6826. warn-vars " "))))))
  6827. (let ((function (get mail-user-agent 'composefunc)))
  6828. (funcall function to subject other-headers continue switch-function
  6829. yank-action send-actions return-action)))
  6830. (defun compose-mail-other-window (&optional to subject other-headers continue
  6831. yank-action send-actions
  6832. return-action)
  6833. "Like \\[compose-mail], but edit the outgoing message in another window."
  6834. (interactive (list nil nil nil current-prefix-arg))
  6835. (compose-mail to subject other-headers continue
  6836. 'switch-to-buffer-other-window yank-action send-actions
  6837. return-action))
  6838. (defun compose-mail-other-frame (&optional to subject other-headers continue
  6839. yank-action send-actions
  6840. return-action)
  6841. "Like \\[compose-mail], but edit the outgoing message in another frame."
  6842. (interactive (list nil nil nil current-prefix-arg))
  6843. (compose-mail to subject other-headers continue
  6844. 'switch-to-buffer-other-frame yank-action send-actions
  6845. return-action))
  6846. (defvar set-variable-value-history nil
  6847. "History of values entered with `set-variable'.
  6848. Maximum length of the history list is determined by the value
  6849. of `history-length', which see.")
  6850. (defun set-variable (variable value &optional make-local)
  6851. "Set VARIABLE to VALUE. VALUE is a Lisp object.
  6852. VARIABLE should be a user option variable name, a Lisp variable
  6853. meant to be customized by users. You should enter VALUE in Lisp syntax,
  6854. so if you want VALUE to be a string, you must surround it with doublequotes.
  6855. VALUE is used literally, not evaluated.
  6856. If VARIABLE has a `variable-interactive' property, that is used as if
  6857. it were the arg to `interactive' (which see) to interactively read VALUE.
  6858. If VARIABLE has been defined with `defcustom', then the type information
  6859. in the definition is used to check that VALUE is valid.
  6860. Note that this function is at heart equivalent to the basic `set' function.
  6861. For a variable defined with `defcustom', it does not pay attention to
  6862. any :set property that the variable might have (if you want that, use
  6863. \\[customize-set-variable] instead).
  6864. With a prefix argument, set VARIABLE to VALUE buffer-locally."
  6865. (interactive
  6866. (let* ((default-var (variable-at-point))
  6867. (var (if (custom-variable-p default-var)
  6868. (read-variable (format "Set variable (default %s): " default-var)
  6869. default-var)
  6870. (read-variable "Set variable: ")))
  6871. (minibuffer-help-form '(describe-variable var))
  6872. (prop (get var 'variable-interactive))
  6873. (obsolete (car (get var 'byte-obsolete-variable)))
  6874. (prompt (format "Set %s %s to value: " var
  6875. (cond ((local-variable-p var)
  6876. "(buffer-local)")
  6877. ((or current-prefix-arg
  6878. (local-variable-if-set-p var))
  6879. "buffer-locally")
  6880. (t "globally"))))
  6881. (val (progn
  6882. (when obsolete
  6883. (message (concat "`%S' is obsolete; "
  6884. (if (symbolp obsolete) "use `%S' instead" "%s"))
  6885. var obsolete)
  6886. (sit-for 3))
  6887. (if prop
  6888. ;; Use VAR's `variable-interactive' property
  6889. ;; as an interactive spec for prompting.
  6890. (call-interactively `(lambda (arg)
  6891. (interactive ,prop)
  6892. arg))
  6893. (read-from-minibuffer prompt nil
  6894. read-expression-map t
  6895. 'set-variable-value-history
  6896. (format "%S" (symbol-value var)))))))
  6897. (list var val current-prefix-arg)))
  6898. (and (custom-variable-p variable)
  6899. (not (get variable 'custom-type))
  6900. (custom-load-symbol variable))
  6901. (let ((type (get variable 'custom-type)))
  6902. (when type
  6903. ;; Match with custom type.
  6904. (require 'cus-edit)
  6905. (setq type (widget-convert type))
  6906. (unless (widget-apply type :match value)
  6907. (user-error "Value `%S' does not match type %S of %S"
  6908. value (car type) variable))))
  6909. (if make-local
  6910. (make-local-variable variable))
  6911. (set variable value)
  6912. ;; Force a thorough redisplay for the case that the variable
  6913. ;; has an effect on the display, like `tab-width' has.
  6914. (force-mode-line-update))
  6915. ;; Define the major mode for lists of completions.
  6916. (defvar completion-list-mode-map
  6917. (let ((map (make-sparse-keymap)))
  6918. (define-key map [mouse-2] 'choose-completion)
  6919. (define-key map [follow-link] 'mouse-face)
  6920. (define-key map [down-mouse-2] nil)
  6921. (define-key map "\C-m" 'choose-completion)
  6922. (define-key map "\e\e\e" 'delete-completion-window)
  6923. (define-key map [left] 'previous-completion)
  6924. (define-key map [right] 'next-completion)
  6925. (define-key map [?\t] 'next-completion)
  6926. (define-key map [backtab] 'previous-completion)
  6927. (define-key map "q" 'quit-window)
  6928. (define-key map "z" 'kill-this-buffer)
  6929. map)
  6930. "Local map for completion list buffers.")
  6931. ;; Completion mode is suitable only for specially formatted data.
  6932. (put 'completion-list-mode 'mode-class 'special)
  6933. (defvar completion-reference-buffer nil
  6934. "Record the buffer that was current when the completion list was requested.
  6935. This is a local variable in the completion list buffer.
  6936. Initial value is nil to avoid some compiler warnings.")
  6937. (defvar completion-no-auto-exit nil
  6938. "Non-nil means `choose-completion-string' should never exit the minibuffer.
  6939. This also applies to other functions such as `choose-completion'.")
  6940. (defvar completion-base-position nil
  6941. "Position of the base of the text corresponding to the shown completions.
  6942. This variable is used in the *Completions* buffers.
  6943. Its value is a list of the form (START END) where START is the place
  6944. where the completion should be inserted and END (if non-nil) is the end
  6945. of the text to replace. If END is nil, point is used instead.")
  6946. (defvar completion-list-insert-choice-function #'completion--replace
  6947. "Function to use to insert the text chosen in *Completions*.
  6948. Called with three arguments (BEG END TEXT), it should replace the text
  6949. between BEG and END with TEXT. Expected to be set buffer-locally
  6950. in the *Completions* buffer.")
  6951. (defvar completion-base-size nil
  6952. "Number of chars before point not involved in completion.
  6953. This is a local variable in the completion list buffer.
  6954. It refers to the chars in the minibuffer if completing in the
  6955. minibuffer, or in `completion-reference-buffer' otherwise.
  6956. Only characters in the field at point are included.
  6957. If nil, Emacs determines which part of the tail end of the
  6958. buffer's text is involved in completion by comparing the text
  6959. directly.")
  6960. (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
  6961. (defun delete-completion-window ()
  6962. "Delete the completion list window.
  6963. Go to the window from which completion was requested."
  6964. (interactive)
  6965. (let ((buf completion-reference-buffer))
  6966. (if (one-window-p t)
  6967. (if (window-dedicated-p) (delete-frame))
  6968. (delete-window (selected-window))
  6969. (if (get-buffer-window buf)
  6970. (select-window (get-buffer-window buf))))))
  6971. (defun previous-completion (n)
  6972. "Move to the previous item in the completion list."
  6973. (interactive "p")
  6974. (next-completion (- n)))
  6975. (defun next-completion (n)
  6976. "Move to the next item in the completion list.
  6977. With prefix argument N, move N items (negative N means move backward)."
  6978. (interactive "p")
  6979. (let ((beg (point-min)) (end (point-max)))
  6980. (while (and (> n 0) (not (eobp)))
  6981. ;; If in a completion, move to the end of it.
  6982. (when (get-text-property (point) 'mouse-face)
  6983. (goto-char (next-single-property-change (point) 'mouse-face nil end)))
  6984. ;; Move to start of next one.
  6985. (unless (get-text-property (point) 'mouse-face)
  6986. (goto-char (next-single-property-change (point) 'mouse-face nil end)))
  6987. (setq n (1- n)))
  6988. (while (and (< n 0) (not (bobp)))
  6989. (let ((prop (get-text-property (1- (point)) 'mouse-face)))
  6990. ;; If in a completion, move to the start of it.
  6991. (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
  6992. (goto-char (previous-single-property-change
  6993. (point) 'mouse-face nil beg)))
  6994. ;; Move to end of the previous completion.
  6995. (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
  6996. (goto-char (previous-single-property-change
  6997. (point) 'mouse-face nil beg)))
  6998. ;; Move to the start of that one.
  6999. (goto-char (previous-single-property-change
  7000. (point) 'mouse-face nil beg))
  7001. (setq n (1+ n))))))
  7002. (defun choose-completion (&optional event)
  7003. "Choose the completion at point.
  7004. If EVENT, use EVENT's position to determine the starting position."
  7005. (interactive (list last-nonmenu-event))
  7006. ;; In case this is run via the mouse, give temporary modes such as
  7007. ;; isearch a chance to turn off.
  7008. (run-hooks 'mouse-leave-buffer-hook)
  7009. (with-current-buffer (window-buffer (posn-window (event-start event)))
  7010. (let ((buffer completion-reference-buffer)
  7011. (base-size completion-base-size)
  7012. (base-position completion-base-position)
  7013. (insert-function completion-list-insert-choice-function)
  7014. (choice
  7015. (save-excursion
  7016. (goto-char (posn-point (event-start event)))
  7017. (let (beg end)
  7018. (cond
  7019. ((and (not (eobp)) (get-text-property (point) 'mouse-face))
  7020. (setq end (point) beg (1+ (point))))
  7021. ((and (not (bobp))
  7022. (get-text-property (1- (point)) 'mouse-face))
  7023. (setq end (1- (point)) beg (point)))
  7024. (t (error "No completion here")))
  7025. (setq beg (previous-single-property-change beg 'mouse-face))
  7026. (setq end (or (next-single-property-change end 'mouse-face)
  7027. (point-max)))
  7028. (buffer-substring-no-properties beg end)))))
  7029. (unless (buffer-live-p buffer)
  7030. (error "Destination buffer is dead"))
  7031. (quit-window nil (posn-window (event-start event)))
  7032. (with-current-buffer buffer
  7033. (choose-completion-string
  7034. choice buffer
  7035. (or base-position
  7036. (when base-size
  7037. ;; Someone's using old completion code that doesn't know
  7038. ;; about base-position yet.
  7039. (list (+ base-size (field-beginning))))
  7040. ;; If all else fails, just guess.
  7041. (list (choose-completion-guess-base-position choice)))
  7042. insert-function)))))
  7043. ;; Delete the longest partial match for STRING
  7044. ;; that can be found before POINT.
  7045. (defun choose-completion-guess-base-position (string)
  7046. (save-excursion
  7047. (let ((opoint (point))
  7048. len)
  7049. ;; Try moving back by the length of the string.
  7050. (goto-char (max (- (point) (length string))
  7051. (minibuffer-prompt-end)))
  7052. ;; See how far back we were actually able to move. That is the
  7053. ;; upper bound on how much we can match and delete.
  7054. (setq len (- opoint (point)))
  7055. (if completion-ignore-case
  7056. (setq string (downcase string)))
  7057. (while (and (> len 0)
  7058. (let ((tail (buffer-substring (point) opoint)))
  7059. (if completion-ignore-case
  7060. (setq tail (downcase tail)))
  7061. (not (string= tail (substring string 0 len)))))
  7062. (setq len (1- len))
  7063. (forward-char 1))
  7064. (point))))
  7065. (defun choose-completion-delete-max-match (string)
  7066. (declare (obsolete choose-completion-guess-base-position "23.2"))
  7067. (delete-region (choose-completion-guess-base-position string) (point)))
  7068. (defvar choose-completion-string-functions nil
  7069. "Functions that may override the normal insertion of a completion choice.
  7070. These functions are called in order with three arguments:
  7071. CHOICE - the string to insert in the buffer,
  7072. BUFFER - the buffer in which the choice should be inserted,
  7073. BASE-POSITION - where to insert the completion.
  7074. If a function in the list returns non-nil, that function is supposed
  7075. to have inserted the CHOICE in the BUFFER, and possibly exited
  7076. the minibuffer; no further functions will be called.
  7077. If all functions in the list return nil, that means to use
  7078. the default method of inserting the completion in BUFFER.")
  7079. (defun choose-completion-string (choice &optional
  7080. buffer base-position insert-function)
  7081. "Switch to BUFFER and insert the completion choice CHOICE.
  7082. BASE-POSITION says where to insert the completion.
  7083. INSERT-FUNCTION says how to insert the completion and falls
  7084. back on `completion-list-insert-choice-function' when nil."
  7085. ;; If BUFFER is the minibuffer, exit the minibuffer
  7086. ;; unless it is reading a file name and CHOICE is a directory,
  7087. ;; or completion-no-auto-exit is non-nil.
  7088. ;; Some older code may call us passing `base-size' instead of
  7089. ;; `base-position'. It's difficult to make any use of `base-size',
  7090. ;; so we just ignore it.
  7091. (unless (consp base-position)
  7092. (message "Obsolete `base-size' passed to choose-completion-string")
  7093. (setq base-position nil))
  7094. (let* ((buffer (or buffer completion-reference-buffer))
  7095. (mini-p (minibufferp buffer)))
  7096. ;; If BUFFER is a minibuffer, barf unless it's the currently
  7097. ;; active minibuffer.
  7098. (if (and mini-p
  7099. (not (and (active-minibuffer-window)
  7100. (equal buffer
  7101. (window-buffer (active-minibuffer-window))))))
  7102. (error "Minibuffer is not active for completion")
  7103. ;; Set buffer so buffer-local choose-completion-string-functions works.
  7104. (set-buffer buffer)
  7105. (unless (run-hook-with-args-until-success
  7106. 'choose-completion-string-functions
  7107. ;; The fourth arg used to be `mini-p' but was useless
  7108. ;; (since minibufferp can be used on the `buffer' arg)
  7109. ;; and indeed unused. The last used to be `base-size', so we
  7110. ;; keep it to try and avoid breaking old code.
  7111. choice buffer base-position nil)
  7112. ;; This remove-text-properties should be unnecessary since `choice'
  7113. ;; comes from buffer-substring-no-properties.
  7114. ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
  7115. ;; Insert the completion into the buffer where it was requested.
  7116. (funcall (or insert-function completion-list-insert-choice-function)
  7117. (or (car base-position) (point))
  7118. (or (cadr base-position) (point))
  7119. choice)
  7120. ;; Update point in the window that BUFFER is showing in.
  7121. (let ((window (get-buffer-window buffer t)))
  7122. (set-window-point window (point)))
  7123. ;; If completing for the minibuffer, exit it with this choice.
  7124. (and (not completion-no-auto-exit)
  7125. (minibufferp buffer)
  7126. minibuffer-completion-table
  7127. ;; If this is reading a file name, and the file name chosen
  7128. ;; is a directory, don't exit the minibuffer.
  7129. (let* ((result (buffer-substring (field-beginning) (point)))
  7130. (bounds
  7131. (completion-boundaries result minibuffer-completion-table
  7132. minibuffer-completion-predicate
  7133. "")))
  7134. (if (eq (car bounds) (length result))
  7135. ;; The completion chosen leads to a new set of completions
  7136. ;; (e.g. it's a directory): don't exit the minibuffer yet.
  7137. (let ((mini (active-minibuffer-window)))
  7138. (select-window mini)
  7139. (when minibuffer-auto-raise
  7140. (raise-frame (window-frame mini))))
  7141. (exit-minibuffer))))))))
  7142. (define-derived-mode completion-list-mode nil "Completion List"
  7143. "Major mode for buffers showing lists of possible completions.
  7144. Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
  7145. to select the completion near point.
  7146. Or click to select one with the mouse.
  7147. \\{completion-list-mode-map}"
  7148. (set (make-local-variable 'completion-base-size) nil))
  7149. (defun completion-list-mode-finish ()
  7150. "Finish setup of the completions buffer.
  7151. Called from `temp-buffer-show-hook'."
  7152. (when (eq major-mode 'completion-list-mode)
  7153. (setq buffer-read-only t)))
  7154. (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
  7155. ;; Variables and faces used in `completion-setup-function'.
  7156. (defcustom completion-show-help t
  7157. "Non-nil means show help message in *Completions* buffer."
  7158. :type 'boolean
  7159. :version "22.1"
  7160. :group 'completion)
  7161. ;; This function goes in completion-setup-hook, so that it is called
  7162. ;; after the text of the completion list buffer is written.
  7163. (defun completion-setup-function ()
  7164. (let* ((mainbuf (current-buffer))
  7165. (base-dir
  7166. ;; FIXME: This is a bad hack. We try to set the default-directory
  7167. ;; in the *Completions* buffer so that the relative file names
  7168. ;; displayed there can be treated as valid file names, independently
  7169. ;; from the completion context. But this suffers from many problems:
  7170. ;; - It's not clear when the completions are file names. With some
  7171. ;; completion tables (e.g. bzr revision specs), the listed
  7172. ;; completions can mix file names and other things.
  7173. ;; - It doesn't pay attention to possible quoting.
  7174. ;; - With fancy completion styles, the code below will not always
  7175. ;; find the right base directory.
  7176. (if minibuffer-completing-file-name
  7177. (file-name-as-directory
  7178. (expand-file-name
  7179. (buffer-substring (minibuffer-prompt-end)
  7180. (- (point) (or completion-base-size 0))))))))
  7181. (with-current-buffer standard-output
  7182. (let ((base-size completion-base-size) ;Read before killing localvars.
  7183. (base-position completion-base-position)
  7184. (insert-fun completion-list-insert-choice-function))
  7185. (completion-list-mode)
  7186. (set (make-local-variable 'completion-base-size) base-size)
  7187. (set (make-local-variable 'completion-base-position) base-position)
  7188. (set (make-local-variable 'completion-list-insert-choice-function)
  7189. insert-fun))
  7190. (set (make-local-variable 'completion-reference-buffer) mainbuf)
  7191. (if base-dir (setq default-directory base-dir))
  7192. ;; Maybe insert help string.
  7193. (when completion-show-help
  7194. (goto-char (point-min))
  7195. (if (display-mouse-p)
  7196. (insert "Click on a completion to select it.\n"))
  7197. (insert (substitute-command-keys
  7198. "In this buffer, type \\[choose-completion] to \
  7199. select the completion near point.\n\n"))))))
  7200. (add-hook 'completion-setup-hook 'completion-setup-function)
  7201. (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
  7202. (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
  7203. (defun switch-to-completions ()
  7204. "Select the completion list window."
  7205. (interactive)
  7206. (let ((window (or (get-buffer-window "*Completions*" 0)
  7207. ;; Make sure we have a completions window.
  7208. (progn (minibuffer-completion-help)
  7209. (get-buffer-window "*Completions*" 0)))))
  7210. (when window
  7211. (select-window window)
  7212. ;; In the new buffer, go to the first completion.
  7213. ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
  7214. (when (bobp)
  7215. (next-completion 1)))))
  7216. ;;; Support keyboard commands to turn on various modifiers.
  7217. ;; These functions -- which are not commands -- each add one modifier
  7218. ;; to the following event.
  7219. (defun event-apply-alt-modifier (_ignore-prompt)
  7220. "\\<function-key-map>Add the Alt modifier to the following event.
  7221. For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
  7222. (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
  7223. (defun event-apply-super-modifier (_ignore-prompt)
  7224. "\\<function-key-map>Add the Super modifier to the following event.
  7225. For example, type \\[event-apply-super-modifier] & to enter Super-&."
  7226. (vector (event-apply-modifier (read-event) 'super 23 "s-")))
  7227. (defun event-apply-hyper-modifier (_ignore-prompt)
  7228. "\\<function-key-map>Add the Hyper modifier to the following event.
  7229. For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
  7230. (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
  7231. (defun event-apply-shift-modifier (_ignore-prompt)
  7232. "\\<function-key-map>Add the Shift modifier to the following event.
  7233. For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
  7234. (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
  7235. (defun event-apply-control-modifier (_ignore-prompt)
  7236. "\\<function-key-map>Add the Ctrl modifier to the following event.
  7237. For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
  7238. (vector (event-apply-modifier (read-event) 'control 26 "C-")))
  7239. (defun event-apply-meta-modifier (_ignore-prompt)
  7240. "\\<function-key-map>Add the Meta modifier to the following event.
  7241. For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
  7242. (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
  7243. (defun event-apply-modifier (event symbol lshiftby prefix)
  7244. "Apply a modifier flag to event EVENT.
  7245. SYMBOL is the name of this modifier, as a symbol.
  7246. LSHIFTBY is the numeric value of this modifier, in keyboard events.
  7247. PREFIX is the string that represents this modifier in an event type symbol."
  7248. (if (numberp event)
  7249. (cond ((eq symbol 'control)
  7250. (if (and (<= (downcase event) ?z)
  7251. (>= (downcase event) ?a))
  7252. (- (downcase event) ?a -1)
  7253. (if (and (<= (downcase event) ?Z)
  7254. (>= (downcase event) ?A))
  7255. (- (downcase event) ?A -1)
  7256. (logior (lsh 1 lshiftby) event))))
  7257. ((eq symbol 'shift)
  7258. (if (and (<= (downcase event) ?z)
  7259. (>= (downcase event) ?a))
  7260. (upcase event)
  7261. (logior (lsh 1 lshiftby) event)))
  7262. (t
  7263. (logior (lsh 1 lshiftby) event)))
  7264. (if (memq symbol (event-modifiers event))
  7265. event
  7266. (let ((event-type (if (symbolp event) event (car event))))
  7267. (setq event-type (intern (concat prefix (symbol-name event-type))))
  7268. (if (symbolp event)
  7269. event-type
  7270. (cons event-type (cdr event)))))))
  7271. (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
  7272. (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
  7273. (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
  7274. (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
  7275. (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
  7276. (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
  7277. ;;;; Keypad support.
  7278. ;; Make the keypad keys act like ordinary typing keys. If people add
  7279. ;; bindings for the function key symbols, then those bindings will
  7280. ;; override these, so this shouldn't interfere with any existing
  7281. ;; bindings.
  7282. ;; Also tell read-char how to handle these keys.
  7283. (mapc
  7284. (lambda (keypad-normal)
  7285. (let ((keypad (nth 0 keypad-normal))
  7286. (normal (nth 1 keypad-normal)))
  7287. (put keypad 'ascii-character normal)
  7288. (define-key function-key-map (vector keypad) (vector normal))))
  7289. ;; See also kp-keys bound in bindings.el.
  7290. '((kp-space ?\s)
  7291. (kp-tab ?\t)
  7292. (kp-enter ?\r)
  7293. (kp-separator ?,)
  7294. (kp-equal ?=)
  7295. ;; Do the same for various keys that are represented as symbols under
  7296. ;; GUIs but naturally correspond to characters.
  7297. (backspace 127)
  7298. (delete 127)
  7299. (tab ?\t)
  7300. (linefeed ?\n)
  7301. (clear ?\C-l)
  7302. (return ?\C-m)
  7303. (escape ?\e)
  7304. ))
  7305. ;;;;
  7306. ;;;; forking a twin copy of a buffer.
  7307. ;;;;
  7308. (defvar clone-buffer-hook nil
  7309. "Normal hook to run in the new buffer at the end of `clone-buffer'.")
  7310. (defvar clone-indirect-buffer-hook nil
  7311. "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
  7312. (defun clone-process (process &optional newname)
  7313. "Create a twin copy of PROCESS.
  7314. If NEWNAME is nil, it defaults to PROCESS' name;
  7315. NEWNAME is modified by adding or incrementing <N> at the end as necessary.
  7316. If PROCESS is associated with a buffer, the new process will be associated
  7317. with the current buffer instead.
  7318. Returns nil if PROCESS has already terminated."
  7319. (setq newname (or newname (process-name process)))
  7320. (if (string-match "<[0-9]+>\\'" newname)
  7321. (setq newname (substring newname 0 (match-beginning 0))))
  7322. (when (memq (process-status process) '(run stop open))
  7323. (let* ((process-connection-type (process-tty-name process))
  7324. (new-process
  7325. (if (memq (process-status process) '(open))
  7326. (let ((args (process-contact process t)))
  7327. (setq args (plist-put args :name newname))
  7328. (setq args (plist-put args :buffer
  7329. (if (process-buffer process)
  7330. (current-buffer))))
  7331. (apply 'make-network-process args))
  7332. (apply 'start-process newname
  7333. (if (process-buffer process) (current-buffer))
  7334. (process-command process)))))
  7335. (set-process-query-on-exit-flag
  7336. new-process (process-query-on-exit-flag process))
  7337. (set-process-inherit-coding-system-flag
  7338. new-process (process-inherit-coding-system-flag process))
  7339. (set-process-filter new-process (process-filter process))
  7340. (set-process-sentinel new-process (process-sentinel process))
  7341. (set-process-plist new-process (copy-sequence (process-plist process)))
  7342. new-process)))
  7343. ;; things to maybe add (currently partly covered by `funcall mode'):
  7344. ;; - syntax-table
  7345. ;; - overlays
  7346. (defun clone-buffer (&optional newname display-flag)
  7347. "Create and return a twin copy of the current buffer.
  7348. Unlike an indirect buffer, the new buffer can be edited
  7349. independently of the old one (if it is not read-only).
  7350. NEWNAME is the name of the new buffer. It may be modified by
  7351. adding or incrementing <N> at the end as necessary to create a
  7352. unique buffer name. If nil, it defaults to the name of the
  7353. current buffer, with the proper suffix. If DISPLAY-FLAG is
  7354. non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
  7355. clone a file-visiting buffer, or a buffer whose major mode symbol
  7356. has a non-nil `no-clone' property, results in an error.
  7357. Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
  7358. current buffer with appropriate suffix. However, if a prefix
  7359. argument is given, then the command prompts for NEWNAME in the
  7360. minibuffer.
  7361. This runs the normal hook `clone-buffer-hook' in the new buffer
  7362. after it has been set up properly in other respects."
  7363. (interactive
  7364. (progn
  7365. (if buffer-file-name
  7366. (error "Cannot clone a file-visiting buffer"))
  7367. (if (get major-mode 'no-clone)
  7368. (error "Cannot clone a buffer in %s mode" mode-name))
  7369. (list (if current-prefix-arg
  7370. (read-buffer "Name of new cloned buffer: " (current-buffer)))
  7371. t)))
  7372. (if buffer-file-name
  7373. (error "Cannot clone a file-visiting buffer"))
  7374. (if (get major-mode 'no-clone)
  7375. (error "Cannot clone a buffer in %s mode" mode-name))
  7376. (setq newname (or newname (buffer-name)))
  7377. (if (string-match "<[0-9]+>\\'" newname)
  7378. (setq newname (substring newname 0 (match-beginning 0))))
  7379. (let ((buf (current-buffer))
  7380. (ptmin (point-min))
  7381. (ptmax (point-max))
  7382. (pt (point))
  7383. (mk (if mark-active (mark t)))
  7384. (modified (buffer-modified-p))
  7385. (mode major-mode)
  7386. (lvars (buffer-local-variables))
  7387. (process (get-buffer-process (current-buffer)))
  7388. (new (generate-new-buffer (or newname (buffer-name)))))
  7389. (save-restriction
  7390. (widen)
  7391. (with-current-buffer new
  7392. (insert-buffer-substring buf)))
  7393. (with-current-buffer new
  7394. (narrow-to-region ptmin ptmax)
  7395. (goto-char pt)
  7396. (if mk (set-mark mk))
  7397. (set-buffer-modified-p modified)
  7398. ;; Clone the old buffer's process, if any.
  7399. (when process (clone-process process))
  7400. ;; Now set up the major mode.
  7401. (funcall mode)
  7402. ;; Set up other local variables.
  7403. (mapc (lambda (v)
  7404. (condition-case () ;in case var is read-only
  7405. (if (symbolp v)
  7406. (makunbound v)
  7407. (set (make-local-variable (car v)) (cdr v)))
  7408. (error nil)))
  7409. lvars)
  7410. ;; Run any hooks (typically set up by the major mode
  7411. ;; for cloning to work properly).
  7412. (run-hooks 'clone-buffer-hook))
  7413. (if display-flag
  7414. ;; Presumably the current buffer is shown in the selected frame, so
  7415. ;; we want to display the clone elsewhere.
  7416. (let ((same-window-regexps nil)
  7417. (same-window-buffer-names))
  7418. (pop-to-buffer new)))
  7419. new))
  7420. (defun clone-indirect-buffer (newname display-flag &optional norecord)
  7421. "Create an indirect buffer that is a twin copy of the current buffer.
  7422. Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
  7423. from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
  7424. or if not called with a prefix arg, NEWNAME defaults to the current
  7425. buffer's name. The name is modified by adding a `<N>' suffix to it
  7426. or by incrementing the N in an existing suffix. Trying to clone a
  7427. buffer whose major mode symbol has a non-nil `no-clone-indirect'
  7428. property results in an error.
  7429. DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
  7430. This is always done when called interactively.
  7431. Optional third arg NORECORD non-nil means do not put this buffer at the
  7432. front of the list of recently selected ones.
  7433. Returns the newly created indirect buffer."
  7434. (interactive
  7435. (progn
  7436. (if (get major-mode 'no-clone-indirect)
  7437. (error "Cannot indirectly clone a buffer in %s mode" mode-name))
  7438. (list (if current-prefix-arg
  7439. (read-buffer "Name of indirect buffer: " (current-buffer)))
  7440. t)))
  7441. (if (get major-mode 'no-clone-indirect)
  7442. (error "Cannot indirectly clone a buffer in %s mode" mode-name))
  7443. (setq newname (or newname (buffer-name)))
  7444. (if (string-match "<[0-9]+>\\'" newname)
  7445. (setq newname (substring newname 0 (match-beginning 0))))
  7446. (let* ((name (generate-new-buffer-name newname))
  7447. (buffer (make-indirect-buffer (current-buffer) name t)))
  7448. (with-current-buffer buffer
  7449. (run-hooks 'clone-indirect-buffer-hook))
  7450. (when display-flag
  7451. (pop-to-buffer buffer norecord))
  7452. buffer))
  7453. (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
  7454. "Like `clone-indirect-buffer' but display in another window."
  7455. (interactive
  7456. (progn
  7457. (if (get major-mode 'no-clone-indirect)
  7458. (error "Cannot indirectly clone a buffer in %s mode" mode-name))
  7459. (list (if current-prefix-arg
  7460. (read-buffer "Name of indirect buffer: " (current-buffer)))
  7461. t)))
  7462. (let ((pop-up-windows t))
  7463. (clone-indirect-buffer newname display-flag norecord)))
  7464. ;;; Handling of Backspace and Delete keys.
  7465. (defcustom normal-erase-is-backspace 'maybe
  7466. "Set the default behavior of the Delete and Backspace keys.
  7467. If set to t, Delete key deletes forward and Backspace key deletes
  7468. backward.
  7469. If set to nil, both Delete and Backspace keys delete backward.
  7470. If set to 'maybe (which is the default), Emacs automatically
  7471. selects a behavior. On window systems, the behavior depends on
  7472. the keyboard used. If the keyboard has both a Backspace key and
  7473. a Delete key, and both are mapped to their usual meanings, the
  7474. option's default value is set to t, so that Backspace can be used
  7475. to delete backward, and Delete can be used to delete forward.
  7476. If not running under a window system, customizing this option
  7477. accomplishes a similar effect by mapping C-h, which is usually
  7478. generated by the Backspace key, to DEL, and by mapping DEL to C-d
  7479. via `keyboard-translate'. The former functionality of C-h is
  7480. available on the F1 key. You should probably not use this
  7481. setting if you don't have both Backspace, Delete and F1 keys.
  7482. Setting this variable with setq doesn't take effect. Programmatically,
  7483. call `normal-erase-is-backspace-mode' (which see) instead."
  7484. :type '(choice (const :tag "Off" nil)
  7485. (const :tag "Maybe" maybe)
  7486. (other :tag "On" t))
  7487. :group 'editing-basics
  7488. :version "21.1"
  7489. :set (lambda (symbol value)
  7490. ;; The fboundp is because of a problem with :set when
  7491. ;; dumping Emacs. It doesn't really matter.
  7492. (if (fboundp 'normal-erase-is-backspace-mode)
  7493. (normal-erase-is-backspace-mode (or value 0))
  7494. (set-default symbol value))))
  7495. (defun normal-erase-is-backspace-setup-frame (&optional frame)
  7496. "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
  7497. (unless frame (setq frame (selected-frame)))
  7498. (with-selected-frame frame
  7499. (unless (terminal-parameter nil 'normal-erase-is-backspace)
  7500. (normal-erase-is-backspace-mode
  7501. (if (if (eq normal-erase-is-backspace 'maybe)
  7502. (and (not noninteractive)
  7503. (or (memq system-type '(ms-dos windows-nt))
  7504. (memq window-system '(w32 ns))
  7505. (and (memq window-system '(x))
  7506. (fboundp 'x-backspace-delete-keys-p)
  7507. (x-backspace-delete-keys-p))
  7508. ;; If the terminal Emacs is running on has erase char
  7509. ;; set to ^H, use the Backspace key for deleting
  7510. ;; backward, and the Delete key for deleting forward.
  7511. (and (null window-system)
  7512. (eq tty-erase-char ?\^H))))
  7513. normal-erase-is-backspace)
  7514. 1 0)))))
  7515. (define-minor-mode normal-erase-is-backspace-mode
  7516. "Toggle the Erase and Delete mode of the Backspace and Delete keys.
  7517. With a prefix argument ARG, enable this feature if ARG is
  7518. positive, and disable it otherwise. If called from Lisp, enable
  7519. the mode if ARG is omitted or nil.
  7520. On window systems, when this mode is on, Delete is mapped to C-d
  7521. and Backspace is mapped to DEL; when this mode is off, both
  7522. Delete and Backspace are mapped to DEL. (The remapping goes via
  7523. `local-function-key-map', so binding Delete or Backspace in the
  7524. global or local keymap will override that.)
  7525. In addition, on window systems, the bindings of C-Delete, M-Delete,
  7526. C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
  7527. the global keymap in accordance with the functionality of Delete and
  7528. Backspace. For example, if Delete is remapped to C-d, which deletes
  7529. forward, C-Delete is bound to `kill-word', but if Delete is remapped
  7530. to DEL, which deletes backward, C-Delete is bound to
  7531. `backward-kill-word'.
  7532. If not running on a window system, a similar effect is accomplished by
  7533. remapping C-h (normally produced by the Backspace key) and DEL via
  7534. `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
  7535. to C-d; if it's off, the keys are not remapped.
  7536. When not running on a window system, and this mode is turned on, the
  7537. former functionality of C-h is available on the F1 key. You should
  7538. probably not turn on this mode on a text-only terminal if you don't
  7539. have both Backspace, Delete and F1 keys.
  7540. See also `normal-erase-is-backspace'."
  7541. :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
  7542. . (lambda (v)
  7543. (setf (terminal-parameter nil 'normal-erase-is-backspace)
  7544. (if v 1 0))))
  7545. (let ((enabled (eq 1 (terminal-parameter
  7546. nil 'normal-erase-is-backspace))))
  7547. (cond ((or (memq window-system '(x w32 ns pc))
  7548. (memq system-type '(ms-dos windows-nt)))
  7549. (let ((bindings
  7550. `(([M-delete] [M-backspace])
  7551. ([C-M-delete] [C-M-backspace])
  7552. ([?\e C-delete] [?\e C-backspace]))))
  7553. (if enabled
  7554. (progn
  7555. (define-key local-function-key-map [delete] [deletechar])
  7556. (define-key local-function-key-map [kp-delete] [deletechar])
  7557. (define-key local-function-key-map [backspace] [?\C-?])
  7558. (dolist (b bindings)
  7559. ;; Not sure if input-decode-map is really right, but
  7560. ;; keyboard-translate-table (used below) only works
  7561. ;; for integer events, and key-translation-table is
  7562. ;; global (like the global-map, used earlier).
  7563. (define-key input-decode-map (car b) nil)
  7564. (define-key input-decode-map (cadr b) nil)))
  7565. (define-key local-function-key-map [delete] [?\C-?])
  7566. (define-key local-function-key-map [kp-delete] [?\C-?])
  7567. (define-key local-function-key-map [backspace] [?\C-?])
  7568. (dolist (b bindings)
  7569. (define-key input-decode-map (car b) (cadr b))
  7570. (define-key input-decode-map (cadr b) (car b))))))
  7571. (t
  7572. (if enabled
  7573. (progn
  7574. (keyboard-translate ?\C-h ?\C-?)
  7575. (keyboard-translate ?\C-? ?\C-d))
  7576. (keyboard-translate ?\C-h ?\C-h)
  7577. (keyboard-translate ?\C-? ?\C-?))))
  7578. (if (called-interactively-p 'interactive)
  7579. (message "Delete key deletes %s"
  7580. (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
  7581. "forward" "backward")))))
  7582. (defvar vis-mode-saved-buffer-invisibility-spec nil
  7583. "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
  7584. (define-minor-mode read-only-mode
  7585. "Change whether the current buffer is read-only.
  7586. With prefix argument ARG, make the buffer read-only if ARG is
  7587. positive, otherwise make it writable. If buffer is read-only
  7588. and `view-read-only' is non-nil, enter view mode.
  7589. Do not call this from a Lisp program unless you really intend to
  7590. do the same thing as the \\[read-only-mode] command, including
  7591. possibly enabling or disabling View mode. Also, note that this
  7592. command works by setting the variable `buffer-read-only', which
  7593. does not affect read-only regions caused by text properties. To
  7594. ignore read-only status in a Lisp program (whether due to text
  7595. properties or buffer state), bind `inhibit-read-only' temporarily
  7596. to a non-nil value."
  7597. :variable buffer-read-only
  7598. (cond
  7599. ((and (not buffer-read-only) view-mode)
  7600. (View-exit-and-edit)
  7601. (make-local-variable 'view-read-only)
  7602. (setq view-read-only t)) ; Must leave view mode.
  7603. ((and buffer-read-only view-read-only
  7604. ;; If view-mode is already active, `view-mode-enter' is a nop.
  7605. (not view-mode)
  7606. (not (eq (get major-mode 'mode-class) 'special)))
  7607. (view-mode-enter))))
  7608. (define-minor-mode visible-mode
  7609. "Toggle making all invisible text temporarily visible (Visible mode).
  7610. With a prefix argument ARG, enable Visible mode if ARG is
  7611. positive, and disable it otherwise. If called from Lisp, enable
  7612. the mode if ARG is omitted or nil.
  7613. This mode works by saving the value of `buffer-invisibility-spec'
  7614. and setting it to nil."
  7615. :lighter " Vis"
  7616. :group 'editing-basics
  7617. (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
  7618. (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
  7619. (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
  7620. (when visible-mode
  7621. (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
  7622. buffer-invisibility-spec)
  7623. (setq buffer-invisibility-spec nil)))
  7624. (defvar messages-buffer-mode-map
  7625. (let ((map (make-sparse-keymap)))
  7626. (set-keymap-parent map special-mode-map)
  7627. (define-key map "g" nil) ; nothing to revert
  7628. map))
  7629. (define-derived-mode messages-buffer-mode special-mode "Messages"
  7630. "Major mode used in the \"*Messages*\" buffer.")
  7631. (defun messages-buffer ()
  7632. "Return the \"*Messages*\" buffer.
  7633. If it does not exist, create and it switch it to `messages-buffer-mode'."
  7634. (or (get-buffer "*Messages*")
  7635. (with-current-buffer (get-buffer-create "*Messages*")
  7636. (messages-buffer-mode)
  7637. (current-buffer))))
  7638. ;; Minibuffer prompt stuff.
  7639. ;;(defun minibuffer-prompt-modification (start end)
  7640. ;; (error "You cannot modify the prompt"))
  7641. ;;
  7642. ;;
  7643. ;;(defun minibuffer-prompt-insertion (start end)
  7644. ;; (let ((inhibit-modification-hooks t))
  7645. ;; (delete-region start end)
  7646. ;; ;; Discard undo information for the text insertion itself
  7647. ;; ;; and for the text deletion.above.
  7648. ;; (when (consp buffer-undo-list)
  7649. ;; (setq buffer-undo-list (cddr buffer-undo-list)))
  7650. ;; (message "You cannot modify the prompt")))
  7651. ;;
  7652. ;;
  7653. ;;(setq minibuffer-prompt-properties
  7654. ;; (list 'modification-hooks '(minibuffer-prompt-modification)
  7655. ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
  7656. ;;;; Problematic external packages.
  7657. ;; rms says this should be done by specifying symbols that define
  7658. ;; versions together with bad values. This is therefore not as
  7659. ;; flexible as it could be. See the thread:
  7660. ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
  7661. (defconst bad-packages-alist
  7662. ;; Not sure exactly which semantic versions have problems.
  7663. ;; Definitely 2.0pre3, probably all 2.0pre's before this.
  7664. '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
  7665. "The version of `semantic' loaded does not work in Emacs 22.
  7666. It can cause constant high CPU load.
  7667. Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
  7668. ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
  7669. ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
  7670. ;; provided the `CUA-mode' feature. Since this is no longer true,
  7671. ;; we can warn the user if the `CUA-mode' feature is ever provided.
  7672. (CUA-mode t nil
  7673. "CUA-mode is now part of the standard GNU Emacs distribution,
  7674. so you can now enable CUA via the Options menu or by customizing `cua-mode'.
  7675. You have loaded an older version of CUA-mode which does not work
  7676. correctly with this version of Emacs. You should remove the old
  7677. version and use the one distributed with Emacs."))
  7678. "Alist of packages known to cause problems in this version of Emacs.
  7679. Each element has the form (PACKAGE SYMBOL REGEXP STRING).
  7680. PACKAGE is either a regular expression to match file names, or a
  7681. symbol (a feature name), like for `with-eval-after-load'.
  7682. SYMBOL is either the name of a string variable, or t. Upon
  7683. loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
  7684. warning using STRING as the message.")
  7685. (defun bad-package-check (package)
  7686. "Run a check using the element from `bad-packages-alist' matching PACKAGE."
  7687. (condition-case nil
  7688. (let* ((list (assoc package bad-packages-alist))
  7689. (symbol (nth 1 list)))
  7690. (and list
  7691. (boundp symbol)
  7692. (or (eq symbol t)
  7693. (and (stringp (setq symbol (eval symbol)))
  7694. (string-match-p (nth 2 list) symbol)))
  7695. (display-warning package (nth 3 list) :warning)))
  7696. (error nil)))
  7697. (dolist (elem bad-packages-alist)
  7698. (let ((pkg (car elem)))
  7699. (with-eval-after-load pkg
  7700. (bad-package-check pkg))))
  7701. ;;; Generic dispatcher commands
  7702. ;; Macro `define-alternatives' is used to create generic commands.
  7703. ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
  7704. ;; that can have different alternative implementations where choosing
  7705. ;; among them is exclusively a matter of user preference.
  7706. ;; (define-alternatives COMMAND) creates a new interactive command
  7707. ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
  7708. ;; Typically, the user will not need to customize this variable; packages
  7709. ;; wanting to add alternative implementations should use
  7710. ;;
  7711. ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
  7712. (defmacro define-alternatives (command &rest customizations)
  7713. "Define the new command `COMMAND'.
  7714. The argument `COMMAND' should be a symbol.
  7715. Running `M-x COMMAND RET' for the first time prompts for which
  7716. alternative to use and records the selected command as a custom
  7717. variable.
  7718. Running `C-u M-x COMMAND RET' prompts again for an alternative
  7719. and overwrites the previous choice.
  7720. The variable `COMMAND-alternatives' contains an alist with
  7721. alternative implementations of COMMAND. `define-alternatives'
  7722. does not have any effect until this variable is set.
  7723. CUSTOMIZATIONS, if non-nil, should be composed of alternating
  7724. `defcustom' keywords and values to add to the declaration of
  7725. `COMMAND-alternatives' (typically :group and :version)."
  7726. (let* ((command-name (symbol-name command))
  7727. (varalt-name (concat command-name "-alternatives"))
  7728. (varalt-sym (intern varalt-name))
  7729. (varimp-sym (intern (concat command-name "--implementation"))))
  7730. `(progn
  7731. (defcustom ,varalt-sym nil
  7732. ,(format "Alist of alternative implementations for the `%s' command.
  7733. Each entry must be a pair (ALTNAME . ALTFUN), where:
  7734. ALTNAME - The name shown at user to describe the alternative implementation.
  7735. ALTFUN - The function called to implement this alternative."
  7736. command-name)
  7737. :type '(alist :key-type string :value-type function)
  7738. ,@customizations)
  7739. (put ',varalt-sym 'definition-name ',command)
  7740. (defvar ,varimp-sym nil "Internal use only.")
  7741. (defun ,command (&optional arg)
  7742. ,(format "Run generic command `%s'.
  7743. If used for the first time, or with interactive ARG, ask the user which
  7744. implementation to use for `%s'. The variable `%s'
  7745. contains the list of implementations currently supported for this command."
  7746. command-name command-name varalt-name)
  7747. (interactive "P")
  7748. (when (or arg (null ,varimp-sym))
  7749. (let ((val (completing-read
  7750. ,(format-message
  7751. "Select implementation for command `%s': "
  7752. command-name)
  7753. ,varalt-sym nil t)))
  7754. (unless (string-equal val "")
  7755. (when (null ,varimp-sym)
  7756. (message
  7757. "Use C-u M-x %s RET`to select another implementation"
  7758. ,command-name)
  7759. (sit-for 3))
  7760. (customize-save-variable ',varimp-sym
  7761. (cdr (assoc-string val ,varalt-sym))))))
  7762. (if ,varimp-sym
  7763. (call-interactively ,varimp-sym)
  7764. (message "%s" ,(format-message
  7765. "No implementation selected for command `%s'"
  7766. command-name)))))))
  7767. ;;; Functions for changing capitalization that Do What I Mean
  7768. (defun upcase-dwim (arg)
  7769. "Upcase words in the region, if active; if not, upcase word at point.
  7770. If the region is active, this function calls `upcase-region'.
  7771. Otherwise, it calls `upcase-word', with prefix argument passed to it
  7772. to upcase ARG words."
  7773. (interactive "*p")
  7774. (if (use-region-p)
  7775. (upcase-region (region-beginning) (region-end))
  7776. (upcase-word arg)))
  7777. (defun downcase-dwim (arg)
  7778. "Downcase words in the region, if active; if not, downcase word at point.
  7779. If the region is active, this function calls `downcase-region'.
  7780. Otherwise, it calls `downcase-word', with prefix argument passed to it
  7781. to downcase ARG words."
  7782. (interactive "*p")
  7783. (if (use-region-p)
  7784. (downcase-region (region-beginning) (region-end))
  7785. (downcase-word arg)))
  7786. (defun capitalize-dwim (arg)
  7787. "Capitalize words in the region, if active; if not, capitalize word at point.
  7788. If the region is active, this function calls `capitalize-region'.
  7789. Otherwise, it calls `capitalize-word', with prefix argument passed to it
  7790. to capitalize ARG words."
  7791. (interactive "*p")
  7792. (if (use-region-p)
  7793. (capitalize-region (region-beginning) (region-end))
  7794. (capitalize-word arg)))
  7795. (provide 'simple)
  7796. ;;; simple.el ends here