simple.el 333 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355
  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. (defun open-line (n)
  395. "Insert a newline and leave point before it.
  396. If there is a fill prefix and/or a `left-margin', insert them
  397. on the new line if the line would have been blank.
  398. With arg N, insert N newlines."
  399. (interactive "*p")
  400. (let* ((do-fill-prefix (and fill-prefix (bolp)))
  401. (do-left-margin (and (bolp) (> (current-left-margin) 0)))
  402. (loc (point-marker))
  403. ;; Don't expand an abbrev before point.
  404. (abbrev-mode nil))
  405. (newline n)
  406. (goto-char loc)
  407. (while (> n 0)
  408. (cond ((bolp)
  409. (if do-left-margin (indent-to (current-left-margin)))
  410. (if do-fill-prefix (insert-and-inherit fill-prefix))))
  411. (forward-line 1)
  412. (setq n (1- n)))
  413. (goto-char loc)
  414. (end-of-line)))
  415. (defun split-line (&optional arg)
  416. "Split current line, moving portion beyond point vertically down.
  417. If the current line starts with `fill-prefix', insert it on the new
  418. line as well. With prefix ARG, don't insert `fill-prefix' on new line.
  419. When called from Lisp code, ARG may be a prefix string to copy."
  420. (interactive "*P")
  421. (skip-chars-forward " \t")
  422. (let* ((col (current-column))
  423. (pos (point))
  424. ;; What prefix should we check for (nil means don't).
  425. (prefix (cond ((stringp arg) arg)
  426. (arg nil)
  427. (t fill-prefix)))
  428. ;; Does this line start with it?
  429. (have-prfx (and prefix
  430. (save-excursion
  431. (beginning-of-line)
  432. (looking-at (regexp-quote prefix))))))
  433. (newline 1)
  434. (if have-prfx (insert-and-inherit prefix))
  435. (indent-to col 0)
  436. (goto-char pos)))
  437. (defun delete-indentation (&optional arg)
  438. "Join this line to previous and fix up whitespace at join.
  439. If there is a fill prefix, delete it from the beginning of this line.
  440. With argument, join this line to following line."
  441. (interactive "*P")
  442. (beginning-of-line)
  443. (if arg (forward-line 1))
  444. (if (eq (preceding-char) ?\n)
  445. (progn
  446. (delete-region (point) (1- (point)))
  447. ;; If the second line started with the fill prefix,
  448. ;; delete the prefix.
  449. (if (and fill-prefix
  450. (<= (+ (point) (length fill-prefix)) (point-max))
  451. (string= fill-prefix
  452. (buffer-substring (point)
  453. (+ (point) (length fill-prefix)))))
  454. (delete-region (point) (+ (point) (length fill-prefix))))
  455. (fixup-whitespace))))
  456. (defalias 'join-line #'delete-indentation) ; easier to find
  457. (defun delete-blank-lines ()
  458. "On blank line, delete all surrounding blank lines, leaving just one.
  459. On isolated blank line, delete that one.
  460. On nonblank line, delete any immediately following blank lines."
  461. (interactive "*")
  462. (let (thisblank singleblank)
  463. (save-excursion
  464. (beginning-of-line)
  465. (setq thisblank (looking-at "[ \t]*$"))
  466. ;; Set singleblank if there is just one blank line here.
  467. (setq singleblank
  468. (and thisblank
  469. (not (looking-at "[ \t]*\n[ \t]*$"))
  470. (or (bobp)
  471. (progn (forward-line -1)
  472. (not (looking-at "[ \t]*$")))))))
  473. ;; Delete preceding blank lines, and this one too if it's the only one.
  474. (if thisblank
  475. (progn
  476. (beginning-of-line)
  477. (if singleblank (forward-line 1))
  478. (delete-region (point)
  479. (if (re-search-backward "[^ \t\n]" nil t)
  480. (progn (forward-line 1) (point))
  481. (point-min)))))
  482. ;; Delete following blank lines, unless the current line is blank
  483. ;; and there are no following blank lines.
  484. (if (not (and thisblank singleblank))
  485. (save-excursion
  486. (end-of-line)
  487. (forward-line 1)
  488. (delete-region (point)
  489. (if (re-search-forward "[^ \t\n]" nil t)
  490. (progn (beginning-of-line) (point))
  491. (point-max)))))
  492. ;; Handle the special case where point is followed by newline and eob.
  493. ;; Delete the line, leaving point at eob.
  494. (if (looking-at "^[ \t]*\n\\'")
  495. (delete-region (point) (point-max)))))
  496. (defcustom delete-trailing-lines t
  497. "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
  498. Trailing lines are deleted only if `delete-trailing-whitespace'
  499. is called on the entire buffer (rather than an active region)."
  500. :type 'boolean
  501. :group 'editing
  502. :version "24.3")
  503. (defun delete-trailing-whitespace (&optional start end)
  504. "Delete trailing whitespace between START and END.
  505. If called interactively, START and END are the start/end of the
  506. region if the mark is active, or of the buffer's accessible
  507. portion if the mark is inactive.
  508. This command deletes whitespace characters after the last
  509. non-whitespace character in each line between START and END. It
  510. does not consider formfeed characters to be whitespace.
  511. If this command acts on the entire buffer (i.e. if called
  512. interactively with the mark inactive, or called from Lisp with
  513. END nil), it also deletes all trailing lines at the end of the
  514. buffer if the variable `delete-trailing-lines' is non-nil."
  515. (interactive (progn
  516. (barf-if-buffer-read-only)
  517. (if (use-region-p)
  518. (list (region-beginning) (region-end))
  519. (list nil nil))))
  520. (save-match-data
  521. (save-excursion
  522. (let ((end-marker (copy-marker (or end (point-max))))
  523. (start (or start (point-min))))
  524. (goto-char start)
  525. (while (re-search-forward "\\s-$" end-marker t)
  526. (skip-syntax-backward "-" (line-beginning-position))
  527. ;; Don't delete formfeeds, even if they are considered whitespace.
  528. (if (looking-at-p ".*\f")
  529. (goto-char (match-end 0)))
  530. (delete-region (point) (match-end 0)))
  531. ;; Delete trailing empty lines.
  532. (goto-char end-marker)
  533. (when (and (not end)
  534. delete-trailing-lines
  535. ;; Really the end of buffer.
  536. (= (point-max) (1+ (buffer-size)))
  537. (<= (skip-chars-backward "\n") -2))
  538. (delete-region (1+ (point)) end-marker))
  539. (set-marker end-marker nil))))
  540. ;; Return nil for the benefit of `write-file-functions'.
  541. nil)
  542. (defun newline-and-indent ()
  543. "Insert a newline, then indent according to major mode.
  544. Indentation is done using the value of `indent-line-function'.
  545. In programming language modes, this is the same as TAB.
  546. In some text modes, where TAB inserts a tab, this command indents to the
  547. column specified by the function `current-left-margin'."
  548. (interactive "*")
  549. (delete-horizontal-space t)
  550. (newline nil t)
  551. (indent-according-to-mode))
  552. (defun reindent-then-newline-and-indent ()
  553. "Reindent current line, insert newline, then indent the new line.
  554. Indentation of both lines is done according to the current major mode,
  555. which means calling the current value of `indent-line-function'.
  556. In programming language modes, this is the same as TAB.
  557. In some text modes, where TAB inserts a tab, this indents to the
  558. column specified by the function `current-left-margin'."
  559. (interactive "*")
  560. (let ((pos (point)))
  561. ;; Be careful to insert the newline before indenting the line.
  562. ;; Otherwise, the indentation might be wrong.
  563. (newline)
  564. (save-excursion
  565. (goto-char pos)
  566. ;; We are at EOL before the call to indent-according-to-mode, and
  567. ;; after it we usually are as well, but not always. We tried to
  568. ;; address it with `save-excursion' but that uses a normal marker
  569. ;; whereas we need `move after insertion', so we do the save/restore
  570. ;; by hand.
  571. (setq pos (copy-marker pos t))
  572. (indent-according-to-mode)
  573. (goto-char pos)
  574. ;; Remove the trailing white-space after indentation because
  575. ;; indentation may introduce the whitespace.
  576. (delete-horizontal-space t))
  577. (indent-according-to-mode)))
  578. (defcustom read-quoted-char-radix 8
  579. "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
  580. Legitimate radix values are 8, 10 and 16."
  581. :type '(choice (const 8) (const 10) (const 16))
  582. :group 'editing-basics)
  583. (defun read-quoted-char (&optional prompt)
  584. "Like `read-char', but do not allow quitting.
  585. Also, if the first character read is an octal digit,
  586. we read any number of octal digits and return the
  587. specified character code. Any nondigit terminates the sequence.
  588. If the terminator is RET, it is discarded;
  589. any other terminator is used itself as input.
  590. The optional argument PROMPT specifies a string to use to prompt the user.
  591. The variable `read-quoted-char-radix' controls which radix to use
  592. for numeric input."
  593. (let ((message-log-max nil)
  594. (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
  595. help-event-list)))
  596. done (first t) (code 0) translated)
  597. (while (not done)
  598. (let ((inhibit-quit first)
  599. ;; Don't let C-h or other help chars get the help
  600. ;; message--only help function keys. See bug#16617.
  601. (help-char nil)
  602. (help-event-list help-events)
  603. (help-form
  604. "Type the special character you want to use,
  605. or the octal character code.
  606. RET terminates the character code and is discarded;
  607. any other non-digit terminates the character code and is then used as input."))
  608. (setq translated (read-key (and prompt (format "%s-" prompt))))
  609. (if inhibit-quit (setq quit-flag nil)))
  610. (if (integerp translated)
  611. (setq translated (char-resolve-modifiers translated)))
  612. (cond ((null translated))
  613. ((not (integerp translated))
  614. (setq unread-command-events
  615. (nconc (listify-key-sequence (this-single-command-raw-keys))
  616. unread-command-events)
  617. done t))
  618. ((/= (logand translated ?\M-\^@) 0)
  619. ;; Turn a meta-character into a character with the 0200 bit set.
  620. (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
  621. done t))
  622. ((and (<= ?0 translated)
  623. (< translated (+ ?0 (min 10 read-quoted-char-radix))))
  624. (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
  625. (and prompt (setq prompt (message "%s %c" prompt translated))))
  626. ((and (<= ?a (downcase translated))
  627. (< (downcase translated)
  628. (+ ?a -10 (min 36 read-quoted-char-radix))))
  629. (setq code (+ (* code read-quoted-char-radix)
  630. (+ 10 (- (downcase translated) ?a))))
  631. (and prompt (setq prompt (message "%s %c" prompt translated))))
  632. ((and (not first) (eq translated ?\C-m))
  633. (setq done t))
  634. ((not first)
  635. (setq unread-command-events
  636. (nconc (listify-key-sequence (this-single-command-raw-keys))
  637. unread-command-events)
  638. done t))
  639. (t (setq code translated
  640. done t)))
  641. (setq first nil))
  642. code))
  643. (defun quoted-insert (arg)
  644. "Read next input character and insert it.
  645. This is useful for inserting control characters.
  646. With argument, insert ARG copies of the character.
  647. If the first character you type after this command is an octal digit,
  648. you should type a sequence of octal digits which specify a character code.
  649. Any nondigit terminates the sequence. If the terminator is a RET,
  650. it is discarded; any other terminator is used itself as input.
  651. The variable `read-quoted-char-radix' specifies the radix for this feature;
  652. set it to 10 or 16 to use decimal or hex instead of octal.
  653. In overwrite mode, this function inserts the character anyway, and
  654. does not handle octal digits specially. This means that if you use
  655. overwrite as your normal editing mode, you can use this function to
  656. insert characters when necessary.
  657. In binary overwrite mode, this function does overwrite, and octal
  658. digits are interpreted as a character code. This is intended to be
  659. useful for editing binary files."
  660. (interactive "*p")
  661. (let* ((char
  662. ;; Avoid "obsolete" warnings for translation-table-for-input.
  663. (with-no-warnings
  664. (let (translation-table-for-input input-method-function)
  665. (if (or (not overwrite-mode)
  666. (eq overwrite-mode 'overwrite-mode-binary))
  667. (read-quoted-char)
  668. (read-char))))))
  669. ;; This used to assume character codes 0240 - 0377 stand for
  670. ;; characters in some single-byte character set, and converted them
  671. ;; to Emacs characters. But in 23.1 this feature is deprecated
  672. ;; in favor of inserting the corresponding Unicode characters.
  673. ;; (if (and enable-multibyte-characters
  674. ;; (>= char ?\240)
  675. ;; (<= char ?\377))
  676. ;; (setq char (unibyte-char-to-multibyte char)))
  677. (unless (characterp char)
  678. (user-error "%s is not a valid character"
  679. (key-description (vector char))))
  680. (if (> arg 0)
  681. (if (eq overwrite-mode 'overwrite-mode-binary)
  682. (delete-char arg)))
  683. (while (> arg 0)
  684. (insert-and-inherit char)
  685. (setq arg (1- arg)))))
  686. (defun forward-to-indentation (&optional arg)
  687. "Move forward ARG lines and position at first nonblank character."
  688. (interactive "^p")
  689. (forward-line (or arg 1))
  690. (skip-chars-forward " \t"))
  691. (defun backward-to-indentation (&optional arg)
  692. "Move backward ARG lines and position at first nonblank character."
  693. (interactive "^p")
  694. (forward-line (- (or arg 1)))
  695. (skip-chars-forward " \t"))
  696. (defun back-to-indentation ()
  697. "Move point to the first non-whitespace character on this line."
  698. (interactive "^")
  699. (beginning-of-line 1)
  700. (skip-syntax-forward " " (line-end-position))
  701. ;; Move back over chars that have whitespace syntax but have the p flag.
  702. (backward-prefix-chars))
  703. (defun fixup-whitespace ()
  704. "Fixup white space between objects around point.
  705. Leave one space or none, according to the context."
  706. (interactive "*")
  707. (save-excursion
  708. (delete-horizontal-space)
  709. (if (or (looking-at "^\\|\\s)")
  710. (save-excursion (forward-char -1)
  711. (looking-at "$\\|\\s(\\|\\s'")))
  712. nil
  713. (insert ?\s))))
  714. (defun delete-horizontal-space (&optional backward-only)
  715. "Delete all spaces and tabs around point.
  716. If BACKWARD-ONLY is non-nil, only delete them before point."
  717. (interactive "*P")
  718. (let ((orig-pos (point)))
  719. (delete-region
  720. (if backward-only
  721. orig-pos
  722. (progn
  723. (skip-chars-forward " \t")
  724. (constrain-to-field nil orig-pos t)))
  725. (progn
  726. (skip-chars-backward " \t")
  727. (constrain-to-field nil orig-pos)))))
  728. (defun just-one-space (&optional n)
  729. "Delete all spaces and tabs around point, leaving one space (or N spaces).
  730. If N is negative, delete newlines as well, leaving -N spaces.
  731. See also `cycle-spacing'."
  732. (interactive "*p")
  733. (cycle-spacing n nil 'single-shot))
  734. (defvar cycle-spacing--context nil
  735. "Store context used in consecutive calls to `cycle-spacing' command.
  736. The first time `cycle-spacing' runs, it saves in this variable:
  737. its N argument, the original point position, and the original spacing
  738. around point.")
  739. (defun cycle-spacing (&optional n preserve-nl-back mode)
  740. "Manipulate whitespace around point in a smart way.
  741. In interactive use, this function behaves differently in successive
  742. consecutive calls.
  743. The first call in a sequence acts like `just-one-space'.
  744. It deletes all spaces and tabs around point, leaving one space
  745. \(or N spaces). N is the prefix argument. If N is negative,
  746. it deletes newlines as well, leaving -N spaces.
  747. \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
  748. The second call in a sequence deletes all spaces.
  749. The third call in a sequence restores the original whitespace (and point).
  750. If MODE is `single-shot', it only performs the first step in the sequence.
  751. If MODE is `fast' and the first step would not result in any change
  752. \(i.e., there are exactly (abs N) spaces around point),
  753. the function goes straight to the second step.
  754. Repeatedly calling the function with different values of N starts a
  755. new sequence each time."
  756. (interactive "*p")
  757. (let ((orig-pos (point))
  758. (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
  759. (num (abs (or n 1))))
  760. (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
  761. (constrain-to-field nil orig-pos)
  762. (cond
  763. ;; Command run for the first time, single-shot mode or different argument
  764. ((or (eq 'single-shot mode)
  765. (not (equal last-command this-command))
  766. (not cycle-spacing--context)
  767. (not (eq (car cycle-spacing--context) n)))
  768. (let* ((start (point))
  769. (num (- num (skip-chars-forward " " (+ num (point)))))
  770. (mid (point))
  771. (end (progn
  772. (skip-chars-forward skip-characters)
  773. (constrain-to-field nil orig-pos t))))
  774. (setq cycle-spacing--context ;; Save for later.
  775. ;; Special handling for case where there was no space at all.
  776. (unless (= start end)
  777. (cons n (cons orig-pos (buffer-substring start (point))))))
  778. ;; If this run causes no change in buffer content, delete all spaces,
  779. ;; otherwise delete all excess spaces.
  780. (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
  781. start mid) end)
  782. (insert (make-string num ?\s))))
  783. ;; Command run for the second time.
  784. ((not (equal orig-pos (point)))
  785. (delete-region (point) orig-pos))
  786. ;; Command run for the third time.
  787. (t
  788. (insert (cddr cycle-spacing--context))
  789. (goto-char (cadr cycle-spacing--context))
  790. (setq cycle-spacing--context nil)))))
  791. (defun beginning-of-buffer (&optional arg)
  792. "Move point to the beginning of the buffer.
  793. With numeric arg N, put point N/10 of the way from the beginning.
  794. If the buffer is narrowed, this command uses the beginning of the
  795. accessible part of the buffer.
  796. If Transient Mark mode is disabled, leave mark at previous
  797. position, unless a \\[universal-argument] prefix is supplied."
  798. (declare (interactive-only "use `(goto-char (point-min))' instead."))
  799. (interactive "^P")
  800. (or (consp arg)
  801. (region-active-p)
  802. (push-mark))
  803. (let ((size (- (point-max) (point-min))))
  804. (goto-char (if (and arg (not (consp arg)))
  805. (+ (point-min)
  806. (if (> size 10000)
  807. ;; Avoid overflow for large buffer sizes!
  808. (* (prefix-numeric-value arg)
  809. (/ size 10))
  810. (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
  811. (point-min))))
  812. (if (and arg (not (consp arg))) (forward-line 1)))
  813. (defun end-of-buffer (&optional arg)
  814. "Move point to the end of the buffer.
  815. With numeric arg N, put point N/10 of the way from the end.
  816. If the buffer is narrowed, this command uses the end of the
  817. accessible part of the buffer.
  818. If Transient Mark mode is disabled, leave mark at previous
  819. position, unless a \\[universal-argument] prefix is supplied."
  820. (declare (interactive-only "use `(goto-char (point-max))' instead."))
  821. (interactive "^P")
  822. (or (consp arg) (region-active-p) (push-mark))
  823. (let ((size (- (point-max) (point-min))))
  824. (goto-char (if (and arg (not (consp arg)))
  825. (- (point-max)
  826. (if (> size 10000)
  827. ;; Avoid overflow for large buffer sizes!
  828. (* (prefix-numeric-value arg)
  829. (/ size 10))
  830. (/ (* size (prefix-numeric-value arg)) 10)))
  831. (point-max))))
  832. ;; If we went to a place in the middle of the buffer,
  833. ;; adjust it to the beginning of a line.
  834. (cond ((and arg (not (consp arg))) (forward-line 1))
  835. ((and (eq (current-buffer) (window-buffer))
  836. (> (point) (window-end nil t)))
  837. ;; If the end of the buffer is not already on the screen,
  838. ;; then scroll specially to put it near, but not at, the bottom.
  839. (overlay-recenter (point))
  840. (recenter -3))))
  841. (defcustom delete-active-region t
  842. "Whether single-char deletion commands delete an active region.
  843. This has an effect only if Transient Mark mode is enabled, and
  844. affects `delete-forward-char' and `delete-backward-char', though
  845. not `delete-char'.
  846. If the value is the symbol `kill', the active region is killed
  847. instead of deleted."
  848. :type '(choice (const :tag "Delete active region" t)
  849. (const :tag "Kill active region" kill)
  850. (const :tag "Do ordinary deletion" nil))
  851. :group 'killing
  852. :version "24.1")
  853. (defvar region-extract-function
  854. (lambda (delete)
  855. (when (region-beginning)
  856. (if (eq delete 'delete-only)
  857. (delete-region (region-beginning) (region-end))
  858. (filter-buffer-substring (region-beginning) (region-end) delete))))
  859. "Function to get the region's content.
  860. Called with one argument DELETE.
  861. If DELETE is `delete-only', then only delete the region and the return value
  862. is undefined. If DELETE is nil, just return the content as a string.
  863. If anything else, delete the region and return its content as a string.")
  864. (defun delete-backward-char (n &optional killflag)
  865. "Delete the previous N characters (following if N is negative).
  866. If Transient Mark mode is enabled, the mark is active, and N is 1,
  867. delete the text in the region and deactivate the mark instead.
  868. To disable this, set option `delete-active-region' to nil.
  869. Optional second arg KILLFLAG, if non-nil, means to kill (save in
  870. kill ring) instead of delete. Interactively, N is the prefix
  871. arg, and KILLFLAG is set if N is explicitly specified.
  872. In Overwrite mode, single character backward deletion may replace
  873. tabs with spaces so as to back over columns, unless point is at
  874. the end of the line."
  875. (declare (interactive-only delete-char))
  876. (interactive "p\nP")
  877. (unless (integerp n)
  878. (signal 'wrong-type-argument (list 'integerp n)))
  879. (cond ((and (use-region-p)
  880. delete-active-region
  881. (= n 1))
  882. ;; If a region is active, kill or delete it.
  883. (if (eq delete-active-region 'kill)
  884. (kill-region (region-beginning) (region-end) 'region)
  885. (funcall region-extract-function 'delete-only)))
  886. ;; In Overwrite mode, maybe untabify while deleting
  887. ((null (or (null overwrite-mode)
  888. (<= n 0)
  889. (memq (char-before) '(?\t ?\n))
  890. (eobp)
  891. (eq (char-after) ?\n)))
  892. (let ((ocol (current-column)))
  893. (delete-char (- n) killflag)
  894. (save-excursion
  895. (insert-char ?\s (- ocol (current-column)) nil))))
  896. ;; Otherwise, do simple deletion.
  897. (t (delete-char (- n) killflag))))
  898. (defun delete-forward-char (n &optional killflag)
  899. "Delete the following N characters (previous if N is negative).
  900. If Transient Mark mode is enabled, the mark is active, and N is 1,
  901. delete the text in the region and deactivate the mark instead.
  902. To disable this, set variable `delete-active-region' to nil.
  903. Optional second arg KILLFLAG non-nil means to kill (save in kill
  904. ring) instead of delete. Interactively, N is the prefix arg, and
  905. KILLFLAG is set if N was explicitly specified."
  906. (declare (interactive-only delete-char))
  907. (interactive "p\nP")
  908. (unless (integerp n)
  909. (signal 'wrong-type-argument (list 'integerp n)))
  910. (cond ((and (use-region-p)
  911. delete-active-region
  912. (= n 1))
  913. ;; If a region is active, kill or delete it.
  914. (if (eq delete-active-region 'kill)
  915. (kill-region (region-beginning) (region-end) 'region)
  916. (funcall region-extract-function 'delete-only)))
  917. ;; Otherwise, do simple deletion.
  918. (t (delete-char n killflag))))
  919. (defun mark-whole-buffer ()
  920. "Put point at beginning and mark at end of buffer.
  921. If narrowing is in effect, only uses the accessible part of the buffer.
  922. You probably should not use this function in Lisp programs;
  923. it is usually a mistake for a Lisp function to use any subroutine
  924. that uses or sets the mark."
  925. (declare (interactive-only t))
  926. (interactive)
  927. (push-mark (point))
  928. (push-mark (point-max) nil t)
  929. (goto-char (point-min)))
  930. ;; Counting lines, one way or another.
  931. (defun goto-line (line &optional buffer)
  932. "Go to LINE, counting from line 1 at beginning of buffer.
  933. If called interactively, a numeric prefix argument specifies
  934. LINE; without a numeric prefix argument, read LINE from the
  935. minibuffer.
  936. If optional argument BUFFER is non-nil, switch to that buffer and
  937. move to line LINE there. If called interactively with \\[universal-argument]
  938. as argument, BUFFER is the most recently selected other buffer.
  939. Prior to moving point, this function sets the mark (without
  940. activating it), unless Transient Mark mode is enabled and the
  941. mark is already active.
  942. This function is usually the wrong thing to use in a Lisp program.
  943. What you probably want instead is something like:
  944. (goto-char (point-min))
  945. (forward-line (1- N))
  946. If at all possible, an even better solution is to use char counts
  947. rather than line counts."
  948. (declare (interactive-only forward-line))
  949. (interactive
  950. (if (and current-prefix-arg (not (consp current-prefix-arg)))
  951. (list (prefix-numeric-value current-prefix-arg))
  952. ;; Look for a default, a number in the buffer at point.
  953. (let* ((default
  954. (save-excursion
  955. (skip-chars-backward "0-9")
  956. (if (looking-at "[0-9]")
  957. (string-to-number
  958. (buffer-substring-no-properties
  959. (point)
  960. (progn (skip-chars-forward "0-9")
  961. (point)))))))
  962. ;; Decide if we're switching buffers.
  963. (buffer
  964. (if (consp current-prefix-arg)
  965. (other-buffer (current-buffer) t)))
  966. (buffer-prompt
  967. (if buffer
  968. (concat " in " (buffer-name buffer))
  969. "")))
  970. ;; Read the argument, offering that number (if any) as default.
  971. (list (read-number (format "Goto line%s: " buffer-prompt)
  972. (list default (line-number-at-pos)))
  973. buffer))))
  974. ;; Switch to the desired buffer, one way or another.
  975. (if buffer
  976. (let ((window (get-buffer-window buffer)))
  977. (if window (select-window window)
  978. (switch-to-buffer-other-window buffer))))
  979. ;; Leave mark at previous position
  980. (or (region-active-p) (push-mark))
  981. ;; Move to the specified line number in that buffer.
  982. (save-restriction
  983. (widen)
  984. (goto-char (point-min))
  985. (if (eq selective-display t)
  986. (re-search-forward "[\n\C-m]" nil 'end (1- line))
  987. (forward-line (1- line)))))
  988. (defun count-words-region (start end &optional arg)
  989. "Count the number of words in the region.
  990. If called interactively, print a message reporting the number of
  991. lines, words, and characters in the region (whether or not the
  992. region is active); with prefix ARG, report for the entire buffer
  993. rather than the region.
  994. If called from Lisp, return the number of words between positions
  995. START and END."
  996. (interactive (if current-prefix-arg
  997. (list nil nil current-prefix-arg)
  998. (list (region-beginning) (region-end) nil)))
  999. (cond ((not (called-interactively-p 'any))
  1000. (count-words start end))
  1001. (arg
  1002. (count-words--buffer-message))
  1003. (t
  1004. (count-words--message "Region" start end))))
  1005. (defun count-words (start end)
  1006. "Count words between START and END.
  1007. If called interactively, START and END are normally the start and
  1008. end of the buffer; but if the region is active, START and END are
  1009. the start and end of the region. Print a message reporting the
  1010. number of lines, words, and chars.
  1011. If called from Lisp, return the number of words between START and
  1012. END, without printing any message."
  1013. (interactive (list nil nil))
  1014. (cond ((not (called-interactively-p 'any))
  1015. (let ((words 0))
  1016. (save-excursion
  1017. (save-restriction
  1018. (narrow-to-region start end)
  1019. (goto-char (point-min))
  1020. (while (forward-word 1)
  1021. (setq words (1+ words)))))
  1022. words))
  1023. ((use-region-p)
  1024. (call-interactively 'count-words-region))
  1025. (t
  1026. (count-words--buffer-message))))
  1027. (defun count-words--buffer-message ()
  1028. (count-words--message
  1029. (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
  1030. (point-min) (point-max)))
  1031. (defun count-words--message (str start end)
  1032. (let ((lines (count-lines start end))
  1033. (words (count-words start end))
  1034. (chars (- end start)))
  1035. (message "%s has %d line%s, %d word%s, and %d character%s."
  1036. str
  1037. lines (if (= lines 1) "" "s")
  1038. words (if (= words 1) "" "s")
  1039. chars (if (= chars 1) "" "s"))))
  1040. (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
  1041. (defun what-line ()
  1042. "Print the current buffer line number and narrowed line number of point."
  1043. (interactive)
  1044. (let ((start (point-min))
  1045. (n (line-number-at-pos)))
  1046. (if (= start 1)
  1047. (message "Line %d" n)
  1048. (save-excursion
  1049. (save-restriction
  1050. (widen)
  1051. (message "line %d (narrowed line %d)"
  1052. (+ n (line-number-at-pos start) -1) n))))))
  1053. (defun count-lines (start end)
  1054. "Return number of lines between START and END.
  1055. This is usually the number of newlines between them,
  1056. but can be one more if START is not equal to END
  1057. and the greater of them is not at the start of a line."
  1058. (save-excursion
  1059. (save-restriction
  1060. (narrow-to-region start end)
  1061. (goto-char (point-min))
  1062. (if (eq selective-display t)
  1063. (save-match-data
  1064. (let ((done 0))
  1065. (while (re-search-forward "[\n\C-m]" nil t 40)
  1066. (setq done (+ 40 done)))
  1067. (while (re-search-forward "[\n\C-m]" nil t 1)
  1068. (setq done (+ 1 done)))
  1069. (goto-char (point-max))
  1070. (if (and (/= start end)
  1071. (not (bolp)))
  1072. (1+ done)
  1073. done)))
  1074. (- (buffer-size) (forward-line (buffer-size)))))))
  1075. (defun line-number-at-pos (&optional pos)
  1076. "Return (narrowed) buffer line number at position POS.
  1077. If POS is nil, use current buffer location.
  1078. Counting starts at (point-min), so the value refers
  1079. to the contents of the accessible portion of the buffer."
  1080. (let ((opoint (or pos (point))) start)
  1081. (save-excursion
  1082. (goto-char (point-min))
  1083. (setq start (point))
  1084. (goto-char opoint)
  1085. (forward-line 0)
  1086. (1+ (count-lines start (point))))))
  1087. (defun what-cursor-position (&optional detail)
  1088. "Print info on cursor position (on screen and within buffer).
  1089. Also describe the character after point, and give its character code
  1090. in octal, decimal and hex.
  1091. For a non-ASCII multibyte character, also give its encoding in the
  1092. buffer's selected coding system if the coding system encodes the
  1093. character safely. If the character is encoded into one byte, that
  1094. code is shown in hex. If the character is encoded into more than one
  1095. byte, just \"...\" is shown.
  1096. In addition, with prefix argument, show details about that character
  1097. in *Help* buffer. See also the command `describe-char'."
  1098. (interactive "P")
  1099. (let* ((char (following-char))
  1100. (bidi-fixer
  1101. ;; If the character is one of LRE, LRO, RLE, RLO, it will
  1102. ;; start a directional embedding, which could completely
  1103. ;; disrupt the rest of the line (e.g., RLO will display the
  1104. ;; rest of the line right-to-left). So we put an invisible
  1105. ;; PDF character after these characters, to end the
  1106. ;; embedding, which eliminates any effects on the rest of
  1107. ;; the line. For RLE and RLO we also append an invisible
  1108. ;; LRM, to avoid reordering the following numerical
  1109. ;; characters. For LRI/RLI/FSI we append a PDI.
  1110. (cond ((memq char '(?\x202a ?\x202d))
  1111. (propertize (string ?\x202c) 'invisible t))
  1112. ((memq char '(?\x202b ?\x202e))
  1113. (propertize (string ?\x202c ?\x200e) 'invisible t))
  1114. ((memq char '(?\x2066 ?\x2067 ?\x2068))
  1115. (propertize (string ?\x2069) 'invisible t))
  1116. ;; Strong right-to-left characters cause reordering of
  1117. ;; the following numerical characters which show the
  1118. ;; codepoint, so append LRM to countermand that.
  1119. ((memq (get-char-code-property char 'bidi-class) '(R AL))
  1120. (propertize (string ?\x200e) 'invisible t))
  1121. (t
  1122. "")))
  1123. (beg (point-min))
  1124. (end (point-max))
  1125. (pos (point))
  1126. (total (buffer-size))
  1127. (percent (round (* 100.0 (1- pos)) (max 1 total)))
  1128. (hscroll (if (= (window-hscroll) 0)
  1129. ""
  1130. (format " Hscroll=%d" (window-hscroll))))
  1131. (col (current-column)))
  1132. (if (= pos end)
  1133. (if (or (/= beg 1) (/= end (1+ total)))
  1134. (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
  1135. pos total percent beg end col hscroll)
  1136. (message "point=%d of %d (EOB) column=%d%s"
  1137. pos total col hscroll))
  1138. (let ((coding buffer-file-coding-system)
  1139. encoded encoding-msg display-prop under-display)
  1140. (if (or (not coding)
  1141. (eq (coding-system-type coding) t))
  1142. (setq coding (default-value 'buffer-file-coding-system)))
  1143. (if (eq (char-charset char) 'eight-bit)
  1144. (setq encoding-msg
  1145. (format "(%d, #o%o, #x%x, raw-byte)" char char char))
  1146. ;; Check if the character is displayed with some `display'
  1147. ;; text property. In that case, set under-display to the
  1148. ;; buffer substring covered by that property.
  1149. (setq display-prop (get-char-property pos 'display))
  1150. (if display-prop
  1151. (let ((to (or (next-single-char-property-change pos 'display)
  1152. (point-max))))
  1153. (if (< to (+ pos 4))
  1154. (setq under-display "")
  1155. (setq under-display "..."
  1156. to (+ pos 4)))
  1157. (setq under-display
  1158. (concat (buffer-substring-no-properties pos to)
  1159. under-display)))
  1160. (setq encoded (and (>= char 128) (encode-coding-char char coding))))
  1161. (setq encoding-msg
  1162. (if display-prop
  1163. (if (not (stringp display-prop))
  1164. (format "(%d, #o%o, #x%x, part of display \"%s\")"
  1165. char char char under-display)
  1166. (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
  1167. char char char under-display display-prop))
  1168. (if encoded
  1169. (format "(%d, #o%o, #x%x, file %s)"
  1170. char char char
  1171. (if (> (length encoded) 1)
  1172. "..."
  1173. (encoded-string-description encoded coding)))
  1174. (format "(%d, #o%o, #x%x)" char char char)))))
  1175. (if detail
  1176. ;; We show the detailed information about CHAR.
  1177. (describe-char (point)))
  1178. (if (or (/= beg 1) (/= end (1+ total)))
  1179. (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
  1180. (if (< char 256)
  1181. (single-key-description char)
  1182. (buffer-substring-no-properties (point) (1+ (point))))
  1183. bidi-fixer
  1184. encoding-msg pos total percent beg end col hscroll)
  1185. (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
  1186. (if enable-multibyte-characters
  1187. (if (< char 128)
  1188. (single-key-description char)
  1189. (buffer-substring-no-properties (point) (1+ (point))))
  1190. (single-key-description char))
  1191. bidi-fixer encoding-msg pos total percent col hscroll))))))
  1192. ;; Initialize read-expression-map. It is defined at C level.
  1193. (defvar read-expression-map
  1194. (let ((m (make-sparse-keymap)))
  1195. (define-key m "\M-\t" 'completion-at-point)
  1196. ;; Might as well bind TAB to completion, since inserting a TAB char is
  1197. ;; much too rarely useful.
  1198. (define-key m "\t" 'completion-at-point)
  1199. (set-keymap-parent m minibuffer-local-map)
  1200. m))
  1201. (defun read-minibuffer (prompt &optional initial-contents)
  1202. "Return a Lisp object read using the minibuffer, unevaluated.
  1203. Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
  1204. is a string to insert in the minibuffer before reading.
  1205. \(INITIAL-CONTENTS can also be a cons of a string and an integer.
  1206. Such arguments are used as in `read-from-minibuffer'.)"
  1207. ;; Used for interactive spec `x'.
  1208. (read-from-minibuffer prompt initial-contents minibuffer-local-map
  1209. t 'minibuffer-history))
  1210. (defun eval-minibuffer (prompt &optional initial-contents)
  1211. "Return value of Lisp expression read using the minibuffer.
  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. (eval (read--expression prompt initial-contents)))
  1218. (defvar minibuffer-completing-symbol nil
  1219. "Non-nil means completing a Lisp symbol in the minibuffer.")
  1220. (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
  1221. (defvar minibuffer-default nil
  1222. "The current default value or list of default values in the minibuffer.
  1223. The functions `read-from-minibuffer' and `completing-read' bind
  1224. this variable locally.")
  1225. (defcustom eval-expression-print-level 4
  1226. "Value for `print-level' while printing value in `eval-expression'.
  1227. A value of nil means no limit."
  1228. :group 'lisp
  1229. :type '(choice (const :tag "No Limit" nil) integer)
  1230. :version "21.1")
  1231. (defcustom eval-expression-print-length 12
  1232. "Value for `print-length' while printing value in `eval-expression'.
  1233. A value of nil means no limit."
  1234. :group 'lisp
  1235. :type '(choice (const :tag "No Limit" nil) integer)
  1236. :version "21.1")
  1237. (defcustom eval-expression-debug-on-error t
  1238. "If non-nil set `debug-on-error' to t in `eval-expression'.
  1239. If nil, don't change the value of `debug-on-error'."
  1240. :group 'lisp
  1241. :type 'boolean
  1242. :version "21.1")
  1243. (defun eval-expression-print-format (value)
  1244. "Format VALUE as a result of evaluated expression.
  1245. Return a formatted string which is displayed in the echo area
  1246. in addition to the value printed by prin1 in functions which
  1247. display the result of expression evaluation."
  1248. (if (and (integerp value)
  1249. (or (eq standard-output t)
  1250. (zerop (prefix-numeric-value current-prefix-arg))))
  1251. (let ((char-string
  1252. (if (and (characterp value)
  1253. (char-displayable-p value))
  1254. (prin1-char value))))
  1255. (if char-string
  1256. (format " (#o%o, #x%x, %s)" value value char-string)
  1257. (format " (#o%o, #x%x)" value value)))))
  1258. (defvar eval-expression-minibuffer-setup-hook nil
  1259. "Hook run by `eval-expression' when entering the minibuffer.")
  1260. (defun read--expression (prompt &optional initial-contents)
  1261. (let ((minibuffer-completing-symbol t))
  1262. (minibuffer-with-setup-hook
  1263. (lambda ()
  1264. ;; FIXME: call emacs-lisp-mode?
  1265. (add-function :before-until (local 'eldoc-documentation-function)
  1266. #'elisp-eldoc-documentation-function)
  1267. (add-hook 'completion-at-point-functions
  1268. #'elisp-completion-at-point nil t)
  1269. (run-hooks 'eval-expression-minibuffer-setup-hook))
  1270. (read-from-minibuffer prompt initial-contents
  1271. read-expression-map t
  1272. 'read-expression-history))))
  1273. ;; We define this, rather than making `eval' interactive,
  1274. ;; for the sake of completion of names like eval-region, eval-buffer.
  1275. (defun eval-expression (exp &optional insert-value)
  1276. "Evaluate EXP and print value in the echo area.
  1277. When called interactively, read an Emacs Lisp expression and evaluate it.
  1278. Value is also consed on to front of the variable `values'.
  1279. Optional argument INSERT-VALUE non-nil (interactively, with prefix
  1280. argument) means insert the result into the current buffer instead of
  1281. printing it in the echo area.
  1282. Normally, this function truncates long output according to the value
  1283. of the variables `eval-expression-print-length' and
  1284. `eval-expression-print-level'. With a prefix argument of zero,
  1285. however, there is no such truncation. Such a prefix argument
  1286. also causes integers to be printed in several additional formats
  1287. \(octal, hexadecimal, and character).
  1288. Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
  1289. minibuffer.
  1290. If `eval-expression-debug-on-error' is non-nil, which is the default,
  1291. this command arranges for all errors to enter the debugger."
  1292. (interactive
  1293. (list (read--expression "Eval: ")
  1294. current-prefix-arg))
  1295. (if (null eval-expression-debug-on-error)
  1296. (push (eval exp lexical-binding) values)
  1297. (let ((old-value (make-symbol "t")) new-value)
  1298. ;; Bind debug-on-error to something unique so that we can
  1299. ;; detect when evalled code changes it.
  1300. (let ((debug-on-error old-value))
  1301. (push (eval (macroexpand-all exp) lexical-binding) values)
  1302. (setq new-value debug-on-error))
  1303. ;; If evalled code has changed the value of debug-on-error,
  1304. ;; propagate that change to the global binding.
  1305. (unless (eq old-value new-value)
  1306. (setq debug-on-error new-value))))
  1307. (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
  1308. eval-expression-print-length))
  1309. (print-level (and (not (zerop (prefix-numeric-value insert-value)))
  1310. eval-expression-print-level))
  1311. (deactivate-mark))
  1312. (if insert-value
  1313. (with-no-warnings
  1314. (let ((standard-output (current-buffer)))
  1315. (prog1
  1316. (prin1 (car values))
  1317. (when (zerop (prefix-numeric-value insert-value))
  1318. (let ((str (eval-expression-print-format (car values))))
  1319. (if str (princ str)))))))
  1320. (prog1
  1321. (prin1 (car values) t)
  1322. (let ((str (eval-expression-print-format (car values))))
  1323. (if str (princ str t)))))))
  1324. (defun edit-and-eval-command (prompt command)
  1325. "Prompting with PROMPT, let user edit COMMAND and eval result.
  1326. COMMAND is a Lisp expression. Let user edit that expression in
  1327. the minibuffer, then read and evaluate the result."
  1328. (let ((command
  1329. (let ((print-level nil)
  1330. (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
  1331. (unwind-protect
  1332. (read-from-minibuffer prompt
  1333. (prin1-to-string command)
  1334. read-expression-map t
  1335. 'command-history)
  1336. ;; If command was added to command-history as a string,
  1337. ;; get rid of that. We want only evaluable expressions there.
  1338. (if (stringp (car command-history))
  1339. (setq command-history (cdr command-history)))))))
  1340. ;; If command to be redone does not match front of history,
  1341. ;; add it to the history.
  1342. (or (equal command (car command-history))
  1343. (setq command-history (cons command command-history)))
  1344. (eval command)))
  1345. (defun repeat-complex-command (arg)
  1346. "Edit and re-evaluate last complex command, or ARGth from last.
  1347. A complex command is one which used the minibuffer.
  1348. The command is placed in the minibuffer as a Lisp form for editing.
  1349. The result is executed, repeating the command as changed.
  1350. If the command has been changed or is not the most recent previous
  1351. command it is added to the front of the command history.
  1352. You can use the minibuffer history commands \
  1353. \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
  1354. to get different commands to edit and resubmit."
  1355. (interactive "p")
  1356. (let ((elt (nth (1- arg) command-history))
  1357. newcmd)
  1358. (if elt
  1359. (progn
  1360. (setq newcmd
  1361. (let ((print-level nil)
  1362. (minibuffer-history-position arg)
  1363. (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
  1364. (unwind-protect
  1365. (read-from-minibuffer
  1366. "Redo: " (prin1-to-string elt) read-expression-map t
  1367. (cons 'command-history arg))
  1368. ;; If command was added to command-history as a
  1369. ;; string, get rid of that. We want only
  1370. ;; evaluable expressions there.
  1371. (if (stringp (car command-history))
  1372. (setq command-history (cdr command-history))))))
  1373. ;; If command to be redone does not match front of history,
  1374. ;; add it to the history.
  1375. (or (equal newcmd (car command-history))
  1376. (setq command-history (cons newcmd command-history)))
  1377. (apply #'funcall-interactively
  1378. (car newcmd)
  1379. (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
  1380. (if command-history
  1381. (error "Argument %d is beyond length of command history" arg)
  1382. (error "There are no previous complex commands to repeat")))))
  1383. (defvar extended-command-history nil)
  1384. (defvar execute-extended-command--last-typed nil)
  1385. (defun read-extended-command ()
  1386. "Read command name to invoke in `execute-extended-command'."
  1387. (minibuffer-with-setup-hook
  1388. (lambda ()
  1389. (add-hook 'post-self-insert-hook
  1390. (lambda ()
  1391. (setq execute-extended-command--last-typed
  1392. (minibuffer-contents)))
  1393. nil 'local)
  1394. (set (make-local-variable 'minibuffer-default-add-function)
  1395. (lambda ()
  1396. ;; Get a command name at point in the original buffer
  1397. ;; to propose it after M-n.
  1398. (with-current-buffer (window-buffer (minibuffer-selected-window))
  1399. (and (commandp (function-called-at-point))
  1400. (format "%S" (function-called-at-point)))))))
  1401. ;; Read a string, completing from and restricting to the set of
  1402. ;; all defined commands. Don't provide any initial input.
  1403. ;; Save the command read on the extended-command history list.
  1404. (completing-read
  1405. (concat (cond
  1406. ((eq current-prefix-arg '-) "- ")
  1407. ((and (consp current-prefix-arg)
  1408. (eq (car current-prefix-arg) 4)) "C-u ")
  1409. ((and (consp current-prefix-arg)
  1410. (integerp (car current-prefix-arg)))
  1411. (format "%d " (car current-prefix-arg)))
  1412. ((integerp current-prefix-arg)
  1413. (format "%d " current-prefix-arg)))
  1414. ;; This isn't strictly correct if `execute-extended-command'
  1415. ;; is bound to anything else (e.g. [menu]).
  1416. ;; It could use (key-description (this-single-command-keys)),
  1417. ;; but actually a prompt other than "M-x" would be confusing,
  1418. ;; because "M-x" is a well-known prompt to read a command
  1419. ;; and it serves as a shorthand for "Extended command: ".
  1420. "M-x ")
  1421. (lambda (string pred action)
  1422. (let ((pred
  1423. (if (memq action '(nil t))
  1424. ;; Exclude obsolete commands from completions.
  1425. (lambda (sym)
  1426. (and (funcall pred sym)
  1427. (or (equal string (symbol-name sym))
  1428. (not (get sym 'byte-obsolete-info)))))
  1429. pred)))
  1430. (complete-with-action action obarray string pred)))
  1431. #'commandp t nil 'extended-command-history)))
  1432. (defcustom suggest-key-bindings t
  1433. "Non-nil means show the equivalent key-binding when M-x command has one.
  1434. The value can be a length of time to show the message for.
  1435. If the value is non-nil and not a number, we wait 2 seconds."
  1436. :group 'keyboard
  1437. :type '(choice (const :tag "off" nil)
  1438. (integer :tag "time" 2)
  1439. (other :tag "on")))
  1440. (defun execute-extended-command--shorter-1 (name length)
  1441. (cond
  1442. ((zerop length) (list ""))
  1443. ((equal name "") nil)
  1444. (t
  1445. (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
  1446. (execute-extended-command--shorter-1
  1447. (substring name 1) (1- length)))
  1448. (when (string-match "\\`\\(-\\)?[^-]*" name)
  1449. (execute-extended-command--shorter-1
  1450. (substring name (match-end 0)) length))))))
  1451. (defun execute-extended-command--shorter (name typed)
  1452. (let ((candidates '())
  1453. (max (length typed))
  1454. (len 1)
  1455. binding)
  1456. (while (and (not binding)
  1457. (progn
  1458. (unless candidates
  1459. (setq len (1+ len))
  1460. (setq candidates (execute-extended-command--shorter-1
  1461. name len)))
  1462. ;; Don't show the help message if the binding isn't
  1463. ;; significantly shorter than the M-x command the user typed.
  1464. (< len (- max 5))))
  1465. (let ((candidate (pop candidates)))
  1466. (when (equal name
  1467. (car-safe (completion-try-completion
  1468. candidate obarray 'commandp len)))
  1469. (setq binding candidate))))
  1470. binding))
  1471. (defun execute-extended-command (prefixarg &optional command-name typed)
  1472. ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
  1473. ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
  1474. "Read a command name, then read the arguments and call the command.
  1475. To pass a prefix argument to the command you are
  1476. invoking, give a prefix argument to `execute-extended-command'."
  1477. (declare (interactive-only command-execute))
  1478. ;; FIXME: Remember the actual text typed by the user before completion,
  1479. ;; so that we don't later on suggest the same shortening.
  1480. (interactive
  1481. (let ((execute-extended-command--last-typed nil))
  1482. (list current-prefix-arg
  1483. (read-extended-command)
  1484. execute-extended-command--last-typed)))
  1485. ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
  1486. (unless command-name
  1487. (let ((current-prefix-arg prefixarg) ; for prompt
  1488. (execute-extended-command--last-typed nil))
  1489. (setq command-name (read-extended-command))
  1490. (setq typed execute-extended-command--last-typed)))
  1491. (let* ((function (and (stringp command-name) (intern-soft command-name)))
  1492. (binding (and suggest-key-bindings
  1493. (not executing-kbd-macro)
  1494. (where-is-internal function overriding-local-map t))))
  1495. (unless (commandp function)
  1496. (error "‘%s’ is not a valid command name" command-name))
  1497. (setq this-command function)
  1498. ;; Normally `real-this-command' should never be changed, but here we really
  1499. ;; want to pretend that M-x <cmd> RET is nothing more than a "key
  1500. ;; binding" for <cmd>, so the command the user really wanted to run is
  1501. ;; `function' and not `execute-extended-command'. The difference is
  1502. ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
  1503. (setq real-this-command function)
  1504. (let ((prefix-arg prefixarg))
  1505. (command-execute function 'record))
  1506. ;; If enabled, show which key runs this command.
  1507. ;; But first wait, and skip the message if there is input.
  1508. (let* ((waited
  1509. ;; If this command displayed something in the echo area;
  1510. ;; wait a few seconds, then display our suggestion message.
  1511. ;; FIXME: Wait *after* running post-command-hook!
  1512. ;; FIXME: Don't wait if execute-extended-command--shorter won't
  1513. ;; find a better answer anyway!
  1514. (when suggest-key-bindings
  1515. (sit-for (cond
  1516. ((zerop (length (current-message))) 0)
  1517. ((numberp suggest-key-bindings) suggest-key-bindings)
  1518. (t 2))))))
  1519. (when (and waited (not (consp unread-command-events)))
  1520. (unless (or binding executing-kbd-macro (not (symbolp function))
  1521. (<= (length (symbol-name function)) 2))
  1522. ;; There's no binding for CMD. Let's try and find the shortest
  1523. ;; string to use in M-x.
  1524. ;; FIXME: Can be slow. Cache it maybe?
  1525. (while-no-input
  1526. (setq binding (execute-extended-command--shorter
  1527. (symbol-name function) typed))))
  1528. (when binding
  1529. (with-temp-message
  1530. (format-message "You can run the command ‘%s’ with %s"
  1531. function
  1532. (if (stringp binding)
  1533. (concat "M-x " binding " RET")
  1534. (key-description binding)))
  1535. (sit-for (if (numberp suggest-key-bindings)
  1536. suggest-key-bindings
  1537. 2))))))))
  1538. (defun command-execute (cmd &optional record-flag keys special)
  1539. ;; BEWARE: Called directly from the C code.
  1540. "Execute CMD as an editor command.
  1541. CMD must be a symbol that satisfies the `commandp' predicate.
  1542. Optional second arg RECORD-FLAG non-nil
  1543. means unconditionally put this command in the variable `command-history'.
  1544. Otherwise, that is done only if an arg is read using the minibuffer.
  1545. The argument KEYS specifies the value to use instead of (this-command-keys)
  1546. when reading the arguments; if it is nil, (this-command-keys) is used.
  1547. The argument SPECIAL, if non-nil, means that this command is executing
  1548. a special event, so ignore the prefix argument and don't clear it."
  1549. (setq debug-on-next-call nil)
  1550. (let ((prefixarg (unless special
  1551. (prog1 prefix-arg
  1552. (setq current-prefix-arg prefix-arg)
  1553. (setq prefix-arg nil)))))
  1554. (if (and (symbolp cmd)
  1555. (get cmd 'disabled)
  1556. disabled-command-function)
  1557. ;; FIXME: Weird calling convention!
  1558. (run-hooks 'disabled-command-function)
  1559. (let ((final cmd))
  1560. (while
  1561. (progn
  1562. (setq final (indirect-function final))
  1563. (if (autoloadp final)
  1564. (setq final (autoload-do-load final cmd)))))
  1565. (cond
  1566. ((arrayp final)
  1567. ;; If requested, place the macro in the command history. For
  1568. ;; other sorts of commands, call-interactively takes care of this.
  1569. (when record-flag
  1570. (push `(execute-kbd-macro ,final ,prefixarg) command-history)
  1571. ;; Don't keep command history around forever.
  1572. (when (and (numberp history-length) (> history-length 0))
  1573. (let ((cell (nthcdr history-length command-history)))
  1574. (if (consp cell) (setcdr cell nil)))))
  1575. (execute-kbd-macro final prefixarg))
  1576. (t
  1577. ;; Pass `cmd' rather than `final', for the backtrace's sake.
  1578. (prog1 (call-interactively cmd record-flag keys)
  1579. (when (and (symbolp cmd)
  1580. (get cmd 'byte-obsolete-info)
  1581. (not (get cmd 'command-execute-obsolete-warned)))
  1582. (put cmd 'command-execute-obsolete-warned t)
  1583. (message "%s" (macroexp--obsolete-warning
  1584. cmd (get cmd 'byte-obsolete-info) "command"))))))))))
  1585. (defvar minibuffer-history nil
  1586. "Default minibuffer history list.
  1587. This is used for all minibuffer input
  1588. except when an alternate history list is specified.
  1589. Maximum length of the history list is determined by the value
  1590. of `history-length', which see.")
  1591. (defvar minibuffer-history-sexp-flag nil
  1592. "Control whether history list elements are expressions or strings.
  1593. If the value of this variable equals current minibuffer depth,
  1594. they are expressions; otherwise they are strings.
  1595. \(That convention is designed to do the right thing for
  1596. recursive uses of the minibuffer.)")
  1597. (setq minibuffer-history-variable 'minibuffer-history)
  1598. (setq minibuffer-history-position nil) ;; Defvar is in C code.
  1599. (defvar minibuffer-history-search-history nil)
  1600. (defvar minibuffer-text-before-history nil
  1601. "Text that was in this minibuffer before any history commands.
  1602. This is nil if there have not yet been any history commands
  1603. in this use of the minibuffer.")
  1604. (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
  1605. (defun minibuffer-history-initialize ()
  1606. (setq minibuffer-text-before-history nil))
  1607. (defun minibuffer-avoid-prompt (_new _old)
  1608. "A point-motion hook for the minibuffer, that moves point out of the prompt."
  1609. (declare (obsolete cursor-intangible-mode "25.1"))
  1610. (constrain-to-field nil (point-max)))
  1611. (defcustom minibuffer-history-case-insensitive-variables nil
  1612. "Minibuffer history variables for which matching should ignore case.
  1613. If a history variable is a member of this list, then the
  1614. \\[previous-matching-history-element] and \\[next-matching-history-element]\
  1615. commands ignore case when searching it, regardless of `case-fold-search'."
  1616. :type '(repeat variable)
  1617. :group 'minibuffer)
  1618. (defun previous-matching-history-element (regexp n)
  1619. "Find the previous history element that matches REGEXP.
  1620. \(Previous history elements refer to earlier actions.)
  1621. With prefix argument N, search for Nth previous match.
  1622. If N is negative, find the next or Nth next match.
  1623. Normally, history elements are matched case-insensitively if
  1624. `case-fold-search' is non-nil, but an uppercase letter in REGEXP
  1625. makes the search case-sensitive.
  1626. See also `minibuffer-history-case-insensitive-variables'."
  1627. (interactive
  1628. (let* ((enable-recursive-minibuffers t)
  1629. (regexp (read-from-minibuffer "Previous element matching (regexp): "
  1630. nil
  1631. minibuffer-local-map
  1632. nil
  1633. 'minibuffer-history-search-history
  1634. (car minibuffer-history-search-history))))
  1635. ;; Use the last regexp specified, by default, if input is empty.
  1636. (list (if (string= regexp "")
  1637. (if minibuffer-history-search-history
  1638. (car minibuffer-history-search-history)
  1639. (user-error "No previous history search regexp"))
  1640. regexp)
  1641. (prefix-numeric-value current-prefix-arg))))
  1642. (unless (zerop n)
  1643. (if (and (zerop minibuffer-history-position)
  1644. (null minibuffer-text-before-history))
  1645. (setq minibuffer-text-before-history
  1646. (minibuffer-contents-no-properties)))
  1647. (let ((history (symbol-value minibuffer-history-variable))
  1648. (case-fold-search
  1649. (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
  1650. ;; On some systems, ignore case for file names.
  1651. (if (memq minibuffer-history-variable
  1652. minibuffer-history-case-insensitive-variables)
  1653. t
  1654. ;; Respect the user's setting for case-fold-search:
  1655. case-fold-search)
  1656. nil))
  1657. prevpos
  1658. match-string
  1659. match-offset
  1660. (pos minibuffer-history-position))
  1661. (while (/= n 0)
  1662. (setq prevpos pos)
  1663. (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
  1664. (when (= pos prevpos)
  1665. (user-error (if (= pos 1)
  1666. "No later matching history item"
  1667. "No earlier matching history item")))
  1668. (setq match-string
  1669. (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
  1670. (let ((print-level nil))
  1671. (prin1-to-string (nth (1- pos) history)))
  1672. (nth (1- pos) history)))
  1673. (setq match-offset
  1674. (if (< n 0)
  1675. (and (string-match regexp match-string)
  1676. (match-end 0))
  1677. (and (string-match (concat ".*\\(" regexp "\\)") match-string)
  1678. (match-beginning 1))))
  1679. (when match-offset
  1680. (setq n (+ n (if (< n 0) 1 -1)))))
  1681. (setq minibuffer-history-position pos)
  1682. (goto-char (point-max))
  1683. (delete-minibuffer-contents)
  1684. (insert match-string)
  1685. (goto-char (+ (minibuffer-prompt-end) match-offset))))
  1686. (if (memq (car (car command-history)) '(previous-matching-history-element
  1687. next-matching-history-element))
  1688. (setq command-history (cdr command-history))))
  1689. (defun next-matching-history-element (regexp n)
  1690. "Find the next history element that matches REGEXP.
  1691. \(The next history element refers to a more recent action.)
  1692. With prefix argument N, search for Nth next match.
  1693. If N is negative, find the previous or Nth previous match.
  1694. Normally, history elements are matched case-insensitively if
  1695. `case-fold-search' is non-nil, but an uppercase letter in REGEXP
  1696. makes the search case-sensitive."
  1697. (interactive
  1698. (let* ((enable-recursive-minibuffers t)
  1699. (regexp (read-from-minibuffer "Next element matching (regexp): "
  1700. nil
  1701. minibuffer-local-map
  1702. nil
  1703. 'minibuffer-history-search-history
  1704. (car minibuffer-history-search-history))))
  1705. ;; Use the last regexp specified, by default, if input is empty.
  1706. (list (if (string= regexp "")
  1707. (if minibuffer-history-search-history
  1708. (car minibuffer-history-search-history)
  1709. (user-error "No previous history search regexp"))
  1710. regexp)
  1711. (prefix-numeric-value current-prefix-arg))))
  1712. (previous-matching-history-element regexp (- n)))
  1713. (defvar minibuffer-temporary-goal-position nil)
  1714. (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
  1715. "Function run by `goto-history-element' before consuming default values.
  1716. This is useful to dynamically add more elements to the list of default values
  1717. when `goto-history-element' reaches the end of this list.
  1718. Before calling this function `goto-history-element' sets the variable
  1719. `minibuffer-default-add-done' to t, so it will call this function only
  1720. once. In special cases, when this function needs to be called more
  1721. than once, it can set `minibuffer-default-add-done' to nil explicitly,
  1722. overriding the setting of this variable to t in `goto-history-element'.")
  1723. (defvar minibuffer-default-add-done nil
  1724. "When nil, add more elements to the end of the list of default values.
  1725. The value nil causes `goto-history-element' to add more elements to
  1726. the list of defaults when it reaches the end of this list. It does
  1727. this by calling a function defined by `minibuffer-default-add-function'.")
  1728. (make-variable-buffer-local 'minibuffer-default-add-done)
  1729. (defun minibuffer-default-add-completions ()
  1730. "Return a list of all completions without the default value.
  1731. This function is used to add all elements of the completion table to
  1732. the end of the list of defaults just after the default value."
  1733. (let ((def minibuffer-default)
  1734. (all (all-completions ""
  1735. minibuffer-completion-table
  1736. minibuffer-completion-predicate)))
  1737. (if (listp def)
  1738. (append def all)
  1739. (cons def (delete def all)))))
  1740. (defun goto-history-element (nabs)
  1741. "Puts element of the minibuffer history in the minibuffer.
  1742. The argument NABS specifies the absolute history position."
  1743. (interactive "p")
  1744. (when (and (not minibuffer-default-add-done)
  1745. (functionp minibuffer-default-add-function)
  1746. (< nabs (- (if (listp minibuffer-default)
  1747. (length minibuffer-default)
  1748. 1))))
  1749. (setq minibuffer-default-add-done t
  1750. minibuffer-default (funcall minibuffer-default-add-function)))
  1751. (let ((minimum (if minibuffer-default
  1752. (- (if (listp minibuffer-default)
  1753. (length minibuffer-default)
  1754. 1))
  1755. 0))
  1756. elt minibuffer-returned-to-present)
  1757. (if (and (zerop minibuffer-history-position)
  1758. (null minibuffer-text-before-history))
  1759. (setq minibuffer-text-before-history
  1760. (minibuffer-contents-no-properties)))
  1761. (if (< nabs minimum)
  1762. (user-error (if minibuffer-default
  1763. "End of defaults; no next item"
  1764. "End of history; no default available")))
  1765. (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
  1766. (length (symbol-value minibuffer-history-variable))
  1767. 0))
  1768. (user-error "Beginning of history; no preceding item"))
  1769. (unless (memq last-command '(next-history-element
  1770. previous-history-element))
  1771. (let ((prompt-end (minibuffer-prompt-end)))
  1772. (set (make-local-variable 'minibuffer-temporary-goal-position)
  1773. (cond ((<= (point) prompt-end) prompt-end)
  1774. ((eobp) nil)
  1775. (t (point))))))
  1776. (goto-char (point-max))
  1777. (delete-minibuffer-contents)
  1778. (setq minibuffer-history-position nabs)
  1779. (cond ((< nabs 0)
  1780. (setq elt (if (listp minibuffer-default)
  1781. (nth (1- (abs nabs)) minibuffer-default)
  1782. minibuffer-default)))
  1783. ((= nabs 0)
  1784. (setq elt (or minibuffer-text-before-history ""))
  1785. (setq minibuffer-returned-to-present t)
  1786. (setq minibuffer-text-before-history nil))
  1787. (t (setq elt (nth (1- minibuffer-history-position)
  1788. (symbol-value minibuffer-history-variable)))))
  1789. (insert
  1790. (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
  1791. (not minibuffer-returned-to-present))
  1792. (let ((print-level nil))
  1793. (prin1-to-string elt))
  1794. elt))
  1795. (goto-char (or minibuffer-temporary-goal-position (point-max)))))
  1796. (defun next-history-element (n)
  1797. "Puts next element of the minibuffer history in the minibuffer.
  1798. With argument N, it uses the Nth following element."
  1799. (interactive "p")
  1800. (or (zerop n)
  1801. (goto-history-element (- minibuffer-history-position n))))
  1802. (defun previous-history-element (n)
  1803. "Puts previous element of the minibuffer history in the minibuffer.
  1804. With argument N, it uses the Nth previous element."
  1805. (interactive "p")
  1806. (or (zerop n)
  1807. (goto-history-element (+ minibuffer-history-position n))))
  1808. (defun next-line-or-history-element (&optional arg)
  1809. "Move cursor vertically down ARG lines, or to the next history element.
  1810. When point moves over the bottom line of multi-line minibuffer, puts ARGth
  1811. next element of the minibuffer history in the minibuffer."
  1812. (interactive "^p")
  1813. (or arg (setq arg 1))
  1814. (let* ((old-point (point))
  1815. ;; Remember the original goal column of possibly multi-line input
  1816. ;; excluding the length of the prompt on the first line.
  1817. (prompt-end (minibuffer-prompt-end))
  1818. (old-column (unless (and (eolp) (> (point) prompt-end))
  1819. (if (= (line-number-at-pos) 1)
  1820. (max (- (current-column) (1- prompt-end)) 0)
  1821. (current-column)))))
  1822. (condition-case nil
  1823. (with-no-warnings
  1824. (next-line arg))
  1825. (end-of-buffer
  1826. ;; Restore old position since `line-move-visual' moves point to
  1827. ;; the end of the line when it fails to go to the next line.
  1828. (goto-char old-point)
  1829. (next-history-element arg)
  1830. ;; Restore the original goal column on the last line
  1831. ;; of possibly multi-line input.
  1832. (goto-char (point-max))
  1833. (when old-column
  1834. (if (= (line-number-at-pos) 1)
  1835. (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
  1836. (move-to-column old-column)))))))
  1837. (defun previous-line-or-history-element (&optional arg)
  1838. "Move cursor vertically up ARG lines, or to the previous history element.
  1839. When point moves over the top line of multi-line minibuffer, puts ARGth
  1840. previous element of the minibuffer history in the minibuffer."
  1841. (interactive "^p")
  1842. (or arg (setq arg 1))
  1843. (let* ((old-point (point))
  1844. ;; Remember the original goal column of possibly multi-line input
  1845. ;; excluding the length of the prompt on the first line.
  1846. (prompt-end (minibuffer-prompt-end))
  1847. (old-column (unless (and (eolp) (> (point) prompt-end))
  1848. (if (= (line-number-at-pos) 1)
  1849. (max (- (current-column) (1- prompt-end)) 0)
  1850. (current-column)))))
  1851. (condition-case nil
  1852. (with-no-warnings
  1853. (previous-line arg))
  1854. (beginning-of-buffer
  1855. ;; Restore old position since `line-move-visual' moves point to
  1856. ;; the beginning of the line when it fails to go to the previous line.
  1857. (goto-char old-point)
  1858. (previous-history-element arg)
  1859. ;; Restore the original goal column on the first line
  1860. ;; of possibly multi-line input.
  1861. (goto-char (minibuffer-prompt-end))
  1862. (if old-column
  1863. (if (= (line-number-at-pos) 1)
  1864. (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
  1865. (move-to-column old-column))
  1866. (goto-char (line-end-position)))))))
  1867. (defun next-complete-history-element (n)
  1868. "Get next history element which completes the minibuffer before the point.
  1869. The contents of the minibuffer after the point are deleted, and replaced
  1870. by the new completion."
  1871. (interactive "p")
  1872. (let ((point-at-start (point)))
  1873. (next-matching-history-element
  1874. (concat
  1875. "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
  1876. n)
  1877. ;; next-matching-history-element always puts us at (point-min).
  1878. ;; Move to the position we were at before changing the buffer contents.
  1879. ;; This is still sensible, because the text before point has not changed.
  1880. (goto-char point-at-start)))
  1881. (defun previous-complete-history-element (n)
  1882. "\
  1883. Get previous history element which completes the minibuffer before the point.
  1884. The contents of the minibuffer after the point are deleted, and replaced
  1885. by the new completion."
  1886. (interactive "p")
  1887. (next-complete-history-element (- n)))
  1888. ;; For compatibility with the old subr of the same name.
  1889. (defun minibuffer-prompt-width ()
  1890. "Return the display width of the minibuffer prompt.
  1891. Return 0 if current buffer is not a minibuffer."
  1892. ;; Return the width of everything before the field at the end of
  1893. ;; the buffer; this should be 0 for normal buffers.
  1894. (1- (minibuffer-prompt-end)))
  1895. ;; isearch minibuffer history
  1896. (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
  1897. (defvar minibuffer-history-isearch-message-overlay)
  1898. (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
  1899. (defun minibuffer-history-isearch-setup ()
  1900. "Set up a minibuffer for using isearch to search the minibuffer history.
  1901. Intended to be added to `minibuffer-setup-hook'."
  1902. (set (make-local-variable 'isearch-search-fun-function)
  1903. 'minibuffer-history-isearch-search)
  1904. (set (make-local-variable 'isearch-message-function)
  1905. 'minibuffer-history-isearch-message)
  1906. (set (make-local-variable 'isearch-wrap-function)
  1907. 'minibuffer-history-isearch-wrap)
  1908. (set (make-local-variable 'isearch-push-state-function)
  1909. 'minibuffer-history-isearch-push-state)
  1910. (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
  1911. (defun minibuffer-history-isearch-end ()
  1912. "Clean up the minibuffer after terminating isearch in the minibuffer."
  1913. (if minibuffer-history-isearch-message-overlay
  1914. (delete-overlay minibuffer-history-isearch-message-overlay)))
  1915. (defun minibuffer-history-isearch-search ()
  1916. "Return the proper search function, for isearch in minibuffer history."
  1917. (lambda (string bound noerror)
  1918. (let ((search-fun
  1919. ;; Use standard functions to search within minibuffer text
  1920. (isearch-search-fun-default))
  1921. found)
  1922. ;; Avoid lazy-highlighting matches in the minibuffer prompt when
  1923. ;; searching forward. Lazy-highlight calls this lambda with the
  1924. ;; bound arg, so skip the minibuffer prompt.
  1925. (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
  1926. (goto-char (minibuffer-prompt-end)))
  1927. (or
  1928. ;; 1. First try searching in the initial minibuffer text
  1929. (funcall search-fun string
  1930. (if isearch-forward bound (minibuffer-prompt-end))
  1931. noerror)
  1932. ;; 2. If the above search fails, start putting next/prev history
  1933. ;; elements in the minibuffer successively, and search the string
  1934. ;; in them. Do this only when bound is nil (i.e. not while
  1935. ;; lazy-highlighting search strings in the current minibuffer text).
  1936. (unless bound
  1937. (condition-case nil
  1938. (progn
  1939. (while (not found)
  1940. (cond (isearch-forward
  1941. (next-history-element 1)
  1942. (goto-char (minibuffer-prompt-end)))
  1943. (t
  1944. (previous-history-element 1)
  1945. (goto-char (point-max))))
  1946. (setq isearch-barrier (point) isearch-opoint (point))
  1947. ;; After putting the next/prev history element, search
  1948. ;; the string in them again, until next-history-element
  1949. ;; or previous-history-element raises an error at the
  1950. ;; beginning/end of history.
  1951. (setq found (funcall search-fun string
  1952. (unless isearch-forward
  1953. ;; For backward search, don't search
  1954. ;; in the minibuffer prompt
  1955. (minibuffer-prompt-end))
  1956. noerror)))
  1957. ;; Return point of the new search result
  1958. (point))
  1959. ;; Return nil when next(prev)-history-element fails
  1960. (error nil)))))))
  1961. (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
  1962. "Display the minibuffer history search prompt.
  1963. If there are no search errors, this function displays an overlay with
  1964. the isearch prompt which replaces the original minibuffer prompt.
  1965. Otherwise, it displays the standard isearch message returned from
  1966. the function `isearch-message'."
  1967. (if (not (and (minibufferp) isearch-success (not isearch-error)))
  1968. ;; Use standard function `isearch-message' when not in the minibuffer,
  1969. ;; or search fails, or has an error (like incomplete regexp).
  1970. ;; This function overwrites minibuffer text with isearch message,
  1971. ;; so it's possible to see what is wrong in the search string.
  1972. (isearch-message c-q-hack ellipsis)
  1973. ;; Otherwise, put the overlay with the standard isearch prompt over
  1974. ;; the initial minibuffer prompt.
  1975. (if (overlayp minibuffer-history-isearch-message-overlay)
  1976. (move-overlay minibuffer-history-isearch-message-overlay
  1977. (point-min) (minibuffer-prompt-end))
  1978. (setq minibuffer-history-isearch-message-overlay
  1979. (make-overlay (point-min) (minibuffer-prompt-end)))
  1980. (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
  1981. (overlay-put minibuffer-history-isearch-message-overlay
  1982. 'display (isearch-message-prefix c-q-hack ellipsis))
  1983. ;; And clear any previous isearch message.
  1984. (message "")))
  1985. (defun minibuffer-history-isearch-wrap ()
  1986. "Wrap the minibuffer history search when search fails.
  1987. Move point to the first history element for a forward search,
  1988. or to the last history element for a backward search."
  1989. ;; When `minibuffer-history-isearch-search' fails on reaching the
  1990. ;; beginning/end of the history, wrap the search to the first/last
  1991. ;; minibuffer history element.
  1992. (if isearch-forward
  1993. (goto-history-element (length (symbol-value minibuffer-history-variable)))
  1994. (goto-history-element 0))
  1995. (setq isearch-success t)
  1996. (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
  1997. (defun minibuffer-history-isearch-push-state ()
  1998. "Save a function restoring the state of minibuffer history search.
  1999. Save `minibuffer-history-position' to the additional state parameter
  2000. in the search status stack."
  2001. (let ((pos minibuffer-history-position))
  2002. (lambda (cmd)
  2003. (minibuffer-history-isearch-pop-state cmd pos))))
  2004. (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
  2005. "Restore the minibuffer history search state.
  2006. Go to the history element by the absolute history position HIST-POS."
  2007. (goto-history-element hist-pos))
  2008. ;Put this on C-x u, so we can force that rather than C-_ into startup msg
  2009. (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
  2010. (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
  2011. "Table mapping redo records to the corresponding undo one.
  2012. A redo record for undo-in-region maps to t.
  2013. A redo record for ordinary undo maps to the following (earlier) undo.")
  2014. (defvar undo-in-region nil
  2015. "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
  2016. (defvar undo-no-redo nil
  2017. "If t, `undo' doesn't go through redo entries.")
  2018. (defvar pending-undo-list nil
  2019. "Within a run of consecutive undo commands, list remaining to be undone.
  2020. If t, we undid all the way to the end of it.")
  2021. (defun undo (&optional arg)
  2022. "Undo some previous changes.
  2023. Repeat this command to undo more changes.
  2024. A numeric ARG serves as a repeat count.
  2025. In Transient Mark mode when the mark is active, only undo changes within
  2026. the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
  2027. as an argument limits undo to changes within the current region."
  2028. (interactive "*P")
  2029. ;; Make last-command indicate for the next command that this was an undo.
  2030. ;; That way, another undo will undo more.
  2031. ;; If we get to the end of the undo history and get an error,
  2032. ;; another undo command will find the undo history empty
  2033. ;; and will get another error. To begin undoing the undos,
  2034. ;; you must type some other command.
  2035. (let* ((modified (buffer-modified-p))
  2036. ;; For an indirect buffer, look in the base buffer for the
  2037. ;; auto-save data.
  2038. (base-buffer (or (buffer-base-buffer) (current-buffer)))
  2039. (recent-save (with-current-buffer base-buffer
  2040. (recent-auto-save-p)))
  2041. message)
  2042. ;; If we get an error in undo-start,
  2043. ;; the next command should not be a "consecutive undo".
  2044. ;; So set `this-command' to something other than `undo'.
  2045. (setq this-command 'undo-start)
  2046. (unless (and (eq last-command 'undo)
  2047. (or (eq pending-undo-list t)
  2048. ;; If something (a timer or filter?) changed the buffer
  2049. ;; since the previous command, don't continue the undo seq.
  2050. (let ((list buffer-undo-list))
  2051. (while (eq (car list) nil)
  2052. (setq list (cdr list)))
  2053. ;; If the last undo record made was made by undo
  2054. ;; it shows nothing else happened in between.
  2055. (gethash list undo-equiv-table))))
  2056. (setq undo-in-region
  2057. (or (region-active-p) (and arg (not (numberp arg)))))
  2058. (if undo-in-region
  2059. (undo-start (region-beginning) (region-end))
  2060. (undo-start))
  2061. ;; get rid of initial undo boundary
  2062. (undo-more 1))
  2063. ;; If we got this far, the next command should be a consecutive undo.
  2064. (setq this-command 'undo)
  2065. ;; Check to see whether we're hitting a redo record, and if
  2066. ;; so, ask the user whether she wants to skip the redo/undo pair.
  2067. (let ((equiv (gethash pending-undo-list undo-equiv-table)))
  2068. (or (eq (selected-window) (minibuffer-window))
  2069. (setq message (format "%s%s!"
  2070. (if (or undo-no-redo (not equiv))
  2071. "Undo" "Redo")
  2072. (if undo-in-region " in region" ""))))
  2073. (when (and (consp equiv) undo-no-redo)
  2074. ;; The equiv entry might point to another redo record if we have done
  2075. ;; undo-redo-undo-redo-... so skip to the very last equiv.
  2076. (while (let ((next (gethash equiv undo-equiv-table)))
  2077. (if next (setq equiv next))))
  2078. (setq pending-undo-list equiv)))
  2079. (undo-more
  2080. (if (numberp arg)
  2081. (prefix-numeric-value arg)
  2082. 1))
  2083. ;; Record the fact that the just-generated undo records come from an
  2084. ;; undo operation--that is, they are redo records.
  2085. ;; In the ordinary case (not within a region), map the redo
  2086. ;; record to the following undos.
  2087. ;; I don't know how to do that in the undo-in-region case.
  2088. (let ((list buffer-undo-list))
  2089. ;; Strip any leading undo boundaries there might be, like we do
  2090. ;; above when checking.
  2091. (while (eq (car list) nil)
  2092. (setq list (cdr list)))
  2093. (puthash list
  2094. ;; Prevent identity mapping. This can happen if
  2095. ;; consecutive nils are erroneously in undo list.
  2096. (if (or undo-in-region (eq list pending-undo-list))
  2097. t
  2098. pending-undo-list)
  2099. undo-equiv-table))
  2100. ;; Don't specify a position in the undo record for the undo command.
  2101. ;; Instead, undoing this should move point to where the change is.
  2102. (let ((tail buffer-undo-list)
  2103. (prev nil))
  2104. (while (car tail)
  2105. (when (integerp (car tail))
  2106. (let ((pos (car tail)))
  2107. (if prev
  2108. (setcdr prev (cdr tail))
  2109. (setq buffer-undo-list (cdr tail)))
  2110. (setq tail (cdr tail))
  2111. (while (car tail)
  2112. (if (eq pos (car tail))
  2113. (if prev
  2114. (setcdr prev (cdr tail))
  2115. (setq buffer-undo-list (cdr tail)))
  2116. (setq prev tail))
  2117. (setq tail (cdr tail)))
  2118. (setq tail nil)))
  2119. (setq prev tail tail (cdr tail))))
  2120. ;; Record what the current undo list says,
  2121. ;; so the next command can tell if the buffer was modified in between.
  2122. (and modified (not (buffer-modified-p))
  2123. (with-current-buffer base-buffer
  2124. (delete-auto-save-file-if-necessary recent-save)))
  2125. ;; Display a message announcing success.
  2126. (if message
  2127. (message "%s" message))))
  2128. (defun buffer-disable-undo (&optional buffer)
  2129. "Make BUFFER stop keeping undo information.
  2130. No argument or nil as argument means do this for the current buffer."
  2131. (interactive)
  2132. (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
  2133. (setq buffer-undo-list t)))
  2134. (defun undo-only (&optional arg)
  2135. "Undo some previous changes.
  2136. Repeat this command to undo more changes.
  2137. A numeric ARG serves as a repeat count.
  2138. Contrary to `undo', this will not redo a previous undo."
  2139. (interactive "*p")
  2140. (let ((undo-no-redo t)) (undo arg)))
  2141. (defvar undo-in-progress nil
  2142. "Non-nil while performing an undo.
  2143. Some change-hooks test this variable to do something different.")
  2144. (defun undo-more (n)
  2145. "Undo back N undo-boundaries beyond what was already undone recently.
  2146. Call `undo-start' to get ready to undo recent changes,
  2147. then call `undo-more' one or more times to undo them."
  2148. (or (listp pending-undo-list)
  2149. (user-error (concat "No further undo information"
  2150. (and undo-in-region " for region"))))
  2151. (let ((undo-in-progress t))
  2152. ;; Note: The following, while pulling elements off
  2153. ;; `pending-undo-list' will call primitive change functions which
  2154. ;; will push more elements onto `buffer-undo-list'.
  2155. (setq pending-undo-list (primitive-undo n pending-undo-list))
  2156. (if (null pending-undo-list)
  2157. (setq pending-undo-list t))))
  2158. (defun primitive-undo (n list)
  2159. "Undo N records from the front of the list LIST.
  2160. Return what remains of the list."
  2161. ;; This is a good feature, but would make undo-start
  2162. ;; unable to do what is expected.
  2163. ;;(when (null (car (list)))
  2164. ;; ;; If the head of the list is a boundary, it is the boundary
  2165. ;; ;; preceding this command. Get rid of it and don't count it.
  2166. ;; (setq list (cdr list))))
  2167. (let ((arg n)
  2168. ;; In a writable buffer, enable undoing read-only text that is
  2169. ;; so because of text properties.
  2170. (inhibit-read-only t)
  2171. ;; Don't let `intangible' properties interfere with undo.
  2172. (inhibit-point-motion-hooks t)
  2173. ;; We use oldlist only to check for EQ. ++kfs
  2174. (oldlist buffer-undo-list)
  2175. (did-apply nil)
  2176. (next nil))
  2177. (while (> arg 0)
  2178. (while (setq next (pop list)) ;Exit inner loop at undo boundary.
  2179. ;; Handle an integer by setting point to that value.
  2180. (pcase next
  2181. ((pred integerp) (goto-char next))
  2182. ;; Element (t . TIME) records previous modtime.
  2183. ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
  2184. ;; UNKNOWN_MODTIME_NSECS.
  2185. (`(t . ,time)
  2186. ;; If this records an obsolete save
  2187. ;; (not matching the actual disk file)
  2188. ;; then don't mark unmodified.
  2189. (when (or (equal time (visited-file-modtime))
  2190. (and (consp time)
  2191. (equal (list (car time) (cdr time))
  2192. (visited-file-modtime))))
  2193. (when (fboundp 'unlock-buffer)
  2194. (unlock-buffer))
  2195. (set-buffer-modified-p nil)))
  2196. ;; Element (nil PROP VAL BEG . END) is property change.
  2197. (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
  2198. (when (or (> (point-min) beg) (< (point-max) end))
  2199. (error "Changes to be undone are outside visible portion of buffer"))
  2200. (put-text-property beg end prop val))
  2201. ;; Element (BEG . END) means range was inserted.
  2202. (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
  2203. ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
  2204. ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
  2205. (when (or (> (point-min) beg) (< (point-max) end))
  2206. (error "Changes to be undone are outside visible portion of buffer"))
  2207. ;; Set point first thing, so that undoing this undo
  2208. ;; does not send point back to where it is now.
  2209. (goto-char beg)
  2210. (delete-region beg end))
  2211. ;; Element (apply FUN . ARGS) means call FUN to undo.
  2212. (`(apply . ,fun-args)
  2213. (let ((currbuff (current-buffer)))
  2214. (if (integerp (car fun-args))
  2215. ;; Long format: (apply DELTA START END FUN . ARGS).
  2216. (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
  2217. (start-mark (copy-marker start nil))
  2218. (end-mark (copy-marker end t)))
  2219. (when (or (> (point-min) start) (< (point-max) end))
  2220. (error "Changes to be undone are outside visible portion of buffer"))
  2221. (apply fun args) ;; Use `save-current-buffer'?
  2222. ;; Check that the function did what the entry
  2223. ;; said it would do.
  2224. (unless (and (= start start-mark)
  2225. (= (+ delta end) end-mark))
  2226. (error "Changes to be undone by function different than announced"))
  2227. (set-marker start-mark nil)
  2228. (set-marker end-mark nil))
  2229. (apply fun-args))
  2230. (unless (eq currbuff (current-buffer))
  2231. (error "Undo function switched buffer"))
  2232. (setq did-apply t)))
  2233. ;; Element (STRING . POS) means STRING was deleted.
  2234. (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
  2235. (when (let ((apos (abs pos)))
  2236. (or (< apos (point-min)) (> apos (point-max))))
  2237. (error "Changes to be undone are outside visible portion of buffer"))
  2238. (let (valid-marker-adjustments)
  2239. ;; Check that marker adjustments which were recorded
  2240. ;; with the (STRING . POS) record are still valid, ie
  2241. ;; the markers haven't moved. We check their validity
  2242. ;; before reinserting the string so as we don't need to
  2243. ;; mind marker insertion-type.
  2244. (while (and (markerp (car-safe (car list)))
  2245. (integerp (cdr-safe (car list))))
  2246. (let* ((marker-adj (pop list))
  2247. (m (car marker-adj)))
  2248. (and (eq (marker-buffer m) (current-buffer))
  2249. (= pos m)
  2250. (push marker-adj valid-marker-adjustments))))
  2251. ;; Insert string and adjust point
  2252. (if (< pos 0)
  2253. (progn
  2254. (goto-char (- pos))
  2255. (insert string))
  2256. (goto-char pos)
  2257. (insert string)
  2258. (goto-char pos))
  2259. ;; Adjust the valid marker adjustments
  2260. (dolist (adj valid-marker-adjustments)
  2261. (set-marker (car adj)
  2262. (- (car adj) (cdr adj))))))
  2263. ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
  2264. (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
  2265. (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
  2266. next)
  2267. ;; Even though these elements are not expected in the undo
  2268. ;; list, adjust them to be conservative for the 24.4
  2269. ;; release. (Bug#16818)
  2270. (when (marker-buffer marker)
  2271. (set-marker marker
  2272. (- marker offset)
  2273. (marker-buffer marker))))
  2274. (_ (error "Unrecognized entry in undo list %S" next))))
  2275. (setq arg (1- arg)))
  2276. ;; Make sure an apply entry produces at least one undo entry,
  2277. ;; so the test in `undo' for continuing an undo series
  2278. ;; will work right.
  2279. (if (and did-apply
  2280. (eq oldlist buffer-undo-list))
  2281. (setq buffer-undo-list
  2282. (cons (list 'apply 'cdr nil) buffer-undo-list))))
  2283. list)
  2284. ;; Deep copy of a list
  2285. (defun undo-copy-list (list)
  2286. "Make a copy of undo list LIST."
  2287. (mapcar 'undo-copy-list-1 list))
  2288. (defun undo-copy-list-1 (elt)
  2289. (if (consp elt)
  2290. (cons (car elt) (undo-copy-list-1 (cdr elt)))
  2291. elt))
  2292. (defun undo-start (&optional beg end)
  2293. "Set `pending-undo-list' to the front of the undo list.
  2294. The next call to `undo-more' will undo the most recently made change.
  2295. If BEG and END are specified, then only undo elements
  2296. that apply to text between BEG and END are used; other undo elements
  2297. are ignored. If BEG and END are nil, all undo elements are used."
  2298. (if (eq buffer-undo-list t)
  2299. (user-error "No undo information in this buffer"))
  2300. (setq pending-undo-list
  2301. (if (and beg end (not (= beg end)))
  2302. (undo-make-selective-list (min beg end) (max beg end))
  2303. buffer-undo-list)))
  2304. ;; The positions given in elements of the undo list are the positions
  2305. ;; as of the time that element was recorded to undo history. In
  2306. ;; general, subsequent buffer edits render those positions invalid in
  2307. ;; the current buffer, unless adjusted according to the intervening
  2308. ;; undo elements.
  2309. ;;
  2310. ;; Undo in region is a use case that requires adjustments to undo
  2311. ;; elements. It must adjust positions of elements in the region based
  2312. ;; on newer elements not in the region so as they may be correctly
  2313. ;; applied in the current buffer. undo-make-selective-list
  2314. ;; accomplishes this with its undo-deltas list of adjustments. An
  2315. ;; example undo history from oldest to newest:
  2316. ;;
  2317. ;; buf pos:
  2318. ;; 123456789 buffer-undo-list undo-deltas
  2319. ;; --------- ---------------- -----------
  2320. ;; aaa (1 . 4) (1 . -3)
  2321. ;; aaba (3 . 4) N/A (in region)
  2322. ;; ccaaba (1 . 3) (1 . -2)
  2323. ;; ccaabaddd (7 . 10) (7 . -3)
  2324. ;; ccaabdd ("ad" . 6) (6 . 2)
  2325. ;; ccaabaddd (6 . 8) (6 . -2)
  2326. ;; | |<-- region: "caab", from 2 to 6
  2327. ;;
  2328. ;; When the user starts a run of undos in region,
  2329. ;; undo-make-selective-list is called to create the full list of in
  2330. ;; region elements. Each element is adjusted forward chronologically
  2331. ;; through undo-deltas to determine if it is in the region.
  2332. ;;
  2333. ;; In the above example, the insertion of "b" is (3 . 4) in the
  2334. ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
  2335. ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
  2336. ;; . 6) is assessed as in the region and placed in the selective list.
  2337. ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
  2338. ;; due to the selected element. The "b" insertion is the only element
  2339. ;; fully in the region, so in this example undo-make-selective-list
  2340. ;; returns (nil (5 . 6)).
  2341. ;;
  2342. ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
  2343. ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
  2344. ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
  2345. ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
  2346. ;; . 10) adjusts to (6 . 8) due to the first undo delta.
  2347. ;;
  2348. ;; More interesting is how to adjust the "ddd" insertion due to the
  2349. ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
  2350. ;; If the reinsertion was a manual retyping of "ad", then the total
  2351. ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
  2352. ;; the reinsertion was due to undo, one might expect the first "d"
  2353. ;; character would again be a part of the "ddd" text, meaning its
  2354. ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
  2355. ;;
  2356. ;; undo-make-selective-list assumes in this situation that "ad" was a
  2357. ;; new edit, even if it was inserted because of an undo.
  2358. ;; Consequently, if the user undos in region "8 to 10" of the
  2359. ;; "ccaabaddd" buffer, they could be surprised that it becomes
  2360. ;; "ccaabad", as though the first "d" became detached from the
  2361. ;; original "ddd" insertion. This quirk is a FIXME.
  2362. (defun undo-make-selective-list (start end)
  2363. "Return a list of undo elements for the region START to END.
  2364. The elements come from `buffer-undo-list', but we keep only the
  2365. elements inside this region, and discard those outside this
  2366. region. The elements' positions are adjusted so as the returned
  2367. list can be applied to the current buffer."
  2368. (let ((ulist buffer-undo-list)
  2369. ;; A list of position adjusted undo elements in the region.
  2370. (selective-list (list nil))
  2371. ;; A list of undo-deltas for out of region undo elements.
  2372. undo-deltas
  2373. undo-elt)
  2374. (while ulist
  2375. (when undo-no-redo
  2376. (while (gethash ulist undo-equiv-table)
  2377. (setq ulist (gethash ulist undo-equiv-table))))
  2378. (setq undo-elt (car ulist))
  2379. (cond
  2380. ((null undo-elt)
  2381. ;; Don't put two nils together in the list
  2382. (when (car selective-list)
  2383. (push nil selective-list)))
  2384. ((and (consp undo-elt) (eq (car undo-elt) t))
  2385. ;; This is a "was unmodified" element. Keep it
  2386. ;; if we have kept everything thus far.
  2387. (when (not undo-deltas)
  2388. (push undo-elt selective-list)))
  2389. ;; Skip over marker adjustments, instead relying
  2390. ;; on finding them after (TEXT . POS) elements
  2391. ((markerp (car-safe undo-elt))
  2392. nil)
  2393. (t
  2394. (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
  2395. undo-deltas)))
  2396. (if (undo-elt-in-region adjusted-undo-elt start end)
  2397. (progn
  2398. (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
  2399. (push adjusted-undo-elt selective-list)
  2400. ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
  2401. ;; kept. primitive-undo may discard them later.
  2402. (when (and (stringp (car-safe adjusted-undo-elt))
  2403. (integerp (cdr-safe adjusted-undo-elt)))
  2404. (let ((list-i (cdr ulist)))
  2405. (while (markerp (car-safe (car list-i)))
  2406. (push (pop list-i) selective-list)))))
  2407. (let ((delta (undo-delta undo-elt)))
  2408. (when (/= 0 (cdr delta))
  2409. (push delta undo-deltas)))))))
  2410. (pop ulist))
  2411. (nreverse selective-list)))
  2412. (defun undo-elt-in-region (undo-elt start end)
  2413. "Determine whether UNDO-ELT falls inside the region START ... END.
  2414. If it crosses the edge, we return nil.
  2415. Generally this function is not useful for determining
  2416. whether (MARKER . ADJUSTMENT) undo elements are in the region,
  2417. because markers can be arbitrarily relocated. Instead, pass the
  2418. marker adjustment's corresponding (TEXT . POS) element."
  2419. (cond ((integerp undo-elt)
  2420. (and (>= undo-elt start)
  2421. (<= undo-elt end)))
  2422. ((eq undo-elt nil)
  2423. t)
  2424. ((atom undo-elt)
  2425. nil)
  2426. ((stringp (car undo-elt))
  2427. ;; (TEXT . POSITION)
  2428. (and (>= (abs (cdr undo-elt)) start)
  2429. (<= (abs (cdr undo-elt)) end)))
  2430. ((and (consp undo-elt) (markerp (car undo-elt)))
  2431. ;; (MARKER . ADJUSTMENT)
  2432. (<= start (car undo-elt) end))
  2433. ((null (car undo-elt))
  2434. ;; (nil PROPERTY VALUE BEG . END)
  2435. (let ((tail (nthcdr 3 undo-elt)))
  2436. (and (>= (car tail) start)
  2437. (<= (cdr tail) end))))
  2438. ((integerp (car undo-elt))
  2439. ;; (BEGIN . END)
  2440. (and (>= (car undo-elt) start)
  2441. (<= (cdr undo-elt) end)))))
  2442. (defun undo-elt-crosses-region (undo-elt start end)
  2443. "Test whether UNDO-ELT crosses one edge of that region START ... END.
  2444. This assumes we have already decided that UNDO-ELT
  2445. is not *inside* the region START...END."
  2446. (declare (obsolete nil "25.1"))
  2447. (cond ((atom undo-elt) nil)
  2448. ((null (car undo-elt))
  2449. ;; (nil PROPERTY VALUE BEG . END)
  2450. (let ((tail (nthcdr 3 undo-elt)))
  2451. (and (< (car tail) end)
  2452. (> (cdr tail) start))))
  2453. ((integerp (car undo-elt))
  2454. ;; (BEGIN . END)
  2455. (and (< (car undo-elt) end)
  2456. (> (cdr undo-elt) start)))))
  2457. (defun undo-adjust-elt (elt deltas)
  2458. "Return adjustment of undo element ELT by the undo DELTAS
  2459. list."
  2460. (pcase elt
  2461. ;; POSITION
  2462. ((pred integerp)
  2463. (undo-adjust-pos elt deltas))
  2464. ;; (BEG . END)
  2465. (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
  2466. (undo-adjust-beg-end beg end deltas))
  2467. ;; (TEXT . POSITION)
  2468. (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
  2469. (cons text (* (if (< pos 0) -1 1)
  2470. (undo-adjust-pos (abs pos) deltas))))
  2471. ;; (nil PROPERTY VALUE BEG . END)
  2472. (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
  2473. `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
  2474. ;; (apply DELTA START END FUN . ARGS)
  2475. ;; FIXME
  2476. ;; All others return same elt
  2477. (_ elt)))
  2478. ;; (BEG . END) can adjust to the same positions, commonly when an
  2479. ;; insertion was undone and they are out of region, for example:
  2480. ;;
  2481. ;; buf pos:
  2482. ;; 123456789 buffer-undo-list undo-deltas
  2483. ;; --------- ---------------- -----------
  2484. ;; [...]
  2485. ;; abbaa (2 . 4) (2 . -2)
  2486. ;; aaa ("bb" . 2) (2 . 2)
  2487. ;; [...]
  2488. ;;
  2489. ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
  2490. ;; undo. Further adjustments to such an element should be the same as
  2491. ;; for (TEXT . POSITION) elements. The options are:
  2492. ;;
  2493. ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
  2494. ;; analogous to marker insertion-type t.
  2495. ;;
  2496. ;; 2: POSITION adjusts using <, resulting in behavior analogous to
  2497. ;; marker insertion-type nil.
  2498. ;;
  2499. ;; There was no strong reason to prefer one or the other, except that
  2500. ;; the first is more consistent with prior undo in region behavior.
  2501. (defun undo-adjust-beg-end (beg end deltas)
  2502. "Return cons of adjustments to BEG and END by the undo DELTAS
  2503. list."
  2504. (let ((adj-beg (undo-adjust-pos beg deltas)))
  2505. ;; Note: option 2 above would be like (cons (min ...) adj-end)
  2506. (cons adj-beg
  2507. (max adj-beg (undo-adjust-pos end deltas t)))))
  2508. (defun undo-adjust-pos (pos deltas &optional use-<)
  2509. "Return adjustment of POS by the undo DELTAS list, comparing
  2510. with < or <= based on USE-<."
  2511. (dolist (d deltas pos)
  2512. (when (if use-<
  2513. (< (car d) pos)
  2514. (<= (car d) pos))
  2515. (setq pos
  2516. ;; Don't allow pos to become less than the undo-delta
  2517. ;; position. This edge case is described in the overview
  2518. ;; comments.
  2519. (max (car d) (- pos (cdr d)))))))
  2520. ;; Return the first affected buffer position and the delta for an undo element
  2521. ;; delta is defined as the change in subsequent buffer positions if we *did*
  2522. ;; the undo.
  2523. (defun undo-delta (undo-elt)
  2524. (if (consp undo-elt)
  2525. (cond ((stringp (car undo-elt))
  2526. ;; (TEXT . POSITION)
  2527. (cons (abs (cdr undo-elt)) (length (car undo-elt))))
  2528. ((integerp (car undo-elt))
  2529. ;; (BEGIN . END)
  2530. (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
  2531. (t
  2532. '(0 . 0)))
  2533. '(0 . 0)))
  2534. (defcustom undo-ask-before-discard nil
  2535. "If non-nil ask about discarding undo info for the current command.
  2536. Normally, Emacs discards the undo info for the current command if
  2537. it exceeds `undo-outer-limit'. But if you set this option
  2538. non-nil, it asks in the echo area whether to discard the info.
  2539. If you answer no, there is a slight risk that Emacs might crash, so
  2540. only do it if you really want to undo the command.
  2541. This option is mainly intended for debugging. You have to be
  2542. careful if you use it for other purposes. Garbage collection is
  2543. inhibited while the question is asked, meaning that Emacs might
  2544. leak memory. So you should make sure that you do not wait
  2545. excessively long before answering the question."
  2546. :type 'boolean
  2547. :group 'undo
  2548. :version "22.1")
  2549. (defvar undo-extra-outer-limit nil
  2550. "If non-nil, an extra level of size that's ok in an undo item.
  2551. We don't ask the user about truncating the undo list until the
  2552. current item gets bigger than this amount.
  2553. This variable only matters if `undo-ask-before-discard' is non-nil.")
  2554. (make-variable-buffer-local 'undo-extra-outer-limit)
  2555. ;; When the first undo batch in an undo list is longer than
  2556. ;; undo-outer-limit, this function gets called to warn the user that
  2557. ;; the undo info for the current command was discarded. Garbage
  2558. ;; collection is inhibited around the call, so it had better not do a
  2559. ;; lot of consing.
  2560. (setq undo-outer-limit-function 'undo-outer-limit-truncate)
  2561. (defun undo-outer-limit-truncate (size)
  2562. (if undo-ask-before-discard
  2563. (when (or (null undo-extra-outer-limit)
  2564. (> size undo-extra-outer-limit))
  2565. ;; Don't ask the question again unless it gets even bigger.
  2566. ;; This applies, in particular, if the user quits from the question.
  2567. ;; Such a quit quits out of GC, but something else will call GC
  2568. ;; again momentarily. It will call this function again,
  2569. ;; but we don't want to ask the question again.
  2570. (setq undo-extra-outer-limit (+ size 50000))
  2571. (if (let (use-dialog-box track-mouse executing-kbd-macro )
  2572. (yes-or-no-p (format-message
  2573. "Buffer ‘%s’ undo info is %d bytes long; discard it? "
  2574. (buffer-name) size)))
  2575. (progn (setq buffer-undo-list nil)
  2576. (setq undo-extra-outer-limit nil)
  2577. t)
  2578. nil))
  2579. (display-warning '(undo discard-info)
  2580. (concat
  2581. (format-message
  2582. "Buffer ‘%s’ undo info was %d bytes long.\n"
  2583. (buffer-name) size)
  2584. "The undo info was discarded because it exceeded \
  2585. `undo-outer-limit'.
  2586. This is normal if you executed a command that made a huge change
  2587. to the buffer. In that case, to prevent similar problems in the
  2588. future, set `undo-outer-limit' to a value that is large enough to
  2589. cover the maximum size of normal changes you expect a single
  2590. command to make, but not so large that it might exceed the
  2591. maximum memory allotted to Emacs.
  2592. If you did not execute any such command, the situation is
  2593. probably due to a bug and you should report it.
  2594. You can disable the popping up of this buffer by adding the entry
  2595. \(undo discard-info) to the user option `warning-suppress-types',
  2596. which is defined in the `warnings' library.\n")
  2597. :warning)
  2598. (setq buffer-undo-list nil)
  2599. t))
  2600. (defcustom password-word-equivalents
  2601. '("password" "passcode" "passphrase" "pass phrase"
  2602. ; These are sorted according to the GNU en_US locale.
  2603. "암호" ; ko
  2604. "パスワード" ; ja
  2605. "ପ୍ରବେଶ ସଙ୍କେତ" ; or
  2606. "ពាក្យសម្ងាត់" ; km
  2607. "adgangskode" ; da
  2608. "contraseña" ; es
  2609. "contrasenya" ; ca
  2610. "geslo" ; sl
  2611. "hasło" ; pl
  2612. "heslo" ; cs, sk
  2613. "iphasiwedi" ; zu
  2614. "jelszó" ; hu
  2615. "lösenord" ; sv
  2616. "lozinka" ; hr, sr
  2617. "mật khẩu" ; vi
  2618. "mot de passe" ; fr
  2619. "parola" ; tr
  2620. "pasahitza" ; eu
  2621. "passord" ; nb
  2622. "passwort" ; de
  2623. "pasvorto" ; eo
  2624. "salasana" ; fi
  2625. "senha" ; pt
  2626. "slaptažodis" ; lt
  2627. "wachtwoord" ; nl
  2628. "كلمة السر" ; ar
  2629. "ססמה" ; he
  2630. "лозинка" ; sr
  2631. "пароль" ; kk, ru, uk
  2632. "गुप्तशब्द" ; mr
  2633. "शब्दकूट" ; hi
  2634. "પાસવર્ડ" ; gu
  2635. "సంకేతపదము" ; te
  2636. "ਪਾਸਵਰਡ" ; pa
  2637. "ಗುಪ್ತಪದ" ; kn
  2638. "கடவுச்சொல்" ; ta
  2639. "അടയാളവാക്ക്" ; ml
  2640. "গুপ্তশব্দ" ; as
  2641. "পাসওয়ার্ড" ; bn_IN
  2642. "රහස්පදය" ; si
  2643. "密码" ; zh_CN
  2644. "密碼" ; zh_TW
  2645. )
  2646. "List of words equivalent to \"password\".
  2647. This is used by Shell mode and other parts of Emacs to recognize
  2648. password prompts, including prompts in languages other than
  2649. English. Different case choices should not be assumed to be
  2650. included; callers should bind `case-fold-search' to t."
  2651. :type '(repeat string)
  2652. :version "24.4"
  2653. :group 'processes)
  2654. (defvar shell-command-history nil
  2655. "History list for some commands that read shell commands.
  2656. Maximum length of the history list is determined by the value
  2657. of `history-length', which see.")
  2658. (defvar shell-command-switch (purecopy "-c")
  2659. "Switch used to have the shell execute its command line argument.")
  2660. (defvar shell-command-default-error-buffer nil
  2661. "Buffer name for `shell-command' and `shell-command-on-region' error output.
  2662. This buffer is used when `shell-command' or `shell-command-on-region'
  2663. is run interactively. A value of nil means that output to stderr and
  2664. stdout will be intermixed in the output stream.")
  2665. (declare-function mailcap-file-default-commands "mailcap" (files))
  2666. (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
  2667. (defun minibuffer-default-add-shell-commands ()
  2668. "Return a list of all commands associated with the current file.
  2669. This function is used to add all related commands retrieved by `mailcap'
  2670. to the end of the list of defaults just after the default value."
  2671. (interactive)
  2672. (let* ((filename (if (listp minibuffer-default)
  2673. (car minibuffer-default)
  2674. minibuffer-default))
  2675. (commands (and filename (require 'mailcap nil t)
  2676. (mailcap-file-default-commands (list filename)))))
  2677. (setq commands (mapcar (lambda (command)
  2678. (concat command " " filename))
  2679. commands))
  2680. (if (listp minibuffer-default)
  2681. (append minibuffer-default commands)
  2682. (cons minibuffer-default commands))))
  2683. (declare-function shell-completion-vars "shell" ())
  2684. (defvar minibuffer-local-shell-command-map
  2685. (let ((map (make-sparse-keymap)))
  2686. (set-keymap-parent map minibuffer-local-map)
  2687. (define-key map "\t" 'completion-at-point)
  2688. map)
  2689. "Keymap used for completing shell commands in minibuffer.")
  2690. (defun read-shell-command (prompt &optional initial-contents hist &rest args)
  2691. "Read a shell command from the minibuffer.
  2692. The arguments are the same as the ones of `read-from-minibuffer',
  2693. except READ and KEYMAP are missing and HIST defaults
  2694. to `shell-command-history'."
  2695. (require 'shell)
  2696. (minibuffer-with-setup-hook
  2697. (lambda ()
  2698. (shell-completion-vars)
  2699. (set (make-local-variable 'minibuffer-default-add-function)
  2700. 'minibuffer-default-add-shell-commands))
  2701. (apply 'read-from-minibuffer prompt initial-contents
  2702. minibuffer-local-shell-command-map
  2703. nil
  2704. (or hist 'shell-command-history)
  2705. args)))
  2706. (defcustom async-shell-command-buffer 'confirm-new-buffer
  2707. "What to do when the output buffer is used by another shell command.
  2708. This option specifies how to resolve the conflict where a new command
  2709. wants to direct its output to the buffer `*Async Shell Command*',
  2710. but this buffer is already taken by another running shell command.
  2711. The value `confirm-kill-process' is used to ask for confirmation before
  2712. killing the already running process and running a new process
  2713. in the same buffer, `confirm-new-buffer' for confirmation before running
  2714. the command in a new buffer with a name other than the default buffer name,
  2715. `new-buffer' for doing the same without confirmation,
  2716. `confirm-rename-buffer' for confirmation before renaming the existing
  2717. output buffer and running a new command in the default buffer,
  2718. `rename-buffer' for doing the same without confirmation."
  2719. :type '(choice (const :tag "Confirm killing of running command"
  2720. confirm-kill-process)
  2721. (const :tag "Confirm creation of a new buffer"
  2722. confirm-new-buffer)
  2723. (const :tag "Create a new buffer"
  2724. new-buffer)
  2725. (const :tag "Confirm renaming of existing buffer"
  2726. confirm-rename-buffer)
  2727. (const :tag "Rename the existing buffer"
  2728. rename-buffer))
  2729. :group 'shell
  2730. :version "24.3")
  2731. (defun async-shell-command (command &optional output-buffer error-buffer)
  2732. "Execute string COMMAND asynchronously in background.
  2733. Like `shell-command', but adds `&' at the end of COMMAND
  2734. to execute it asynchronously.
  2735. The output appears in the buffer `*Async Shell Command*'.
  2736. That buffer is in shell mode.
  2737. You can configure `async-shell-command-buffer' to specify what to do in
  2738. case when `*Async Shell Command*' buffer is already taken by another
  2739. running shell command. To run COMMAND without displaying the output
  2740. in a window you can configure `display-buffer-alist' to use the action
  2741. `display-buffer-no-window' for the buffer `*Async Shell Command*'.
  2742. In Elisp, you will often be better served by calling `start-process'
  2743. directly, since it offers more control and does not impose the use of a
  2744. shell (with its need to quote arguments)."
  2745. (interactive
  2746. (list
  2747. (read-shell-command "Async shell command: " nil nil
  2748. (let ((filename
  2749. (cond
  2750. (buffer-file-name)
  2751. ((eq major-mode 'dired-mode)
  2752. (dired-get-filename nil t)))))
  2753. (and filename (file-relative-name filename))))
  2754. current-prefix-arg
  2755. shell-command-default-error-buffer))
  2756. (unless (string-match "&[ \t]*\\'" command)
  2757. (setq command (concat command " &")))
  2758. (shell-command command output-buffer error-buffer))
  2759. (defun shell-command (command &optional output-buffer error-buffer)
  2760. "Execute string COMMAND in inferior shell; display output, if any.
  2761. With prefix argument, insert the COMMAND's output at point.
  2762. If COMMAND ends in `&', execute it asynchronously.
  2763. The output appears in the buffer `*Async Shell Command*'.
  2764. That buffer is in shell mode. You can also use
  2765. `async-shell-command' that automatically adds `&'.
  2766. Otherwise, COMMAND is executed synchronously. The output appears in
  2767. the buffer `*Shell Command Output*'. If the output is short enough to
  2768. display in the echo area (which is determined by the variables
  2769. `resize-mini-windows' and `max-mini-window-height'), it is shown
  2770. there, but it is nonetheless available in buffer `*Shell Command
  2771. Output*' even though that buffer is not automatically displayed.
  2772. To specify a coding system for converting non-ASCII characters
  2773. in the shell command output, use \\[universal-coding-system-argument] \
  2774. before this command.
  2775. Noninteractive callers can specify coding systems by binding
  2776. `coding-system-for-read' and `coding-system-for-write'.
  2777. The optional second argument OUTPUT-BUFFER, if non-nil,
  2778. says to put the output in some other buffer.
  2779. If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
  2780. If OUTPUT-BUFFER is not a buffer and not nil,
  2781. insert output in current buffer. (This cannot be done asynchronously.)
  2782. In either case, the buffer is first erased, and the output is
  2783. inserted after point (leaving mark after it).
  2784. If the command terminates without error, but generates output,
  2785. and you did not specify \"insert it in the current buffer\",
  2786. the output can be displayed in the echo area or in its buffer.
  2787. If the output is short enough to display in the echo area
  2788. \(determined by the variable `max-mini-window-height' if
  2789. `resize-mini-windows' is non-nil), it is shown there.
  2790. Otherwise,the buffer containing the output is displayed.
  2791. If there is output and an error, and you did not specify \"insert it
  2792. in the current buffer\", a message about the error goes at the end
  2793. of the output.
  2794. If there is no output, or if output is inserted in the current buffer,
  2795. then `*Shell Command Output*' is deleted.
  2796. If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
  2797. or buffer name to which to direct the command's standard error output.
  2798. If it is nil, error output is mingled with regular output.
  2799. In an interactive call, the variable `shell-command-default-error-buffer'
  2800. specifies the value of ERROR-BUFFER.
  2801. In Elisp, you will often be better served by calling `call-process' or
  2802. `start-process' directly, since it offers more control and does not impose
  2803. the use of a shell (with its need to quote arguments)."
  2804. (interactive
  2805. (list
  2806. (read-shell-command "Shell command: " nil nil
  2807. (let ((filename
  2808. (cond
  2809. (buffer-file-name)
  2810. ((eq major-mode 'dired-mode)
  2811. (dired-get-filename nil t)))))
  2812. (and filename (file-relative-name filename))))
  2813. current-prefix-arg
  2814. shell-command-default-error-buffer))
  2815. ;; Look for a handler in case default-directory is a remote file name.
  2816. (let ((handler
  2817. (find-file-name-handler (directory-file-name default-directory)
  2818. 'shell-command)))
  2819. (if handler
  2820. (funcall handler 'shell-command command output-buffer error-buffer)
  2821. (if (and output-buffer
  2822. (not (or (bufferp output-buffer) (stringp output-buffer))))
  2823. ;; Output goes in current buffer.
  2824. (let ((error-file
  2825. (if error-buffer
  2826. (make-temp-file
  2827. (expand-file-name "scor"
  2828. (or small-temporary-file-directory
  2829. temporary-file-directory)))
  2830. nil)))
  2831. (barf-if-buffer-read-only)
  2832. (push-mark nil t)
  2833. ;; We do not use -f for csh; we will not support broken use of
  2834. ;; .cshrcs. Even the BSD csh manual says to use
  2835. ;; "if ($?prompt) exit" before things which are not useful
  2836. ;; non-interactively. Besides, if someone wants their other
  2837. ;; aliases for shell commands then they can still have them.
  2838. (call-process shell-file-name nil
  2839. (if error-file
  2840. (list t error-file)
  2841. t)
  2842. nil shell-command-switch command)
  2843. (when (and error-file (file-exists-p error-file))
  2844. (if (< 0 (nth 7 (file-attributes error-file)))
  2845. (with-current-buffer (get-buffer-create error-buffer)
  2846. (let ((pos-from-end (- (point-max) (point))))
  2847. (or (bobp)
  2848. (insert "\f\n"))
  2849. ;; Do no formatting while reading error file,
  2850. ;; because that can run a shell command, and we
  2851. ;; don't want that to cause an infinite recursion.
  2852. (format-insert-file error-file nil)
  2853. ;; Put point after the inserted errors.
  2854. (goto-char (- (point-max) pos-from-end)))
  2855. (display-buffer (current-buffer))))
  2856. (delete-file error-file))
  2857. ;; This is like exchange-point-and-mark, but doesn't
  2858. ;; activate the mark. It is cleaner to avoid activation,
  2859. ;; even though the command loop would deactivate the mark
  2860. ;; because we inserted text.
  2861. (goto-char (prog1 (mark t)
  2862. (set-marker (mark-marker) (point)
  2863. (current-buffer)))))
  2864. ;; Output goes in a separate buffer.
  2865. ;; Preserve the match data in case called from a program.
  2866. (save-match-data
  2867. (if (string-match "[ \t]*&[ \t]*\\'" command)
  2868. ;; Command ending with ampersand means asynchronous.
  2869. (let ((buffer (get-buffer-create
  2870. (or output-buffer "*Async Shell Command*")))
  2871. (directory default-directory)
  2872. proc)
  2873. ;; Remove the ampersand.
  2874. (setq command (substring command 0 (match-beginning 0)))
  2875. ;; Ask the user what to do with already running process.
  2876. (setq proc (get-buffer-process buffer))
  2877. (when proc
  2878. (cond
  2879. ((eq async-shell-command-buffer 'confirm-kill-process)
  2880. ;; If will kill a process, query first.
  2881. (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
  2882. (kill-process proc)
  2883. (error "Shell command in progress")))
  2884. ((eq async-shell-command-buffer 'confirm-new-buffer)
  2885. ;; If will create a new buffer, query first.
  2886. (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
  2887. (setq buffer (generate-new-buffer
  2888. (or (and (bufferp output-buffer) (buffer-name output-buffer))
  2889. output-buffer "*Async Shell Command*")))
  2890. (error "Shell command in progress")))
  2891. ((eq async-shell-command-buffer 'new-buffer)
  2892. ;; It will create a new buffer.
  2893. (setq buffer (generate-new-buffer
  2894. (or (and (bufferp output-buffer) (buffer-name output-buffer))
  2895. output-buffer "*Async Shell Command*"))))
  2896. ((eq async-shell-command-buffer 'confirm-rename-buffer)
  2897. ;; If will rename the buffer, query first.
  2898. (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
  2899. (progn
  2900. (with-current-buffer buffer
  2901. (rename-uniquely))
  2902. (setq buffer (get-buffer-create
  2903. (or output-buffer "*Async Shell Command*"))))
  2904. (error "Shell command in progress")))
  2905. ((eq async-shell-command-buffer 'rename-buffer)
  2906. ;; It will rename the buffer.
  2907. (with-current-buffer buffer
  2908. (rename-uniquely))
  2909. (setq buffer (get-buffer-create
  2910. (or output-buffer "*Async Shell Command*"))))))
  2911. (with-current-buffer buffer
  2912. (setq buffer-read-only nil)
  2913. ;; Setting buffer-read-only to nil doesn't suffice
  2914. ;; if some text has a non-nil read-only property,
  2915. ;; which comint sometimes adds for prompts.
  2916. (let ((inhibit-read-only t))
  2917. (erase-buffer))
  2918. (display-buffer buffer '(nil (allow-no-window . t)))
  2919. (setq default-directory directory)
  2920. (setq proc (start-process "Shell" buffer shell-file-name
  2921. shell-command-switch command))
  2922. (setq mode-line-process '(":%s"))
  2923. (require 'shell) (shell-mode)
  2924. (set-process-sentinel proc 'shell-command-sentinel)
  2925. ;; Use the comint filter for proper handling of carriage motion
  2926. ;; (see `comint-inhibit-carriage-motion'),.
  2927. (set-process-filter proc 'comint-output-filter)
  2928. ))
  2929. ;; Otherwise, command is executed synchronously.
  2930. (shell-command-on-region (point) (point) command
  2931. output-buffer nil error-buffer)))))))
  2932. (defun display-message-or-buffer (message
  2933. &optional buffer-name not-this-window frame)
  2934. "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
  2935. MESSAGE may be either a string or a buffer.
  2936. A buffer is displayed using `display-buffer' if MESSAGE is too long for
  2937. the maximum height of the echo area, as defined by `max-mini-window-height'
  2938. if `resize-mini-windows' is non-nil.
  2939. Returns either the string shown in the echo area, or when a pop-up
  2940. buffer is used, the window used to display it.
  2941. If MESSAGE is a string, then the optional argument BUFFER-NAME is the
  2942. name of the buffer used to display it in the case where a pop-up buffer
  2943. is used, defaulting to `*Message*'. In the case where MESSAGE is a
  2944. string and it is displayed in the echo area, it is not specified whether
  2945. the contents are inserted into the buffer anyway.
  2946. Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
  2947. and only used if a buffer is displayed."
  2948. (cond ((and (stringp message) (not (string-match "\n" message)))
  2949. ;; Trivial case where we can use the echo area
  2950. (message "%s" message))
  2951. ((and (stringp message)
  2952. (= (string-match "\n" message) (1- (length message))))
  2953. ;; Trivial case where we can just remove single trailing newline
  2954. (message "%s" (substring message 0 (1- (length message)))))
  2955. (t
  2956. ;; General case
  2957. (with-current-buffer
  2958. (if (bufferp message)
  2959. message
  2960. (get-buffer-create (or buffer-name "*Message*")))
  2961. (unless (bufferp message)
  2962. (erase-buffer)
  2963. (insert message))
  2964. (let ((lines
  2965. (if (= (buffer-size) 0)
  2966. 0
  2967. (count-screen-lines nil nil nil (minibuffer-window)))))
  2968. (cond ((= lines 0))
  2969. ((and (or (<= lines 1)
  2970. (<= lines
  2971. (if resize-mini-windows
  2972. (cond ((floatp max-mini-window-height)
  2973. (* (frame-height)
  2974. max-mini-window-height))
  2975. ((integerp max-mini-window-height)
  2976. max-mini-window-height)
  2977. (t
  2978. 1))
  2979. 1)))
  2980. ;; Don't use the echo area if the output buffer is
  2981. ;; already displayed in the selected frame.
  2982. (not (get-buffer-window (current-buffer))))
  2983. ;; Echo area
  2984. (goto-char (point-max))
  2985. (when (bolp)
  2986. (backward-char 1))
  2987. (message "%s" (buffer-substring (point-min) (point))))
  2988. (t
  2989. ;; Buffer
  2990. (goto-char (point-min))
  2991. (display-buffer (current-buffer)
  2992. not-this-window frame))))))))
  2993. ;; We have a sentinel to prevent insertion of a termination message
  2994. ;; in the buffer itself.
  2995. (defun shell-command-sentinel (process signal)
  2996. (if (memq (process-status process) '(exit signal))
  2997. (message "%s: %s."
  2998. (car (cdr (cdr (process-command process))))
  2999. (substring signal 0 -1))))
  3000. (defun shell-command-on-region (start end command
  3001. &optional output-buffer replace
  3002. error-buffer display-error-buffer)
  3003. "Execute string COMMAND in inferior shell with region as input.
  3004. Normally display output (if any) in temp buffer `*Shell Command Output*';
  3005. Prefix arg means replace the region with it. Return the exit code of
  3006. COMMAND.
  3007. To specify a coding system for converting non-ASCII characters
  3008. in the input and output to the shell command, use \\[universal-coding-system-argument]
  3009. before this command. By default, the input (from the current buffer)
  3010. is encoded using coding-system specified by `process-coding-system-alist',
  3011. falling back to `default-process-coding-system' if no match for COMMAND
  3012. is found in `process-coding-system-alist'.
  3013. Noninteractive callers can specify coding systems by binding
  3014. `coding-system-for-read' and `coding-system-for-write'.
  3015. If the command generates output, the output may be displayed
  3016. in the echo area or in a buffer.
  3017. If the output is short enough to display in the echo area
  3018. \(determined by the variable `max-mini-window-height' if
  3019. `resize-mini-windows' is non-nil), it is shown there.
  3020. Otherwise it is displayed in the buffer `*Shell Command Output*'.
  3021. The output is available in that buffer in both cases.
  3022. If there is output and an error, a message about the error
  3023. appears at the end of the output. If there is no output, or if
  3024. output is inserted in the current buffer, the buffer `*Shell
  3025. Command Output*' is deleted.
  3026. Optional fourth arg OUTPUT-BUFFER specifies where to put the
  3027. command's output. If the value is a buffer or buffer name,
  3028. put the output there. If the value is nil, use the buffer
  3029. `*Shell Command Output*'. Any other value, excluding nil,
  3030. means to insert the output in the current buffer. In either case,
  3031. the output is inserted after point (leaving mark after it).
  3032. Optional fifth arg REPLACE, if non-nil, means to insert the
  3033. output in place of text from START to END, putting point and mark
  3034. around it.
  3035. Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
  3036. or buffer name to which to direct the command's standard error
  3037. output. If nil, error output is mingled with regular output.
  3038. When called interactively, `shell-command-default-error-buffer'
  3039. is used for ERROR-BUFFER.
  3040. Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
  3041. display the error buffer if there were any errors. When called
  3042. interactively, this is t."
  3043. (interactive (let (string)
  3044. (unless (mark)
  3045. (user-error "The mark is not set now, so there is no region"))
  3046. ;; Do this before calling region-beginning
  3047. ;; and region-end, in case subprocess output
  3048. ;; relocates them while we are in the minibuffer.
  3049. (setq string (read-shell-command "Shell command on region: "))
  3050. ;; call-interactively recognizes region-beginning and
  3051. ;; region-end specially, leaving them in the history.
  3052. (list (region-beginning) (region-end)
  3053. string
  3054. current-prefix-arg
  3055. current-prefix-arg
  3056. shell-command-default-error-buffer
  3057. t)))
  3058. (let ((error-file
  3059. (if error-buffer
  3060. (make-temp-file
  3061. (expand-file-name "scor"
  3062. (or small-temporary-file-directory
  3063. temporary-file-directory)))
  3064. nil))
  3065. exit-status)
  3066. (if (or replace
  3067. (and output-buffer
  3068. (not (or (bufferp output-buffer) (stringp output-buffer)))))
  3069. ;; Replace specified region with output from command.
  3070. (let ((swap (and replace (< start end))))
  3071. ;; Don't muck with mark unless REPLACE says we should.
  3072. (goto-char start)
  3073. (and replace (push-mark (point) 'nomsg))
  3074. (setq exit-status
  3075. (call-process-region start end shell-file-name replace
  3076. (if error-file
  3077. (list t error-file)
  3078. t)
  3079. nil shell-command-switch command))
  3080. ;; It is rude to delete a buffer which the command is not using.
  3081. ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
  3082. ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
  3083. ;; (kill-buffer shell-buffer)))
  3084. ;; Don't muck with mark unless REPLACE says we should.
  3085. (and replace swap (exchange-point-and-mark)))
  3086. ;; No prefix argument: put the output in a temp buffer,
  3087. ;; replacing its entire contents.
  3088. (let ((buffer (get-buffer-create
  3089. (or output-buffer "*Shell Command Output*"))))
  3090. (unwind-protect
  3091. (if (eq buffer (current-buffer))
  3092. ;; If the input is the same buffer as the output,
  3093. ;; delete everything but the specified region,
  3094. ;; then replace that region with the output.
  3095. (progn (setq buffer-read-only nil)
  3096. (delete-region (max start end) (point-max))
  3097. (delete-region (point-min) (min start end))
  3098. (setq exit-status
  3099. (call-process-region (point-min) (point-max)
  3100. shell-file-name t
  3101. (if error-file
  3102. (list t error-file)
  3103. t)
  3104. nil shell-command-switch
  3105. command)))
  3106. ;; Clear the output buffer, then run the command with
  3107. ;; output there.
  3108. (let ((directory default-directory))
  3109. (with-current-buffer buffer
  3110. (setq buffer-read-only nil)
  3111. (if (not output-buffer)
  3112. (setq default-directory directory))
  3113. (erase-buffer)))
  3114. (setq exit-status
  3115. (call-process-region start end shell-file-name nil
  3116. (if error-file
  3117. (list buffer error-file)
  3118. buffer)
  3119. nil shell-command-switch command)))
  3120. ;; Report the output.
  3121. (with-current-buffer buffer
  3122. (setq mode-line-process
  3123. (cond ((null exit-status)
  3124. " - Error")
  3125. ((stringp exit-status)
  3126. (format " - Signal [%s]" exit-status))
  3127. ((not (equal 0 exit-status))
  3128. (format " - Exit [%d]" exit-status)))))
  3129. (if (with-current-buffer buffer (> (point-max) (point-min)))
  3130. ;; There's some output, display it
  3131. (display-message-or-buffer buffer)
  3132. ;; No output; error?
  3133. (let ((output
  3134. (if (and error-file
  3135. (< 0 (nth 7 (file-attributes error-file))))
  3136. (format "some error output%s"
  3137. (if shell-command-default-error-buffer
  3138. (format " to the \"%s\" buffer"
  3139. shell-command-default-error-buffer)
  3140. ""))
  3141. "no output")))
  3142. (cond ((null exit-status)
  3143. (message "(Shell command failed with error)"))
  3144. ((equal 0 exit-status)
  3145. (message "(Shell command succeeded with %s)"
  3146. output))
  3147. ((stringp exit-status)
  3148. (message "(Shell command killed by signal %s)"
  3149. exit-status))
  3150. (t
  3151. (message "(Shell command failed with code %d and %s)"
  3152. exit-status output))))
  3153. ;; Don't kill: there might be useful info in the undo-log.
  3154. ;; (kill-buffer buffer)
  3155. ))))
  3156. (when (and error-file (file-exists-p error-file))
  3157. (if (< 0 (nth 7 (file-attributes error-file)))
  3158. (with-current-buffer (get-buffer-create error-buffer)
  3159. (let ((pos-from-end (- (point-max) (point))))
  3160. (or (bobp)
  3161. (insert "\f\n"))
  3162. ;; Do no formatting while reading error file,
  3163. ;; because that can run a shell command, and we
  3164. ;; don't want that to cause an infinite recursion.
  3165. (format-insert-file error-file nil)
  3166. ;; Put point after the inserted errors.
  3167. (goto-char (- (point-max) pos-from-end)))
  3168. (and display-error-buffer
  3169. (display-buffer (current-buffer)))))
  3170. (delete-file error-file))
  3171. exit-status))
  3172. (defun shell-command-to-string (command)
  3173. "Execute shell command COMMAND and return its output as a string."
  3174. (with-output-to-string
  3175. (with-current-buffer
  3176. standard-output
  3177. (process-file shell-file-name nil t nil shell-command-switch command))))
  3178. (defun process-file (program &optional infile buffer display &rest args)
  3179. "Process files synchronously in a separate process.
  3180. Similar to `call-process', but may invoke a file handler based on
  3181. `default-directory'. The current working directory of the
  3182. subprocess is `default-directory'.
  3183. File names in INFILE and BUFFER are handled normally, but file
  3184. names in ARGS should be relative to `default-directory', as they
  3185. are passed to the process verbatim. (This is a difference to
  3186. `call-process' which does not support file handlers for INFILE
  3187. and BUFFER.)
  3188. Some file handlers might not support all variants, for example
  3189. they might behave as if DISPLAY was nil, regardless of the actual
  3190. value passed."
  3191. (let ((fh (find-file-name-handler default-directory 'process-file))
  3192. lc stderr-file)
  3193. (unwind-protect
  3194. (if fh (apply fh 'process-file program infile buffer display args)
  3195. (when infile (setq lc (file-local-copy infile)))
  3196. (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
  3197. (make-temp-file "emacs")))
  3198. (prog1
  3199. (apply 'call-process program
  3200. (or lc infile)
  3201. (if stderr-file (list (car buffer) stderr-file) buffer)
  3202. display args)
  3203. (when stderr-file (copy-file stderr-file (cadr buffer) t))))
  3204. (when stderr-file (delete-file stderr-file))
  3205. (when lc (delete-file lc)))))
  3206. (defvar process-file-side-effects t
  3207. "Whether a call of `process-file' changes remote files.
  3208. By default, this variable is always set to t, meaning that a
  3209. call of `process-file' could potentially change any file on a
  3210. remote host. When set to nil, a file handler could optimize
  3211. its behavior with respect to remote file attribute caching.
  3212. You should only ever change this variable with a let-binding;
  3213. never with `setq'.")
  3214. (defun start-file-process (name buffer program &rest program-args)
  3215. "Start a program in a subprocess. Return the process object for it.
  3216. Similar to `start-process', but may invoke a file handler based on
  3217. `default-directory'. See Info node `(elisp)Magic File Names'.
  3218. This handler ought to run PROGRAM, perhaps on the local host,
  3219. perhaps on a remote host that corresponds to `default-directory'.
  3220. In the latter case, the local part of `default-directory' becomes
  3221. the working directory of the process.
  3222. PROGRAM and PROGRAM-ARGS might be file names. They are not
  3223. objects of file handler invocation. File handlers might not
  3224. support pty association, if PROGRAM is nil."
  3225. (let ((fh (find-file-name-handler default-directory 'start-file-process)))
  3226. (if fh (apply fh 'start-file-process name buffer program program-args)
  3227. (apply 'start-process name buffer program program-args))))
  3228. ;;;; Process menu
  3229. (defvar tabulated-list-format)
  3230. (defvar tabulated-list-entries)
  3231. (defvar tabulated-list-sort-key)
  3232. (declare-function tabulated-list-init-header "tabulated-list" ())
  3233. (declare-function tabulated-list-print "tabulated-list"
  3234. (&optional remember-pos update))
  3235. (defvar process-menu-query-only nil)
  3236. (defvar process-menu-mode-map
  3237. (let ((map (make-sparse-keymap)))
  3238. (define-key map [?d] 'process-menu-delete-process)
  3239. map))
  3240. (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
  3241. "Major mode for listing the processes called by Emacs."
  3242. (setq tabulated-list-format [("Process" 15 t)
  3243. ("Status" 7 t)
  3244. ("Buffer" 15 t)
  3245. ("TTY" 12 t)
  3246. ("Command" 0 t)])
  3247. (make-local-variable 'process-menu-query-only)
  3248. (setq tabulated-list-sort-key (cons "Process" nil))
  3249. (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
  3250. (tabulated-list-init-header))
  3251. (defun process-menu-delete-process ()
  3252. "Kill process at point in a `list-processes' buffer."
  3253. (interactive)
  3254. (delete-process (tabulated-list-get-id))
  3255. (revert-buffer))
  3256. (defun list-processes--refresh ()
  3257. "Recompute the list of processes for the Process List buffer.
  3258. Also, delete any process that is exited or signaled."
  3259. (setq tabulated-list-entries nil)
  3260. (dolist (p (process-list))
  3261. (cond ((memq (process-status p) '(exit signal closed))
  3262. (delete-process p))
  3263. ((or (not process-menu-query-only)
  3264. (process-query-on-exit-flag p))
  3265. (let* ((buf (process-buffer p))
  3266. (type (process-type p))
  3267. (name (process-name p))
  3268. (status (symbol-name (process-status p)))
  3269. (buf-label (if (buffer-live-p buf)
  3270. `(,(buffer-name buf)
  3271. face link
  3272. help-echo ,(format-message
  3273. "Visit buffer ‘%s’"
  3274. (buffer-name buf))
  3275. follow-link t
  3276. process-buffer ,buf
  3277. action process-menu-visit-buffer)
  3278. "--"))
  3279. (tty (or (process-tty-name p) "--"))
  3280. (cmd
  3281. (if (memq type '(network serial))
  3282. (let ((contact (process-contact p t)))
  3283. (if (eq type 'network)
  3284. (format "(%s %s)"
  3285. (if (plist-get contact :type)
  3286. "datagram"
  3287. "network")
  3288. (if (plist-get contact :server)
  3289. (format "server on %s"
  3290. (or
  3291. (plist-get contact :host)
  3292. (plist-get contact :local)))
  3293. (format "connection to %s"
  3294. (plist-get contact :host))))
  3295. (format "(serial port %s%s)"
  3296. (or (plist-get contact :port) "?")
  3297. (let ((speed (plist-get contact :speed)))
  3298. (if speed
  3299. (format " at %s b/s" speed)
  3300. "")))))
  3301. (mapconcat 'identity (process-command p) " "))))
  3302. (push (list p (vector name status buf-label tty cmd))
  3303. tabulated-list-entries))))))
  3304. (defun process-menu-visit-buffer (button)
  3305. (display-buffer (button-get button 'process-buffer)))
  3306. (defun list-processes (&optional query-only buffer)
  3307. "Display a list of all processes that are Emacs sub-processes.
  3308. If optional argument QUERY-ONLY is non-nil, only processes with
  3309. the query-on-exit flag set are listed.
  3310. Any process listed as exited or signaled is actually eliminated
  3311. after the listing is made.
  3312. Optional argument BUFFER specifies a buffer to use, instead of
  3313. \"*Process List*\".
  3314. The return value is always nil.
  3315. This function lists only processes that were launched by Emacs. To
  3316. see other processes running on the system, use `list-system-processes'."
  3317. (interactive)
  3318. (or (fboundp 'process-list)
  3319. (error "Asynchronous subprocesses are not supported on this system"))
  3320. (unless (bufferp buffer)
  3321. (setq buffer (get-buffer-create "*Process List*")))
  3322. (with-current-buffer buffer
  3323. (process-menu-mode)
  3324. (setq process-menu-query-only query-only)
  3325. (list-processes--refresh)
  3326. (tabulated-list-print))
  3327. (display-buffer buffer)
  3328. nil)
  3329. (defvar universal-argument-map
  3330. (let ((map (make-sparse-keymap))
  3331. (universal-argument-minus
  3332. ;; For backward compatibility, minus with no modifiers is an ordinary
  3333. ;; command if digits have already been entered.
  3334. `(menu-item "" negative-argument
  3335. :filter ,(lambda (cmd)
  3336. (if (integerp prefix-arg) nil cmd)))))
  3337. (define-key map [switch-frame]
  3338. (lambda (e) (interactive "e")
  3339. (handle-switch-frame e) (universal-argument--mode)))
  3340. (define-key map [?\C-u] 'universal-argument-more)
  3341. (define-key map [?-] universal-argument-minus)
  3342. (define-key map [?0] 'digit-argument)
  3343. (define-key map [?1] 'digit-argument)
  3344. (define-key map [?2] 'digit-argument)
  3345. (define-key map [?3] 'digit-argument)
  3346. (define-key map [?4] 'digit-argument)
  3347. (define-key map [?5] 'digit-argument)
  3348. (define-key map [?6] 'digit-argument)
  3349. (define-key map [?7] 'digit-argument)
  3350. (define-key map [?8] 'digit-argument)
  3351. (define-key map [?9] 'digit-argument)
  3352. (define-key map [kp-0] 'digit-argument)
  3353. (define-key map [kp-1] 'digit-argument)
  3354. (define-key map [kp-2] 'digit-argument)
  3355. (define-key map [kp-3] 'digit-argument)
  3356. (define-key map [kp-4] 'digit-argument)
  3357. (define-key map [kp-5] 'digit-argument)
  3358. (define-key map [kp-6] 'digit-argument)
  3359. (define-key map [kp-7] 'digit-argument)
  3360. (define-key map [kp-8] 'digit-argument)
  3361. (define-key map [kp-9] 'digit-argument)
  3362. (define-key map [kp-subtract] universal-argument-minus)
  3363. map)
  3364. "Keymap used while processing \\[universal-argument].")
  3365. (defun universal-argument--mode ()
  3366. (set-transient-map universal-argument-map))
  3367. (defun universal-argument ()
  3368. "Begin a numeric argument for the following command.
  3369. Digits or minus sign following \\[universal-argument] make up the numeric argument.
  3370. \\[universal-argument] following the digits or minus sign ends the argument.
  3371. \\[universal-argument] without digits or minus sign provides 4 as argument.
  3372. Repeating \\[universal-argument] without digits or minus sign
  3373. multiplies the argument by 4 each time.
  3374. For some commands, just \\[universal-argument] by itself serves as a flag
  3375. which is different in effect from any particular numeric argument.
  3376. These commands include \\[set-mark-command] and \\[start-kbd-macro]."
  3377. (interactive)
  3378. (setq prefix-arg (list 4))
  3379. (universal-argument--mode))
  3380. (defun universal-argument-more (arg)
  3381. ;; A subsequent C-u means to multiply the factor by 4 if we've typed
  3382. ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
  3383. (interactive "P")
  3384. (setq prefix-arg (if (consp arg)
  3385. (list (* 4 (car arg)))
  3386. (if (eq arg '-)
  3387. (list -4)
  3388. arg)))
  3389. (when (consp prefix-arg) (universal-argument--mode)))
  3390. (defun negative-argument (arg)
  3391. "Begin a negative numeric argument for the next command.
  3392. \\[universal-argument] following digits or minus sign ends the argument."
  3393. (interactive "P")
  3394. (setq prefix-arg (cond ((integerp arg) (- arg))
  3395. ((eq arg '-) nil)
  3396. (t '-)))
  3397. (universal-argument--mode))
  3398. (defun digit-argument (arg)
  3399. "Part of the numeric argument for the next command.
  3400. \\[universal-argument] following digits or minus sign ends the argument."
  3401. (interactive "P")
  3402. (let* ((char (if (integerp last-command-event)
  3403. last-command-event
  3404. (get last-command-event 'ascii-character)))
  3405. (digit (- (logand char ?\177) ?0)))
  3406. (setq prefix-arg (cond ((integerp arg)
  3407. (+ (* arg 10)
  3408. (if (< arg 0) (- digit) digit)))
  3409. ((eq arg '-)
  3410. ;; Treat -0 as just -, so that -01 will work.
  3411. (if (zerop digit) '- (- digit)))
  3412. (t
  3413. digit))))
  3414. (universal-argument--mode))
  3415. (defvar filter-buffer-substring-functions nil
  3416. "This variable is a wrapper hook around `buffer-substring--filter'.")
  3417. (make-obsolete-variable 'filter-buffer-substring-functions
  3418. 'filter-buffer-substring-function "24.4")
  3419. (defvar filter-buffer-substring-function #'buffer-substring--filter
  3420. "Function to perform the filtering in `filter-buffer-substring'.
  3421. The function is called with the same 3 arguments (BEG END DELETE)
  3422. that `filter-buffer-substring' received. It should return the
  3423. buffer substring between BEG and END, after filtering. If DELETE is
  3424. non-nil, it should delete the text between BEG and END from the buffer.")
  3425. (defvar buffer-substring-filters nil
  3426. "List of filter functions for `buffer-substring--filter'.
  3427. Each function must accept a single argument, a string, and return a string.
  3428. The buffer substring is passed to the first function in the list,
  3429. and the return value of each function is passed to the next.
  3430. As a special convention, point is set to the start of the buffer text
  3431. being operated on (i.e., the first argument of `buffer-substring--filter')
  3432. before these functions are called.")
  3433. (make-obsolete-variable 'buffer-substring-filters
  3434. 'filter-buffer-substring-function "24.1")
  3435. (defun filter-buffer-substring (beg end &optional delete)
  3436. "Return the buffer substring between BEG and END, after filtering.
  3437. If DELETE is non-nil, delete the text between BEG and END from the buffer.
  3438. This calls the function that `filter-buffer-substring-function' specifies
  3439. \(passing the same three arguments that it received) to do the work,
  3440. and returns whatever it does. The default function does no filtering,
  3441. unless a hook has been set.
  3442. Use `filter-buffer-substring' instead of `buffer-substring',
  3443. `buffer-substring-no-properties', or `delete-and-extract-region' when
  3444. you want to allow filtering to take place. For example, major or minor
  3445. modes can use `filter-buffer-substring-function' to extract characters
  3446. that are special to a buffer, and should not be copied into other buffers."
  3447. (funcall filter-buffer-substring-function beg end delete))
  3448. (defun buffer-substring--filter (beg end &optional delete)
  3449. "Default function to use for `filter-buffer-substring-function'.
  3450. Its arguments and return value are as specified for `filter-buffer-substring'.
  3451. This respects the wrapper hook `filter-buffer-substring-functions',
  3452. and the abnormal hook `buffer-substring-filters'.
  3453. No filtering is done unless a hook says to."
  3454. (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
  3455. (cond
  3456. ((or delete buffer-substring-filters)
  3457. (save-excursion
  3458. (goto-char beg)
  3459. (let ((string (if delete (delete-and-extract-region beg end)
  3460. (buffer-substring beg end))))
  3461. (dolist (filter buffer-substring-filters)
  3462. (setq string (funcall filter string)))
  3463. string)))
  3464. (t
  3465. (buffer-substring beg end)))))
  3466. ;;;; Window system cut and paste hooks.
  3467. (defvar interprogram-cut-function #'gui-select-text
  3468. "Function to call to make a killed region available to other programs.
  3469. Most window systems provide a facility for cutting and pasting
  3470. text between different programs, such as the clipboard on X and
  3471. MS-Windows, or the pasteboard on Nextstep/Mac OS.
  3472. This variable holds a function that Emacs calls whenever text is
  3473. put in the kill ring, to make the new kill available to other
  3474. programs. The function takes one argument, TEXT, which is a
  3475. string containing the text which should be made available.")
  3476. (defvar interprogram-paste-function #'gui-selection-value
  3477. "Function to call to get text cut from other programs.
  3478. Most window systems provide a facility for cutting and pasting
  3479. text between different programs, such as the clipboard on X and
  3480. MS-Windows, or the pasteboard on Nextstep/Mac OS.
  3481. This variable holds a function that Emacs calls to obtain text
  3482. that other programs have provided for pasting. The function is
  3483. called with no arguments. If no other program has provided text
  3484. to paste, the function should return nil (in which case the
  3485. caller, usually `current-kill', should use the top of the Emacs
  3486. kill ring). If another program has provided text to paste, the
  3487. function should return that text as a string (in which case the
  3488. caller should put this string in the kill ring as the latest
  3489. kill).
  3490. The function may also return a list of strings if the window
  3491. system supports multiple selections. The first string will be
  3492. used as the pasted text, but the other will be placed in the kill
  3493. ring for easy access via `yank-pop'.
  3494. Note that the function should return a string only if a program
  3495. other than Emacs has provided a string for pasting; if Emacs
  3496. provided the most recent string, the function should return nil.
  3497. If it is difficult to tell whether Emacs or some other program
  3498. provided the current string, it is probably good enough to return
  3499. nil if the string is equal (according to `string=') to the last
  3500. text Emacs provided.")
  3501. ;;;; The kill ring data structure.
  3502. (defvar kill-ring nil
  3503. "List of killed text sequences.
  3504. Since the kill ring is supposed to interact nicely with cut-and-paste
  3505. facilities offered by window systems, use of this variable should
  3506. interact nicely with `interprogram-cut-function' and
  3507. `interprogram-paste-function'. The functions `kill-new',
  3508. `kill-append', and `current-kill' are supposed to implement this
  3509. interaction; you may want to use them instead of manipulating the kill
  3510. ring directly.")
  3511. (defcustom kill-ring-max 60
  3512. "Maximum length of kill ring before oldest elements are thrown away."
  3513. :type 'integer
  3514. :group 'killing)
  3515. (defvar kill-ring-yank-pointer nil
  3516. "The tail of the kill ring whose car is the last thing yanked.")
  3517. (defcustom save-interprogram-paste-before-kill nil
  3518. "Save clipboard strings into kill ring before replacing them.
  3519. When one selects something in another program to paste it into Emacs,
  3520. but kills something in Emacs before actually pasting it,
  3521. this selection is gone unless this variable is non-nil,
  3522. in which case the other program's selection is saved in the `kill-ring'
  3523. before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
  3524. :type 'boolean
  3525. :group 'killing
  3526. :version "23.2")
  3527. (defcustom kill-do-not-save-duplicates nil
  3528. "Do not add a new string to `kill-ring' if it duplicates the last one.
  3529. The comparison is done using `equal-including-properties'."
  3530. :type 'boolean
  3531. :group 'killing
  3532. :version "23.2")
  3533. (defun kill-new (string &optional replace)
  3534. "Make STRING the latest kill in the kill ring.
  3535. Set `kill-ring-yank-pointer' to point to it.
  3536. If `interprogram-cut-function' is non-nil, apply it to STRING.
  3537. Optional second argument REPLACE non-nil means that STRING will replace
  3538. the front of the kill ring, rather than being added to the list.
  3539. When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
  3540. are non-nil, saves the interprogram paste string(s) into `kill-ring' before
  3541. STRING.
  3542. When the yank handler has a non-nil PARAM element, the original STRING
  3543. argument is not used by `insert-for-yank'. However, since Lisp code
  3544. may access and use elements from the kill ring directly, the STRING
  3545. argument should still be a \"useful\" string for such uses."
  3546. (unless (and kill-do-not-save-duplicates
  3547. ;; Due to text properties such as 'yank-handler that
  3548. ;; can alter the contents to yank, comparison using
  3549. ;; `equal' is unsafe.
  3550. (equal-including-properties string (car kill-ring)))
  3551. (if (fboundp 'menu-bar-update-yank-menu)
  3552. (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
  3553. (when save-interprogram-paste-before-kill
  3554. (let ((interprogram-paste (and interprogram-paste-function
  3555. (funcall interprogram-paste-function))))
  3556. (when interprogram-paste
  3557. (dolist (s (if (listp interprogram-paste)
  3558. (nreverse interprogram-paste)
  3559. (list interprogram-paste)))
  3560. (unless (and kill-do-not-save-duplicates
  3561. (equal-including-properties s (car kill-ring)))
  3562. (push s kill-ring))))))
  3563. (unless (and kill-do-not-save-duplicates
  3564. (equal-including-properties string (car kill-ring)))
  3565. (if (and replace kill-ring)
  3566. (setcar kill-ring string)
  3567. (push string kill-ring)
  3568. (if (> (length kill-ring) kill-ring-max)
  3569. (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
  3570. (setq kill-ring-yank-pointer kill-ring)
  3571. (if interprogram-cut-function
  3572. (funcall interprogram-cut-function string)))
  3573. ;; It has been argued that this should work similar to `self-insert-command'
  3574. ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
  3575. (defcustom kill-append-merge-undo nil
  3576. "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
  3577. :type 'boolean
  3578. :group 'killing
  3579. :version "25.1")
  3580. (defun kill-append (string before-p)
  3581. "Append STRING to the end of the latest kill in the kill ring.
  3582. If BEFORE-P is non-nil, prepend STRING to the kill.
  3583. Also removes the last undo boundary in the current buffer,
  3584. depending on `kill-append-merge-undo'.
  3585. If `interprogram-cut-function' is set, pass the resulting kill to it."
  3586. (let* ((cur (car kill-ring)))
  3587. (kill-new (if before-p (concat string cur) (concat cur string))
  3588. (or (= (length cur) 0)
  3589. (equal nil (get-text-property 0 'yank-handler cur))))
  3590. (when (and kill-append-merge-undo (not buffer-read-only))
  3591. (let ((prev buffer-undo-list)
  3592. (next (cdr buffer-undo-list)))
  3593. ;; find the next undo boundary
  3594. (while (car next)
  3595. (pop next)
  3596. (pop prev))
  3597. ;; remove this undo boundary
  3598. (when prev
  3599. (setcdr prev (cdr next)))))))
  3600. (defcustom yank-pop-change-selection nil
  3601. "Whether rotating the kill ring changes the window system selection.
  3602. If non-nil, whenever the kill ring is rotated (usually via the
  3603. `yank-pop' command), Emacs also calls `interprogram-cut-function'
  3604. to copy the new kill to the window system selection."
  3605. :type 'boolean
  3606. :group 'killing
  3607. :version "23.1")
  3608. (defun current-kill (n &optional do-not-move)
  3609. "Rotate the yanking point by N places, and then return that kill.
  3610. If N is zero and `interprogram-paste-function' is set to a
  3611. function that returns a string or a list of strings, and if that
  3612. function doesn't return nil, then that string (or list) is added
  3613. to the front of the kill ring and the string (or first string in
  3614. the list) is returned as the latest kill.
  3615. If N is not zero, and if `yank-pop-change-selection' is
  3616. non-nil, use `interprogram-cut-function' to transfer the
  3617. kill at the new yank point into the window system selection.
  3618. If optional arg DO-NOT-MOVE is non-nil, then don't actually
  3619. move the yanking point; just return the Nth kill forward."
  3620. (let ((interprogram-paste (and (= n 0)
  3621. interprogram-paste-function
  3622. (funcall interprogram-paste-function))))
  3623. (if interprogram-paste
  3624. (progn
  3625. ;; Disable the interprogram cut function when we add the new
  3626. ;; text to the kill ring, so Emacs doesn't try to own the
  3627. ;; selection, with identical text.
  3628. (let ((interprogram-cut-function nil))
  3629. (if (listp interprogram-paste)
  3630. (mapc 'kill-new (nreverse interprogram-paste))
  3631. (kill-new interprogram-paste)))
  3632. (car kill-ring))
  3633. (or kill-ring (error "Kill ring is empty"))
  3634. (let ((ARGth-kill-element
  3635. (nthcdr (mod (- n (length kill-ring-yank-pointer))
  3636. (length kill-ring))
  3637. kill-ring)))
  3638. (unless do-not-move
  3639. (setq kill-ring-yank-pointer ARGth-kill-element)
  3640. (when (and yank-pop-change-selection
  3641. (> n 0)
  3642. interprogram-cut-function)
  3643. (funcall interprogram-cut-function (car ARGth-kill-element))))
  3644. (car ARGth-kill-element)))))
  3645. ;;;; Commands for manipulating the kill ring.
  3646. (defcustom kill-read-only-ok nil
  3647. "Non-nil means don't signal an error for killing read-only text."
  3648. :type 'boolean
  3649. :group 'killing)
  3650. (defun kill-region (beg end &optional region)
  3651. "Kill (\"cut\") text between point and mark.
  3652. This deletes the text from the buffer and saves it in the kill ring.
  3653. The command \\[yank] can retrieve it from there.
  3654. \(If you want to save the region without killing it, use \\[kill-ring-save].)
  3655. If you want to append the killed region to the last killed text,
  3656. use \\[append-next-kill] before \\[kill-region].
  3657. If the buffer is read-only, Emacs will beep and refrain from deleting
  3658. the text, but put the text in the kill ring anyway. This means that
  3659. you can use the killing commands to copy text from a read-only buffer.
  3660. Lisp programs should use this function for killing text.
  3661. (To delete text, use `delete-region'.)
  3662. Supply two arguments, character positions indicating the stretch of text
  3663. to be killed.
  3664. Any command that calls this function is a \"kill command\".
  3665. If the previous command was also a kill command,
  3666. the text killed this time appends to the text killed last time
  3667. to make one entry in the kill ring.
  3668. The optional argument REGION if non-nil, indicates that we're not just killing
  3669. some text between BEG and END, but we're killing the region."
  3670. ;; Pass mark first, then point, because the order matters when
  3671. ;; calling `kill-append'.
  3672. (interactive (list (mark) (point) 'region))
  3673. (unless (and beg end)
  3674. (user-error "The mark is not set now, so there is no region"))
  3675. (condition-case nil
  3676. (let ((string (if region
  3677. (funcall region-extract-function 'delete)
  3678. (filter-buffer-substring beg end 'delete))))
  3679. (when string ;STRING is nil if BEG = END
  3680. ;; Add that string to the kill ring, one way or another.
  3681. (if (eq last-command 'kill-region)
  3682. (kill-append string (< end beg))
  3683. (kill-new string)))
  3684. (when (or string (eq last-command 'kill-region))
  3685. (setq this-command 'kill-region))
  3686. (setq deactivate-mark t)
  3687. nil)
  3688. ((buffer-read-only text-read-only)
  3689. ;; The code above failed because the buffer, or some of the characters
  3690. ;; in the region, are read-only.
  3691. ;; We should beep, in case the user just isn't aware of this.
  3692. ;; However, there's no harm in putting
  3693. ;; the region's text in the kill ring, anyway.
  3694. (copy-region-as-kill beg end region)
  3695. ;; Set this-command now, so it will be set even if we get an error.
  3696. (setq this-command 'kill-region)
  3697. ;; This should barf, if appropriate, and give us the correct error.
  3698. (if kill-read-only-ok
  3699. (progn (message "Read only text copied to kill ring") nil)
  3700. ;; Signal an error if the buffer is read-only.
  3701. (barf-if-buffer-read-only)
  3702. ;; If the buffer isn't read-only, the text is.
  3703. (signal 'text-read-only (list (current-buffer)))))))
  3704. ;; copy-region-as-kill no longer sets this-command, because it's confusing
  3705. ;; to get two copies of the text when the user accidentally types M-w and
  3706. ;; then corrects it with the intended C-w.
  3707. (defun copy-region-as-kill (beg end &optional region)
  3708. "Save the region as if killed, but don't kill it.
  3709. In Transient Mark mode, deactivate the mark.
  3710. If `interprogram-cut-function' is non-nil, also save the text for a window
  3711. system cut and paste.
  3712. The optional argument REGION if non-nil, indicates that we're not just copying
  3713. some text between BEG and END, but we're copying the region.
  3714. This command's old key binding has been given to `kill-ring-save'."
  3715. ;; Pass mark first, then point, because the order matters when
  3716. ;; calling `kill-append'.
  3717. (interactive (list (mark) (point)
  3718. (prefix-numeric-value current-prefix-arg)))
  3719. (let ((str (if region
  3720. (funcall region-extract-function nil)
  3721. (filter-buffer-substring beg end))))
  3722. (if (eq last-command 'kill-region)
  3723. (kill-append str (< end beg))
  3724. (kill-new str)))
  3725. (setq deactivate-mark t)
  3726. nil)
  3727. (defun kill-ring-save (beg end &optional region)
  3728. "Save the region as if killed, but don't kill it.
  3729. In Transient Mark mode, deactivate the mark.
  3730. If `interprogram-cut-function' is non-nil, also save the text for a window
  3731. system cut and paste.
  3732. If you want to append the killed line to the last killed text,
  3733. use \\[append-next-kill] before \\[kill-ring-save].
  3734. The optional argument REGION if non-nil, indicates that we're not just copying
  3735. some text between BEG and END, but we're copying the region.
  3736. This command is similar to `copy-region-as-kill', except that it gives
  3737. visual feedback indicating the extent of the region being copied."
  3738. ;; Pass mark first, then point, because the order matters when
  3739. ;; calling `kill-append'.
  3740. (interactive (list (mark) (point)
  3741. (prefix-numeric-value current-prefix-arg)))
  3742. (copy-region-as-kill beg end region)
  3743. ;; This use of called-interactively-p is correct because the code it
  3744. ;; controls just gives the user visual feedback.
  3745. (if (called-interactively-p 'interactive)
  3746. (indicate-copied-region)))
  3747. (defun indicate-copied-region (&optional message-len)
  3748. "Indicate that the region text has been copied interactively.
  3749. If the mark is visible in the selected window, blink the cursor
  3750. between point and mark if there is currently no active region
  3751. highlighting.
  3752. If the mark lies outside the selected window, display an
  3753. informative message containing a sample of the copied text. The
  3754. optional argument MESSAGE-LEN, if non-nil, specifies the length
  3755. of this sample text; it defaults to 40."
  3756. (let ((mark (mark t))
  3757. (point (point))
  3758. ;; Inhibit quitting so we can make a quit here
  3759. ;; look like a C-g typed as a command.
  3760. (inhibit-quit t))
  3761. (if (pos-visible-in-window-p mark (selected-window))
  3762. ;; Swap point-and-mark quickly so as to show the region that
  3763. ;; was selected. Don't do it if the region is highlighted.
  3764. (unless (and (region-active-p)
  3765. (face-background 'region))
  3766. ;; Swap point and mark.
  3767. (set-marker (mark-marker) (point) (current-buffer))
  3768. (goto-char mark)
  3769. (sit-for blink-matching-delay)
  3770. ;; Swap back.
  3771. (set-marker (mark-marker) mark (current-buffer))
  3772. (goto-char point)
  3773. ;; If user quit, deactivate the mark
  3774. ;; as C-g would as a command.
  3775. (and quit-flag (region-active-p)
  3776. (deactivate-mark)))
  3777. (let ((len (min (abs (- mark point))
  3778. (or message-len 40))))
  3779. (if (< point mark)
  3780. ;; Don't say "killed"; that is misleading.
  3781. (message "Saved text until \"%s\""
  3782. (buffer-substring-no-properties (- mark len) mark))
  3783. (message "Saved text from \"%s\""
  3784. (buffer-substring-no-properties mark (+ mark len))))))))
  3785. (defun append-next-kill (&optional interactive)
  3786. "Cause following command, if it kills, to add to previous kill.
  3787. If the next command kills forward from point, the kill is
  3788. appended to the previous killed text. If the command kills
  3789. backward, the kill is prepended. Kill commands that act on the
  3790. region, such as `kill-region', are regarded as killing forward if
  3791. point is after mark, and killing backward if point is before
  3792. mark.
  3793. If the next command is not a kill command, `append-next-kill' has
  3794. no effect.
  3795. The argument is used for internal purposes; do not supply one."
  3796. (interactive "p")
  3797. ;; We don't use (interactive-p), since that breaks kbd macros.
  3798. (if interactive
  3799. (progn
  3800. (setq this-command 'kill-region)
  3801. (message "If the next command is a kill, it will append"))
  3802. (setq last-command 'kill-region)))
  3803. (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
  3804. "Character set that matches bidirectional formatting control characters.")
  3805. (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
  3806. "Character set that matches any character except bidirectional controls.")
  3807. (defun squeeze-bidi-context-1 (from to category replacement)
  3808. "A subroutine of `squeeze-bidi-context'.
  3809. FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
  3810. (let ((pt (copy-marker from))
  3811. (limit (copy-marker to))
  3812. (old-pt 0)
  3813. lim1)
  3814. (setq lim1 limit)
  3815. (goto-char pt)
  3816. (while (< pt limit)
  3817. (if (> pt old-pt)
  3818. (move-marker lim1
  3819. (save-excursion
  3820. ;; L and R categories include embedding and
  3821. ;; override controls, but we don't want to
  3822. ;; replace them, because that might change
  3823. ;; the visual order. Likewise with PDF and
  3824. ;; isolate controls.
  3825. (+ pt (skip-chars-forward
  3826. bidi-directional-non-controls-chars
  3827. limit)))))
  3828. ;; Replace any run of non-RTL characters by a single LRM.
  3829. (if (null (re-search-forward category lim1 t))
  3830. ;; No more characters of CATEGORY, we are done.
  3831. (setq pt limit)
  3832. (replace-match replacement nil t)
  3833. (move-marker pt (point)))
  3834. (setq old-pt pt)
  3835. ;; Skip directional controls, if any.
  3836. (move-marker
  3837. pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
  3838. (defun squeeze-bidi-context (from to)
  3839. "Replace characters between FROM and TO while keeping bidi context.
  3840. This function replaces the region of text with as few characters
  3841. as possible, while preserving the effect that region will have on
  3842. bidirectional display before and after the region."
  3843. (let ((start (set-marker (make-marker)
  3844. (if (> from 0) from (+ (point-max) from))))
  3845. (end (set-marker (make-marker) to))
  3846. ;; This is for when they copy text with read-only text
  3847. ;; properties.
  3848. (inhibit-read-only t))
  3849. (if (null (marker-position end))
  3850. (setq end (point-max-marker)))
  3851. ;; Replace each run of non-RTL characters with a single LRM.
  3852. (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
  3853. ;; Replace each run of non-LTR characters with a single RLM. Note
  3854. ;; that the \cR category includes both the Arabic Letter (AL) and
  3855. ;; R characters; here we ignore the distinction between them,
  3856. ;; because that distinction only affects Arabic Number (AN)
  3857. ;; characters, which are weak and don't affect the reordering.
  3858. (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
  3859. (defun line-substring-with-bidi-context (start end &optional no-properties)
  3860. "Return buffer text between START and END with its bidi context.
  3861. START and END are assumed to belong to the same physical line
  3862. of buffer text. This function prepends and appends to the text
  3863. between START and END bidi control characters that preserve the
  3864. visual order of that text when it is inserted at some other place."
  3865. (if (or (< start (point-min))
  3866. (> end (point-max)))
  3867. (signal 'args-out-of-range (list (current-buffer) start end)))
  3868. (let ((buf (current-buffer))
  3869. substr para-dir from to)
  3870. (save-excursion
  3871. (goto-char start)
  3872. (setq para-dir (current-bidi-paragraph-direction))
  3873. (setq from (line-beginning-position)
  3874. to (line-end-position))
  3875. (goto-char from)
  3876. ;; If we don't have any mixed directional characters in the
  3877. ;; entire line, we can just copy the substring without adding
  3878. ;; any context.
  3879. (if (or (looking-at-p "\\CR*$")
  3880. (looking-at-p "\\CL*$"))
  3881. (setq substr (if no-properties
  3882. (buffer-substring-no-properties start end)
  3883. (buffer-substring start end)))
  3884. (setq substr
  3885. (with-temp-buffer
  3886. (if no-properties
  3887. (insert-buffer-substring-no-properties buf from to)
  3888. (insert-buffer-substring buf from to))
  3889. (squeeze-bidi-context 1 (1+ (- start from)))
  3890. (squeeze-bidi-context (- end to) nil)
  3891. (buffer-substring 1 (point-max)))))
  3892. ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
  3893. ;; (1) force the string to have the same base embedding
  3894. ;; direction as the paragraph direction at the source, no matter
  3895. ;; what is the paragraph direction at destination; and (2) avoid
  3896. ;; affecting the visual order of the surrounding text at
  3897. ;; destination if there are characters of different
  3898. ;; directionality there.
  3899. (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
  3900. substr "\x2069"))))
  3901. (defun buffer-substring-with-bidi-context (start end &optional no-properties)
  3902. "Return portion of current buffer between START and END with bidi context.
  3903. This function works similar to `buffer-substring', but it prepends and
  3904. appends to the text bidi directional control characters necessary to
  3905. preserve the visual appearance of the text if it is inserted at another
  3906. place. This is useful when the buffer substring includes bidirectional
  3907. text and control characters that cause non-trivial reordering on display.
  3908. If copied verbatim, such text can have a very different visual appearance,
  3909. and can also change the visual appearance of the surrounding text at the
  3910. destination of the copy.
  3911. Optional argument NO-PROPERTIES, if non-nil, means copy the text without
  3912. the text properties."
  3913. (let (line-end substr)
  3914. (if (or (< start (point-min))
  3915. (> end (point-max)))
  3916. (signal 'args-out-of-range (list (current-buffer) start end)))
  3917. (save-excursion
  3918. (goto-char start)
  3919. (setq line-end (min end (line-end-position)))
  3920. (while (< start end)
  3921. (setq substr
  3922. (concat substr
  3923. (if substr "\n" "")
  3924. (line-substring-with-bidi-context start line-end
  3925. no-properties)))
  3926. (forward-line 1)
  3927. (setq start (point))
  3928. (setq line-end (min end (line-end-position))))
  3929. substr)))
  3930. ;; Yanking.
  3931. (defcustom yank-handled-properties
  3932. '((font-lock-face . yank-handle-font-lock-face-property)
  3933. (category . yank-handle-category-property))
  3934. "List of special text property handling conditions for yanking.
  3935. Each element should have the form (PROP . FUN), where PROP is a
  3936. property symbol and FUN is a function. When the `yank' command
  3937. inserts text into the buffer, it scans the inserted text for
  3938. stretches of text that have `eq' values of the text property
  3939. PROP; for each such stretch of text, FUN is called with three
  3940. arguments: the property's value in that text, and the start and
  3941. end positions of the text.
  3942. This is done prior to removing the properties specified by
  3943. `yank-excluded-properties'."
  3944. :group 'killing
  3945. :type '(repeat (cons (symbol :tag "property symbol")
  3946. function))
  3947. :version "24.3")
  3948. ;; This is actually used in subr.el but defcustom does not work there.
  3949. (defcustom yank-excluded-properties
  3950. '(category field follow-link fontified font-lock-face help-echo
  3951. intangible invisible keymap local-map mouse-face read-only
  3952. yank-handler)
  3953. "Text properties to discard when yanking.
  3954. The value should be a list of text properties to discard or t,
  3955. which means to discard all text properties.
  3956. See also `yank-handled-properties'."
  3957. :type '(choice (const :tag "All" t) (repeat symbol))
  3958. :group 'killing
  3959. :version "24.3")
  3960. (defvar yank-window-start nil)
  3961. (defvar yank-undo-function nil
  3962. "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
  3963. Function is called with two parameters, START and END corresponding to
  3964. the value of the mark and point; it is guaranteed that START <= END.
  3965. Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
  3966. (defun yank-pop (&optional arg)
  3967. "Replace just-yanked stretch of killed text with a different stretch.
  3968. This command is allowed only immediately after a `yank' or a `yank-pop'.
  3969. At such a time, the region contains a stretch of reinserted
  3970. previously-killed text. `yank-pop' deletes that text and inserts in its
  3971. place a different stretch of killed text.
  3972. With no argument, the previous kill is inserted.
  3973. With argument N, insert the Nth previous kill.
  3974. If N is negative, this is a more recent kill.
  3975. The sequence of kills wraps around, so that after the oldest one
  3976. comes the newest one.
  3977. When this command inserts killed text into the buffer, it honors
  3978. `yank-excluded-properties' and `yank-handler' as described in the
  3979. doc string for `insert-for-yank-1', which see."
  3980. (interactive "*p")
  3981. (if (not (eq last-command 'yank))
  3982. (user-error "Previous command was not a yank"))
  3983. (setq this-command 'yank)
  3984. (unless arg (setq arg 1))
  3985. (let ((inhibit-read-only t)
  3986. (before (< (point) (mark t))))
  3987. (if before
  3988. (funcall (or yank-undo-function 'delete-region) (point) (mark t))
  3989. (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
  3990. (setq yank-undo-function nil)
  3991. (set-marker (mark-marker) (point) (current-buffer))
  3992. (insert-for-yank (current-kill arg))
  3993. ;; Set the window start back where it was in the yank command,
  3994. ;; if possible.
  3995. (set-window-start (selected-window) yank-window-start t)
  3996. (if before
  3997. ;; This is like exchange-point-and-mark, but doesn't activate the mark.
  3998. ;; It is cleaner to avoid activation, even though the command
  3999. ;; loop would deactivate the mark because we inserted text.
  4000. (goto-char (prog1 (mark t)
  4001. (set-marker (mark-marker) (point) (current-buffer))))))
  4002. nil)
  4003. (defun yank (&optional arg)
  4004. "Reinsert (\"paste\") the last stretch of killed text.
  4005. More precisely, reinsert the most recent kill, which is the
  4006. stretch of killed text most recently killed OR yanked. Put point
  4007. at the end, and set mark at the beginning without activating it.
  4008. With just \\[universal-argument] as argument, put point at beginning, and mark at end.
  4009. With argument N, reinsert the Nth most recent kill.
  4010. When this command inserts text into the buffer, it honors the
  4011. `yank-handled-properties' and `yank-excluded-properties'
  4012. variables, and the `yank-handler' text property. See
  4013. `insert-for-yank-1' for details.
  4014. See also the command `yank-pop' (\\[yank-pop])."
  4015. (interactive "*P")
  4016. (setq yank-window-start (window-start))
  4017. ;; If we don't get all the way thru, make last-command indicate that
  4018. ;; for the following command.
  4019. (setq this-command t)
  4020. (push-mark (point))
  4021. (insert-for-yank (current-kill (cond
  4022. ((listp arg) 0)
  4023. ((eq arg '-) -2)
  4024. (t (1- arg)))))
  4025. (if (consp arg)
  4026. ;; This is like exchange-point-and-mark, but doesn't activate the mark.
  4027. ;; It is cleaner to avoid activation, even though the command
  4028. ;; loop would deactivate the mark because we inserted text.
  4029. (goto-char (prog1 (mark t)
  4030. (set-marker (mark-marker) (point) (current-buffer)))))
  4031. ;; If we do get all the way thru, make this-command indicate that.
  4032. (if (eq this-command t)
  4033. (setq this-command 'yank))
  4034. nil)
  4035. (defun rotate-yank-pointer (arg)
  4036. "Rotate the yanking point in the kill ring.
  4037. With ARG, rotate that many kills forward (or backward, if negative)."
  4038. (interactive "p")
  4039. (current-kill arg))
  4040. ;; Some kill commands.
  4041. ;; Internal subroutine of delete-char
  4042. (defun kill-forward-chars (arg)
  4043. (if (listp arg) (setq arg (car arg)))
  4044. (if (eq arg '-) (setq arg -1))
  4045. (kill-region (point) (+ (point) arg)))
  4046. ;; Internal subroutine of backward-delete-char
  4047. (defun kill-backward-chars (arg)
  4048. (if (listp arg) (setq arg (car arg)))
  4049. (if (eq arg '-) (setq arg -1))
  4050. (kill-region (point) (- (point) arg)))
  4051. (defcustom backward-delete-char-untabify-method 'untabify
  4052. "The method for untabifying when deleting backward.
  4053. Can be `untabify' -- turn a tab to many spaces, then delete one space;
  4054. `hungry' -- delete all whitespace, both tabs and spaces;
  4055. `all' -- delete all whitespace, including tabs, spaces and newlines;
  4056. nil -- just delete one character."
  4057. :type '(choice (const untabify) (const hungry) (const all) (const nil))
  4058. :version "20.3"
  4059. :group 'killing)
  4060. (defun backward-delete-char-untabify (arg &optional killp)
  4061. "Delete characters backward, changing tabs into spaces.
  4062. The exact behavior depends on `backward-delete-char-untabify-method'.
  4063. Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
  4064. Interactively, ARG is the prefix arg (default 1)
  4065. and KILLP is t if a prefix arg was specified."
  4066. (interactive "*p\nP")
  4067. (when (eq backward-delete-char-untabify-method 'untabify)
  4068. (let ((count arg))
  4069. (save-excursion
  4070. (while (and (> count 0) (not (bobp)))
  4071. (if (= (preceding-char) ?\t)
  4072. (let ((col (current-column)))
  4073. (forward-char -1)
  4074. (setq col (- col (current-column)))
  4075. (insert-char ?\s col)
  4076. (delete-char 1)))
  4077. (forward-char -1)
  4078. (setq count (1- count))))))
  4079. (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
  4080. ((eq backward-delete-char-untabify-method 'all)
  4081. " \t\n\r")))
  4082. (n (if skip
  4083. (let* ((oldpt (point))
  4084. (wh (- oldpt (save-excursion
  4085. (skip-chars-backward skip)
  4086. (constrain-to-field nil oldpt)))))
  4087. (+ arg (if (zerop wh) 0 (1- wh))))
  4088. arg)))
  4089. ;; Avoid warning about delete-backward-char
  4090. (with-no-warnings (delete-backward-char n killp))))
  4091. (defun zap-to-char (arg char)
  4092. "Kill up to and including ARGth occurrence of CHAR.
  4093. Case is ignored if `case-fold-search' is non-nil in the current buffer.
  4094. Goes backward if ARG is negative; error if CHAR not found."
  4095. (interactive (list (prefix-numeric-value current-prefix-arg)
  4096. (read-char "Zap to char: " t)))
  4097. ;; Avoid "obsolete" warnings for translation-table-for-input.
  4098. (with-no-warnings
  4099. (if (char-table-p translation-table-for-input)
  4100. (setq char (or (aref translation-table-for-input char) char))))
  4101. (kill-region (point) (progn
  4102. (search-forward (char-to-string char) nil nil arg)
  4103. (point))))
  4104. ;; kill-line and its subroutines.
  4105. (defcustom kill-whole-line nil
  4106. "If non-nil, `kill-line' with no arg at start of line kills the whole line."
  4107. :type 'boolean
  4108. :group 'killing)
  4109. (defun kill-line (&optional arg)
  4110. "Kill the rest of the current line; if no nonblanks there, kill thru newline.
  4111. With prefix argument ARG, kill that many lines from point.
  4112. Negative arguments kill lines backward.
  4113. With zero argument, kills the text before point on the current line.
  4114. When calling from a program, nil means \"no arg\",
  4115. a number counts as a prefix arg.
  4116. To kill a whole line, when point is not at the beginning, type \
  4117. \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
  4118. If `show-trailing-whitespace' is non-nil, this command will just
  4119. kill the rest of the current line, even if there are only
  4120. nonblanks there.
  4121. If option `kill-whole-line' is non-nil, then this command kills the whole line
  4122. including its terminating newline, when used at the beginning of a line
  4123. with no argument. As a consequence, you can always kill a whole line
  4124. by typing \\[move-beginning-of-line] \\[kill-line].
  4125. If you want to append the killed line to the last killed text,
  4126. use \\[append-next-kill] before \\[kill-line].
  4127. If the buffer is read-only, Emacs will beep and refrain from deleting
  4128. the line, but put the line in the kill ring anyway. This means that
  4129. you can use this command to copy text from a read-only buffer.
  4130. \(If the variable `kill-read-only-ok' is non-nil, then this won't
  4131. even beep.)"
  4132. (interactive "P")
  4133. (kill-region (point)
  4134. ;; It is better to move point to the other end of the kill
  4135. ;; before killing. That way, in a read-only buffer, point
  4136. ;; moves across the text that is copied to the kill ring.
  4137. ;; The choice has no effect on undo now that undo records
  4138. ;; the value of point from before the command was run.
  4139. (progn
  4140. (if arg
  4141. (forward-visible-line (prefix-numeric-value arg))
  4142. (if (eobp)
  4143. (signal 'end-of-buffer nil))
  4144. (let ((end
  4145. (save-excursion
  4146. (end-of-visible-line) (point))))
  4147. (if (or (save-excursion
  4148. ;; If trailing whitespace is visible,
  4149. ;; don't treat it as nothing.
  4150. (unless show-trailing-whitespace
  4151. (skip-chars-forward " \t" end))
  4152. (= (point) end))
  4153. (and kill-whole-line (bolp)))
  4154. (forward-visible-line 1)
  4155. (goto-char end))))
  4156. (point))))
  4157. (defun kill-whole-line (&optional arg)
  4158. "Kill current line.
  4159. With prefix ARG, kill that many lines starting from the current line.
  4160. If ARG is negative, kill backward. Also kill the preceding newline.
  4161. \(This is meant to make \\[repeat] work well with negative arguments.)
  4162. If ARG is zero, kill current line but exclude the trailing newline."
  4163. (interactive "p")
  4164. (or arg (setq arg 1))
  4165. (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
  4166. (signal 'end-of-buffer nil))
  4167. (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
  4168. (signal 'beginning-of-buffer nil))
  4169. (unless (eq last-command 'kill-region)
  4170. (kill-new "")
  4171. (setq last-command 'kill-region))
  4172. (cond ((zerop arg)
  4173. ;; We need to kill in two steps, because the previous command
  4174. ;; could have been a kill command, in which case the text
  4175. ;; before point needs to be prepended to the current kill
  4176. ;; ring entry and the text after point appended. Also, we
  4177. ;; need to use save-excursion to avoid copying the same text
  4178. ;; twice to the kill ring in read-only buffers.
  4179. (save-excursion
  4180. (kill-region (point) (progn (forward-visible-line 0) (point))))
  4181. (kill-region (point) (progn (end-of-visible-line) (point))))
  4182. ((< arg 0)
  4183. (save-excursion
  4184. (kill-region (point) (progn (end-of-visible-line) (point))))
  4185. (kill-region (point)
  4186. (progn (forward-visible-line (1+ arg))
  4187. (unless (bobp) (backward-char))
  4188. (point))))
  4189. (t
  4190. (save-excursion
  4191. (kill-region (point) (progn (forward-visible-line 0) (point))))
  4192. (kill-region (point)
  4193. (progn (forward-visible-line arg) (point))))))
  4194. (defun forward-visible-line (arg)
  4195. "Move forward by ARG lines, ignoring currently invisible newlines only.
  4196. If ARG is negative, move backward -ARG lines.
  4197. If ARG is zero, move to the beginning of the current line."
  4198. (condition-case nil
  4199. (if (> arg 0)
  4200. (progn
  4201. (while (> arg 0)
  4202. (or (zerop (forward-line 1))
  4203. (signal 'end-of-buffer nil))
  4204. ;; If the newline we just skipped is invisible,
  4205. ;; don't count it.
  4206. (let ((prop
  4207. (get-char-property (1- (point)) 'invisible)))
  4208. (if (if (eq buffer-invisibility-spec t)
  4209. prop
  4210. (or (memq prop buffer-invisibility-spec)
  4211. (assq prop buffer-invisibility-spec)))
  4212. (setq arg (1+ arg))))
  4213. (setq arg (1- arg)))
  4214. ;; If invisible text follows, and it is a number of complete lines,
  4215. ;; skip it.
  4216. (let ((opoint (point)))
  4217. (while (and (not (eobp))
  4218. (let ((prop
  4219. (get-char-property (point) 'invisible)))
  4220. (if (eq buffer-invisibility-spec t)
  4221. prop
  4222. (or (memq prop buffer-invisibility-spec)
  4223. (assq prop buffer-invisibility-spec)))))
  4224. (goto-char
  4225. (if (get-text-property (point) 'invisible)
  4226. (or (next-single-property-change (point) 'invisible)
  4227. (point-max))
  4228. (next-overlay-change (point)))))
  4229. (unless (bolp)
  4230. (goto-char opoint))))
  4231. (let ((first t))
  4232. (while (or first (<= arg 0))
  4233. (if first
  4234. (beginning-of-line)
  4235. (or (zerop (forward-line -1))
  4236. (signal 'beginning-of-buffer nil)))
  4237. ;; If the newline we just moved to is invisible,
  4238. ;; don't count it.
  4239. (unless (bobp)
  4240. (let ((prop
  4241. (get-char-property (1- (point)) 'invisible)))
  4242. (unless (if (eq buffer-invisibility-spec t)
  4243. prop
  4244. (or (memq prop buffer-invisibility-spec)
  4245. (assq prop buffer-invisibility-spec)))
  4246. (setq arg (1+ arg)))))
  4247. (setq first nil))
  4248. ;; If invisible text follows, and it is a number of complete lines,
  4249. ;; skip it.
  4250. (let ((opoint (point)))
  4251. (while (and (not (bobp))
  4252. (let ((prop
  4253. (get-char-property (1- (point)) 'invisible)))
  4254. (if (eq buffer-invisibility-spec t)
  4255. prop
  4256. (or (memq prop buffer-invisibility-spec)
  4257. (assq prop buffer-invisibility-spec)))))
  4258. (goto-char
  4259. (if (get-text-property (1- (point)) 'invisible)
  4260. (or (previous-single-property-change (point) 'invisible)
  4261. (point-min))
  4262. (previous-overlay-change (point)))))
  4263. (unless (bolp)
  4264. (goto-char opoint)))))
  4265. ((beginning-of-buffer end-of-buffer)
  4266. nil)))
  4267. (defun end-of-visible-line ()
  4268. "Move to end of current visible line."
  4269. (end-of-line)
  4270. ;; If the following character is currently invisible,
  4271. ;; skip all characters with that same `invisible' property value,
  4272. ;; then find the next newline.
  4273. (while (and (not (eobp))
  4274. (save-excursion
  4275. (skip-chars-forward "^\n")
  4276. (let ((prop
  4277. (get-char-property (point) 'invisible)))
  4278. (if (eq buffer-invisibility-spec t)
  4279. prop
  4280. (or (memq prop buffer-invisibility-spec)
  4281. (assq prop buffer-invisibility-spec))))))
  4282. (skip-chars-forward "^\n")
  4283. (if (get-text-property (point) 'invisible)
  4284. (goto-char (or (next-single-property-change (point) 'invisible)
  4285. (point-max)))
  4286. (goto-char (next-overlay-change (point))))
  4287. (end-of-line)))
  4288. (defun insert-buffer (buffer)
  4289. "Insert after point the contents of BUFFER.
  4290. Puts mark after the inserted text.
  4291. BUFFER may be a buffer or a buffer name."
  4292. (declare (interactive-only insert-buffer-substring))
  4293. (interactive
  4294. (list
  4295. (progn
  4296. (barf-if-buffer-read-only)
  4297. (read-buffer "Insert buffer: "
  4298. (if (eq (selected-window) (next-window))
  4299. (other-buffer (current-buffer))
  4300. (window-buffer (next-window)))
  4301. t))))
  4302. (push-mark
  4303. (save-excursion
  4304. (insert-buffer-substring (get-buffer buffer))
  4305. (point)))
  4306. nil)
  4307. (defun append-to-buffer (buffer start end)
  4308. "Append to specified buffer the text of the region.
  4309. It is inserted into that buffer before its point.
  4310. When calling from a program, give three arguments:
  4311. BUFFER (or buffer name), START and END.
  4312. START and END specify the portion of the current buffer to be copied."
  4313. (interactive
  4314. (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
  4315. (region-beginning) (region-end)))
  4316. (let* ((oldbuf (current-buffer))
  4317. (append-to (get-buffer-create buffer))
  4318. (windows (get-buffer-window-list append-to t t))
  4319. point)
  4320. (save-excursion
  4321. (with-current-buffer append-to
  4322. (setq point (point))
  4323. (barf-if-buffer-read-only)
  4324. (insert-buffer-substring oldbuf start end)
  4325. (dolist (window windows)
  4326. (when (= (window-point window) point)
  4327. (set-window-point window (point))))))))
  4328. (defun prepend-to-buffer (buffer start end)
  4329. "Prepend to specified buffer the text of the region.
  4330. It is inserted into that buffer after its point.
  4331. When calling from a program, give three arguments:
  4332. BUFFER (or buffer name), START and END.
  4333. START and END specify the portion of the current buffer to be copied."
  4334. (interactive "BPrepend to buffer: \nr")
  4335. (let ((oldbuf (current-buffer)))
  4336. (with-current-buffer (get-buffer-create buffer)
  4337. (barf-if-buffer-read-only)
  4338. (save-excursion
  4339. (insert-buffer-substring oldbuf start end)))))
  4340. (defun copy-to-buffer (buffer start end)
  4341. "Copy to specified buffer the text of the region.
  4342. It is inserted into that buffer, replacing existing text there.
  4343. When calling from a program, give three arguments:
  4344. BUFFER (or buffer name), START and END.
  4345. START and END specify the portion of the current buffer to be copied."
  4346. (interactive "BCopy to buffer: \nr")
  4347. (let ((oldbuf (current-buffer)))
  4348. (with-current-buffer (get-buffer-create buffer)
  4349. (barf-if-buffer-read-only)
  4350. (erase-buffer)
  4351. (save-excursion
  4352. (insert-buffer-substring oldbuf start end)))))
  4353. (define-error 'mark-inactive (purecopy "The mark is not active now"))
  4354. (defvar activate-mark-hook nil
  4355. "Hook run when the mark becomes active.
  4356. It is also run at the end of a command, if the mark is active and
  4357. it is possible that the region may have changed.")
  4358. (defvar deactivate-mark-hook nil
  4359. "Hook run when the mark becomes inactive.")
  4360. (defun mark (&optional force)
  4361. "Return this buffer's mark value as integer, or nil if never set.
  4362. In Transient Mark mode, this function signals an error if
  4363. the mark is not active. However, if `mark-even-if-inactive' is non-nil,
  4364. or the argument FORCE is non-nil, it disregards whether the mark
  4365. is active, and returns an integer or nil in the usual way.
  4366. If you are using this in an editing command, you are most likely making
  4367. a mistake; see the documentation of `set-mark'."
  4368. (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
  4369. (marker-position (mark-marker))
  4370. (signal 'mark-inactive nil)))
  4371. ;; Behind display-selections-p.
  4372. (defun deactivate-mark (&optional force)
  4373. "Deactivate the mark.
  4374. If Transient Mark mode is disabled, this function normally does
  4375. nothing; but if FORCE is non-nil, it deactivates the mark anyway.
  4376. Deactivating the mark sets `mark-active' to nil, updates the
  4377. primary selection according to `select-active-regions', and runs
  4378. `deactivate-mark-hook'.
  4379. If Transient Mark mode was temporarily enabled, reset the value
  4380. of the variable `transient-mark-mode'; if this causes Transient
  4381. Mark mode to be disabled, don't change `mark-active' to nil or
  4382. run `deactivate-mark-hook'."
  4383. (when (or (region-active-p) force)
  4384. (when (and (if (eq select-active-regions 'only)
  4385. (eq (car-safe transient-mark-mode) 'only)
  4386. select-active-regions)
  4387. (region-active-p)
  4388. (display-selections-p))
  4389. ;; The var `saved-region-selection', if non-nil, is the text in
  4390. ;; the region prior to the last command modifying the buffer.
  4391. ;; Set the selection to that, or to the current region.
  4392. (cond (saved-region-selection
  4393. (if (gui-backend-selection-owner-p 'PRIMARY)
  4394. (gui-set-selection 'PRIMARY saved-region-selection))
  4395. (setq saved-region-selection nil))
  4396. ;; If another program has acquired the selection, region
  4397. ;; deactivation should not clobber it (Bug#11772).
  4398. ((and (/= (region-beginning) (region-end))
  4399. (or (gui-backend-selection-owner-p 'PRIMARY)
  4400. (null (gui-backend-selection-exists-p 'PRIMARY))))
  4401. (gui-set-selection 'PRIMARY
  4402. (funcall region-extract-function nil)))))
  4403. (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
  4404. (cond
  4405. ((eq (car-safe transient-mark-mode) 'only)
  4406. (setq transient-mark-mode (cdr transient-mark-mode))
  4407. (if (eq transient-mark-mode (default-value 'transient-mark-mode))
  4408. (kill-local-variable 'transient-mark-mode)))
  4409. ((eq transient-mark-mode 'lambda)
  4410. (kill-local-variable 'transient-mark-mode)))
  4411. (setq mark-active nil)
  4412. (run-hooks 'deactivate-mark-hook)
  4413. (redisplay--update-region-highlight (selected-window))))
  4414. (defun activate-mark (&optional no-tmm)
  4415. "Activate the mark.
  4416. If NO-TMM is non-nil, leave `transient-mark-mode' alone."
  4417. (when (mark t)
  4418. (unless (region-active-p)
  4419. (force-mode-line-update) ;Refresh toolbar (bug#16382).
  4420. (setq mark-active t)
  4421. (unless (or transient-mark-mode no-tmm)
  4422. (setq-local transient-mark-mode 'lambda))
  4423. (run-hooks 'activate-mark-hook))))
  4424. (defun set-mark (pos)
  4425. "Set this buffer's mark to POS. Don't use this function!
  4426. That is to say, don't use this function unless you want
  4427. the user to see that the mark has moved, and you want the previous
  4428. mark position to be lost.
  4429. Normally, when a new mark is set, the old one should go on the stack.
  4430. This is why most applications should use `push-mark', not `set-mark'.
  4431. Novice Emacs Lisp programmers often try to use the mark for the wrong
  4432. purposes. The mark saves a location for the user's convenience.
  4433. Most editing commands should not alter the mark.
  4434. To remember a location for internal use in the Lisp program,
  4435. store it in a Lisp variable. Example:
  4436. (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
  4437. (if pos
  4438. (progn
  4439. (set-marker (mark-marker) pos (current-buffer))
  4440. (activate-mark 'no-tmm))
  4441. ;; Normally we never clear mark-active except in Transient Mark mode.
  4442. ;; But when we actually clear out the mark value too, we must
  4443. ;; clear mark-active in any mode.
  4444. (deactivate-mark t)
  4445. ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
  4446. ;; it should never be nil if the mark is nil.
  4447. (setq mark-active nil)
  4448. (set-marker (mark-marker) nil)))
  4449. (defun save-mark-and-excursion--save ()
  4450. (cons
  4451. (let ((mark (mark-marker)))
  4452. (and (marker-position mark) (copy-marker mark)))
  4453. mark-active))
  4454. (defun save-mark-and-excursion--restore (saved-mark-info)
  4455. (let ((saved-mark (car saved-mark-info))
  4456. (omark (marker-position (mark-marker)))
  4457. (nmark nil)
  4458. (saved-mark-active (cdr saved-mark-info)))
  4459. ;; Mark marker
  4460. (if (null saved-mark)
  4461. (set-marker (mark-marker) nil)
  4462. (setf nmark (marker-position saved-mark))
  4463. (set-marker (mark-marker) nmark)
  4464. (set-marker saved-mark nil))
  4465. ;; Mark active
  4466. (let ((cur-mark-active mark-active))
  4467. (setq mark-active saved-mark-active)
  4468. ;; If mark is active now, and either was not active or was at a
  4469. ;; different place, run the activate hook.
  4470. (if saved-mark-active
  4471. (when (or (not cur-mark-active)
  4472. (not (eq omark nmark)))
  4473. (run-hooks 'activate-mark-hook))
  4474. ;; If mark has ceased to be active, run deactivate hook.
  4475. (when cur-mark-active
  4476. (run-hooks 'deactivate-mark-hook))))))
  4477. (defmacro save-mark-and-excursion (&rest body)
  4478. "Like `save-excursion', but also save and restore the mark state.
  4479. This macro does what `save-excursion' did before Emacs 25.1."
  4480. (let ((saved-marker-sym (make-symbol "saved-marker")))
  4481. `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
  4482. (unwind-protect
  4483. (save-excursion ,@body)
  4484. (save-mark-and-excursion--restore ,saved-marker-sym)))))
  4485. (defcustom use-empty-active-region nil
  4486. "Whether \"region-aware\" commands should act on empty regions.
  4487. If nil, region-aware commands treat empty regions as inactive.
  4488. If non-nil, region-aware commands treat the region as active as
  4489. long as the mark is active, even if the region is empty.
  4490. Region-aware commands are those that act on the region if it is
  4491. active and Transient Mark mode is enabled, and on the text near
  4492. point otherwise."
  4493. :type 'boolean
  4494. :version "23.1"
  4495. :group 'editing-basics)
  4496. (defun use-region-p ()
  4497. "Return t if the region is active and it is appropriate to act on it.
  4498. This is used by commands that act specially on the region under
  4499. Transient Mark mode.
  4500. The return value is t if Transient Mark mode is enabled and the
  4501. mark is active; furthermore, if `use-empty-active-region' is nil,
  4502. the region must not be empty. Otherwise, the return value is nil.
  4503. For some commands, it may be appropriate to ignore the value of
  4504. `use-empty-active-region'; in that case, use `region-active-p'."
  4505. (and (region-active-p)
  4506. (or use-empty-active-region (> (region-end) (region-beginning)))))
  4507. (defun region-active-p ()
  4508. "Return non-nil if Transient Mark mode is enabled and the mark is active.
  4509. Some commands act specially on the region when Transient Mark
  4510. mode is enabled. Usually, such commands should use
  4511. `use-region-p' instead of this function, because `use-region-p'
  4512. also checks the value of `use-empty-active-region'."
  4513. (and transient-mark-mode mark-active
  4514. ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
  4515. ;; without the mark being set (e.g. bug#17324). We really should fix
  4516. ;; that problem, but in the mean time, let's make sure we don't say the
  4517. ;; region is active when there's no mark.
  4518. (progn (cl-assert (mark)) t)))
  4519. (defvar redisplay-unhighlight-region-function
  4520. (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
  4521. (defvar redisplay-highlight-region-function
  4522. (lambda (start end window rol)
  4523. (if (not (overlayp rol))
  4524. (let ((nrol (make-overlay start end)))
  4525. (funcall redisplay-unhighlight-region-function rol)
  4526. (overlay-put nrol 'window window)
  4527. (overlay-put nrol 'face 'region)
  4528. ;; Normal priority so that a large region doesn't hide all the
  4529. ;; overlays within it, but high secondary priority so that if it
  4530. ;; ends/starts in the middle of a small overlay, that small overlay
  4531. ;; won't hide the region's boundaries.
  4532. (overlay-put nrol 'priority '(nil . 100))
  4533. nrol)
  4534. (unless (and (eq (overlay-buffer rol) (current-buffer))
  4535. (eq (overlay-start rol) start)
  4536. (eq (overlay-end rol) end))
  4537. (move-overlay rol start end (current-buffer)))
  4538. rol)))
  4539. (defun redisplay--update-region-highlight (window)
  4540. (let ((rol (window-parameter window 'internal-region-overlay)))
  4541. (if (not (and (region-active-p)
  4542. (or highlight-nonselected-windows
  4543. (eq window (selected-window))
  4544. (and (window-minibuffer-p)
  4545. (eq window (minibuffer-selected-window))))))
  4546. (funcall redisplay-unhighlight-region-function rol)
  4547. (let* ((pt (window-point window))
  4548. (mark (mark))
  4549. (start (min pt mark))
  4550. (end (max pt mark))
  4551. (new
  4552. (funcall redisplay-highlight-region-function
  4553. start end window rol)))
  4554. (unless (equal new rol)
  4555. (set-window-parameter window 'internal-region-overlay
  4556. new))))))
  4557. (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
  4558. "Hook run just before redisplay.
  4559. It is called in each window that is to be redisplayed. It takes one argument,
  4560. which is the window that will be redisplayed. When run, the `current-buffer'
  4561. is set to the buffer displayed in that window.")
  4562. (defun redisplay--pre-redisplay-functions (windows)
  4563. (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
  4564. (if (null windows)
  4565. (with-current-buffer (window-buffer (selected-window))
  4566. (run-hook-with-args 'pre-redisplay-functions (selected-window)))
  4567. (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
  4568. (with-current-buffer (window-buffer win)
  4569. (run-hook-with-args 'pre-redisplay-functions win))))))
  4570. (add-function :before pre-redisplay-function
  4571. #'redisplay--pre-redisplay-functions)
  4572. (defvar-local mark-ring nil
  4573. "The list of former marks of the current buffer, most recent first.")
  4574. (put 'mark-ring 'permanent-local t)
  4575. (defcustom mark-ring-max 16
  4576. "Maximum size of mark ring. Start discarding off end if gets this big."
  4577. :type 'integer
  4578. :group 'editing-basics)
  4579. (defvar global-mark-ring nil
  4580. "The list of saved global marks, most recent first.")
  4581. (defcustom global-mark-ring-max 16
  4582. "Maximum size of global mark ring. \
  4583. Start discarding off end if gets this big."
  4584. :type 'integer
  4585. :group 'editing-basics)
  4586. (defun pop-to-mark-command ()
  4587. "Jump to mark, and pop a new position for mark off the ring.
  4588. \(Does not affect global mark ring)."
  4589. (interactive)
  4590. (if (null (mark t))
  4591. (user-error "No mark set in this buffer")
  4592. (if (= (point) (mark t))
  4593. (message "Mark popped"))
  4594. (goto-char (mark t))
  4595. (pop-mark)))
  4596. (defun push-mark-command (arg &optional nomsg)
  4597. "Set mark at where point is.
  4598. If no prefix ARG and mark is already set there, just activate it.
  4599. Display `Mark set' unless the optional second arg NOMSG is non-nil."
  4600. (interactive "P")
  4601. (let ((mark (mark t)))
  4602. (if (or arg (null mark) (/= mark (point)))
  4603. (push-mark nil nomsg t)
  4604. (activate-mark 'no-tmm)
  4605. (unless nomsg
  4606. (message "Mark activated")))))
  4607. (defcustom set-mark-command-repeat-pop nil
  4608. "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
  4609. That means that C-u \\[set-mark-command] \\[set-mark-command]
  4610. will pop the mark twice, and
  4611. C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
  4612. will pop the mark three times.
  4613. A value of nil means \\[set-mark-command]'s behavior does not change
  4614. after C-u \\[set-mark-command]."
  4615. :type 'boolean
  4616. :group 'editing-basics)
  4617. (defun set-mark-command (arg)
  4618. "Set the mark where point is, or jump to the mark.
  4619. Setting the mark also alters the region, which is the text
  4620. between point and mark; this is the closest equivalent in
  4621. Emacs to what some editors call the \"selection\".
  4622. With no prefix argument, set the mark at point, and push the
  4623. old mark position on local mark ring. Also push the old mark on
  4624. global mark ring, if the previous mark was set in another buffer.
  4625. When Transient Mark Mode is off, immediately repeating this
  4626. command activates `transient-mark-mode' temporarily.
  4627. With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
  4628. jump to the mark, and set the mark from
  4629. position popped off the local mark ring (this does not affect the global
  4630. mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
  4631. mark ring (see `pop-global-mark').
  4632. If `set-mark-command-repeat-pop' is non-nil, repeating
  4633. the \\[set-mark-command] command with no prefix argument pops the next position
  4634. off the local (or global) mark ring and jumps there.
  4635. With \\[universal-argument] \\[universal-argument] as prefix
  4636. argument, unconditionally set mark where point is, even if
  4637. `set-mark-command-repeat-pop' is non-nil.
  4638. Novice Emacs Lisp programmers often try to use the mark for the wrong
  4639. purposes. See the documentation of `set-mark' for more information."
  4640. (interactive "P")
  4641. (cond ((eq transient-mark-mode 'lambda)
  4642. (kill-local-variable 'transient-mark-mode))
  4643. ((eq (car-safe transient-mark-mode) 'only)
  4644. (deactivate-mark)))
  4645. (cond
  4646. ((and (consp arg) (> (prefix-numeric-value arg) 4))
  4647. (push-mark-command nil))
  4648. ((not (eq this-command 'set-mark-command))
  4649. (if arg
  4650. (pop-to-mark-command)
  4651. (push-mark-command t)))
  4652. ((and set-mark-command-repeat-pop
  4653. (eq last-command 'pop-global-mark)
  4654. (not arg))
  4655. (setq this-command 'pop-global-mark)
  4656. (pop-global-mark))
  4657. ((or (and set-mark-command-repeat-pop
  4658. (eq last-command 'pop-to-mark-command))
  4659. arg)
  4660. (setq this-command 'pop-to-mark-command)
  4661. (pop-to-mark-command))
  4662. ((eq last-command 'set-mark-command)
  4663. (if (region-active-p)
  4664. (progn
  4665. (deactivate-mark)
  4666. (message "Mark deactivated"))
  4667. (activate-mark)
  4668. (message "Mark activated")))
  4669. (t
  4670. (push-mark-command nil))))
  4671. (defun push-mark (&optional location nomsg activate)
  4672. "Set mark at LOCATION (point, by default) and push old mark on mark ring.
  4673. If the last global mark pushed was not in the current buffer,
  4674. also push LOCATION on the global mark ring.
  4675. Display `Mark set' unless the optional second arg NOMSG is non-nil.
  4676. Novice Emacs Lisp programmers often try to use the mark for the wrong
  4677. purposes. See the documentation of `set-mark' for more information.
  4678. In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
  4679. (unless (null (mark t))
  4680. (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
  4681. (when (> (length mark-ring) mark-ring-max)
  4682. (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
  4683. (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
  4684. (set-marker (mark-marker) (or location (point)) (current-buffer))
  4685. ;; Now push the mark on the global mark ring.
  4686. (if (and global-mark-ring
  4687. (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
  4688. ;; The last global mark pushed was in this same buffer.
  4689. ;; Don't push another one.
  4690. nil
  4691. (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
  4692. (when (> (length global-mark-ring) global-mark-ring-max)
  4693. (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
  4694. (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
  4695. (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
  4696. (message "Mark set"))
  4697. (if (or activate (not transient-mark-mode))
  4698. (set-mark (mark t)))
  4699. nil)
  4700. (defun pop-mark ()
  4701. "Pop off mark ring into the buffer's actual mark.
  4702. Does not set point. Does nothing if mark ring is empty."
  4703. (when mark-ring
  4704. (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
  4705. (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
  4706. (move-marker (car mark-ring) nil)
  4707. (if (null (mark t)) (ding))
  4708. (setq mark-ring (cdr mark-ring)))
  4709. (deactivate-mark))
  4710. (define-obsolete-function-alias
  4711. 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
  4712. (defun exchange-point-and-mark (&optional arg)
  4713. "Put the mark where point is now, and point where the mark is now.
  4714. This command works even when the mark is not active,
  4715. and it reactivates the mark.
  4716. If Transient Mark mode is on, a prefix ARG deactivates the mark
  4717. if it is active, and otherwise avoids reactivating it. If
  4718. Transient Mark mode is off, a prefix ARG enables Transient Mark
  4719. mode temporarily."
  4720. (interactive "P")
  4721. (let ((omark (mark t))
  4722. (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
  4723. (if (null omark)
  4724. (user-error "No mark set in this buffer"))
  4725. (set-mark (point))
  4726. (goto-char omark)
  4727. (cond (temp-highlight
  4728. (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
  4729. ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
  4730. (not (or arg (region-active-p))))
  4731. (deactivate-mark))
  4732. (t (activate-mark)))
  4733. nil))
  4734. (defcustom shift-select-mode t
  4735. "When non-nil, shifted motion keys activate the mark momentarily.
  4736. While the mark is activated in this way, any shift-translated point
  4737. motion key extends the region, and if Transient Mark mode was off, it
  4738. is temporarily turned on. Furthermore, the mark will be deactivated
  4739. by any subsequent point motion key that was not shift-translated, or
  4740. by any action that normally deactivates the mark in Transient Mark mode.
  4741. See `this-command-keys-shift-translated' for the meaning of
  4742. shift-translation."
  4743. :type 'boolean
  4744. :group 'editing-basics)
  4745. (defun handle-shift-selection ()
  4746. "Activate/deactivate mark depending on invocation thru shift translation.
  4747. This function is called by `call-interactively' when a command
  4748. with a `^' character in its `interactive' spec is invoked, before
  4749. running the command itself.
  4750. If `shift-select-mode' is enabled and the command was invoked
  4751. through shift translation, set the mark and activate the region
  4752. temporarily, unless it was already set in this way. See
  4753. `this-command-keys-shift-translated' for the meaning of shift
  4754. translation.
  4755. Otherwise, if the region has been activated temporarily,
  4756. deactivate it, and restore the variable `transient-mark-mode' to
  4757. its earlier value."
  4758. (cond ((and shift-select-mode this-command-keys-shift-translated)
  4759. (unless (and mark-active
  4760. (eq (car-safe transient-mark-mode) 'only))
  4761. (setq-local transient-mark-mode
  4762. (cons 'only
  4763. (unless (eq transient-mark-mode 'lambda)
  4764. transient-mark-mode)))
  4765. (push-mark nil nil t)))
  4766. ((eq (car-safe transient-mark-mode) 'only)
  4767. (setq transient-mark-mode (cdr transient-mark-mode))
  4768. (if (eq transient-mark-mode (default-value 'transient-mark-mode))
  4769. (kill-local-variable 'transient-mark-mode))
  4770. (deactivate-mark))))
  4771. (define-minor-mode transient-mark-mode
  4772. "Toggle Transient Mark mode.
  4773. With a prefix argument ARG, enable Transient Mark mode if ARG is
  4774. positive, and disable it otherwise. If called from Lisp, enable
  4775. Transient Mark mode if ARG is omitted or nil.
  4776. Transient Mark mode is a global minor mode. When enabled, the
  4777. region is highlighted with the `region' face whenever the mark
  4778. is active. The mark is \"deactivated\" by changing the buffer,
  4779. and after certain other operations that set the mark but whose
  4780. main purpose is something else--for example, incremental search,
  4781. \\[beginning-of-buffer], and \\[end-of-buffer].
  4782. You can also deactivate the mark by typing \\[keyboard-quit] or
  4783. \\[keyboard-escape-quit].
  4784. Many commands change their behavior when Transient Mark mode is
  4785. in effect and the mark is active, by acting on the region instead
  4786. of their usual default part of the buffer's text. Examples of
  4787. such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
  4788. \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
  4789. To see the documentation of commands which are sensitive to the
  4790. Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
  4791. or \"mark.*active\" at the prompt."
  4792. :global t
  4793. ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
  4794. :variable (default-value 'transient-mark-mode))
  4795. (defvar widen-automatically t
  4796. "Non-nil means it is ok for commands to call `widen' when they want to.
  4797. Some commands will do this in order to go to positions outside
  4798. the current accessible part of the buffer.
  4799. If `widen-automatically' is nil, these commands will do something else
  4800. as a fallback, and won't change the buffer bounds.")
  4801. (defvar non-essential nil
  4802. "Whether the currently executing code is performing an essential task.
  4803. This variable should be non-nil only when running code which should not
  4804. disturb the user. E.g. it can be used to prevent Tramp from prompting the
  4805. user for a password when we are simply scanning a set of files in the
  4806. background or displaying possible completions before the user even asked
  4807. for it.")
  4808. (defun pop-global-mark ()
  4809. "Pop off global mark ring and jump to the top location."
  4810. (interactive)
  4811. ;; Pop entries which refer to non-existent buffers.
  4812. (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
  4813. (setq global-mark-ring (cdr global-mark-ring)))
  4814. (or global-mark-ring
  4815. (error "No global mark set"))
  4816. (let* ((marker (car global-mark-ring))
  4817. (buffer (marker-buffer marker))
  4818. (position (marker-position marker)))
  4819. (setq global-mark-ring (nconc (cdr global-mark-ring)
  4820. (list (car global-mark-ring))))
  4821. (set-buffer buffer)
  4822. (or (and (>= position (point-min))
  4823. (<= position (point-max)))
  4824. (if widen-automatically
  4825. (widen)
  4826. (error "Global mark position is outside accessible part of buffer")))
  4827. (goto-char position)
  4828. (switch-to-buffer buffer)))
  4829. (defcustom next-line-add-newlines nil
  4830. "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
  4831. :type 'boolean
  4832. :version "21.1"
  4833. :group 'editing-basics)
  4834. (defun next-line (&optional arg try-vscroll)
  4835. "Move cursor vertically down ARG lines.
  4836. Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
  4837. Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
  4838. lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
  4839. function will not vscroll.
  4840. ARG defaults to 1.
  4841. If there is no character in the target line exactly under the current column,
  4842. the cursor is positioned after the character in that line which spans this
  4843. column, or at the end of the line if it is not long enough.
  4844. If there is no line in the buffer after this one, behavior depends on the
  4845. value of `next-line-add-newlines'. If non-nil, it inserts a newline character
  4846. to create a line, and moves the cursor to that line. Otherwise it moves the
  4847. cursor to the end of the buffer.
  4848. If the variable `line-move-visual' is non-nil, this command moves
  4849. by display lines. Otherwise, it moves by buffer lines, without
  4850. taking variable-width characters or continued lines into account.
  4851. The command \\[set-goal-column] can be used to create
  4852. a semipermanent goal column for this command.
  4853. Then instead of trying to move exactly vertically (or as close as possible),
  4854. this command moves to the specified goal column (or as close as possible).
  4855. The goal column is stored in the variable `goal-column', which is nil
  4856. when there is no goal column. Note that setting `goal-column'
  4857. overrides `line-move-visual' and causes this command to move by buffer
  4858. lines rather than by display lines."
  4859. (declare (interactive-only forward-line))
  4860. (interactive "^p\np")
  4861. (or arg (setq arg 1))
  4862. (if (and next-line-add-newlines (= arg 1))
  4863. (if (save-excursion (end-of-line) (eobp))
  4864. ;; When adding a newline, don't expand an abbrev.
  4865. (let ((abbrev-mode nil))
  4866. (end-of-line)
  4867. (insert (if use-hard-newlines hard-newline "\n")))
  4868. (line-move arg nil nil try-vscroll))
  4869. (if (called-interactively-p 'interactive)
  4870. (condition-case err
  4871. (line-move arg nil nil try-vscroll)
  4872. ((beginning-of-buffer end-of-buffer)
  4873. (signal (car err) (cdr err))))
  4874. (line-move arg nil nil try-vscroll)))
  4875. nil)
  4876. (defun previous-line (&optional arg try-vscroll)
  4877. "Move cursor vertically up ARG lines.
  4878. Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
  4879. Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
  4880. lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
  4881. function will not vscroll.
  4882. ARG defaults to 1.
  4883. If there is no character in the target line exactly over the current column,
  4884. the cursor is positioned after the character in that line which spans this
  4885. column, or at the end of the line if it is not long enough.
  4886. If the variable `line-move-visual' is non-nil, this command moves
  4887. by display lines. Otherwise, it moves by buffer lines, without
  4888. taking variable-width characters or continued lines into account.
  4889. The command \\[set-goal-column] can be used to create
  4890. a semipermanent goal column for this command.
  4891. Then instead of trying to move exactly vertically (or as close as possible),
  4892. this command moves to the specified goal column (or as close as possible).
  4893. The goal column is stored in the variable `goal-column', which is nil
  4894. when there is no goal column. Note that setting `goal-column'
  4895. overrides `line-move-visual' and causes this command to move by buffer
  4896. lines rather than by display lines."
  4897. (declare (interactive-only
  4898. "use `forward-line' with negative argument instead."))
  4899. (interactive "^p\np")
  4900. (or arg (setq arg 1))
  4901. (if (called-interactively-p 'interactive)
  4902. (condition-case err
  4903. (line-move (- arg) nil nil try-vscroll)
  4904. ((beginning-of-buffer end-of-buffer)
  4905. (signal (car err) (cdr err))))
  4906. (line-move (- arg) nil nil try-vscroll))
  4907. nil)
  4908. (defcustom track-eol nil
  4909. "Non-nil means vertical motion starting at end of line keeps to ends of lines.
  4910. This means moving to the end of each line moved onto.
  4911. The beginning of a blank line does not count as the end of a line.
  4912. This has no effect when the variable `line-move-visual' is non-nil."
  4913. :type 'boolean
  4914. :group 'editing-basics)
  4915. (defcustom goal-column nil
  4916. "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
  4917. A non-nil setting overrides the variable `line-move-visual', which see."
  4918. :type '(choice integer
  4919. (const :tag "None" nil))
  4920. :group 'editing-basics)
  4921. (make-variable-buffer-local 'goal-column)
  4922. (defvar temporary-goal-column 0
  4923. "Current goal column for vertical motion.
  4924. It is the column where point was at the start of the current run
  4925. of vertical motion commands.
  4926. When moving by visual lines via the function `line-move-visual', it is a cons
  4927. cell (COL . HSCROLL), where COL is the x-position, in pixels,
  4928. divided by the default column width, and HSCROLL is the number of
  4929. columns by which window is scrolled from left margin.
  4930. When the `track-eol' feature is doing its job, the value is
  4931. `most-positive-fixnum'.")
  4932. (defcustom line-move-ignore-invisible t
  4933. "Non-nil means commands that move by lines ignore invisible newlines.
  4934. When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
  4935. as if newlines that are invisible didn't exist, and count
  4936. only visible newlines. Thus, moving across across 2 newlines
  4937. one of which is invisible will be counted as a one-line move.
  4938. Also, a non-nil value causes invisible text to be ignored when
  4939. counting columns for the purposes of keeping point in the same
  4940. column by \\[next-line] and \\[previous-line].
  4941. Outline mode sets this."
  4942. :type 'boolean
  4943. :group 'editing-basics)
  4944. (defcustom line-move-visual t
  4945. "When non-nil, `line-move' moves point by visual lines.
  4946. This movement is based on where the cursor is displayed on the
  4947. screen, instead of relying on buffer contents alone. It takes
  4948. into account variable-width characters and line continuation.
  4949. If nil, `line-move' moves point by logical lines.
  4950. A non-nil setting of `goal-column' overrides the value of this variable
  4951. and forces movement by logical lines.
  4952. A window that is horizontally scrolled also forces movement by logical
  4953. lines."
  4954. :type 'boolean
  4955. :group 'editing-basics
  4956. :version "23.1")
  4957. ;; Only used if display-graphic-p.
  4958. (declare-function font-info "font.c" (name &optional frame))
  4959. (defun default-font-height ()
  4960. "Return the height in pixels of the current buffer's default face font.
  4961. If the default font is remapped (see `face-remapping-alist'), the
  4962. function returns the height of the remapped face."
  4963. (let ((default-font (face-font 'default)))
  4964. (cond
  4965. ((and (display-multi-font-p)
  4966. ;; Avoid calling font-info if the frame's default font was
  4967. ;; not changed since the frame was created. That's because
  4968. ;; font-info is expensive for some fonts, see bug #14838.
  4969. (not (string= (frame-parameter nil 'font) default-font)))
  4970. (aref (font-info default-font) 3))
  4971. (t (frame-char-height)))))
  4972. (defun default-font-width ()
  4973. "Return the width in pixels of the current buffer's default face font.
  4974. If the default font is remapped (see `face-remapping-alist'), the
  4975. function returns the width of the remapped face."
  4976. (let ((default-font (face-font 'default)))
  4977. (cond
  4978. ((and (display-multi-font-p)
  4979. ;; Avoid calling font-info if the frame's default font was
  4980. ;; not changed since the frame was created. That's because
  4981. ;; font-info is expensive for some fonts, see bug #14838.
  4982. (not (string= (frame-parameter nil 'font) default-font)))
  4983. (let* ((info (font-info (face-font 'default)))
  4984. (width (aref info 11)))
  4985. (if (> width 0)
  4986. width
  4987. (aref info 10))))
  4988. (t (frame-char-width)))))
  4989. (defun default-line-height ()
  4990. "Return the pixel height of current buffer's default-face text line.
  4991. The value includes `line-spacing', if any, defined for the buffer
  4992. or the frame."
  4993. (let ((dfh (default-font-height))
  4994. (lsp (if (display-graphic-p)
  4995. (or line-spacing
  4996. (default-value 'line-spacing)
  4997. (frame-parameter nil 'line-spacing)
  4998. 0)
  4999. 0)))
  5000. (if (floatp lsp)
  5001. (setq lsp (truncate (* (frame-char-height) lsp))))
  5002. (+ dfh lsp)))
  5003. (defun window-screen-lines ()
  5004. "Return the number of screen lines in the text area of the selected window.
  5005. This is different from `window-text-height' in that this function counts
  5006. lines in units of the height of the font used by the default face displayed
  5007. in the window, not in units of the frame's default font, and also accounts
  5008. for `line-spacing', if any, defined for the window's buffer or frame.
  5009. The value is a floating-point number."
  5010. (let ((edges (window-inside-pixel-edges))
  5011. (dlh (default-line-height)))
  5012. (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
  5013. ;; Returns non-nil if partial move was done.
  5014. (defun line-move-partial (arg noerror to-end)
  5015. (if (< arg 0)
  5016. ;; Move backward (up).
  5017. ;; If already vscrolled, reduce vscroll
  5018. (let ((vs (window-vscroll nil t))
  5019. (dlh (default-line-height)))
  5020. (when (> vs dlh)
  5021. (set-window-vscroll nil (- vs dlh) t)))
  5022. ;; Move forward (down).
  5023. (let* ((lh (window-line-height -1))
  5024. (rowh (car lh))
  5025. (vpos (nth 1 lh))
  5026. (ypos (nth 2 lh))
  5027. (rbot (nth 3 lh))
  5028. (this-lh (window-line-height))
  5029. (this-height (car this-lh))
  5030. (this-ypos (nth 2 this-lh))
  5031. (dlh (default-line-height))
  5032. (wslines (window-screen-lines))
  5033. (edges (window-inside-pixel-edges))
  5034. (winh (- (nth 3 edges) (nth 1 edges) 1))
  5035. py vs last-line)
  5036. (if (> (mod wslines 1.0) 0.0)
  5037. (setq wslines (round (+ wslines 0.5))))
  5038. (when (or (null lh)
  5039. (>= rbot dlh)
  5040. (<= ypos (- dlh))
  5041. (null this-lh)
  5042. (<= this-ypos (- dlh)))
  5043. (unless lh
  5044. (let ((wend (pos-visible-in-window-p t nil t)))
  5045. (setq rbot (nth 3 wend)
  5046. rowh (nth 4 wend)
  5047. vpos (nth 5 wend))))
  5048. (unless this-lh
  5049. (let ((wstart (pos-visible-in-window-p nil nil t)))
  5050. (setq this-ypos (nth 2 wstart)
  5051. this-height (nth 4 wstart))))
  5052. (setq py
  5053. (or (nth 1 this-lh)
  5054. (let ((ppos (posn-at-point))
  5055. col-row)
  5056. (setq col-row (posn-actual-col-row ppos))
  5057. (if col-row
  5058. (- (cdr col-row) (window-vscroll))
  5059. (cdr (posn-col-row ppos))))))
  5060. ;; VPOS > 0 means the last line is only partially visible.
  5061. ;; But if the part that is visible is at least as tall as the
  5062. ;; default font, that means the line is actually fully
  5063. ;; readable, and something like line-spacing is hidden. So in
  5064. ;; that case we accept the last line in the window as still
  5065. ;; visible, and consider the margin as starting one line
  5066. ;; later.
  5067. (if (and vpos (> vpos 0))
  5068. (if (and rowh
  5069. (>= rowh (default-font-height))
  5070. (< rowh dlh))
  5071. (setq last-line (min (- wslines scroll-margin) vpos))
  5072. (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
  5073. (cond
  5074. ;; If last line of window is fully visible, and vscrolling
  5075. ;; more would make this line invisible, move forward.
  5076. ((and (or (< (setq vs (window-vscroll nil t)) dlh)
  5077. (null this-height)
  5078. (<= this-height dlh))
  5079. (or (null rbot) (= rbot 0)))
  5080. nil)
  5081. ;; If cursor is not in the bottom scroll margin, and the
  5082. ;; current line is is not too tall, move forward.
  5083. ((and (or (null this-height) (<= this-height winh))
  5084. vpos
  5085. (> vpos 0)
  5086. (< py last-line))
  5087. nil)
  5088. ;; When already vscrolled, we vscroll some more if we can,
  5089. ;; or clear vscroll and move forward at end of tall image.
  5090. ((> vs 0)
  5091. (when (or (and rbot (> rbot 0))
  5092. (and this-height (> this-height dlh)))
  5093. (set-window-vscroll nil (+ vs dlh) t)))
  5094. ;; If cursor just entered the bottom scroll margin, move forward,
  5095. ;; but also optionally vscroll one line so redisplay won't recenter.
  5096. ((and vpos
  5097. (> vpos 0)
  5098. (= py last-line))
  5099. ;; Don't vscroll if the partially-visible line at window
  5100. ;; bottom is not too tall (a.k.a. "just one more text
  5101. ;; line"): in that case, we do want redisplay to behave
  5102. ;; normally, i.e. recenter or whatever.
  5103. ;;
  5104. ;; Note: ROWH + RBOT from the value returned by
  5105. ;; pos-visible-in-window-p give the total height of the
  5106. ;; partially-visible glyph row at the end of the window. As
  5107. ;; we are dealing with floats, we disregard sub-pixel
  5108. ;; discrepancies between that and DLH.
  5109. (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
  5110. (set-window-vscroll nil dlh t))
  5111. (line-move-1 arg noerror to-end)
  5112. t)
  5113. ;; If there are lines above the last line, scroll-up one line.
  5114. ((and vpos (> vpos 0))
  5115. (scroll-up 1)
  5116. t)
  5117. ;; Finally, start vscroll.
  5118. (t
  5119. (set-window-vscroll nil dlh t)))))))
  5120. ;; This is like line-move-1 except that it also performs
  5121. ;; vertical scrolling of tall images if appropriate.
  5122. ;; That is not really a clean thing to do, since it mixes
  5123. ;; scrolling with cursor motion. But so far we don't have
  5124. ;; a cleaner solution to the problem of making C-n do something
  5125. ;; useful given a tall image.
  5126. (defun line-move (arg &optional noerror to-end try-vscroll)
  5127. "Move forward ARG lines.
  5128. If NOERROR, don't signal an error if we can't move ARG lines.
  5129. TO-END is unused.
  5130. TRY-VSCROLL controls whether to vscroll tall lines: if either
  5131. `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
  5132. not vscroll."
  5133. (if noninteractive
  5134. (line-move-1 arg noerror to-end)
  5135. (unless (and auto-window-vscroll try-vscroll
  5136. ;; Only vscroll for single line moves
  5137. (= (abs arg) 1)
  5138. ;; Under scroll-conservatively, the display engine
  5139. ;; does this better.
  5140. (zerop scroll-conservatively)
  5141. ;; But don't vscroll in a keyboard macro.
  5142. (not defining-kbd-macro)
  5143. (not executing-kbd-macro)
  5144. (line-move-partial arg noerror to-end))
  5145. (set-window-vscroll nil 0 t)
  5146. (if (and line-move-visual
  5147. ;; Display-based column are incompatible with goal-column.
  5148. (not goal-column)
  5149. ;; When the text in the window is scrolled to the left,
  5150. ;; display-based motion doesn't make sense (because each
  5151. ;; logical line occupies exactly one screen line).
  5152. (not (> (window-hscroll) 0))
  5153. ;; Likewise when the text _was_ scrolled to the left
  5154. ;; when the current run of vertical motion commands
  5155. ;; started.
  5156. (not (and (memq last-command
  5157. `(next-line previous-line ,this-command))
  5158. auto-hscroll-mode
  5159. (numberp temporary-goal-column)
  5160. (>= temporary-goal-column
  5161. (- (window-width) hscroll-margin)))))
  5162. (prog1 (line-move-visual arg noerror)
  5163. ;; If we moved into a tall line, set vscroll to make
  5164. ;; scrolling through tall images more smooth.
  5165. (let ((lh (line-pixel-height))
  5166. (edges (window-inside-pixel-edges))
  5167. (dlh (default-line-height))
  5168. winh)
  5169. (setq winh (- (nth 3 edges) (nth 1 edges) 1))
  5170. (if (and (< arg 0)
  5171. (< (point) (window-start))
  5172. (> lh winh))
  5173. (set-window-vscroll
  5174. nil
  5175. (- lh dlh) t))))
  5176. (line-move-1 arg noerror to-end)))))
  5177. ;; Display-based alternative to line-move-1.
  5178. ;; Arg says how many lines to move. The value is t if we can move the
  5179. ;; specified number of lines.
  5180. (defun line-move-visual (arg &optional noerror)
  5181. "Move ARG lines forward.
  5182. If NOERROR, don't signal an error if we can't move that many lines."
  5183. (let ((opoint (point))
  5184. (hscroll (window-hscroll))
  5185. target-hscroll)
  5186. ;; Check if the previous command was a line-motion command, or if
  5187. ;; we were called from some other command.
  5188. (if (and (consp temporary-goal-column)
  5189. (memq last-command `(next-line previous-line ,this-command)))
  5190. ;; If so, there's no need to reset `temporary-goal-column',
  5191. ;; but we may need to hscroll.
  5192. (if (or (/= (cdr temporary-goal-column) hscroll)
  5193. (> (cdr temporary-goal-column) 0))
  5194. (setq target-hscroll (cdr temporary-goal-column)))
  5195. ;; Otherwise, we should reset `temporary-goal-column'.
  5196. (let ((posn (posn-at-point))
  5197. x-pos)
  5198. (cond
  5199. ;; Handle the `overflow-newline-into-fringe' case:
  5200. ((eq (nth 1 posn) 'right-fringe)
  5201. (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
  5202. ((car (posn-x-y posn))
  5203. (setq x-pos (car (posn-x-y posn)))
  5204. ;; In R2L lines, the X pixel coordinate is measured from the
  5205. ;; left edge of the window, but columns are still counted
  5206. ;; from the logical-order beginning of the line, i.e. from
  5207. ;; the right edge in this case. We need to adjust for that.
  5208. (if (eq (current-bidi-paragraph-direction) 'right-to-left)
  5209. (setq x-pos (- (window-body-width nil t) 1 x-pos)))
  5210. (setq temporary-goal-column
  5211. (cons (/ (float x-pos)
  5212. (frame-char-width))
  5213. hscroll))))))
  5214. (if target-hscroll
  5215. (set-window-hscroll (selected-window) target-hscroll))
  5216. ;; vertical-motion can move more than it was asked to if it moves
  5217. ;; across display strings with newlines. We don't want to ring
  5218. ;; the bell and announce beginning/end of buffer in that case.
  5219. (or (and (or (and (>= arg 0)
  5220. (>= (vertical-motion
  5221. (cons (or goal-column
  5222. (if (consp temporary-goal-column)
  5223. (car temporary-goal-column)
  5224. temporary-goal-column))
  5225. arg))
  5226. arg))
  5227. (and (< arg 0)
  5228. (<= (vertical-motion
  5229. (cons (or goal-column
  5230. (if (consp temporary-goal-column)
  5231. (car temporary-goal-column)
  5232. temporary-goal-column))
  5233. arg))
  5234. arg)))
  5235. (or (>= arg 0)
  5236. (/= (point) opoint)
  5237. ;; If the goal column lies on a display string,
  5238. ;; `vertical-motion' advances the cursor to the end
  5239. ;; of the string. For arg < 0, this can cause the
  5240. ;; cursor to get stuck. (Bug#3020).
  5241. (= (vertical-motion arg) arg)))
  5242. (unless noerror
  5243. (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
  5244. nil)))))
  5245. ;; This is the guts of next-line and previous-line.
  5246. ;; Arg says how many lines to move.
  5247. ;; The value is t if we can move the specified number of lines.
  5248. (defun line-move-1 (arg &optional noerror _to-end)
  5249. ;; Don't run any point-motion hooks, and disregard intangibility,
  5250. ;; for intermediate positions.
  5251. (let ((inhibit-point-motion-hooks t)
  5252. (opoint (point))
  5253. (orig-arg arg))
  5254. (if (consp temporary-goal-column)
  5255. (setq temporary-goal-column (+ (car temporary-goal-column)
  5256. (cdr temporary-goal-column))))
  5257. (unwind-protect
  5258. (progn
  5259. (if (not (memq last-command '(next-line previous-line)))
  5260. (setq temporary-goal-column
  5261. (if (and track-eol (eolp)
  5262. ;; Don't count beg of empty line as end of line
  5263. ;; unless we just did explicit end-of-line.
  5264. (or (not (bolp)) (eq last-command 'move-end-of-line)))
  5265. most-positive-fixnum
  5266. (current-column))))
  5267. (if (not (or (integerp selective-display)
  5268. line-move-ignore-invisible))
  5269. ;; Use just newline characters.
  5270. ;; Set ARG to 0 if we move as many lines as requested.
  5271. (or (if (> arg 0)
  5272. (progn (if (> arg 1) (forward-line (1- arg)))
  5273. ;; This way of moving forward ARG lines
  5274. ;; verifies that we have a newline after the last one.
  5275. ;; It doesn't get confused by intangible text.
  5276. (end-of-line)
  5277. (if (zerop (forward-line 1))
  5278. (setq arg 0)))
  5279. (and (zerop (forward-line arg))
  5280. (bolp)
  5281. (setq arg 0)))
  5282. (unless noerror
  5283. (signal (if (< arg 0)
  5284. 'beginning-of-buffer
  5285. 'end-of-buffer)
  5286. nil)))
  5287. ;; Move by arg lines, but ignore invisible ones.
  5288. (let (done)
  5289. (while (and (> arg 0) (not done))
  5290. ;; If the following character is currently invisible,
  5291. ;; skip all characters with that same `invisible' property value.
  5292. (while (and (not (eobp)) (invisible-p (point)))
  5293. (goto-char (next-char-property-change (point))))
  5294. ;; Move a line.
  5295. ;; We don't use `end-of-line', since we want to escape
  5296. ;; from field boundaries occurring exactly at point.
  5297. (goto-char (constrain-to-field
  5298. (let ((inhibit-field-text-motion t))
  5299. (line-end-position))
  5300. (point) t t
  5301. 'inhibit-line-move-field-capture))
  5302. ;; If there's no invisibility here, move over the newline.
  5303. (cond
  5304. ((eobp)
  5305. (if (not noerror)
  5306. (signal 'end-of-buffer nil)
  5307. (setq done t)))
  5308. ((and (> arg 1) ;; Use vertical-motion for last move
  5309. (not (integerp selective-display))
  5310. (not (invisible-p (point))))
  5311. ;; We avoid vertical-motion when possible
  5312. ;; because that has to fontify.
  5313. (forward-line 1))
  5314. ;; Otherwise move a more sophisticated way.
  5315. ((zerop (vertical-motion 1))
  5316. (if (not noerror)
  5317. (signal 'end-of-buffer nil)
  5318. (setq done t))))
  5319. (unless done
  5320. (setq arg (1- arg))))
  5321. ;; The logic of this is the same as the loop above,
  5322. ;; it just goes in the other direction.
  5323. (while (and (< arg 0) (not done))
  5324. ;; For completely consistency with the forward-motion
  5325. ;; case, we should call beginning-of-line here.
  5326. ;; However, if point is inside a field and on a
  5327. ;; continued line, the call to (vertical-motion -1)
  5328. ;; below won't move us back far enough; then we return
  5329. ;; to the same column in line-move-finish, and point
  5330. ;; gets stuck -- cyd
  5331. (forward-line 0)
  5332. (cond
  5333. ((bobp)
  5334. (if (not noerror)
  5335. (signal 'beginning-of-buffer nil)
  5336. (setq done t)))
  5337. ((and (< arg -1) ;; Use vertical-motion for last move
  5338. (not (integerp selective-display))
  5339. (not (invisible-p (1- (point)))))
  5340. (forward-line -1))
  5341. ((zerop (vertical-motion -1))
  5342. (if (not noerror)
  5343. (signal 'beginning-of-buffer nil)
  5344. (setq done t))))
  5345. (unless done
  5346. (setq arg (1+ arg))
  5347. (while (and ;; Don't move over previous invis lines
  5348. ;; if our target is the middle of this line.
  5349. (or (zerop (or goal-column temporary-goal-column))
  5350. (< arg 0))
  5351. (not (bobp)) (invisible-p (1- (point))))
  5352. (goto-char (previous-char-property-change (point))))))))
  5353. ;; This is the value the function returns.
  5354. (= arg 0))
  5355. (cond ((> arg 0)
  5356. ;; If we did not move down as far as desired, at least go
  5357. ;; to end of line. Be sure to call point-entered and
  5358. ;; point-left-hooks.
  5359. (let* ((npoint (prog1 (line-end-position)
  5360. (goto-char opoint)))
  5361. (inhibit-point-motion-hooks nil))
  5362. (goto-char npoint)))
  5363. ((< arg 0)
  5364. ;; If we did not move up as far as desired,
  5365. ;; at least go to beginning of line.
  5366. (let* ((npoint (prog1 (line-beginning-position)
  5367. (goto-char opoint)))
  5368. (inhibit-point-motion-hooks nil))
  5369. (goto-char npoint)))
  5370. (t
  5371. (line-move-finish (or goal-column temporary-goal-column)
  5372. opoint (> orig-arg 0)))))))
  5373. (defun line-move-finish (column opoint forward)
  5374. (let ((repeat t))
  5375. (while repeat
  5376. ;; Set REPEAT to t to repeat the whole thing.
  5377. (setq repeat nil)
  5378. (let (new
  5379. (old (point))
  5380. (line-beg (line-beginning-position))
  5381. (line-end
  5382. ;; Compute the end of the line
  5383. ;; ignoring effectively invisible newlines.
  5384. (save-excursion
  5385. ;; Like end-of-line but ignores fields.
  5386. (skip-chars-forward "^\n")
  5387. (while (and (not (eobp)) (invisible-p (point)))
  5388. (goto-char (next-char-property-change (point)))
  5389. (skip-chars-forward "^\n"))
  5390. (point))))
  5391. ;; Move to the desired column.
  5392. (line-move-to-column (truncate column))
  5393. ;; Corner case: suppose we start out in a field boundary in
  5394. ;; the middle of a continued line. When we get to
  5395. ;; line-move-finish, point is at the start of a new *screen*
  5396. ;; line but the same text line; then line-move-to-column would
  5397. ;; move us backwards. Test using C-n with point on the "x" in
  5398. ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
  5399. (and forward
  5400. (< (point) old)
  5401. (goto-char old))
  5402. (setq new (point))
  5403. ;; Process intangibility within a line.
  5404. ;; With inhibit-point-motion-hooks bound to nil, a call to
  5405. ;; goto-char moves point past intangible text.
  5406. ;; However, inhibit-point-motion-hooks controls both the
  5407. ;; intangibility and the point-entered/point-left hooks. The
  5408. ;; following hack avoids calling the point-* hooks
  5409. ;; unnecessarily. Note that we move *forward* past intangible
  5410. ;; text when the initial and final points are the same.
  5411. (goto-char new)
  5412. (let ((inhibit-point-motion-hooks nil))
  5413. (goto-char new)
  5414. ;; If intangibility moves us to a different (later) place
  5415. ;; in the same line, use that as the destination.
  5416. (if (<= (point) line-end)
  5417. (setq new (point))
  5418. ;; If that position is "too late",
  5419. ;; try the previous allowable position.
  5420. ;; See if it is ok.
  5421. (backward-char)
  5422. (if (if forward
  5423. ;; If going forward, don't accept the previous
  5424. ;; allowable position if it is before the target line.
  5425. (< line-beg (point))
  5426. ;; If going backward, don't accept the previous
  5427. ;; allowable position if it is still after the target line.
  5428. (<= (point) line-end))
  5429. (setq new (point))
  5430. ;; As a last resort, use the end of the line.
  5431. (setq new line-end))))
  5432. ;; Now move to the updated destination, processing fields
  5433. ;; as well as intangibility.
  5434. (goto-char opoint)
  5435. (let ((inhibit-point-motion-hooks nil))
  5436. (goto-char
  5437. ;; Ignore field boundaries if the initial and final
  5438. ;; positions have the same `field' property, even if the
  5439. ;; fields are non-contiguous. This seems to be "nicer"
  5440. ;; behavior in many situations.
  5441. (if (eq (get-char-property new 'field)
  5442. (get-char-property opoint 'field))
  5443. new
  5444. (constrain-to-field new opoint t t
  5445. 'inhibit-line-move-field-capture))))
  5446. ;; If all this moved us to a different line,
  5447. ;; retry everything within that new line.
  5448. (when (or (< (point) line-beg) (> (point) line-end))
  5449. ;; Repeat the intangibility and field processing.
  5450. (setq repeat t))))))
  5451. (defun line-move-to-column (col)
  5452. "Try to find column COL, considering invisibility.
  5453. This function works only in certain cases,
  5454. because what we really need is for `move-to-column'
  5455. and `current-column' to be able to ignore invisible text."
  5456. (if (zerop col)
  5457. (beginning-of-line)
  5458. (move-to-column col))
  5459. (when (and line-move-ignore-invisible
  5460. (not (bolp)) (invisible-p (1- (point))))
  5461. (let ((normal-location (point))
  5462. (normal-column (current-column)))
  5463. ;; If the following character is currently invisible,
  5464. ;; skip all characters with that same `invisible' property value.
  5465. (while (and (not (eobp))
  5466. (invisible-p (point)))
  5467. (goto-char (next-char-property-change (point))))
  5468. ;; Have we advanced to a larger column position?
  5469. (if (> (current-column) normal-column)
  5470. ;; We have made some progress towards the desired column.
  5471. ;; See if we can make any further progress.
  5472. (line-move-to-column (+ (current-column) (- col normal-column)))
  5473. ;; Otherwise, go to the place we originally found
  5474. ;; and move back over invisible text.
  5475. ;; that will get us to the same place on the screen
  5476. ;; but with a more reasonable buffer position.
  5477. (goto-char normal-location)
  5478. (let ((line-beg
  5479. ;; We want the real line beginning, so it's consistent
  5480. ;; with bolp below, otherwise we might infloop.
  5481. (let ((inhibit-field-text-motion t))
  5482. (line-beginning-position))))
  5483. (while (and (not (bolp)) (invisible-p (1- (point))))
  5484. (goto-char (previous-char-property-change (point) line-beg))))))))
  5485. (defun move-end-of-line (arg)
  5486. "Move point to end of current line as displayed.
  5487. With argument ARG not nil or 1, move forward ARG - 1 lines first.
  5488. If point reaches the beginning or end of buffer, it stops there.
  5489. To ignore the effects of the `intangible' text or overlay
  5490. property, bind `inhibit-point-motion-hooks' to t.
  5491. If there is an image in the current line, this function
  5492. disregards newlines that are part of the text on which the image
  5493. rests."
  5494. (interactive "^p")
  5495. (or arg (setq arg 1))
  5496. (let (done)
  5497. (while (not done)
  5498. (let ((newpos
  5499. (save-excursion
  5500. (let ((goal-column 0)
  5501. (line-move-visual nil))
  5502. (and (line-move arg t)
  5503. ;; With bidi reordering, we may not be at bol,
  5504. ;; so make sure we are.
  5505. (skip-chars-backward "^\n")
  5506. (not (bobp))
  5507. (progn
  5508. (while (and (not (bobp)) (invisible-p (1- (point))))
  5509. (goto-char (previous-single-char-property-change
  5510. (point) 'invisible)))
  5511. (backward-char 1)))
  5512. (point)))))
  5513. (goto-char newpos)
  5514. (if (and (> (point) newpos)
  5515. (eq (preceding-char) ?\n))
  5516. (backward-char 1)
  5517. (if (and (> (point) newpos) (not (eobp))
  5518. (not (eq (following-char) ?\n)))
  5519. ;; If we skipped something intangible and now we're not
  5520. ;; really at eol, keep going.
  5521. (setq arg 1)
  5522. (setq done t)))))))
  5523. (defun move-beginning-of-line (arg)
  5524. "Move point to beginning of current line as displayed.
  5525. \(If there's an image in the line, this disregards newlines
  5526. which are part of the text that the image rests on.)
  5527. With argument ARG not nil or 1, move forward ARG - 1 lines first.
  5528. If point reaches the beginning or end of buffer, it stops there.
  5529. To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
  5530. (interactive "^p")
  5531. (or arg (setq arg 1))
  5532. (let ((orig (point))
  5533. first-vis first-vis-field-value)
  5534. ;; Move by lines, if ARG is not 1 (the default).
  5535. (if (/= arg 1)
  5536. (let ((line-move-visual nil))
  5537. (line-move (1- arg) t)))
  5538. ;; Move to beginning-of-line, ignoring fields and invisible text.
  5539. (skip-chars-backward "^\n")
  5540. (while (and (not (bobp)) (invisible-p (1- (point))))
  5541. (goto-char (previous-char-property-change (point)))
  5542. (skip-chars-backward "^\n"))
  5543. ;; Now find first visible char in the line.
  5544. (while (and (< (point) orig) (invisible-p (point)))
  5545. (goto-char (next-char-property-change (point) orig)))
  5546. (setq first-vis (point))
  5547. ;; See if fields would stop us from reaching FIRST-VIS.
  5548. (setq first-vis-field-value
  5549. (constrain-to-field first-vis orig (/= arg 1) t nil))
  5550. (goto-char (if (/= first-vis-field-value first-vis)
  5551. ;; If yes, obey them.
  5552. first-vis-field-value
  5553. ;; Otherwise, move to START with attention to fields.
  5554. ;; (It is possible that fields never matter in this case.)
  5555. (constrain-to-field (point) orig
  5556. (/= arg 1) t nil)))))
  5557. ;; Many people have said they rarely use this feature, and often type
  5558. ;; it by accident. Maybe it shouldn't even be on a key.
  5559. (put 'set-goal-column 'disabled t)
  5560. (defun set-goal-column (arg)
  5561. "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
  5562. Those commands will move to this position in the line moved to
  5563. rather than trying to keep the same horizontal position.
  5564. With a non-nil argument ARG, clears out the goal column
  5565. so that \\[next-line] and \\[previous-line] resume vertical motion.
  5566. The goal column is stored in the variable `goal-column'."
  5567. (interactive "P")
  5568. (if arg
  5569. (progn
  5570. (setq goal-column nil)
  5571. (message "No goal column"))
  5572. (setq goal-column (current-column))
  5573. ;; The older method below can be erroneous if `set-goal-column' is bound
  5574. ;; to a sequence containing %
  5575. ;;(message (substitute-command-keys
  5576. ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
  5577. ;;goal-column)
  5578. (message "%s"
  5579. (concat
  5580. (format "Goal column %d " goal-column)
  5581. (substitute-command-keys
  5582. "(use \\[set-goal-column] with an arg to unset it)")))
  5583. )
  5584. nil)
  5585. ;;; Editing based on visual lines, as opposed to logical lines.
  5586. (defun end-of-visual-line (&optional n)
  5587. "Move point to end of current visual line.
  5588. With argument N not nil or 1, move forward N - 1 visual lines first.
  5589. If point reaches the beginning or end of buffer, it stops there.
  5590. To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
  5591. (interactive "^p")
  5592. (or n (setq n 1))
  5593. (if (/= n 1)
  5594. (let ((line-move-visual t))
  5595. (line-move (1- n) t)))
  5596. ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
  5597. ;; constrain to field boundaries, so we don't either.
  5598. (vertical-motion (cons (window-width) 0)))
  5599. (defun beginning-of-visual-line (&optional n)
  5600. "Move point to beginning of current visual line.
  5601. With argument N not nil or 1, move forward N - 1 visual lines first.
  5602. If point reaches the beginning or end of buffer, it stops there.
  5603. To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
  5604. (interactive "^p")
  5605. (or n (setq n 1))
  5606. (let ((opoint (point)))
  5607. (if (/= n 1)
  5608. (let ((line-move-visual t))
  5609. (line-move (1- n) t)))
  5610. (vertical-motion 0)
  5611. ;; Constrain to field boundaries, like `move-beginning-of-line'.
  5612. (goto-char (constrain-to-field (point) opoint (/= n 1)))))
  5613. (defun kill-visual-line (&optional arg)
  5614. "Kill the rest of the visual line.
  5615. With prefix argument ARG, kill that many visual lines from point.
  5616. If ARG is negative, kill visual lines backward.
  5617. If ARG is zero, kill the text before point on the current visual
  5618. line.
  5619. If you want to append the killed line to the last killed text,
  5620. use \\[append-next-kill] before \\[kill-line].
  5621. If the buffer is read-only, Emacs will beep and refrain from deleting
  5622. the line, but put the line in the kill ring anyway. This means that
  5623. you can use this command to copy text from a read-only buffer.
  5624. \(If the variable `kill-read-only-ok' is non-nil, then this won't
  5625. even beep.)"
  5626. (interactive "P")
  5627. ;; Like in `kill-line', it's better to move point to the other end
  5628. ;; of the kill before killing.
  5629. (let ((opoint (point))
  5630. (kill-whole-line (and kill-whole-line (bolp))))
  5631. (if arg
  5632. (vertical-motion (prefix-numeric-value arg))
  5633. (end-of-visual-line 1)
  5634. (if (= (point) opoint)
  5635. (vertical-motion 1)
  5636. ;; Skip any trailing whitespace at the end of the visual line.
  5637. ;; We used to do this only if `show-trailing-whitespace' is
  5638. ;; nil, but that's wrong; the correct thing would be to check
  5639. ;; whether the trailing whitespace is highlighted. But, it's
  5640. ;; OK to just do this unconditionally.
  5641. (skip-chars-forward " \t")))
  5642. (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
  5643. (1+ (point))
  5644. (point)))))
  5645. (defun next-logical-line (&optional arg try-vscroll)
  5646. "Move cursor vertically down ARG lines.
  5647. This is identical to `next-line', except that it always moves
  5648. by logical lines instead of visual lines, ignoring the value of
  5649. the variable `line-move-visual'."
  5650. (interactive "^p\np")
  5651. (let ((line-move-visual nil))
  5652. (with-no-warnings
  5653. (next-line arg try-vscroll))))
  5654. (defun previous-logical-line (&optional arg try-vscroll)
  5655. "Move cursor vertically up ARG lines.
  5656. This is identical to `previous-line', except that it always moves
  5657. by logical lines instead of visual lines, ignoring the value of
  5658. the variable `line-move-visual'."
  5659. (interactive "^p\np")
  5660. (let ((line-move-visual nil))
  5661. (with-no-warnings
  5662. (previous-line arg try-vscroll))))
  5663. (defgroup visual-line nil
  5664. "Editing based on visual lines."
  5665. :group 'convenience
  5666. :version "23.1")
  5667. (defvar visual-line-mode-map
  5668. (let ((map (make-sparse-keymap)))
  5669. (define-key map [remap kill-line] 'kill-visual-line)
  5670. (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
  5671. (define-key map [remap move-end-of-line] 'end-of-visual-line)
  5672. ;; These keybindings interfere with xterm function keys. Are
  5673. ;; there any other suitable bindings?
  5674. ;; (define-key map "\M-[" 'previous-logical-line)
  5675. ;; (define-key map "\M-]" 'next-logical-line)
  5676. map))
  5677. (defcustom visual-line-fringe-indicators '(nil nil)
  5678. "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
  5679. The value should be a list of the form (LEFT RIGHT), where LEFT
  5680. and RIGHT are symbols representing the bitmaps to display, to
  5681. indicate wrapped lines, in the left and right fringes respectively.
  5682. See also `fringe-indicator-alist'.
  5683. The default is not to display fringe indicators for wrapped lines.
  5684. This variable does not affect fringe indicators displayed for
  5685. other purposes."
  5686. :type '(list (choice (const :tag "Hide left indicator" nil)
  5687. (const :tag "Left curly arrow" left-curly-arrow)
  5688. (symbol :tag "Other bitmap"))
  5689. (choice (const :tag "Hide right indicator" nil)
  5690. (const :tag "Right curly arrow" right-curly-arrow)
  5691. (symbol :tag "Other bitmap")))
  5692. :set (lambda (symbol value)
  5693. (dolist (buf (buffer-list))
  5694. (with-current-buffer buf
  5695. (when (and (boundp 'visual-line-mode)
  5696. (symbol-value 'visual-line-mode))
  5697. (setq fringe-indicator-alist
  5698. (cons (cons 'continuation value)
  5699. (assq-delete-all
  5700. 'continuation
  5701. (copy-tree fringe-indicator-alist)))))))
  5702. (set-default symbol value)))
  5703. (defvar visual-line--saved-state nil)
  5704. (define-minor-mode visual-line-mode
  5705. "Toggle visual line based editing (Visual Line mode).
  5706. With a prefix argument ARG, enable Visual Line mode if ARG is
  5707. positive, and disable it otherwise. If called from Lisp, enable
  5708. the mode if ARG is omitted or nil.
  5709. When Visual Line mode is enabled, `word-wrap' is turned on in
  5710. this buffer, and simple editing commands are redefined to act on
  5711. visual lines, not logical lines. See Info node `Visual Line
  5712. Mode' for details."
  5713. :keymap visual-line-mode-map
  5714. :group 'visual-line
  5715. :lighter " Wrap"
  5716. (if visual-line-mode
  5717. (progn
  5718. (set (make-local-variable 'visual-line--saved-state) nil)
  5719. ;; Save the local values of some variables, to be restored if
  5720. ;; visual-line-mode is turned off.
  5721. (dolist (var '(line-move-visual truncate-lines
  5722. truncate-partial-width-windows
  5723. word-wrap fringe-indicator-alist))
  5724. (if (local-variable-p var)
  5725. (push (cons var (symbol-value var))
  5726. visual-line--saved-state)))
  5727. (set (make-local-variable 'line-move-visual) t)
  5728. (set (make-local-variable 'truncate-partial-width-windows) nil)
  5729. (setq truncate-lines nil
  5730. word-wrap t
  5731. fringe-indicator-alist
  5732. (cons (cons 'continuation visual-line-fringe-indicators)
  5733. fringe-indicator-alist)))
  5734. (kill-local-variable 'line-move-visual)
  5735. (kill-local-variable 'word-wrap)
  5736. (kill-local-variable 'truncate-lines)
  5737. (kill-local-variable 'truncate-partial-width-windows)
  5738. (kill-local-variable 'fringe-indicator-alist)
  5739. (dolist (saved visual-line--saved-state)
  5740. (set (make-local-variable (car saved)) (cdr saved)))
  5741. (kill-local-variable 'visual-line--saved-state)))
  5742. (defun turn-on-visual-line-mode ()
  5743. (visual-line-mode 1))
  5744. (define-globalized-minor-mode global-visual-line-mode
  5745. visual-line-mode turn-on-visual-line-mode)
  5746. (defun transpose-chars (arg)
  5747. "Interchange characters around point, moving forward one character.
  5748. With prefix arg ARG, effect is to take character before point
  5749. and drag it forward past ARG other characters (backward if ARG negative).
  5750. If no argument and at end of line, the previous two chars are exchanged."
  5751. (interactive "*P")
  5752. (when (and (null arg) (eolp) (not (bobp))
  5753. (not (get-text-property (1- (point)) 'read-only)))
  5754. (forward-char -1))
  5755. (transpose-subr 'forward-char (prefix-numeric-value arg)))
  5756. (defun transpose-words (arg)
  5757. "Interchange words around point, leaving point at end of them.
  5758. With prefix arg ARG, effect is to take word before or around point
  5759. and drag it forward past ARG other words (backward if ARG negative).
  5760. If ARG is zero, the words around or after point and around or after mark
  5761. are interchanged."
  5762. ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
  5763. (interactive "*p")
  5764. (transpose-subr 'forward-word arg))
  5765. (defun transpose-sexps (arg)
  5766. "Like \\[transpose-words] but applies to sexps.
  5767. Does not work on a sexp that point is in the middle of
  5768. if it is a list or string."
  5769. (interactive "*p")
  5770. (transpose-subr
  5771. (lambda (arg)
  5772. ;; Here we should try to simulate the behavior of
  5773. ;; (cons (progn (forward-sexp x) (point))
  5774. ;; (progn (forward-sexp (- x)) (point)))
  5775. ;; Except that we don't want to rely on the second forward-sexp
  5776. ;; putting us back to where we want to be, since forward-sexp-function
  5777. ;; might do funny things like infix-precedence.
  5778. (if (if (> arg 0)
  5779. (looking-at "\\sw\\|\\s_")
  5780. (and (not (bobp))
  5781. (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
  5782. ;; Jumping over a symbol. We might be inside it, mind you.
  5783. (progn (funcall (if (> arg 0)
  5784. 'skip-syntax-backward 'skip-syntax-forward)
  5785. "w_")
  5786. (cons (save-excursion (forward-sexp arg) (point)) (point)))
  5787. ;; Otherwise, we're between sexps. Take a step back before jumping
  5788. ;; to make sure we'll obey the same precedence no matter which direction
  5789. ;; we're going.
  5790. (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
  5791. (cons (save-excursion (forward-sexp arg) (point))
  5792. (progn (while (or (forward-comment (if (> arg 0) 1 -1))
  5793. (not (zerop (funcall (if (> arg 0)
  5794. 'skip-syntax-forward
  5795. 'skip-syntax-backward)
  5796. ".")))))
  5797. (point)))))
  5798. arg 'special))
  5799. (defun transpose-lines (arg)
  5800. "Exchange current line and previous line, leaving point after both.
  5801. With argument ARG, takes previous line and moves it past ARG lines.
  5802. With argument 0, interchanges line point is in with line mark is in."
  5803. (interactive "*p")
  5804. (transpose-subr (function
  5805. (lambda (arg)
  5806. (if (> arg 0)
  5807. (progn
  5808. ;; Move forward over ARG lines,
  5809. ;; but create newlines if necessary.
  5810. (setq arg (forward-line arg))
  5811. (if (/= (preceding-char) ?\n)
  5812. (setq arg (1+ arg)))
  5813. (if (> arg 0)
  5814. (newline arg)))
  5815. (forward-line arg))))
  5816. arg))
  5817. ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
  5818. ;; which seems inconsistent with the ARG /= 0 case.
  5819. ;; FIXME document SPECIAL.
  5820. (defun transpose-subr (mover arg &optional special)
  5821. "Subroutine to do the work of transposing objects.
  5822. Works for lines, sentences, paragraphs, etc. MOVER is a function that
  5823. moves forward by units of the given object (e.g. forward-sentence,
  5824. forward-paragraph). If ARG is zero, exchanges the current object
  5825. with the one containing mark. If ARG is an integer, moves the
  5826. current object past ARG following (if ARG is positive) or
  5827. preceding (if ARG is negative) objects, leaving point after the
  5828. current object."
  5829. (let ((aux (if special mover
  5830. (lambda (x)
  5831. (cons (progn (funcall mover x) (point))
  5832. (progn (funcall mover (- x)) (point))))))
  5833. pos1 pos2)
  5834. (cond
  5835. ((= arg 0)
  5836. (save-excursion
  5837. (setq pos1 (funcall aux 1))
  5838. (goto-char (or (mark) (error "No mark set in this buffer")))
  5839. (setq pos2 (funcall aux 1))
  5840. (transpose-subr-1 pos1 pos2))
  5841. (exchange-point-and-mark))
  5842. ((> arg 0)
  5843. (setq pos1 (funcall aux -1))
  5844. (setq pos2 (funcall aux arg))
  5845. (transpose-subr-1 pos1 pos2)
  5846. (goto-char (car pos2)))
  5847. (t
  5848. (setq pos1 (funcall aux -1))
  5849. (goto-char (car pos1))
  5850. (setq pos2 (funcall aux arg))
  5851. (transpose-subr-1 pos1 pos2)))))
  5852. (defun transpose-subr-1 (pos1 pos2)
  5853. (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
  5854. (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
  5855. (when (> (car pos1) (car pos2))
  5856. (let ((swap pos1))
  5857. (setq pos1 pos2 pos2 swap)))
  5858. (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
  5859. (atomic-change-group
  5860. ;; This sequence of insertions attempts to preserve marker
  5861. ;; positions at the start and end of the transposed objects.
  5862. (let* ((word (buffer-substring (car pos2) (cdr pos2)))
  5863. (len1 (- (cdr pos1) (car pos1)))
  5864. (len2 (length word))
  5865. (boundary (make-marker)))
  5866. (set-marker boundary (car pos2))
  5867. (goto-char (cdr pos1))
  5868. (insert-before-markers word)
  5869. (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
  5870. (goto-char boundary)
  5871. (insert word)
  5872. (goto-char (+ boundary len1))
  5873. (delete-region (point) (+ (point) len2))
  5874. (set-marker boundary nil))))
  5875. (defun backward-word (&optional arg)
  5876. "Move backward until encountering the beginning of a word.
  5877. With argument ARG, do this that many times.
  5878. If ARG is omitted or nil, move point backward one word."
  5879. (interactive "^p")
  5880. (forward-word (- (or arg 1))))
  5881. (defun mark-word (&optional arg allow-extend)
  5882. "Set mark ARG words away from point.
  5883. The place mark goes is the same place \\[forward-word] would
  5884. move to with the same argument.
  5885. Interactively, if this command is repeated
  5886. or (in Transient Mark mode) if the mark is active,
  5887. it marks the next ARG words after the ones already marked."
  5888. (interactive "P\np")
  5889. (cond ((and allow-extend
  5890. (or (and (eq last-command this-command) (mark t))
  5891. (region-active-p)))
  5892. (setq arg (if arg (prefix-numeric-value arg)
  5893. (if (< (mark) (point)) -1 1)))
  5894. (set-mark
  5895. (save-excursion
  5896. (goto-char (mark))
  5897. (forward-word arg)
  5898. (point))))
  5899. (t
  5900. (push-mark
  5901. (save-excursion
  5902. (forward-word (prefix-numeric-value arg))
  5903. (point))
  5904. nil t))))
  5905. (defun kill-word (arg)
  5906. "Kill characters forward until encountering the end of a word.
  5907. With argument ARG, do this that many times."
  5908. (interactive "p")
  5909. (kill-region (point) (progn (forward-word arg) (point))))
  5910. (defun backward-kill-word (arg)
  5911. "Kill characters backward until encountering the beginning of a word.
  5912. With argument ARG, do this that many times."
  5913. (interactive "p")
  5914. (kill-word (- arg)))
  5915. (defun current-word (&optional strict really-word)
  5916. "Return the symbol or word that point is on (or a nearby one) as a string.
  5917. The return value includes no text properties.
  5918. If optional arg STRICT is non-nil, return nil unless point is within
  5919. or adjacent to a symbol or word. In all cases the value can be nil
  5920. if there is no word nearby.
  5921. The function, belying its name, normally finds a symbol.
  5922. If optional arg REALLY-WORD is non-nil, it finds just a word."
  5923. (save-excursion
  5924. (let* ((oldpoint (point)) (start (point)) (end (point))
  5925. (syntaxes (if really-word "w" "w_"))
  5926. (not-syntaxes (concat "^" syntaxes)))
  5927. (skip-syntax-backward syntaxes) (setq start (point))
  5928. (goto-char oldpoint)
  5929. (skip-syntax-forward syntaxes) (setq end (point))
  5930. (when (and (eq start oldpoint) (eq end oldpoint)
  5931. ;; Point is neither within nor adjacent to a word.
  5932. (not strict))
  5933. ;; Look for preceding word in same line.
  5934. (skip-syntax-backward not-syntaxes (line-beginning-position))
  5935. (if (bolp)
  5936. ;; No preceding word in same line.
  5937. ;; Look for following word in same line.
  5938. (progn
  5939. (skip-syntax-forward not-syntaxes (line-end-position))
  5940. (setq start (point))
  5941. (skip-syntax-forward syntaxes)
  5942. (setq end (point)))
  5943. (setq end (point))
  5944. (skip-syntax-backward syntaxes)
  5945. (setq start (point))))
  5946. ;; If we found something nonempty, return it as a string.
  5947. (unless (= start end)
  5948. (buffer-substring-no-properties start end)))))
  5949. (defcustom fill-prefix nil
  5950. "String for filling to insert at front of new line, or nil for none."
  5951. :type '(choice (const :tag "None" nil)
  5952. string)
  5953. :group 'fill)
  5954. (make-variable-buffer-local 'fill-prefix)
  5955. (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
  5956. (defcustom auto-fill-inhibit-regexp nil
  5957. "Regexp to match lines which should not be auto-filled."
  5958. :type '(choice (const :tag "None" nil)
  5959. regexp)
  5960. :group 'fill)
  5961. (defun do-auto-fill ()
  5962. "The default value for `normal-auto-fill-function'.
  5963. This is the default auto-fill function, some major modes use a different one.
  5964. Returns t if it really did any work."
  5965. (let (fc justify give-up
  5966. (fill-prefix fill-prefix))
  5967. (if (or (not (setq justify (current-justification)))
  5968. (null (setq fc (current-fill-column)))
  5969. (and (eq justify 'left)
  5970. (<= (current-column) fc))
  5971. (and auto-fill-inhibit-regexp
  5972. (save-excursion (beginning-of-line)
  5973. (looking-at auto-fill-inhibit-regexp))))
  5974. nil ;; Auto-filling not required
  5975. (if (memq justify '(full center right))
  5976. (save-excursion (unjustify-current-line)))
  5977. ;; Choose a fill-prefix automatically.
  5978. (when (and adaptive-fill-mode
  5979. (or (null fill-prefix) (string= fill-prefix "")))
  5980. (let ((prefix
  5981. (fill-context-prefix
  5982. (save-excursion (fill-forward-paragraph -1) (point))
  5983. (save-excursion (fill-forward-paragraph 1) (point)))))
  5984. (and prefix (not (equal prefix ""))
  5985. ;; Use auto-indentation rather than a guessed empty prefix.
  5986. (not (and fill-indent-according-to-mode
  5987. (string-match "\\`[ \t]*\\'" prefix)))
  5988. (setq fill-prefix prefix))))
  5989. (while (and (not give-up) (> (current-column) fc))
  5990. ;; Determine where to split the line.
  5991. (let* (after-prefix
  5992. (fill-point
  5993. (save-excursion
  5994. (beginning-of-line)
  5995. (setq after-prefix (point))
  5996. (and fill-prefix
  5997. (looking-at (regexp-quote fill-prefix))
  5998. (setq after-prefix (match-end 0)))
  5999. (move-to-column (1+ fc))
  6000. (fill-move-to-break-point after-prefix)
  6001. (point))))
  6002. ;; See whether the place we found is any good.
  6003. (if (save-excursion
  6004. (goto-char fill-point)
  6005. (or (bolp)
  6006. ;; There is no use breaking at end of line.
  6007. (save-excursion (skip-chars-forward " ") (eolp))
  6008. ;; It is futile to split at the end of the prefix
  6009. ;; since we would just insert the prefix again.
  6010. (and after-prefix (<= (point) after-prefix))
  6011. ;; Don't split right after a comment starter
  6012. ;; since we would just make another comment starter.
  6013. (and comment-start-skip
  6014. (let ((limit (point)))
  6015. (beginning-of-line)
  6016. (and (re-search-forward comment-start-skip
  6017. limit t)
  6018. (eq (point) limit))))))
  6019. ;; No good place to break => stop trying.
  6020. (setq give-up t)
  6021. ;; Ok, we have a useful place to break the line. Do it.
  6022. (let ((prev-column (current-column)))
  6023. ;; If point is at the fill-point, do not `save-excursion'.
  6024. ;; Otherwise, if a comment prefix or fill-prefix is inserted,
  6025. ;; point will end up before it rather than after it.
  6026. (if (save-excursion
  6027. (skip-chars-backward " \t")
  6028. (= (point) fill-point))
  6029. (default-indent-new-line t)
  6030. (save-excursion
  6031. (goto-char fill-point)
  6032. (default-indent-new-line t)))
  6033. ;; Now do justification, if required
  6034. (if (not (eq justify 'left))
  6035. (save-excursion
  6036. (end-of-line 0)
  6037. (justify-current-line justify nil t)))
  6038. ;; If making the new line didn't reduce the hpos of
  6039. ;; the end of the line, then give up now;
  6040. ;; trying again will not help.
  6041. (if (>= (current-column) prev-column)
  6042. (setq give-up t))))))
  6043. ;; Justify last line.
  6044. (justify-current-line justify t t)
  6045. t)))
  6046. (defvar comment-line-break-function 'comment-indent-new-line
  6047. "Mode-specific function which line breaks and continues a comment.
  6048. This function is called during auto-filling when a comment syntax
  6049. is defined.
  6050. The function should take a single optional argument, which is a flag
  6051. indicating whether it should use soft newlines.")
  6052. (defun default-indent-new-line (&optional soft)
  6053. "Break line at point and indent.
  6054. If a comment syntax is defined, call `comment-indent-new-line'.
  6055. The inserted newline is marked hard if variable `use-hard-newlines' is true,
  6056. unless optional argument SOFT is non-nil."
  6057. (interactive)
  6058. (if comment-start
  6059. (funcall comment-line-break-function soft)
  6060. ;; Insert the newline before removing empty space so that markers
  6061. ;; get preserved better.
  6062. (if soft (insert-and-inherit ?\n) (newline 1))
  6063. (save-excursion (forward-char -1) (delete-horizontal-space))
  6064. (delete-horizontal-space)
  6065. (if (and fill-prefix (not adaptive-fill-mode))
  6066. ;; Blindly trust a non-adaptive fill-prefix.
  6067. (progn
  6068. (indent-to-left-margin)
  6069. (insert-before-markers-and-inherit fill-prefix))
  6070. (cond
  6071. ;; If there's an adaptive prefix, use it unless we're inside
  6072. ;; a comment and the prefix is not a comment starter.
  6073. (fill-prefix
  6074. (indent-to-left-margin)
  6075. (insert-and-inherit fill-prefix))
  6076. ;; If we're not inside a comment, just try to indent.
  6077. (t (indent-according-to-mode))))))
  6078. (defvar normal-auto-fill-function 'do-auto-fill
  6079. "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
  6080. Some major modes set this.")
  6081. (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
  6082. ;; `functions' and `hooks' are usually unsafe to set, but setting
  6083. ;; auto-fill-function to nil in a file-local setting is safe and
  6084. ;; can be useful to prevent auto-filling.
  6085. (put 'auto-fill-function 'safe-local-variable 'null)
  6086. (define-minor-mode auto-fill-mode
  6087. "Toggle automatic line breaking (Auto Fill mode).
  6088. With a prefix argument ARG, enable Auto Fill mode if ARG is
  6089. positive, and disable it otherwise. If called from Lisp, enable
  6090. the mode if ARG is omitted or nil.
  6091. When Auto Fill mode is enabled, inserting a space at a column
  6092. beyond `current-fill-column' automatically breaks the line at a
  6093. previous space.
  6094. When `auto-fill-mode' is on, the `auto-fill-function' variable is
  6095. non-nil.
  6096. The value of `normal-auto-fill-function' specifies the function to use
  6097. for `auto-fill-function' when turning Auto Fill mode on."
  6098. :variable (auto-fill-function
  6099. . (lambda (v) (setq auto-fill-function
  6100. (if v normal-auto-fill-function)))))
  6101. ;; This holds a document string used to document auto-fill-mode.
  6102. (defun auto-fill-function ()
  6103. "Automatically break line at a previous space, in insertion of text."
  6104. nil)
  6105. (defun turn-on-auto-fill ()
  6106. "Unconditionally turn on Auto Fill mode."
  6107. (auto-fill-mode 1))
  6108. (defun turn-off-auto-fill ()
  6109. "Unconditionally turn off Auto Fill mode."
  6110. (auto-fill-mode -1))
  6111. (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
  6112. (defun set-fill-column (arg)
  6113. "Set `fill-column' to specified argument.
  6114. Use \\[universal-argument] followed by a number to specify a column.
  6115. Just \\[universal-argument] as argument means to use the current column."
  6116. (interactive
  6117. (list (or current-prefix-arg
  6118. ;; We used to use current-column silently, but C-x f is too easily
  6119. ;; typed as a typo for C-x C-f, so we turned it into an error and
  6120. ;; now an interactive prompt.
  6121. (read-number "Set fill-column to: " (current-column)))))
  6122. (if (consp arg)
  6123. (setq arg (current-column)))
  6124. (if (not (integerp arg))
  6125. ;; Disallow missing argument; it's probably a typo for C-x C-f.
  6126. (error "set-fill-column requires an explicit argument")
  6127. (message "Fill column set to %d (was %d)" arg fill-column)
  6128. (setq fill-column arg)))
  6129. (defun set-selective-display (arg)
  6130. "Set `selective-display' to ARG; clear it if no arg.
  6131. When the value of `selective-display' is a number > 0,
  6132. lines whose indentation is >= that value are not displayed.
  6133. The variable `selective-display' has a separate value for each buffer."
  6134. (interactive "P")
  6135. (if (eq selective-display t)
  6136. (error "selective-display already in use for marked lines"))
  6137. (let ((current-vpos
  6138. (save-restriction
  6139. (narrow-to-region (point-min) (point))
  6140. (goto-char (window-start))
  6141. (vertical-motion (window-height)))))
  6142. (setq selective-display
  6143. (and arg (prefix-numeric-value arg)))
  6144. (recenter current-vpos))
  6145. (set-window-start (selected-window) (window-start))
  6146. (princ "selective-display set to " t)
  6147. (prin1 selective-display t)
  6148. (princ "." t))
  6149. (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
  6150. (defun toggle-truncate-lines (&optional arg)
  6151. "Toggle truncating of long lines for the current buffer.
  6152. When truncating is off, long lines are folded.
  6153. With prefix argument ARG, truncate long lines if ARG is positive,
  6154. otherwise fold them. Note that in side-by-side windows, this
  6155. command has no effect if `truncate-partial-width-windows' is
  6156. non-nil."
  6157. (interactive "P")
  6158. (setq truncate-lines
  6159. (if (null arg)
  6160. (not truncate-lines)
  6161. (> (prefix-numeric-value arg) 0)))
  6162. (force-mode-line-update)
  6163. (unless truncate-lines
  6164. (let ((buffer (current-buffer)))
  6165. (walk-windows (lambda (window)
  6166. (if (eq buffer (window-buffer window))
  6167. (set-window-hscroll window 0)))
  6168. nil t)))
  6169. (message "Truncate long lines %s"
  6170. (if truncate-lines "enabled" "disabled")))
  6171. (defun toggle-word-wrap (&optional arg)
  6172. "Toggle whether to use word-wrapping for continuation lines.
  6173. With prefix argument ARG, wrap continuation lines at word boundaries
  6174. if ARG is positive, otherwise wrap them at the right screen edge.
  6175. This command toggles the value of `word-wrap'. It has no effect
  6176. if long lines are truncated."
  6177. (interactive "P")
  6178. (setq word-wrap
  6179. (if (null arg)
  6180. (not word-wrap)
  6181. (> (prefix-numeric-value arg) 0)))
  6182. (force-mode-line-update)
  6183. (message "Word wrapping %s"
  6184. (if word-wrap "enabled" "disabled")))
  6185. (defvar overwrite-mode-textual (purecopy " Ovwrt")
  6186. "The string displayed in the mode line when in overwrite mode.")
  6187. (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
  6188. "The string displayed in the mode line when in binary overwrite mode.")
  6189. (define-minor-mode overwrite-mode
  6190. "Toggle Overwrite mode.
  6191. With a prefix argument ARG, enable Overwrite mode if ARG is
  6192. positive, and disable it otherwise. If called from Lisp, enable
  6193. the mode if ARG is omitted or nil.
  6194. When Overwrite mode is enabled, printing characters typed in
  6195. replace existing text on a one-for-one basis, rather than pushing
  6196. it to the right. At the end of a line, such characters extend
  6197. the line. Before a tab, such characters insert until the tab is
  6198. filled in. \\[quoted-insert] still inserts characters in
  6199. overwrite mode; this is supposed to make it easier to insert
  6200. characters when necessary."
  6201. :variable (overwrite-mode
  6202. . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
  6203. (define-minor-mode binary-overwrite-mode
  6204. "Toggle Binary Overwrite mode.
  6205. With a prefix argument ARG, enable Binary Overwrite mode if ARG
  6206. is positive, and disable it otherwise. If called from Lisp,
  6207. enable the mode if ARG is omitted or nil.
  6208. When Binary Overwrite mode is enabled, printing characters typed
  6209. in replace existing text. Newlines are not treated specially, so
  6210. typing at the end of a line joins the line to the next, with the
  6211. typed character between them. Typing before a tab character
  6212. simply replaces the tab with the character typed.
  6213. \\[quoted-insert] replaces the text at the cursor, just as
  6214. ordinary typing characters do.
  6215. Note that Binary Overwrite mode is not its own minor mode; it is
  6216. a specialization of overwrite mode, entered by setting the
  6217. `overwrite-mode' variable to `overwrite-mode-binary'."
  6218. :variable (overwrite-mode
  6219. . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
  6220. (define-minor-mode line-number-mode
  6221. "Toggle line number display in the mode line (Line Number mode).
  6222. With a prefix argument ARG, enable Line Number mode if ARG is
  6223. positive, and disable it otherwise. If called from Lisp, enable
  6224. the mode if ARG is omitted or nil.
  6225. Line numbers do not appear for very large buffers and buffers
  6226. with very long lines; see variables `line-number-display-limit'
  6227. and `line-number-display-limit-width'."
  6228. :init-value t :global t :group 'mode-line)
  6229. (define-minor-mode column-number-mode
  6230. "Toggle column number display in the mode line (Column Number mode).
  6231. With a prefix argument ARG, enable Column Number mode if ARG is
  6232. positive, and disable it otherwise.
  6233. If called from Lisp, enable the mode if ARG is omitted or nil."
  6234. :global t :group 'mode-line)
  6235. (define-minor-mode size-indication-mode
  6236. "Toggle buffer size display in the mode line (Size Indication mode).
  6237. With a prefix argument ARG, enable Size Indication mode if ARG is
  6238. positive, and disable it otherwise.
  6239. If called from Lisp, enable the mode if ARG is omitted or nil."
  6240. :global t :group 'mode-line)
  6241. (define-minor-mode auto-save-mode
  6242. "Toggle auto-saving in the current buffer (Auto Save mode).
  6243. With a prefix argument ARG, enable Auto Save mode if ARG is
  6244. positive, and disable it otherwise.
  6245. If called from Lisp, enable the mode if ARG is omitted or nil."
  6246. :variable ((and buffer-auto-save-file-name
  6247. ;; If auto-save is off because buffer has shrunk,
  6248. ;; then toggling should turn it on.
  6249. (>= buffer-saved-size 0))
  6250. . (lambda (val)
  6251. (setq buffer-auto-save-file-name
  6252. (cond
  6253. ((null val) nil)
  6254. ((and buffer-file-name auto-save-visited-file-name
  6255. (not buffer-read-only))
  6256. buffer-file-name)
  6257. (t (make-auto-save-file-name))))))
  6258. ;; If -1 was stored here, to temporarily turn off saving,
  6259. ;; turn it back on.
  6260. (and (< buffer-saved-size 0)
  6261. (setq buffer-saved-size 0)))
  6262. (defgroup paren-blinking nil
  6263. "Blinking matching of parens and expressions."
  6264. :prefix "blink-matching-"
  6265. :group 'paren-matching)
  6266. (defcustom blink-matching-paren t
  6267. "Non-nil means show matching open-paren when close-paren is inserted.
  6268. If t, highlight the paren. If `jump', briefly move cursor to its
  6269. position. If `jump-offscreen', move cursor there even if the
  6270. position is off screen. With any other non-nil value, the
  6271. off-screen position of the opening paren will be shown in the
  6272. echo area."
  6273. :type '(choice
  6274. (const :tag "Disable" nil)
  6275. (const :tag "Highlight" t)
  6276. (const :tag "Move cursor" jump)
  6277. (const :tag "Move cursor, even if off screen" jump-offscreen))
  6278. :group 'paren-blinking)
  6279. (defcustom blink-matching-paren-on-screen t
  6280. "Non-nil means show matching open-paren when it is on screen.
  6281. If nil, don't show it (but the open-paren can still be shown
  6282. in the echo area when it is off screen).
  6283. This variable has no effect if `blink-matching-paren' is nil.
  6284. \(In that case, the open-paren is never shown.)
  6285. It is also ignored if `show-paren-mode' is enabled."
  6286. :type 'boolean
  6287. :group 'paren-blinking)
  6288. (defcustom blink-matching-paren-distance (* 100 1024)
  6289. "If non-nil, maximum distance to search backwards for matching open-paren.
  6290. If nil, search stops at the beginning of the accessible portion of the buffer."
  6291. :version "23.2" ; 25->100k
  6292. :type '(choice (const nil) integer)
  6293. :group 'paren-blinking)
  6294. (defcustom blink-matching-delay 1
  6295. "Time in seconds to delay after showing a matching paren."
  6296. :type 'number
  6297. :group 'paren-blinking)
  6298. (defcustom blink-matching-paren-dont-ignore-comments nil
  6299. "If nil, `blink-matching-paren' ignores comments.
  6300. More precisely, when looking for the matching parenthesis,
  6301. it skips the contents of comments that end before point."
  6302. :type 'boolean
  6303. :group 'paren-blinking)
  6304. (defun blink-matching-check-mismatch (start end)
  6305. "Return whether or not START...END are matching parens.
  6306. END is the current point and START is the blink position.
  6307. START might be nil if no matching starter was found.
  6308. Returns non-nil if we find there is a mismatch."
  6309. (let* ((end-syntax (syntax-after (1- end)))
  6310. (matching-paren (and (consp end-syntax)
  6311. (eq (syntax-class end-syntax) 5)
  6312. (cdr end-syntax))))
  6313. ;; For self-matched chars like " and $, we can't know when they're
  6314. ;; mismatched or unmatched, so we can only do it for parens.
  6315. (when matching-paren
  6316. (not (and start
  6317. (or
  6318. (eq (char-after start) matching-paren)
  6319. ;; The cdr might hold a new paren-class info rather than
  6320. ;; a matching-char info, in which case the two CDRs
  6321. ;; should match.
  6322. (eq matching-paren (cdr-safe (syntax-after start)))))))))
  6323. (defvar blink-matching-check-function #'blink-matching-check-mismatch
  6324. "Function to check parentheses mismatches.
  6325. The function takes two arguments (START and END) where START is the
  6326. position just before the opening token and END is the position right after.
  6327. START can be nil, if it was not found.
  6328. The function should return non-nil if the two tokens do not match.")
  6329. (defvar blink-matching--overlay
  6330. (let ((ol (make-overlay (point) (point) nil t)))
  6331. (overlay-put ol 'face 'show-paren-match)
  6332. (delete-overlay ol)
  6333. ol)
  6334. "Overlay used to highlight the matching paren.")
  6335. (defun blink-matching-open ()
  6336. "Momentarily highlight the beginning of the sexp before point."
  6337. (interactive)
  6338. (when (and (not (bobp))
  6339. blink-matching-paren)
  6340. (let* ((oldpos (point))
  6341. (message-log-max nil) ; Don't log messages about paren matching.
  6342. (blinkpos
  6343. (save-excursion
  6344. (save-restriction
  6345. (if blink-matching-paren-distance
  6346. (narrow-to-region
  6347. (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
  6348. (- (point) blink-matching-paren-distance))
  6349. oldpos))
  6350. (let ((parse-sexp-ignore-comments
  6351. (and parse-sexp-ignore-comments
  6352. (not blink-matching-paren-dont-ignore-comments))))
  6353. (condition-case ()
  6354. (progn
  6355. (syntax-propertize (point))
  6356. (forward-sexp -1)
  6357. ;; backward-sexp skips backward over prefix chars,
  6358. ;; so move back to the matching paren.
  6359. (while (and (< (point) (1- oldpos))
  6360. (let ((code (syntax-after (point))))
  6361. (or (eq (syntax-class code) 6)
  6362. (eq (logand 1048576 (car code))
  6363. 1048576))))
  6364. (forward-char 1))
  6365. (point))
  6366. (error nil))))))
  6367. (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
  6368. (cond
  6369. (mismatch
  6370. (if blinkpos
  6371. (if (minibufferp)
  6372. (minibuffer-message "Mismatched parentheses")
  6373. (message "Mismatched parentheses"))
  6374. (if (minibufferp)
  6375. (minibuffer-message "No matching parenthesis found")
  6376. (message "No matching parenthesis found"))))
  6377. ((not blinkpos) nil)
  6378. ((or
  6379. (eq blink-matching-paren 'jump-offscreen)
  6380. (pos-visible-in-window-p blinkpos))
  6381. ;; Matching open within window, temporarily move to or highlight
  6382. ;; char after blinkpos but only if `blink-matching-paren-on-screen'
  6383. ;; is non-nil.
  6384. (and blink-matching-paren-on-screen
  6385. (not show-paren-mode)
  6386. (if (memq blink-matching-paren '(jump jump-offscreen))
  6387. (save-excursion
  6388. (goto-char blinkpos)
  6389. (sit-for blink-matching-delay))
  6390. (unwind-protect
  6391. (progn
  6392. (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
  6393. (current-buffer))
  6394. (sit-for blink-matching-delay))
  6395. (delete-overlay blink-matching--overlay)))))
  6396. (t
  6397. (let ((open-paren-line-string
  6398. (save-excursion
  6399. (goto-char blinkpos)
  6400. ;; Show what precedes the open in its line, if anything.
  6401. (cond
  6402. ((save-excursion (skip-chars-backward " \t") (not (bolp)))
  6403. (buffer-substring (line-beginning-position)
  6404. (1+ blinkpos)))
  6405. ;; Show what follows the open in its line, if anything.
  6406. ((save-excursion
  6407. (forward-char 1)
  6408. (skip-chars-forward " \t")
  6409. (not (eolp)))
  6410. (buffer-substring blinkpos
  6411. (line-end-position)))
  6412. ;; Otherwise show the previous nonblank line,
  6413. ;; if there is one.
  6414. ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
  6415. (concat
  6416. (buffer-substring (progn
  6417. (skip-chars-backward "\n \t")
  6418. (line-beginning-position))
  6419. (progn (end-of-line)
  6420. (skip-chars-backward " \t")
  6421. (point)))
  6422. ;; Replace the newline and other whitespace with `...'.
  6423. "..."
  6424. (buffer-substring blinkpos (1+ blinkpos))))
  6425. ;; There is nothing to show except the char itself.
  6426. (t (buffer-substring blinkpos (1+ blinkpos)))))))
  6427. (minibuffer-message
  6428. "Matches %s"
  6429. (substring-no-properties open-paren-line-string))))))))
  6430. (defvar blink-paren-function 'blink-matching-open
  6431. "Function called, if non-nil, whenever a close parenthesis is inserted.
  6432. More precisely, a char with closeparen syntax is self-inserted.")
  6433. (defun blink-paren-post-self-insert-function ()
  6434. (when (and (eq (char-before) last-command-event) ; Sanity check.
  6435. (memq (char-syntax last-command-event) '(?\) ?\$))
  6436. blink-paren-function
  6437. (not executing-kbd-macro)
  6438. (not noninteractive)
  6439. ;; Verify an even number of quoting characters precede the close.
  6440. ;; FIXME: Also check if this parenthesis closes a comment as
  6441. ;; can happen in Pascal and SML.
  6442. (= 1 (logand 1 (- (point)
  6443. (save-excursion
  6444. (forward-char -1)
  6445. (skip-syntax-backward "/\\")
  6446. (point))))))
  6447. (funcall blink-paren-function)))
  6448. (put 'blink-paren-post-self-insert-function 'priority 100)
  6449. (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
  6450. ;; Most likely, this hook is nil, so this arg doesn't matter,
  6451. ;; but I use it as a reminder that this function usually
  6452. ;; likes to be run after others since it does
  6453. ;; `sit-for'. That's also the reason it get a `priority' prop
  6454. ;; of 100.
  6455. 'append)
  6456. ;; This executes C-g typed while Emacs is waiting for a command.
  6457. ;; Quitting out of a program does not go through here;
  6458. ;; that happens in the QUIT macro at the C code level.
  6459. (defun keyboard-quit ()
  6460. "Signal a `quit' condition.
  6461. During execution of Lisp code, this character causes a quit directly.
  6462. At top-level, as an editor command, this simply beeps."
  6463. (interactive)
  6464. ;; Avoid adding the region to the window selection.
  6465. (setq saved-region-selection nil)
  6466. (let (select-active-regions)
  6467. (deactivate-mark))
  6468. (if (fboundp 'kmacro-keyboard-quit)
  6469. (kmacro-keyboard-quit))
  6470. (when completion-in-region-mode
  6471. (completion-in-region-mode -1))
  6472. ;; Force the next redisplay cycle to remove the "Def" indicator from
  6473. ;; all the mode lines.
  6474. (if defining-kbd-macro
  6475. (force-mode-line-update t))
  6476. (setq defining-kbd-macro nil)
  6477. (let ((debug-on-quit nil))
  6478. (signal 'quit nil)))
  6479. (defvar buffer-quit-function nil
  6480. "Function to call to \"quit\" the current buffer, or nil if none.
  6481. \\[keyboard-escape-quit] calls this function when its more local actions
  6482. \(such as canceling a prefix argument, minibuffer or region) do not apply.")
  6483. (defun keyboard-escape-quit ()
  6484. "Exit the current \"mode\" (in a generalized sense of the word).
  6485. This command can exit an interactive command such as `query-replace',
  6486. can clear out a prefix argument or a region,
  6487. can get out of the minibuffer or other recursive edit,
  6488. cancel the use of the current buffer (for special-purpose buffers),
  6489. or go back to just one window (by deleting all but the selected window)."
  6490. (interactive)
  6491. (cond ((eq last-command 'mode-exited) nil)
  6492. ((region-active-p)
  6493. (deactivate-mark))
  6494. ((> (minibuffer-depth) 0)
  6495. (abort-recursive-edit))
  6496. (current-prefix-arg
  6497. nil)
  6498. ((> (recursion-depth) 0)
  6499. (exit-recursive-edit))
  6500. (buffer-quit-function
  6501. (funcall buffer-quit-function))
  6502. ((not (one-window-p t))
  6503. (delete-other-windows))
  6504. ((string-match "^ \\*" (buffer-name (current-buffer)))
  6505. (bury-buffer))))
  6506. (defun play-sound-file (file &optional volume device)
  6507. "Play sound stored in FILE.
  6508. VOLUME and DEVICE correspond to the keywords of the sound
  6509. specification for `play-sound'."
  6510. (interactive "fPlay sound file: ")
  6511. (let ((sound (list :file file)))
  6512. (if volume
  6513. (plist-put sound :volume volume))
  6514. (if device
  6515. (plist-put sound :device device))
  6516. (push 'sound sound)
  6517. (play-sound sound)))
  6518. (defcustom read-mail-command 'rmail
  6519. "Your preference for a mail reading package.
  6520. This is used by some keybindings which support reading mail.
  6521. See also `mail-user-agent' concerning sending mail."
  6522. :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
  6523. (function-item :tag "Gnus" :format "%t\n" gnus)
  6524. (function-item :tag "Emacs interface to MH"
  6525. :format "%t\n" mh-rmail)
  6526. (function :tag "Other"))
  6527. :version "21.1"
  6528. :group 'mail)
  6529. (defcustom mail-user-agent 'message-user-agent
  6530. "Your preference for a mail composition package.
  6531. Various Emacs Lisp packages (e.g. Reporter) require you to compose an
  6532. outgoing email message. This variable lets you specify which
  6533. mail-sending package you prefer.
  6534. Valid values include:
  6535. `message-user-agent' -- use the Message package.
  6536. See Info node `(message)'.
  6537. `sendmail-user-agent' -- use the Mail package.
  6538. See Info node `(emacs)Sending Mail'.
  6539. `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
  6540. See Info node `(mh-e)'.
  6541. `gnus-user-agent' -- like `message-user-agent', but with Gnus
  6542. paraphernalia if Gnus is running, particularly
  6543. the Gcc: header for archiving.
  6544. Additional valid symbols may be available; check with the author of
  6545. your package for details. The function should return non-nil if it
  6546. succeeds.
  6547. See also `read-mail-command' concerning reading mail."
  6548. :type '(radio (function-item :tag "Message package"
  6549. :format "%t\n"
  6550. message-user-agent)
  6551. (function-item :tag "Mail package"
  6552. :format "%t\n"
  6553. sendmail-user-agent)
  6554. (function-item :tag "Emacs interface to MH"
  6555. :format "%t\n"
  6556. mh-e-user-agent)
  6557. (function-item :tag "Message with full Gnus features"
  6558. :format "%t\n"
  6559. gnus-user-agent)
  6560. (function :tag "Other"))
  6561. :version "23.2" ; sendmail->message
  6562. :group 'mail)
  6563. (defcustom compose-mail-user-agent-warnings t
  6564. "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
  6565. If the value of `mail-user-agent' is the default, and the user
  6566. appears to have customizations applying to the old default,
  6567. `compose-mail' issues a warning."
  6568. :type 'boolean
  6569. :version "23.2"
  6570. :group 'mail)
  6571. (defun rfc822-goto-eoh ()
  6572. "If the buffer starts with a mail header, move point to the header's end.
  6573. Otherwise, moves to `point-min'.
  6574. The end of the header is the start of the next line, if there is one,
  6575. else the end of the last line. This function obeys RFC822."
  6576. (goto-char (point-min))
  6577. (when (re-search-forward
  6578. "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
  6579. (goto-char (match-beginning 0))))
  6580. ;; Used by Rmail (e.g., rmail-forward).
  6581. (defvar mail-encode-mml nil
  6582. "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
  6583. the outgoing message before sending it.")
  6584. (defun compose-mail (&optional to subject other-headers continue
  6585. switch-function yank-action send-actions
  6586. return-action)
  6587. "Start composing a mail message to send.
  6588. This uses the user's chosen mail composition package
  6589. as selected with the variable `mail-user-agent'.
  6590. The optional arguments TO and SUBJECT specify recipients
  6591. and the initial Subject field, respectively.
  6592. OTHER-HEADERS is an alist specifying additional
  6593. header fields. Elements look like (HEADER . VALUE) where both
  6594. HEADER and VALUE are strings.
  6595. CONTINUE, if non-nil, says to continue editing a message already
  6596. being composed. Interactively, CONTINUE is the prefix argument.
  6597. SWITCH-FUNCTION, if non-nil, is a function to use to
  6598. switch to and display the buffer used for mail composition.
  6599. YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
  6600. to insert the raw text of the message being replied to.
  6601. It has the form (FUNCTION . ARGS). The user agent will apply
  6602. FUNCTION to ARGS, to insert the raw text of the original message.
  6603. \(The user agent will also run `mail-citation-hook', *after* the
  6604. original text has been inserted in this way.)
  6605. SEND-ACTIONS is a list of actions to call when the message is sent.
  6606. Each action has the form (FUNCTION . ARGS).
  6607. RETURN-ACTION, if non-nil, is an action for returning to the
  6608. caller. It has the form (FUNCTION . ARGS). The function is
  6609. called after the mail has been sent or put aside, and the mail
  6610. buffer buried."
  6611. (interactive
  6612. (list nil nil nil current-prefix-arg))
  6613. ;; In Emacs 23.2, the default value of `mail-user-agent' changed
  6614. ;; from sendmail-user-agent to message-user-agent. Some users may
  6615. ;; encounter incompatibilities. This hack tries to detect problems
  6616. ;; and warn about them.
  6617. (and compose-mail-user-agent-warnings
  6618. (eq mail-user-agent 'message-user-agent)
  6619. (let (warn-vars)
  6620. (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
  6621. mail-yank-hooks mail-archive-file-name
  6622. mail-default-reply-to mail-mailing-lists
  6623. mail-self-blind))
  6624. (and (boundp var)
  6625. (symbol-value var)
  6626. (push var warn-vars)))
  6627. (when warn-vars
  6628. (display-warning 'mail
  6629. (format "\
  6630. The default mail mode is now Message mode.
  6631. You have the following Mail mode variable%s customized:
  6632. \n %s\n\nTo use Mail mode, set ‘mail-user-agent’ to sendmail-user-agent.
  6633. To disable this warning, set ‘compose-mail-user-agent-warnings’ to nil."
  6634. (if (> (length warn-vars) 1) "s" "")
  6635. (mapconcat 'symbol-name
  6636. warn-vars " "))))))
  6637. (let ((function (get mail-user-agent 'composefunc)))
  6638. (funcall function to subject other-headers continue switch-function
  6639. yank-action send-actions return-action)))
  6640. (defun compose-mail-other-window (&optional to subject other-headers continue
  6641. yank-action send-actions
  6642. return-action)
  6643. "Like \\[compose-mail], but edit the outgoing message in another window."
  6644. (interactive (list nil nil nil current-prefix-arg))
  6645. (compose-mail to subject other-headers continue
  6646. 'switch-to-buffer-other-window yank-action send-actions
  6647. return-action))
  6648. (defun compose-mail-other-frame (&optional to subject other-headers continue
  6649. yank-action send-actions
  6650. return-action)
  6651. "Like \\[compose-mail], but edit the outgoing message in another frame."
  6652. (interactive (list nil nil nil current-prefix-arg))
  6653. (compose-mail to subject other-headers continue
  6654. 'switch-to-buffer-other-frame yank-action send-actions
  6655. return-action))
  6656. (defvar set-variable-value-history nil
  6657. "History of values entered with `set-variable'.
  6658. Maximum length of the history list is determined by the value
  6659. of `history-length', which see.")
  6660. (defun set-variable (variable value &optional make-local)
  6661. "Set VARIABLE to VALUE. VALUE is a Lisp object.
  6662. VARIABLE should be a user option variable name, a Lisp variable
  6663. meant to be customized by users. You should enter VALUE in Lisp syntax,
  6664. so if you want VALUE to be a string, you must surround it with doublequotes.
  6665. VALUE is used literally, not evaluated.
  6666. If VARIABLE has a `variable-interactive' property, that is used as if
  6667. it were the arg to `interactive' (which see) to interactively read VALUE.
  6668. If VARIABLE has been defined with `defcustom', then the type information
  6669. in the definition is used to check that VALUE is valid.
  6670. Note that this function is at heart equivalent to the basic `set' function.
  6671. For a variable defined with `defcustom', it does not pay attention to
  6672. any :set property that the variable might have (if you want that, use
  6673. \\[customize-set-variable] instead).
  6674. With a prefix argument, set VARIABLE to VALUE buffer-locally."
  6675. (interactive
  6676. (let* ((default-var (variable-at-point))
  6677. (var (if (custom-variable-p default-var)
  6678. (read-variable (format "Set variable (default %s): " default-var)
  6679. default-var)
  6680. (read-variable "Set variable: ")))
  6681. (minibuffer-help-form '(describe-variable var))
  6682. (prop (get var 'variable-interactive))
  6683. (obsolete (car (get var 'byte-obsolete-variable)))
  6684. (prompt (format "Set %s %s to value: " var
  6685. (cond ((local-variable-p var)
  6686. "(buffer-local)")
  6687. ((or current-prefix-arg
  6688. (local-variable-if-set-p var))
  6689. "buffer-locally")
  6690. (t "globally"))))
  6691. (val (progn
  6692. (when obsolete
  6693. (message (concat "‘%S’ is obsolete; "
  6694. (if (symbolp obsolete) "use ‘%S’ instead" "%s"))
  6695. var obsolete)
  6696. (sit-for 3))
  6697. (if prop
  6698. ;; Use VAR's `variable-interactive' property
  6699. ;; as an interactive spec for prompting.
  6700. (call-interactively `(lambda (arg)
  6701. (interactive ,prop)
  6702. arg))
  6703. (read-from-minibuffer prompt nil
  6704. read-expression-map t
  6705. 'set-variable-value-history
  6706. (format "%S" (symbol-value var)))))))
  6707. (list var val current-prefix-arg)))
  6708. (and (custom-variable-p variable)
  6709. (not (get variable 'custom-type))
  6710. (custom-load-symbol variable))
  6711. (let ((type (get variable 'custom-type)))
  6712. (when type
  6713. ;; Match with custom type.
  6714. (require 'cus-edit)
  6715. (setq type (widget-convert type))
  6716. (unless (widget-apply type :match value)
  6717. (user-error "Value ‘%S’ does not match type %S of %S"
  6718. value (car type) variable))))
  6719. (if make-local
  6720. (make-local-variable variable))
  6721. (set variable value)
  6722. ;; Force a thorough redisplay for the case that the variable
  6723. ;; has an effect on the display, like `tab-width' has.
  6724. (force-mode-line-update))
  6725. ;; Define the major mode for lists of completions.
  6726. (defvar completion-list-mode-map
  6727. (let ((map (make-sparse-keymap)))
  6728. (define-key map [mouse-2] 'choose-completion)
  6729. (define-key map [follow-link] 'mouse-face)
  6730. (define-key map [down-mouse-2] nil)
  6731. (define-key map "\C-m" 'choose-completion)
  6732. (define-key map "\e\e\e" 'delete-completion-window)
  6733. (define-key map [left] 'previous-completion)
  6734. (define-key map [right] 'next-completion)
  6735. (define-key map [?\t] 'next-completion)
  6736. (define-key map [backtab] 'previous-completion)
  6737. (define-key map "q" 'quit-window)
  6738. (define-key map "z" 'kill-this-buffer)
  6739. map)
  6740. "Local map for completion list buffers.")
  6741. ;; Completion mode is suitable only for specially formatted data.
  6742. (put 'completion-list-mode 'mode-class 'special)
  6743. (defvar completion-reference-buffer nil
  6744. "Record the buffer that was current when the completion list was requested.
  6745. This is a local variable in the completion list buffer.
  6746. Initial value is nil to avoid some compiler warnings.")
  6747. (defvar completion-no-auto-exit nil
  6748. "Non-nil means `choose-completion-string' should never exit the minibuffer.
  6749. This also applies to other functions such as `choose-completion'.")
  6750. (defvar completion-base-position nil
  6751. "Position of the base of the text corresponding to the shown completions.
  6752. This variable is used in the *Completions* buffers.
  6753. Its value is a list of the form (START END) where START is the place
  6754. where the completion should be inserted and END (if non-nil) is the end
  6755. of the text to replace. If END is nil, point is used instead.")
  6756. (defvar completion-list-insert-choice-function #'completion--replace
  6757. "Function to use to insert the text chosen in *Completions*.
  6758. Called with three arguments (BEG END TEXT), it should replace the text
  6759. between BEG and END with TEXT. Expected to be set buffer-locally
  6760. in the *Completions* buffer.")
  6761. (defvar completion-base-size nil
  6762. "Number of chars before point not involved in completion.
  6763. This is a local variable in the completion list buffer.
  6764. It refers to the chars in the minibuffer if completing in the
  6765. minibuffer, or in `completion-reference-buffer' otherwise.
  6766. Only characters in the field at point are included.
  6767. If nil, Emacs determines which part of the tail end of the
  6768. buffer's text is involved in completion by comparing the text
  6769. directly.")
  6770. (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
  6771. (defun delete-completion-window ()
  6772. "Delete the completion list window.
  6773. Go to the window from which completion was requested."
  6774. (interactive)
  6775. (let ((buf completion-reference-buffer))
  6776. (if (one-window-p t)
  6777. (if (window-dedicated-p) (delete-frame))
  6778. (delete-window (selected-window))
  6779. (if (get-buffer-window buf)
  6780. (select-window (get-buffer-window buf))))))
  6781. (defun previous-completion (n)
  6782. "Move to the previous item in the completion list."
  6783. (interactive "p")
  6784. (next-completion (- n)))
  6785. (defun next-completion (n)
  6786. "Move to the next item in the completion list.
  6787. With prefix argument N, move N items (negative N means move backward)."
  6788. (interactive "p")
  6789. (let ((beg (point-min)) (end (point-max)))
  6790. (while (and (> n 0) (not (eobp)))
  6791. ;; If in a completion, move to the end of it.
  6792. (when (get-text-property (point) 'mouse-face)
  6793. (goto-char (next-single-property-change (point) 'mouse-face nil end)))
  6794. ;; Move to start of next one.
  6795. (unless (get-text-property (point) 'mouse-face)
  6796. (goto-char (next-single-property-change (point) 'mouse-face nil end)))
  6797. (setq n (1- n)))
  6798. (while (and (< n 0) (not (bobp)))
  6799. (let ((prop (get-text-property (1- (point)) 'mouse-face)))
  6800. ;; If in a completion, move to the start of it.
  6801. (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
  6802. (goto-char (previous-single-property-change
  6803. (point) 'mouse-face nil beg)))
  6804. ;; Move to end of the previous completion.
  6805. (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
  6806. (goto-char (previous-single-property-change
  6807. (point) 'mouse-face nil beg)))
  6808. ;; Move to the start of that one.
  6809. (goto-char (previous-single-property-change
  6810. (point) 'mouse-face nil beg))
  6811. (setq n (1+ n))))))
  6812. (defun choose-completion (&optional event)
  6813. "Choose the completion at point.
  6814. If EVENT, use EVENT's position to determine the starting position."
  6815. (interactive (list last-nonmenu-event))
  6816. ;; In case this is run via the mouse, give temporary modes such as
  6817. ;; isearch a chance to turn off.
  6818. (run-hooks 'mouse-leave-buffer-hook)
  6819. (with-current-buffer (window-buffer (posn-window (event-start event)))
  6820. (let ((buffer completion-reference-buffer)
  6821. (base-size completion-base-size)
  6822. (base-position completion-base-position)
  6823. (insert-function completion-list-insert-choice-function)
  6824. (choice
  6825. (save-excursion
  6826. (goto-char (posn-point (event-start event)))
  6827. (let (beg end)
  6828. (cond
  6829. ((and (not (eobp)) (get-text-property (point) 'mouse-face))
  6830. (setq end (point) beg (1+ (point))))
  6831. ((and (not (bobp))
  6832. (get-text-property (1- (point)) 'mouse-face))
  6833. (setq end (1- (point)) beg (point)))
  6834. (t (error "No completion here")))
  6835. (setq beg (previous-single-property-change beg 'mouse-face))
  6836. (setq end (or (next-single-property-change end 'mouse-face)
  6837. (point-max)))
  6838. (buffer-substring-no-properties beg end)))))
  6839. (unless (buffer-live-p buffer)
  6840. (error "Destination buffer is dead"))
  6841. (quit-window nil (posn-window (event-start event)))
  6842. (with-current-buffer buffer
  6843. (choose-completion-string
  6844. choice buffer
  6845. (or base-position
  6846. (when base-size
  6847. ;; Someone's using old completion code that doesn't know
  6848. ;; about base-position yet.
  6849. (list (+ base-size (field-beginning))))
  6850. ;; If all else fails, just guess.
  6851. (list (choose-completion-guess-base-position choice)))
  6852. insert-function)))))
  6853. ;; Delete the longest partial match for STRING
  6854. ;; that can be found before POINT.
  6855. (defun choose-completion-guess-base-position (string)
  6856. (save-excursion
  6857. (let ((opoint (point))
  6858. len)
  6859. ;; Try moving back by the length of the string.
  6860. (goto-char (max (- (point) (length string))
  6861. (minibuffer-prompt-end)))
  6862. ;; See how far back we were actually able to move. That is the
  6863. ;; upper bound on how much we can match and delete.
  6864. (setq len (- opoint (point)))
  6865. (if completion-ignore-case
  6866. (setq string (downcase string)))
  6867. (while (and (> len 0)
  6868. (let ((tail (buffer-substring (point) opoint)))
  6869. (if completion-ignore-case
  6870. (setq tail (downcase tail)))
  6871. (not (string= tail (substring string 0 len)))))
  6872. (setq len (1- len))
  6873. (forward-char 1))
  6874. (point))))
  6875. (defun choose-completion-delete-max-match (string)
  6876. (declare (obsolete choose-completion-guess-base-position "23.2"))
  6877. (delete-region (choose-completion-guess-base-position string) (point)))
  6878. (defvar choose-completion-string-functions nil
  6879. "Functions that may override the normal insertion of a completion choice.
  6880. These functions are called in order with three arguments:
  6881. CHOICE - the string to insert in the buffer,
  6882. BUFFER - the buffer in which the choice should be inserted,
  6883. BASE-POSITION - where to insert the completion.
  6884. If a function in the list returns non-nil, that function is supposed
  6885. to have inserted the CHOICE in the BUFFER, and possibly exited
  6886. the minibuffer; no further functions will be called.
  6887. If all functions in the list return nil, that means to use
  6888. the default method of inserting the completion in BUFFER.")
  6889. (defun choose-completion-string (choice &optional
  6890. buffer base-position insert-function)
  6891. "Switch to BUFFER and insert the completion choice CHOICE.
  6892. BASE-POSITION says where to insert the completion.
  6893. INSERT-FUNCTION says how to insert the completion and falls
  6894. back on `completion-list-insert-choice-function' when nil."
  6895. ;; If BUFFER is the minibuffer, exit the minibuffer
  6896. ;; unless it is reading a file name and CHOICE is a directory,
  6897. ;; or completion-no-auto-exit is non-nil.
  6898. ;; Some older code may call us passing `base-size' instead of
  6899. ;; `base-position'. It's difficult to make any use of `base-size',
  6900. ;; so we just ignore it.
  6901. (unless (consp base-position)
  6902. (message "Obsolete ‘base-size’ passed to choose-completion-string")
  6903. (setq base-position nil))
  6904. (let* ((buffer (or buffer completion-reference-buffer))
  6905. (mini-p (minibufferp buffer)))
  6906. ;; If BUFFER is a minibuffer, barf unless it's the currently
  6907. ;; active minibuffer.
  6908. (if (and mini-p
  6909. (not (and (active-minibuffer-window)
  6910. (equal buffer
  6911. (window-buffer (active-minibuffer-window))))))
  6912. (error "Minibuffer is not active for completion")
  6913. ;; Set buffer so buffer-local choose-completion-string-functions works.
  6914. (set-buffer buffer)
  6915. (unless (run-hook-with-args-until-success
  6916. 'choose-completion-string-functions
  6917. ;; The fourth arg used to be `mini-p' but was useless
  6918. ;; (since minibufferp can be used on the `buffer' arg)
  6919. ;; and indeed unused. The last used to be `base-size', so we
  6920. ;; keep it to try and avoid breaking old code.
  6921. choice buffer base-position nil)
  6922. ;; This remove-text-properties should be unnecessary since `choice'
  6923. ;; comes from buffer-substring-no-properties.
  6924. ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
  6925. ;; Insert the completion into the buffer where it was requested.
  6926. (funcall (or insert-function completion-list-insert-choice-function)
  6927. (or (car base-position) (point))
  6928. (or (cadr base-position) (point))
  6929. choice)
  6930. ;; Update point in the window that BUFFER is showing in.
  6931. (let ((window (get-buffer-window buffer t)))
  6932. (set-window-point window (point)))
  6933. ;; If completing for the minibuffer, exit it with this choice.
  6934. (and (not completion-no-auto-exit)
  6935. (minibufferp buffer)
  6936. minibuffer-completion-table
  6937. ;; If this is reading a file name, and the file name chosen
  6938. ;; is a directory, don't exit the minibuffer.
  6939. (let* ((result (buffer-substring (field-beginning) (point)))
  6940. (bounds
  6941. (completion-boundaries result minibuffer-completion-table
  6942. minibuffer-completion-predicate
  6943. "")))
  6944. (if (eq (car bounds) (length result))
  6945. ;; The completion chosen leads to a new set of completions
  6946. ;; (e.g. it's a directory): don't exit the minibuffer yet.
  6947. (let ((mini (active-minibuffer-window)))
  6948. (select-window mini)
  6949. (when minibuffer-auto-raise
  6950. (raise-frame (window-frame mini))))
  6951. (exit-minibuffer))))))))
  6952. (define-derived-mode completion-list-mode nil "Completion List"
  6953. "Major mode for buffers showing lists of possible completions.
  6954. Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
  6955. to select the completion near point.
  6956. Or click to select one with the mouse.
  6957. \\{completion-list-mode-map}"
  6958. (set (make-local-variable 'completion-base-size) nil))
  6959. (defun completion-list-mode-finish ()
  6960. "Finish setup of the completions buffer.
  6961. Called from `temp-buffer-show-hook'."
  6962. (when (eq major-mode 'completion-list-mode)
  6963. (setq buffer-read-only t)))
  6964. (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
  6965. ;; Variables and faces used in `completion-setup-function'.
  6966. (defcustom completion-show-help t
  6967. "Non-nil means show help message in *Completions* buffer."
  6968. :type 'boolean
  6969. :version "22.1"
  6970. :group 'completion)
  6971. ;; This function goes in completion-setup-hook, so that it is called
  6972. ;; after the text of the completion list buffer is written.
  6973. (defun completion-setup-function ()
  6974. (let* ((mainbuf (current-buffer))
  6975. (base-dir
  6976. ;; FIXME: This is a bad hack. We try to set the default-directory
  6977. ;; in the *Completions* buffer so that the relative file names
  6978. ;; displayed there can be treated as valid file names, independently
  6979. ;; from the completion context. But this suffers from many problems:
  6980. ;; - It's not clear when the completions are file names. With some
  6981. ;; completion tables (e.g. bzr revision specs), the listed
  6982. ;; completions can mix file names and other things.
  6983. ;; - It doesn't pay attention to possible quoting.
  6984. ;; - With fancy completion styles, the code below will not always
  6985. ;; find the right base directory.
  6986. (if minibuffer-completing-file-name
  6987. (file-name-as-directory
  6988. (expand-file-name
  6989. (buffer-substring (minibuffer-prompt-end)
  6990. (- (point) (or completion-base-size 0))))))))
  6991. (with-current-buffer standard-output
  6992. (let ((base-size completion-base-size) ;Read before killing localvars.
  6993. (base-position completion-base-position)
  6994. (insert-fun completion-list-insert-choice-function))
  6995. (completion-list-mode)
  6996. (set (make-local-variable 'completion-base-size) base-size)
  6997. (set (make-local-variable 'completion-base-position) base-position)
  6998. (set (make-local-variable 'completion-list-insert-choice-function)
  6999. insert-fun))
  7000. (set (make-local-variable 'completion-reference-buffer) mainbuf)
  7001. (if base-dir (setq default-directory base-dir))
  7002. ;; Maybe insert help string.
  7003. (when completion-show-help
  7004. (goto-char (point-min))
  7005. (if (display-mouse-p)
  7006. (insert "Click on a completion to select it.\n"))
  7007. (insert (substitute-command-keys
  7008. "In this buffer, type \\[choose-completion] to \
  7009. select the completion near point.\n\n"))))))
  7010. (add-hook 'completion-setup-hook 'completion-setup-function)
  7011. (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
  7012. (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
  7013. (defun switch-to-completions ()
  7014. "Select the completion list window."
  7015. (interactive)
  7016. (let ((window (or (get-buffer-window "*Completions*" 0)
  7017. ;; Make sure we have a completions window.
  7018. (progn (minibuffer-completion-help)
  7019. (get-buffer-window "*Completions*" 0)))))
  7020. (when window
  7021. (select-window window)
  7022. ;; In the new buffer, go to the first completion.
  7023. ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
  7024. (when (bobp)
  7025. (next-completion 1)))))
  7026. ;;; Support keyboard commands to turn on various modifiers.
  7027. ;; These functions -- which are not commands -- each add one modifier
  7028. ;; to the following event.
  7029. (defun event-apply-alt-modifier (_ignore-prompt)
  7030. "\\<function-key-map>Add the Alt modifier to the following event.
  7031. For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
  7032. (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
  7033. (defun event-apply-super-modifier (_ignore-prompt)
  7034. "\\<function-key-map>Add the Super modifier to the following event.
  7035. For example, type \\[event-apply-super-modifier] & to enter Super-&."
  7036. (vector (event-apply-modifier (read-event) 'super 23 "s-")))
  7037. (defun event-apply-hyper-modifier (_ignore-prompt)
  7038. "\\<function-key-map>Add the Hyper modifier to the following event.
  7039. For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
  7040. (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
  7041. (defun event-apply-shift-modifier (_ignore-prompt)
  7042. "\\<function-key-map>Add the Shift modifier to the following event.
  7043. For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
  7044. (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
  7045. (defun event-apply-control-modifier (_ignore-prompt)
  7046. "\\<function-key-map>Add the Ctrl modifier to the following event.
  7047. For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
  7048. (vector (event-apply-modifier (read-event) 'control 26 "C-")))
  7049. (defun event-apply-meta-modifier (_ignore-prompt)
  7050. "\\<function-key-map>Add the Meta modifier to the following event.
  7051. For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
  7052. (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
  7053. (defun event-apply-modifier (event symbol lshiftby prefix)
  7054. "Apply a modifier flag to event EVENT.
  7055. SYMBOL is the name of this modifier, as a symbol.
  7056. LSHIFTBY is the numeric value of this modifier, in keyboard events.
  7057. PREFIX is the string that represents this modifier in an event type symbol."
  7058. (if (numberp event)
  7059. (cond ((eq symbol 'control)
  7060. (if (and (<= (downcase event) ?z)
  7061. (>= (downcase event) ?a))
  7062. (- (downcase event) ?a -1)
  7063. (if (and (<= (downcase event) ?Z)
  7064. (>= (downcase event) ?A))
  7065. (- (downcase event) ?A -1)
  7066. (logior (lsh 1 lshiftby) event))))
  7067. ((eq symbol 'shift)
  7068. (if (and (<= (downcase event) ?z)
  7069. (>= (downcase event) ?a))
  7070. (upcase event)
  7071. (logior (lsh 1 lshiftby) event)))
  7072. (t
  7073. (logior (lsh 1 lshiftby) event)))
  7074. (if (memq symbol (event-modifiers event))
  7075. event
  7076. (let ((event-type (if (symbolp event) event (car event))))
  7077. (setq event-type (intern (concat prefix (symbol-name event-type))))
  7078. (if (symbolp event)
  7079. event-type
  7080. (cons event-type (cdr event)))))))
  7081. (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
  7082. (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
  7083. (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
  7084. (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
  7085. (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
  7086. (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
  7087. ;;;; Keypad support.
  7088. ;; Make the keypad keys act like ordinary typing keys. If people add
  7089. ;; bindings for the function key symbols, then those bindings will
  7090. ;; override these, so this shouldn't interfere with any existing
  7091. ;; bindings.
  7092. ;; Also tell read-char how to handle these keys.
  7093. (mapc
  7094. (lambda (keypad-normal)
  7095. (let ((keypad (nth 0 keypad-normal))
  7096. (normal (nth 1 keypad-normal)))
  7097. (put keypad 'ascii-character normal)
  7098. (define-key function-key-map (vector keypad) (vector normal))))
  7099. ;; See also kp-keys bound in bindings.el.
  7100. '((kp-space ?\s)
  7101. (kp-tab ?\t)
  7102. (kp-enter ?\r)
  7103. (kp-separator ?,)
  7104. (kp-equal ?=)
  7105. ;; Do the same for various keys that are represented as symbols under
  7106. ;; GUIs but naturally correspond to characters.
  7107. (backspace 127)
  7108. (delete 127)
  7109. (tab ?\t)
  7110. (linefeed ?\n)
  7111. (clear ?\C-l)
  7112. (return ?\C-m)
  7113. (escape ?\e)
  7114. ))
  7115. ;;;;
  7116. ;;;; forking a twin copy of a buffer.
  7117. ;;;;
  7118. (defvar clone-buffer-hook nil
  7119. "Normal hook to run in the new buffer at the end of `clone-buffer'.")
  7120. (defvar clone-indirect-buffer-hook nil
  7121. "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
  7122. (defun clone-process (process &optional newname)
  7123. "Create a twin copy of PROCESS.
  7124. If NEWNAME is nil, it defaults to PROCESS' name;
  7125. NEWNAME is modified by adding or incrementing <N> at the end as necessary.
  7126. If PROCESS is associated with a buffer, the new process will be associated
  7127. with the current buffer instead.
  7128. Returns nil if PROCESS has already terminated."
  7129. (setq newname (or newname (process-name process)))
  7130. (if (string-match "<[0-9]+>\\'" newname)
  7131. (setq newname (substring newname 0 (match-beginning 0))))
  7132. (when (memq (process-status process) '(run stop open))
  7133. (let* ((process-connection-type (process-tty-name process))
  7134. (new-process
  7135. (if (memq (process-status process) '(open))
  7136. (let ((args (process-contact process t)))
  7137. (setq args (plist-put args :name newname))
  7138. (setq args (plist-put args :buffer
  7139. (if (process-buffer process)
  7140. (current-buffer))))
  7141. (apply 'make-network-process args))
  7142. (apply 'start-process newname
  7143. (if (process-buffer process) (current-buffer))
  7144. (process-command process)))))
  7145. (set-process-query-on-exit-flag
  7146. new-process (process-query-on-exit-flag process))
  7147. (set-process-inherit-coding-system-flag
  7148. new-process (process-inherit-coding-system-flag process))
  7149. (set-process-filter new-process (process-filter process))
  7150. (set-process-sentinel new-process (process-sentinel process))
  7151. (set-process-plist new-process (copy-sequence (process-plist process)))
  7152. new-process)))
  7153. ;; things to maybe add (currently partly covered by `funcall mode'):
  7154. ;; - syntax-table
  7155. ;; - overlays
  7156. (defun clone-buffer (&optional newname display-flag)
  7157. "Create and return a twin copy of the current buffer.
  7158. Unlike an indirect buffer, the new buffer can be edited
  7159. independently of the old one (if it is not read-only).
  7160. NEWNAME is the name of the new buffer. It may be modified by
  7161. adding or incrementing <N> at the end as necessary to create a
  7162. unique buffer name. If nil, it defaults to the name of the
  7163. current buffer, with the proper suffix. If DISPLAY-FLAG is
  7164. non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
  7165. clone a file-visiting buffer, or a buffer whose major mode symbol
  7166. has a non-nil `no-clone' property, results in an error.
  7167. Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
  7168. current buffer with appropriate suffix. However, if a prefix
  7169. argument is given, then the command prompts for NEWNAME in the
  7170. minibuffer.
  7171. This runs the normal hook `clone-buffer-hook' in the new buffer
  7172. after it has been set up properly in other respects."
  7173. (interactive
  7174. (progn
  7175. (if buffer-file-name
  7176. (error "Cannot clone a file-visiting buffer"))
  7177. (if (get major-mode 'no-clone)
  7178. (error "Cannot clone a buffer in %s mode" mode-name))
  7179. (list (if current-prefix-arg
  7180. (read-buffer "Name of new cloned buffer: " (current-buffer)))
  7181. t)))
  7182. (if buffer-file-name
  7183. (error "Cannot clone a file-visiting buffer"))
  7184. (if (get major-mode 'no-clone)
  7185. (error "Cannot clone a buffer in %s mode" mode-name))
  7186. (setq newname (or newname (buffer-name)))
  7187. (if (string-match "<[0-9]+>\\'" newname)
  7188. (setq newname (substring newname 0 (match-beginning 0))))
  7189. (let ((buf (current-buffer))
  7190. (ptmin (point-min))
  7191. (ptmax (point-max))
  7192. (pt (point))
  7193. (mk (if mark-active (mark t)))
  7194. (modified (buffer-modified-p))
  7195. (mode major-mode)
  7196. (lvars (buffer-local-variables))
  7197. (process (get-buffer-process (current-buffer)))
  7198. (new (generate-new-buffer (or newname (buffer-name)))))
  7199. (save-restriction
  7200. (widen)
  7201. (with-current-buffer new
  7202. (insert-buffer-substring buf)))
  7203. (with-current-buffer new
  7204. (narrow-to-region ptmin ptmax)
  7205. (goto-char pt)
  7206. (if mk (set-mark mk))
  7207. (set-buffer-modified-p modified)
  7208. ;; Clone the old buffer's process, if any.
  7209. (when process (clone-process process))
  7210. ;; Now set up the major mode.
  7211. (funcall mode)
  7212. ;; Set up other local variables.
  7213. (mapc (lambda (v)
  7214. (condition-case () ;in case var is read-only
  7215. (if (symbolp v)
  7216. (makunbound v)
  7217. (set (make-local-variable (car v)) (cdr v)))
  7218. (error nil)))
  7219. lvars)
  7220. ;; Run any hooks (typically set up by the major mode
  7221. ;; for cloning to work properly).
  7222. (run-hooks 'clone-buffer-hook))
  7223. (if display-flag
  7224. ;; Presumably the current buffer is shown in the selected frame, so
  7225. ;; we want to display the clone elsewhere.
  7226. (let ((same-window-regexps nil)
  7227. (same-window-buffer-names))
  7228. (pop-to-buffer new)))
  7229. new))
  7230. (defun clone-indirect-buffer (newname display-flag &optional norecord)
  7231. "Create an indirect buffer that is a twin copy of the current buffer.
  7232. Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
  7233. from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
  7234. or if not called with a prefix arg, NEWNAME defaults to the current
  7235. buffer's name. The name is modified by adding a `<N>' suffix to it
  7236. or by incrementing the N in an existing suffix. Trying to clone a
  7237. buffer whose major mode symbol has a non-nil `no-clone-indirect'
  7238. property results in an error.
  7239. DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
  7240. This is always done when called interactively.
  7241. Optional third arg NORECORD non-nil means do not put this buffer at the
  7242. front of the list of recently selected ones.
  7243. Returns the newly created indirect buffer."
  7244. (interactive
  7245. (progn
  7246. (if (get major-mode 'no-clone-indirect)
  7247. (error "Cannot indirectly clone a buffer in %s mode" mode-name))
  7248. (list (if current-prefix-arg
  7249. (read-buffer "Name of indirect buffer: " (current-buffer)))
  7250. t)))
  7251. (if (get major-mode 'no-clone-indirect)
  7252. (error "Cannot indirectly clone a buffer in %s mode" mode-name))
  7253. (setq newname (or newname (buffer-name)))
  7254. (if (string-match "<[0-9]+>\\'" newname)
  7255. (setq newname (substring newname 0 (match-beginning 0))))
  7256. (let* ((name (generate-new-buffer-name newname))
  7257. (buffer (make-indirect-buffer (current-buffer) name t)))
  7258. (with-current-buffer buffer
  7259. (run-hooks 'clone-indirect-buffer-hook))
  7260. (when display-flag
  7261. (pop-to-buffer buffer norecord))
  7262. buffer))
  7263. (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
  7264. "Like `clone-indirect-buffer' but display in another window."
  7265. (interactive
  7266. (progn
  7267. (if (get major-mode 'no-clone-indirect)
  7268. (error "Cannot indirectly clone a buffer in %s mode" mode-name))
  7269. (list (if current-prefix-arg
  7270. (read-buffer "Name of indirect buffer: " (current-buffer)))
  7271. t)))
  7272. (let ((pop-up-windows t))
  7273. (clone-indirect-buffer newname display-flag norecord)))
  7274. ;;; Handling of Backspace and Delete keys.
  7275. (defcustom normal-erase-is-backspace 'maybe
  7276. "Set the default behavior of the Delete and Backspace keys.
  7277. If set to t, Delete key deletes forward and Backspace key deletes
  7278. backward.
  7279. If set to nil, both Delete and Backspace keys delete backward.
  7280. If set to 'maybe (which is the default), Emacs automatically
  7281. selects a behavior. On window systems, the behavior depends on
  7282. the keyboard used. If the keyboard has both a Backspace key and
  7283. a Delete key, and both are mapped to their usual meanings, the
  7284. option's default value is set to t, so that Backspace can be used
  7285. to delete backward, and Delete can be used to delete forward.
  7286. If not running under a window system, customizing this option
  7287. accomplishes a similar effect by mapping C-h, which is usually
  7288. generated by the Backspace key, to DEL, and by mapping DEL to C-d
  7289. via `keyboard-translate'. The former functionality of C-h is
  7290. available on the F1 key. You should probably not use this
  7291. setting if you don't have both Backspace, Delete and F1 keys.
  7292. Setting this variable with setq doesn't take effect. Programmatically,
  7293. call `normal-erase-is-backspace-mode' (which see) instead."
  7294. :type '(choice (const :tag "Off" nil)
  7295. (const :tag "Maybe" maybe)
  7296. (other :tag "On" t))
  7297. :group 'editing-basics
  7298. :version "21.1"
  7299. :set (lambda (symbol value)
  7300. ;; The fboundp is because of a problem with :set when
  7301. ;; dumping Emacs. It doesn't really matter.
  7302. (if (fboundp 'normal-erase-is-backspace-mode)
  7303. (normal-erase-is-backspace-mode (or value 0))
  7304. (set-default symbol value))))
  7305. (defun normal-erase-is-backspace-setup-frame (&optional frame)
  7306. "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
  7307. (unless frame (setq frame (selected-frame)))
  7308. (with-selected-frame frame
  7309. (unless (terminal-parameter nil 'normal-erase-is-backspace)
  7310. (normal-erase-is-backspace-mode
  7311. (if (if (eq normal-erase-is-backspace 'maybe)
  7312. (and (not noninteractive)
  7313. (or (memq system-type '(ms-dos windows-nt))
  7314. (memq window-system '(w32 ns))
  7315. (and (memq window-system '(x))
  7316. (fboundp 'x-backspace-delete-keys-p)
  7317. (x-backspace-delete-keys-p))
  7318. ;; If the terminal Emacs is running on has erase char
  7319. ;; set to ^H, use the Backspace key for deleting
  7320. ;; backward, and the Delete key for deleting forward.
  7321. (and (null window-system)
  7322. (eq tty-erase-char ?\^H))))
  7323. normal-erase-is-backspace)
  7324. 1 0)))))
  7325. (define-minor-mode normal-erase-is-backspace-mode
  7326. "Toggle the Erase and Delete mode of the Backspace and Delete keys.
  7327. With a prefix argument ARG, enable this feature if ARG is
  7328. positive, and disable it otherwise. If called from Lisp, enable
  7329. the mode if ARG is omitted or nil.
  7330. On window systems, when this mode is on, Delete is mapped to C-d
  7331. and Backspace is mapped to DEL; when this mode is off, both
  7332. Delete and Backspace are mapped to DEL. (The remapping goes via
  7333. `local-function-key-map', so binding Delete or Backspace in the
  7334. global or local keymap will override that.)
  7335. In addition, on window systems, the bindings of C-Delete, M-Delete,
  7336. C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
  7337. the global keymap in accordance with the functionality of Delete and
  7338. Backspace. For example, if Delete is remapped to C-d, which deletes
  7339. forward, C-Delete is bound to `kill-word', but if Delete is remapped
  7340. to DEL, which deletes backward, C-Delete is bound to
  7341. `backward-kill-word'.
  7342. If not running on a window system, a similar effect is accomplished by
  7343. remapping C-h (normally produced by the Backspace key) and DEL via
  7344. `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
  7345. to C-d; if it's off, the keys are not remapped.
  7346. When not running on a window system, and this mode is turned on, the
  7347. former functionality of C-h is available on the F1 key. You should
  7348. probably not turn on this mode on a text-only terminal if you don't
  7349. have both Backspace, Delete and F1 keys.
  7350. See also `normal-erase-is-backspace'."
  7351. :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
  7352. . (lambda (v)
  7353. (setf (terminal-parameter nil 'normal-erase-is-backspace)
  7354. (if v 1 0))))
  7355. (let ((enabled (eq 1 (terminal-parameter
  7356. nil 'normal-erase-is-backspace))))
  7357. (cond ((or (memq window-system '(x w32 ns pc))
  7358. (memq system-type '(ms-dos windows-nt)))
  7359. (let ((bindings
  7360. `(([M-delete] [M-backspace])
  7361. ([C-M-delete] [C-M-backspace])
  7362. ([?\e C-delete] [?\e C-backspace]))))
  7363. (if enabled
  7364. (progn
  7365. (define-key local-function-key-map [delete] [deletechar])
  7366. (define-key local-function-key-map [kp-delete] [deletechar])
  7367. (define-key local-function-key-map [backspace] [?\C-?])
  7368. (dolist (b bindings)
  7369. ;; Not sure if input-decode-map is really right, but
  7370. ;; keyboard-translate-table (used below) only works
  7371. ;; for integer events, and key-translation-table is
  7372. ;; global (like the global-map, used earlier).
  7373. (define-key input-decode-map (car b) nil)
  7374. (define-key input-decode-map (cadr b) nil)))
  7375. (define-key local-function-key-map [delete] [?\C-?])
  7376. (define-key local-function-key-map [kp-delete] [?\C-?])
  7377. (define-key local-function-key-map [backspace] [?\C-?])
  7378. (dolist (b bindings)
  7379. (define-key input-decode-map (car b) (cadr b))
  7380. (define-key input-decode-map (cadr b) (car b))))))
  7381. (t
  7382. (if enabled
  7383. (progn
  7384. (keyboard-translate ?\C-h ?\C-?)
  7385. (keyboard-translate ?\C-? ?\C-d))
  7386. (keyboard-translate ?\C-h ?\C-h)
  7387. (keyboard-translate ?\C-? ?\C-?))))
  7388. (if (called-interactively-p 'interactive)
  7389. (message "Delete key deletes %s"
  7390. (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
  7391. "forward" "backward")))))
  7392. (defvar vis-mode-saved-buffer-invisibility-spec nil
  7393. "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
  7394. (define-minor-mode read-only-mode
  7395. "Change whether the current buffer is read-only.
  7396. With prefix argument ARG, make the buffer read-only if ARG is
  7397. positive, otherwise make it writable. If buffer is read-only
  7398. and `view-read-only' is non-nil, enter view mode.
  7399. Do not call this from a Lisp program unless you really intend to
  7400. do the same thing as the \\[read-only-mode] command, including
  7401. possibly enabling or disabling View mode. Also, note that this
  7402. command works by setting the variable `buffer-read-only', which
  7403. does not affect read-only regions caused by text properties. To
  7404. ignore read-only status in a Lisp program (whether due to text
  7405. properties or buffer state), bind `inhibit-read-only' temporarily
  7406. to a non-nil value."
  7407. :variable buffer-read-only
  7408. (cond
  7409. ((and (not buffer-read-only) view-mode)
  7410. (View-exit-and-edit)
  7411. (make-local-variable 'view-read-only)
  7412. (setq view-read-only t)) ; Must leave view mode.
  7413. ((and buffer-read-only view-read-only
  7414. ;; If view-mode is already active, `view-mode-enter' is a nop.
  7415. (not view-mode)
  7416. (not (eq (get major-mode 'mode-class) 'special)))
  7417. (view-mode-enter))))
  7418. (define-minor-mode visible-mode
  7419. "Toggle making all invisible text temporarily visible (Visible mode).
  7420. With a prefix argument ARG, enable Visible mode if ARG is
  7421. positive, and disable it otherwise. If called from Lisp, enable
  7422. the mode if ARG is omitted or nil.
  7423. This mode works by saving the value of `buffer-invisibility-spec'
  7424. and setting it to nil."
  7425. :lighter " Vis"
  7426. :group 'editing-basics
  7427. (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
  7428. (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
  7429. (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
  7430. (when visible-mode
  7431. (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
  7432. buffer-invisibility-spec)
  7433. (setq buffer-invisibility-spec nil)))
  7434. (defvar messages-buffer-mode-map
  7435. (let ((map (make-sparse-keymap)))
  7436. (set-keymap-parent map special-mode-map)
  7437. (define-key map "g" nil) ; nothing to revert
  7438. map))
  7439. (define-derived-mode messages-buffer-mode special-mode "Messages"
  7440. "Major mode used in the \"*Messages*\" buffer.")
  7441. (defun messages-buffer ()
  7442. "Return the \"*Messages*\" buffer.
  7443. If it does not exist, create and it switch it to `messages-buffer-mode'."
  7444. (or (get-buffer "*Messages*")
  7445. (with-current-buffer (get-buffer-create "*Messages*")
  7446. (messages-buffer-mode)
  7447. (current-buffer))))
  7448. ;; Minibuffer prompt stuff.
  7449. ;;(defun minibuffer-prompt-modification (start end)
  7450. ;; (error "You cannot modify the prompt"))
  7451. ;;
  7452. ;;
  7453. ;;(defun minibuffer-prompt-insertion (start end)
  7454. ;; (let ((inhibit-modification-hooks t))
  7455. ;; (delete-region start end)
  7456. ;; ;; Discard undo information for the text insertion itself
  7457. ;; ;; and for the text deletion.above.
  7458. ;; (when (consp buffer-undo-list)
  7459. ;; (setq buffer-undo-list (cddr buffer-undo-list)))
  7460. ;; (message "You cannot modify the prompt")))
  7461. ;;
  7462. ;;
  7463. ;;(setq minibuffer-prompt-properties
  7464. ;; (list 'modification-hooks '(minibuffer-prompt-modification)
  7465. ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
  7466. ;;;; Problematic external packages.
  7467. ;; rms says this should be done by specifying symbols that define
  7468. ;; versions together with bad values. This is therefore not as
  7469. ;; flexible as it could be. See the thread:
  7470. ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
  7471. (defconst bad-packages-alist
  7472. ;; Not sure exactly which semantic versions have problems.
  7473. ;; Definitely 2.0pre3, probably all 2.0pre's before this.
  7474. '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
  7475. "The version of `semantic' loaded does not work in Emacs 22.
  7476. It can cause constant high CPU load.
  7477. Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
  7478. ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
  7479. ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
  7480. ;; provided the `CUA-mode' feature. Since this is no longer true,
  7481. ;; we can warn the user if the `CUA-mode' feature is ever provided.
  7482. (CUA-mode t nil
  7483. "CUA-mode is now part of the standard GNU Emacs distribution,
  7484. so you can now enable CUA via the Options menu or by customizing `cua-mode'.
  7485. You have loaded an older version of CUA-mode which does not work
  7486. correctly with this version of Emacs. You should remove the old
  7487. version and use the one distributed with Emacs."))
  7488. "Alist of packages known to cause problems in this version of Emacs.
  7489. Each element has the form (PACKAGE SYMBOL REGEXP STRING).
  7490. PACKAGE is either a regular expression to match file names, or a
  7491. symbol (a feature name), like for `with-eval-after-load'.
  7492. SYMBOL is either the name of a string variable, or t. Upon
  7493. loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
  7494. warning using STRING as the message.")
  7495. (defun bad-package-check (package)
  7496. "Run a check using the element from `bad-packages-alist' matching PACKAGE."
  7497. (condition-case nil
  7498. (let* ((list (assoc package bad-packages-alist))
  7499. (symbol (nth 1 list)))
  7500. (and list
  7501. (boundp symbol)
  7502. (or (eq symbol t)
  7503. (and (stringp (setq symbol (eval symbol)))
  7504. (string-match-p (nth 2 list) symbol)))
  7505. (display-warning package (nth 3 list) :warning)))
  7506. (error nil)))
  7507. (dolist (elem bad-packages-alist)
  7508. (let ((pkg (car elem)))
  7509. (with-eval-after-load pkg
  7510. (bad-package-check pkg))))
  7511. ;;; Generic dispatcher commands
  7512. ;; Macro `define-alternatives' is used to create generic commands.
  7513. ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
  7514. ;; that can have different alternative implementations where choosing
  7515. ;; among them is exclusively a matter of user preference.
  7516. ;; (define-alternatives COMMAND) creates a new interactive command
  7517. ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
  7518. ;; Typically, the user will not need to customize this variable; packages
  7519. ;; wanting to add alternative implementations should use
  7520. ;;
  7521. ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
  7522. (defmacro define-alternatives (command &rest customizations)
  7523. "Define the new command `COMMAND'.
  7524. The argument `COMMAND' should be a symbol.
  7525. Running `M-x COMMAND RET' for the first time prompts for which
  7526. alternative to use and records the selected command as a custom
  7527. variable.
  7528. Running `C-u M-x COMMAND RET' prompts again for an alternative
  7529. and overwrites the previous choice.
  7530. The variable `COMMAND-alternatives' contains an alist with
  7531. alternative implementations of COMMAND. `define-alternatives'
  7532. does not have any effect until this variable is set.
  7533. CUSTOMIZATIONS, if non-nil, should be composed of alternating
  7534. `defcustom' keywords and values to add to the declaration of
  7535. `COMMAND-alternatives' (typically :group and :version)."
  7536. (let* ((command-name (symbol-name command))
  7537. (varalt-name (concat command-name "-alternatives"))
  7538. (varalt-sym (intern varalt-name))
  7539. (varimp-sym (intern (concat command-name "--implementation"))))
  7540. `(progn
  7541. (defcustom ,varalt-sym nil
  7542. ,(format "Alist of alternative implementations for the ‘%s’ command.
  7543. Each entry must be a pair (ALTNAME . ALTFUN), where:
  7544. ALTNAME - The name shown at user to describe the alternative implementation.
  7545. ALTFUN - The function called to implement this alternative."
  7546. command-name)
  7547. :type '(alist :key-type string :value-type function)
  7548. ,@customizations)
  7549. (put ',varalt-sym 'definition-name ',command)
  7550. (defvar ,varimp-sym nil "Internal use only.")
  7551. (defun ,command (&optional arg)
  7552. ,(format "Run generic command ‘%s’.
  7553. If used for the first time, or with interactive ARG, ask the user which
  7554. implementation to use for ‘%s’. The variable ‘%s’
  7555. contains the list of implementations currently supported for this command."
  7556. command-name command-name varalt-name)
  7557. (interactive "P")
  7558. (when (or arg (null ,varimp-sym))
  7559. (let ((val (completing-read
  7560. ,(format-message
  7561. "Select implementation for command ‘%s’: "
  7562. command-name)
  7563. ,varalt-sym nil t)))
  7564. (unless (string-equal val "")
  7565. (when (null ,varimp-sym)
  7566. (message
  7567. "Use ‘C-u M-x %s RET’ to select another implementation"
  7568. ,command-name)
  7569. (sit-for 3))
  7570. (customize-save-variable ',varimp-sym
  7571. (cdr (assoc-string val ,varalt-sym))))))
  7572. (if ,varimp-sym
  7573. (call-interactively ,varimp-sym)
  7574. (message "%s" ,(format-message
  7575. "No implementation selected for command ‘%s’"
  7576. command-name)))))))
  7577. (provide 'simple)
  7578. ;;; simple.el ends here