simple.el 361 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987
  1. ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
  2. ;; Copyright (C) 1985-1987, 1993-2017 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 shell-command-dont-erase-buffer nil
  28. "If non-nil, output buffer is not erased between shell commands.
  29. Also, a non-nil value set the point in the output buffer
  30. once the command complete.
  31. The value `beg-last-out' set point at the beginning of the output,
  32. `end-last-out' set point at the end of the buffer, `save-point'
  33. restore the buffer position before the command."
  34. :type '(choice
  35. (const :tag "Erase buffer" nil)
  36. (const :tag "Set point to beginning of last output" beg-last-out)
  37. (const :tag "Set point to end of last output" end-last-out)
  38. (const :tag "Save point" save-point))
  39. :group 'shell
  40. :version "26.1")
  41. (defvar shell-command-saved-pos nil
  42. "Point position in the output buffer after command complete.
  43. It is an alist (BUFFER . POS), where BUFFER is the output
  44. buffer, and POS is the point position in BUFFER once the command finish.
  45. This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
  46. (defcustom idle-update-delay 0.5
  47. "Idle time delay before updating various things on the screen.
  48. Various Emacs features that update auxiliary information when point moves
  49. wait this many seconds after Emacs becomes idle before doing an update."
  50. :type 'number
  51. :group 'display
  52. :version "22.1")
  53. (defgroup killing nil
  54. "Killing and yanking commands."
  55. :group 'editing)
  56. (defgroup paren-matching nil
  57. "Highlight (un)matching of parens and expressions."
  58. :group 'matching)
  59. ;;; next-error support framework
  60. (defgroup next-error nil
  61. "`next-error' support framework."
  62. :group 'compilation
  63. :version "22.1")
  64. (defface next-error
  65. '((t (:inherit region)))
  66. "Face used to highlight next error locus."
  67. :group 'next-error
  68. :version "22.1")
  69. (defcustom next-error-highlight 0.5
  70. "Highlighting of locations in selected source buffers.
  71. If a number, highlight the locus in `next-error' face for the given time
  72. in seconds, or until the next command is executed.
  73. If t, highlight the locus until the next command is executed, or until
  74. some other locus replaces it.
  75. If nil, don't highlight the locus in the source buffer.
  76. If `fringe-arrow', indicate the locus by the fringe arrow
  77. indefinitely until some other locus replaces it."
  78. :type '(choice (number :tag "Highlight for specified time")
  79. (const :tag "Semipermanent highlighting" t)
  80. (const :tag "No highlighting" nil)
  81. (const :tag "Fringe arrow" fringe-arrow))
  82. :group 'next-error
  83. :version "22.1")
  84. (defcustom next-error-highlight-no-select 0.5
  85. "Highlighting of locations in `next-error-no-select'.
  86. If number, highlight the locus in `next-error' face for given time in seconds.
  87. If t, highlight the locus indefinitely until some other locus replaces it.
  88. If nil, don't highlight the locus in the source buffer.
  89. If `fringe-arrow', indicate the locus by the fringe arrow
  90. indefinitely until some other locus replaces it."
  91. :type '(choice (number :tag "Highlight for specified time")
  92. (const :tag "Semipermanent highlighting" t)
  93. (const :tag "No highlighting" nil)
  94. (const :tag "Fringe arrow" fringe-arrow))
  95. :group 'next-error
  96. :version "22.1")
  97. (defcustom next-error-recenter nil
  98. "Display the line in the visited source file recentered as specified.
  99. If non-nil, the value is passed directly to `recenter'."
  100. :type '(choice (integer :tag "Line to recenter to")
  101. (const :tag "Center of window" (4))
  102. (const :tag "No recentering" nil))
  103. :group 'next-error
  104. :version "23.1")
  105. (defcustom next-error-hook nil
  106. "List of hook functions run by `next-error' after visiting source file."
  107. :type 'hook
  108. :group 'next-error)
  109. (defvar next-error-highlight-timer nil)
  110. (defvar next-error-overlay-arrow-position nil)
  111. (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
  112. (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
  113. (defvar next-error-last-buffer nil
  114. "The most recent `next-error' buffer.
  115. A buffer becomes most recent when its compilation, grep, or
  116. similar mode is started, or when it is used with \\[next-error]
  117. or \\[compile-goto-error].")
  118. (defvar next-error-function nil
  119. "Function to use to find the next error in the current buffer.
  120. The function is called with 2 parameters:
  121. ARG is an integer specifying by how many errors to move.
  122. RESET is a boolean which, if non-nil, says to go back to the beginning
  123. of the errors before moving.
  124. Major modes providing compile-like functionality should set this variable
  125. to indicate to `next-error' that this is a candidate buffer and how
  126. to navigate in it.")
  127. (make-variable-buffer-local 'next-error-function)
  128. (defvar next-error-move-function nil
  129. "Function to use to move to an error locus.
  130. It takes two arguments, a buffer position in the error buffer
  131. and a buffer position in the error locus buffer.
  132. The buffer for the error locus should already be current.
  133. nil means use goto-char using the second argument position.")
  134. (make-variable-buffer-local 'next-error-move-function)
  135. (defsubst next-error-buffer-p (buffer
  136. &optional avoid-current
  137. extra-test-inclusive
  138. extra-test-exclusive)
  139. "Return non-nil if BUFFER is a `next-error' capable buffer.
  140. If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
  141. return nil.
  142. The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
  143. BUFFER would not normally qualify. If it returns non-nil, BUFFER
  144. is considered `next-error' capable, anyway, and the function
  145. returns non-nil.
  146. The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
  147. buffer would normally qualify. If it returns nil, BUFFER is
  148. rejected, and the function returns nil."
  149. (and (buffer-name buffer) ;First make sure it's live.
  150. (not (and avoid-current (eq buffer (current-buffer))))
  151. (with-current-buffer buffer
  152. (if next-error-function ; This is the normal test.
  153. ;; Optionally reject some buffers.
  154. (if extra-test-exclusive
  155. (funcall extra-test-exclusive)
  156. t)
  157. ;; Optionally accept some other buffers.
  158. (and extra-test-inclusive
  159. (funcall extra-test-inclusive))))))
  160. (defun next-error-find-buffer (&optional avoid-current
  161. extra-test-inclusive
  162. extra-test-exclusive)
  163. "Return a `next-error' capable buffer.
  164. If AVOID-CURRENT is non-nil, treat the current buffer
  165. as an absolute last resort only.
  166. The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
  167. that normally would not qualify. If it returns t, the buffer
  168. in question is treated as usable.
  169. The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
  170. that would normally be considered usable. If it returns nil,
  171. that buffer is rejected."
  172. (or
  173. ;; 1. If one window on the selected frame displays such buffer, return it.
  174. (let ((window-buffers
  175. (delete-dups
  176. (delq nil (mapcar (lambda (w)
  177. (if (next-error-buffer-p
  178. (window-buffer w)
  179. avoid-current
  180. extra-test-inclusive extra-test-exclusive)
  181. (window-buffer w)))
  182. (window-list))))))
  183. (if (eq (length window-buffers) 1)
  184. (car window-buffers)))
  185. ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
  186. (if (and next-error-last-buffer
  187. (next-error-buffer-p next-error-last-buffer avoid-current
  188. extra-test-inclusive extra-test-exclusive))
  189. next-error-last-buffer)
  190. ;; 3. If the current buffer is acceptable, choose it.
  191. (if (next-error-buffer-p (current-buffer) avoid-current
  192. extra-test-inclusive extra-test-exclusive)
  193. (current-buffer))
  194. ;; 4. Look for any acceptable buffer.
  195. (let ((buffers (buffer-list)))
  196. (while (and buffers
  197. (not (next-error-buffer-p
  198. (car buffers) avoid-current
  199. extra-test-inclusive extra-test-exclusive)))
  200. (setq buffers (cdr buffers)))
  201. (car buffers))
  202. ;; 5. Use the current buffer as a last resort if it qualifies,
  203. ;; even despite AVOID-CURRENT.
  204. (and avoid-current
  205. (next-error-buffer-p (current-buffer) nil
  206. extra-test-inclusive extra-test-exclusive)
  207. (progn
  208. (message "This is the only buffer with error message locations")
  209. (current-buffer)))
  210. ;; 6. Give up.
  211. (error "No buffers contain error message locations")))
  212. (defun next-error (&optional arg reset)
  213. "Visit next `next-error' message and corresponding source code.
  214. If all the error messages parsed so far have been processed already,
  215. the message buffer is checked for new ones.
  216. A prefix ARG specifies how many error messages to move;
  217. negative means move back to previous error messages.
  218. Just \\[universal-argument] as a prefix means reparse the error message buffer
  219. and start at the first error.
  220. The RESET argument specifies that we should restart from the beginning.
  221. \\[next-error] normally uses the most recently started
  222. compilation, grep, or occur buffer. It can also operate on any
  223. buffer with output from the \\[compile], \\[grep] commands, or,
  224. more generally, on any buffer in Compilation mode or with
  225. Compilation Minor mode enabled, or any buffer in which
  226. `next-error-function' is bound to an appropriate function.
  227. To specify use of a particular buffer for error messages, type
  228. \\[next-error] in that buffer when it is the only one displayed
  229. in the current frame.
  230. Once \\[next-error] has chosen the buffer for error messages, it
  231. runs `next-error-hook' with `run-hooks', and stays with that buffer
  232. until you use it in some other buffer which uses Compilation mode
  233. or Compilation Minor mode.
  234. To control which errors are matched, customize the variable
  235. `compilation-error-regexp-alist'."
  236. (interactive "P")
  237. (if (consp arg) (setq reset t arg nil))
  238. (when (setq next-error-last-buffer (next-error-find-buffer))
  239. ;; we know here that next-error-function is a valid symbol we can funcall
  240. (with-current-buffer next-error-last-buffer
  241. (funcall next-error-function (prefix-numeric-value arg) reset)
  242. (when next-error-recenter
  243. (recenter next-error-recenter))
  244. (run-hooks 'next-error-hook))))
  245. (defun next-error-internal ()
  246. "Visit the source code corresponding to the `next-error' message at point."
  247. (setq next-error-last-buffer (current-buffer))
  248. ;; we know here that next-error-function is a valid symbol we can funcall
  249. (with-current-buffer next-error-last-buffer
  250. (funcall next-error-function 0 nil)
  251. (when next-error-recenter
  252. (recenter next-error-recenter))
  253. (run-hooks 'next-error-hook)))
  254. (defalias 'goto-next-locus 'next-error)
  255. (defalias 'next-match 'next-error)
  256. (defun previous-error (&optional n)
  257. "Visit previous `next-error' message and corresponding source code.
  258. Prefix arg N says how many error messages to move backwards (or
  259. forwards, if negative).
  260. This operates on the output from the \\[compile] and \\[grep] commands."
  261. (interactive "p")
  262. (next-error (- (or n 1))))
  263. (defun first-error (&optional n)
  264. "Restart at the first error.
  265. Visit corresponding source code.
  266. With prefix arg N, visit the source code of the Nth error.
  267. This operates on the output from the \\[compile] command, for instance."
  268. (interactive "p")
  269. (next-error n t))
  270. (defun next-error-no-select (&optional n)
  271. "Move point to the next error in the `next-error' buffer and highlight match.
  272. Prefix arg N says how many error messages to move forwards (or
  273. backwards, if negative).
  274. Finds and highlights the source line like \\[next-error], but does not
  275. select the source buffer."
  276. (interactive "p")
  277. (let ((next-error-highlight next-error-highlight-no-select))
  278. (next-error n))
  279. (pop-to-buffer next-error-last-buffer))
  280. (defun previous-error-no-select (&optional n)
  281. "Move point to the previous error in the `next-error' buffer and highlight match.
  282. Prefix arg N says how many error messages to move backwards (or
  283. forwards, if negative).
  284. Finds and highlights the source line like \\[previous-error], but does not
  285. select the source buffer."
  286. (interactive "p")
  287. (next-error-no-select (- (or n 1))))
  288. ;; Internal variable for `next-error-follow-mode-post-command-hook'.
  289. (defvar next-error-follow-last-line nil)
  290. (define-minor-mode next-error-follow-minor-mode
  291. "Minor mode for compilation, occur and diff modes.
  292. With a prefix argument ARG, enable mode if ARG is positive, and
  293. disable it otherwise. If called from Lisp, enable mode if ARG is
  294. omitted or nil.
  295. When turned on, cursor motion in the compilation, grep, occur or diff
  296. buffer causes automatic display of the corresponding source code location."
  297. :group 'next-error :init-value nil :lighter " Fol"
  298. (if (not next-error-follow-minor-mode)
  299. (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
  300. (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
  301. (make-local-variable 'next-error-follow-last-line)))
  302. ;; Used as a `post-command-hook' by `next-error-follow-mode'
  303. ;; for the *Compilation* *grep* and *Occur* buffers.
  304. (defun next-error-follow-mode-post-command-hook ()
  305. (unless (equal next-error-follow-last-line (line-number-at-pos))
  306. (setq next-error-follow-last-line (line-number-at-pos))
  307. (condition-case nil
  308. (let ((compilation-context-lines nil))
  309. (setq compilation-current-error (point))
  310. (next-error-no-select 0))
  311. (error t))))
  312. ;;;
  313. (defun fundamental-mode ()
  314. "Major mode not specialized for anything in particular.
  315. Other major modes are defined by comparison with this one."
  316. (interactive)
  317. (kill-all-local-variables)
  318. (run-mode-hooks))
  319. ;; Special major modes to view specially formatted data rather than files.
  320. (defvar special-mode-map
  321. (let ((map (make-sparse-keymap)))
  322. (suppress-keymap map)
  323. (define-key map "q" 'quit-window)
  324. (define-key map " " 'scroll-up-command)
  325. (define-key map [?\S-\ ] 'scroll-down-command)
  326. (define-key map "\C-?" 'scroll-down-command)
  327. (define-key map "?" 'describe-mode)
  328. (define-key map "h" 'describe-mode)
  329. (define-key map ">" 'end-of-buffer)
  330. (define-key map "<" 'beginning-of-buffer)
  331. (define-key map "g" 'revert-buffer)
  332. map))
  333. (put 'special-mode 'mode-class 'special)
  334. (define-derived-mode special-mode nil "Special"
  335. "Parent major mode from which special major modes should inherit."
  336. (setq buffer-read-only t))
  337. ;; Making and deleting lines.
  338. (defvar self-insert-uses-region-functions nil
  339. "Special hook to tell if `self-insert-command' will use the region.
  340. It must be called via `run-hook-with-args-until-success' with no arguments.
  341. Any `post-self-insert-command' which consumes the region should
  342. register a function on this hook so that things like `delete-selection-mode'
  343. can refrain from consuming the region.")
  344. (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
  345. "Propertized string representing a hard newline character.")
  346. (defun newline (&optional arg interactive)
  347. "Insert a newline, and move to left margin of the new line if it's blank.
  348. If option `use-hard-newlines' is non-nil, the newline is marked with the
  349. text-property `hard'.
  350. With ARG, insert that many newlines.
  351. If `electric-indent-mode' is enabled, this indents the final new line
  352. that it adds, and reindents the preceding line. To just insert
  353. a newline, use \\[electric-indent-just-newline].
  354. Calls `auto-fill-function' if the current column number is greater
  355. than the value of `fill-column' and ARG is nil.
  356. A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
  357. (interactive "*P\np")
  358. (barf-if-buffer-read-only)
  359. ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
  360. ;; Set last-command-event to tell self-insert what to insert.
  361. (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
  362. (beforepos (point))
  363. (last-command-event ?\n)
  364. ;; Don't auto-fill if we have a numeric argument.
  365. (auto-fill-function (if arg nil auto-fill-function))
  366. (arg (prefix-numeric-value arg))
  367. (postproc
  368. ;; Do the rest in post-self-insert-hook, because we want to do it
  369. ;; *before* other functions on that hook.
  370. (lambda ()
  371. ;; We are not going to insert any newlines if arg is
  372. ;; non-positive.
  373. (or (and (numberp arg) (<= arg 0))
  374. (cl-assert (eq ?\n (char-before))))
  375. ;; Mark the newline(s) `hard'.
  376. (if use-hard-newlines
  377. (set-hard-newline-properties
  378. (- (point) arg) (point)))
  379. ;; If the newline leaves the previous line blank, and we
  380. ;; have a left margin, delete that from the blank line.
  381. (save-excursion
  382. (goto-char beforepos)
  383. (beginning-of-line)
  384. (and (looking-at "[ \t]$")
  385. (> (current-left-margin) 0)
  386. (delete-region (point)
  387. (line-end-position))))
  388. ;; Indent the line after the newline, except in one case:
  389. ;; when we added the newline at the beginning of a line which
  390. ;; starts a page.
  391. (or was-page-start
  392. (move-to-left-margin nil t)))))
  393. (unwind-protect
  394. (if (not interactive)
  395. ;; FIXME: For non-interactive uses, many calls actually
  396. ;; just want (insert "\n"), so maybe we should do just
  397. ;; that, so as to avoid the risk of filling or running
  398. ;; abbrevs unexpectedly.
  399. (let ((post-self-insert-hook (list postproc)))
  400. (self-insert-command arg))
  401. (unwind-protect
  402. (progn
  403. (add-hook 'post-self-insert-hook postproc nil t)
  404. (self-insert-command arg))
  405. ;; We first used let-binding to protect the hook, but that
  406. ;; was naive since add-hook affects the symbol-default
  407. ;; value of the variable, whereas the let-binding might
  408. ;; only protect the buffer-local value.
  409. (remove-hook 'post-self-insert-hook postproc t)))
  410. (cl-assert (not (member postproc post-self-insert-hook)))
  411. (cl-assert (not (member postproc (default-value 'post-self-insert-hook))))))
  412. nil)
  413. (defun set-hard-newline-properties (from to)
  414. (let ((sticky (get-text-property from 'rear-nonsticky)))
  415. (put-text-property from to 'hard 't)
  416. ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
  417. (if (and (listp sticky) (not (memq 'hard sticky)))
  418. (put-text-property from (point) 'rear-nonsticky
  419. (cons 'hard sticky)))))
  420. (defun open-line (n)
  421. "Insert a newline and leave point before it.
  422. If there is a fill prefix and/or a `left-margin', insert them on
  423. the new line if the line would have been blank.
  424. With arg N, insert N newlines."
  425. (interactive "*p")
  426. (let* ((do-fill-prefix (and fill-prefix (bolp)))
  427. (do-left-margin (and (bolp) (> (current-left-margin) 0)))
  428. (loc (point-marker))
  429. ;; Don't expand an abbrev before point.
  430. (abbrev-mode nil))
  431. (newline n)
  432. (goto-char loc)
  433. (while (> n 0)
  434. (cond ((bolp)
  435. (if do-left-margin (indent-to (current-left-margin)))
  436. (if do-fill-prefix (insert-and-inherit fill-prefix))))
  437. (forward-line 1)
  438. (setq n (1- n)))
  439. (goto-char loc)
  440. ;; Necessary in case a margin or prefix was inserted.
  441. (end-of-line)))
  442. (defun split-line (&optional arg)
  443. "Split current line, moving portion beyond point vertically down.
  444. If the current line starts with `fill-prefix', insert it on the new
  445. line as well. With prefix ARG, don't insert `fill-prefix' on new line.
  446. When called from Lisp code, ARG may be a prefix string to copy."
  447. (interactive "*P")
  448. (skip-chars-forward " \t")
  449. (let* ((col (current-column))
  450. (pos (point))
  451. ;; What prefix should we check for (nil means don't).
  452. (prefix (cond ((stringp arg) arg)
  453. (arg nil)
  454. (t fill-prefix)))
  455. ;; Does this line start with it?
  456. (have-prfx (and prefix
  457. (save-excursion
  458. (beginning-of-line)
  459. (looking-at (regexp-quote prefix))))))
  460. (newline 1)
  461. (if have-prfx (insert-and-inherit prefix))
  462. (indent-to col 0)
  463. (goto-char pos)))
  464. (defun delete-indentation (&optional arg)
  465. "Join this line to previous and fix up whitespace at join.
  466. If there is a fill prefix, delete it from the beginning of this line.
  467. With argument, join this line to following line."
  468. (interactive "*P")
  469. (beginning-of-line)
  470. (if arg (forward-line 1))
  471. (if (eq (preceding-char) ?\n)
  472. (progn
  473. (delete-region (point) (1- (point)))
  474. ;; If the second line started with the fill prefix,
  475. ;; delete the prefix.
  476. (if (and fill-prefix
  477. (<= (+ (point) (length fill-prefix)) (point-max))
  478. (string= fill-prefix
  479. (buffer-substring (point)
  480. (+ (point) (length fill-prefix)))))
  481. (delete-region (point) (+ (point) (length fill-prefix))))
  482. (fixup-whitespace))))
  483. (defalias 'join-line #'delete-indentation) ; easier to find
  484. (defun delete-blank-lines ()
  485. "On blank line, delete all surrounding blank lines, leaving just one.
  486. On isolated blank line, delete that one.
  487. On nonblank line, delete any immediately following blank lines."
  488. (interactive "*")
  489. (let (thisblank singleblank)
  490. (save-excursion
  491. (beginning-of-line)
  492. (setq thisblank (looking-at "[ \t]*$"))
  493. ;; Set singleblank if there is just one blank line here.
  494. (setq singleblank
  495. (and thisblank
  496. (not (looking-at "[ \t]*\n[ \t]*$"))
  497. (or (bobp)
  498. (progn (forward-line -1)
  499. (not (looking-at "[ \t]*$")))))))
  500. ;; Delete preceding blank lines, and this one too if it's the only one.
  501. (if thisblank
  502. (progn
  503. (beginning-of-line)
  504. (if singleblank (forward-line 1))
  505. (delete-region (point)
  506. (if (re-search-backward "[^ \t\n]" nil t)
  507. (progn (forward-line 1) (point))
  508. (point-min)))))
  509. ;; Delete following blank lines, unless the current line is blank
  510. ;; and there are no following blank lines.
  511. (if (not (and thisblank singleblank))
  512. (save-excursion
  513. (end-of-line)
  514. (forward-line 1)
  515. (delete-region (point)
  516. (if (re-search-forward "[^ \t\n]" nil t)
  517. (progn (beginning-of-line) (point))
  518. (point-max)))))
  519. ;; Handle the special case where point is followed by newline and eob.
  520. ;; Delete the line, leaving point at eob.
  521. (if (looking-at "^[ \t]*\n\\'")
  522. (delete-region (point) (point-max)))))
  523. (defcustom delete-trailing-lines t
  524. "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
  525. Trailing lines are deleted only if `delete-trailing-whitespace'
  526. is called on the entire buffer (rather than an active region)."
  527. :type 'boolean
  528. :group 'editing
  529. :version "24.3")
  530. (defun region-modifiable-p (start end)
  531. "Return non-nil if the region contains no read-only text."
  532. (and (not (get-text-property start 'read-only))
  533. (eq end (next-single-property-change start 'read-only nil end))))
  534. (defun delete-trailing-whitespace (&optional start end)
  535. "Delete trailing whitespace between START and END.
  536. If called interactively, START and END are the start/end of the
  537. region if the mark is active, or of the buffer's accessible
  538. portion if the mark is inactive.
  539. This command deletes whitespace characters after the last
  540. non-whitespace character in each line between START and END. It
  541. does not consider formfeed characters to be whitespace.
  542. If this command acts on the entire buffer (i.e. if called
  543. interactively with the mark inactive, or called from Lisp with
  544. END nil), it also deletes all trailing lines at the end of the
  545. buffer if the variable `delete-trailing-lines' is non-nil."
  546. (interactive (progn
  547. (barf-if-buffer-read-only)
  548. (if (use-region-p)
  549. (list (region-beginning) (region-end))
  550. (list nil nil))))
  551. (save-match-data
  552. (save-excursion
  553. (let ((end-marker (and end (copy-marker end))))
  554. (goto-char (or start (point-min)))
  555. (with-syntax-table (make-syntax-table (syntax-table))
  556. ;; Don't delete formfeeds, even if they are considered whitespace.
  557. (modify-syntax-entry ?\f "_")
  558. (while (re-search-forward "\\s-$" end-marker t)
  559. (skip-syntax-backward "-" (line-beginning-position))
  560. (let ((b (point)) (e (match-end 0)))
  561. (when (region-modifiable-p b e)
  562. (delete-region b e)))))
  563. (if end
  564. (set-marker end-marker nil)
  565. ;; Delete trailing empty lines.
  566. (and delete-trailing-lines
  567. ;; Really the end of buffer.
  568. (= (goto-char (point-max)) (1+ (buffer-size)))
  569. (<= (skip-chars-backward "\n") -2)
  570. (region-modifiable-p (1+ (point)) (point-max))
  571. (delete-region (1+ (point)) (point-max)))))))
  572. ;; Return nil for the benefit of `write-file-functions'.
  573. nil)
  574. (defun newline-and-indent ()
  575. "Insert a newline, then indent according to major mode.
  576. Indentation is done using the value of `indent-line-function'.
  577. In programming language modes, this is the same as TAB.
  578. In some text modes, where TAB inserts a tab, this command indents to the
  579. column specified by the function `current-left-margin'."
  580. (interactive "*")
  581. (delete-horizontal-space t)
  582. (newline nil t)
  583. (indent-according-to-mode))
  584. (defun reindent-then-newline-and-indent ()
  585. "Reindent current line, insert newline, then indent the new line.
  586. Indentation of both lines is done according to the current major mode,
  587. which means calling the current value of `indent-line-function'.
  588. In programming language modes, this is the same as TAB.
  589. In some text modes, where TAB inserts a tab, this indents to the
  590. column specified by the function `current-left-margin'."
  591. (interactive "*")
  592. (let ((pos (point)))
  593. ;; Be careful to insert the newline before indenting the line.
  594. ;; Otherwise, the indentation might be wrong.
  595. (newline)
  596. (save-excursion
  597. (goto-char pos)
  598. ;; We are at EOL before the call to indent-according-to-mode, and
  599. ;; after it we usually are as well, but not always. We tried to
  600. ;; address it with `save-excursion' but that uses a normal marker
  601. ;; whereas we need `move after insertion', so we do the save/restore
  602. ;; by hand.
  603. (setq pos (copy-marker pos t))
  604. (indent-according-to-mode)
  605. (goto-char pos)
  606. ;; Remove the trailing white-space after indentation because
  607. ;; indentation may introduce the whitespace.
  608. (delete-horizontal-space t))
  609. (indent-according-to-mode)))
  610. (defcustom read-quoted-char-radix 8
  611. "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
  612. Legitimate radix values are 8, 10 and 16."
  613. :type '(choice (const 8) (const 10) (const 16))
  614. :group 'editing-basics)
  615. (defun read-quoted-char (&optional prompt)
  616. "Like `read-char', but do not allow quitting.
  617. Also, if the first character read is an octal digit,
  618. we read any number of octal digits and return the
  619. specified character code. Any nondigit terminates the sequence.
  620. If the terminator is RET, it is discarded;
  621. any other terminator is used itself as input.
  622. The optional argument PROMPT specifies a string to use to prompt the user.
  623. The variable `read-quoted-char-radix' controls which radix to use
  624. for numeric input."
  625. (let ((message-log-max nil)
  626. (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
  627. help-event-list)))
  628. done (first t) (code 0) char translated)
  629. (while (not done)
  630. (let ((inhibit-quit first)
  631. ;; Don't let C-h or other help chars get the help
  632. ;; message--only help function keys. See bug#16617.
  633. (help-char nil)
  634. (help-event-list help-events)
  635. (help-form
  636. "Type the special character you want to use,
  637. or the octal character code.
  638. RET terminates the character code and is discarded;
  639. any other non-digit terminates the character code and is then used as input."))
  640. (setq char (read-event (and prompt (format "%s-" prompt)) t))
  641. (if inhibit-quit (setq quit-flag nil)))
  642. ;; Translate TAB key into control-I ASCII character, and so on.
  643. ;; Note: `read-char' does it using the `ascii-character' property.
  644. ;; We tried using read-key instead, but that disables the keystroke
  645. ;; echo produced by 'C-q', see bug#24635.
  646. (let ((translation (lookup-key local-function-key-map (vector char))))
  647. (setq translated (if (arrayp translation)
  648. (aref translation 0)
  649. char)))
  650. (if (integerp translated)
  651. (setq translated (char-resolve-modifiers translated)))
  652. (cond ((null translated))
  653. ((not (integerp translated))
  654. (setq unread-command-events (list char)
  655. done t))
  656. ((/= (logand translated ?\M-\^@) 0)
  657. ;; Turn a meta-character into a character with the 0200 bit set.
  658. (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
  659. done t))
  660. ((and (<= ?0 translated)
  661. (< translated (+ ?0 (min 10 read-quoted-char-radix))))
  662. (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
  663. (and prompt (setq prompt (message "%s %c" prompt translated))))
  664. ((and (<= ?a (downcase translated))
  665. (< (downcase translated)
  666. (+ ?a -10 (min 36 read-quoted-char-radix))))
  667. (setq code (+ (* code read-quoted-char-radix)
  668. (+ 10 (- (downcase translated) ?a))))
  669. (and prompt (setq prompt (message "%s %c" prompt translated))))
  670. ((and (not first) (eq translated ?\C-m))
  671. (setq done t))
  672. ((not first)
  673. (setq unread-command-events (list char)
  674. done t))
  675. (t (setq code translated
  676. done t)))
  677. (setq first nil))
  678. code))
  679. (defun quoted-insert (arg)
  680. "Read next input character and insert it.
  681. This is useful for inserting control characters.
  682. With argument, insert ARG copies of the character.
  683. If the first character you type after this command is an octal digit,
  684. you should type a sequence of octal digits which specify a character code.
  685. Any nondigit terminates the sequence. If the terminator is a RET,
  686. it is discarded; any other terminator is used itself as input.
  687. The variable `read-quoted-char-radix' specifies the radix for this feature;
  688. set it to 10 or 16 to use decimal or hex instead of octal.
  689. In overwrite mode, this function inserts the character anyway, and
  690. does not handle octal digits specially. This means that if you use
  691. overwrite as your normal editing mode, you can use this function to
  692. insert characters when necessary.
  693. In binary overwrite mode, this function does overwrite, and octal
  694. digits are interpreted as a character code. This is intended to be
  695. useful for editing binary files."
  696. (interactive "*p")
  697. (let* ((char
  698. ;; Avoid "obsolete" warnings for translation-table-for-input.
  699. (with-no-warnings
  700. (let (translation-table-for-input input-method-function)
  701. (if (or (not overwrite-mode)
  702. (eq overwrite-mode 'overwrite-mode-binary))
  703. (read-quoted-char)
  704. (read-char))))))
  705. ;; This used to assume character codes 0240 - 0377 stand for
  706. ;; characters in some single-byte character set, and converted them
  707. ;; to Emacs characters. But in 23.1 this feature is deprecated
  708. ;; in favor of inserting the corresponding Unicode characters.
  709. ;; (if (and enable-multibyte-characters
  710. ;; (>= char ?\240)
  711. ;; (<= char ?\377))
  712. ;; (setq char (unibyte-char-to-multibyte char)))
  713. (unless (characterp char)
  714. (user-error "%s is not a valid character"
  715. (key-description (vector char))))
  716. (if (> arg 0)
  717. (if (eq overwrite-mode 'overwrite-mode-binary)
  718. (delete-char arg)))
  719. (while (> arg 0)
  720. (insert-and-inherit char)
  721. (setq arg (1- arg)))))
  722. (defun forward-to-indentation (&optional arg)
  723. "Move forward ARG lines and position at first nonblank character."
  724. (interactive "^p")
  725. (forward-line (or arg 1))
  726. (skip-chars-forward " \t"))
  727. (defun backward-to-indentation (&optional arg)
  728. "Move backward ARG lines and position at first nonblank character."
  729. (interactive "^p")
  730. (forward-line (- (or arg 1)))
  731. (skip-chars-forward " \t"))
  732. (defun back-to-indentation ()
  733. "Move point to the first non-whitespace character on this line."
  734. (interactive "^")
  735. (beginning-of-line 1)
  736. (skip-syntax-forward " " (line-end-position))
  737. ;; Move back over chars that have whitespace syntax but have the p flag.
  738. (backward-prefix-chars))
  739. (defun fixup-whitespace ()
  740. "Fixup white space between objects around point.
  741. Leave one space or none, according to the context."
  742. (interactive "*")
  743. (save-excursion
  744. (delete-horizontal-space)
  745. (if (or (looking-at "^\\|$\\|\\s)")
  746. (save-excursion (forward-char -1)
  747. (looking-at "$\\|\\s(\\|\\s'")))
  748. nil
  749. (insert ?\s))))
  750. (defun delete-horizontal-space (&optional backward-only)
  751. "Delete all spaces and tabs around point.
  752. If BACKWARD-ONLY is non-nil, only delete them before point."
  753. (interactive "*P")
  754. (let ((orig-pos (point)))
  755. (delete-region
  756. (if backward-only
  757. orig-pos
  758. (progn
  759. (skip-chars-forward " \t")
  760. (constrain-to-field nil orig-pos t)))
  761. (progn
  762. (skip-chars-backward " \t")
  763. (constrain-to-field nil orig-pos)))))
  764. (defun just-one-space (&optional n)
  765. "Delete all spaces and tabs around point, leaving one space (or N spaces).
  766. If N is negative, delete newlines as well, leaving -N spaces.
  767. See also `cycle-spacing'."
  768. (interactive "*p")
  769. (cycle-spacing n nil 'single-shot))
  770. (defvar cycle-spacing--context nil
  771. "Store context used in consecutive calls to `cycle-spacing' command.
  772. The first time `cycle-spacing' runs, it saves in this variable:
  773. its N argument, the original point position, and the original spacing
  774. around point.")
  775. (defun cycle-spacing (&optional n preserve-nl-back mode)
  776. "Manipulate whitespace around point in a smart way.
  777. In interactive use, this function behaves differently in successive
  778. consecutive calls.
  779. The first call in a sequence acts like `just-one-space'.
  780. It deletes all spaces and tabs around point, leaving one space
  781. \(or N spaces). N is the prefix argument. If N is negative,
  782. it deletes newlines as well, leaving -N spaces.
  783. \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
  784. The second call in a sequence deletes all spaces.
  785. The third call in a sequence restores the original whitespace (and point).
  786. If MODE is `single-shot', it only performs the first step in the sequence.
  787. If MODE is `fast' and the first step would not result in any change
  788. \(i.e., there are exactly (abs N) spaces around point),
  789. the function goes straight to the second step.
  790. Repeatedly calling the function with different values of N starts a
  791. new sequence each time."
  792. (interactive "*p")
  793. (let ((orig-pos (point))
  794. (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
  795. (num (abs (or n 1))))
  796. (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
  797. (constrain-to-field nil orig-pos)
  798. (cond
  799. ;; Command run for the first time, single-shot mode or different argument
  800. ((or (eq 'single-shot mode)
  801. (not (equal last-command this-command))
  802. (not cycle-spacing--context)
  803. (not (eq (car cycle-spacing--context) n)))
  804. (let* ((start (point))
  805. (num (- num (skip-chars-forward " " (+ num (point)))))
  806. (mid (point))
  807. (end (progn
  808. (skip-chars-forward skip-characters)
  809. (constrain-to-field nil orig-pos t))))
  810. (setq cycle-spacing--context ;; Save for later.
  811. ;; Special handling for case where there was no space at all.
  812. (unless (= start end)
  813. (cons n (cons orig-pos (buffer-substring start (point))))))
  814. ;; If this run causes no change in buffer content, delete all spaces,
  815. ;; otherwise delete all excess spaces.
  816. (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
  817. start mid) end)
  818. (insert (make-string num ?\s))))
  819. ;; Command run for the second time.
  820. ((not (equal orig-pos (point)))
  821. (delete-region (point) orig-pos))
  822. ;; Command run for the third time.
  823. (t
  824. (insert (cddr cycle-spacing--context))
  825. (goto-char (cadr cycle-spacing--context))
  826. (setq cycle-spacing--context nil)))))
  827. (defun beginning-of-buffer (&optional arg)
  828. "Move point to the beginning of the buffer.
  829. With numeric arg N, put point N/10 of the way from the beginning.
  830. If the buffer is narrowed, this command uses the beginning of the
  831. accessible part of the buffer.
  832. Push mark at previous position, unless either a \\[universal-argument] prefix
  833. is supplied, or Transient Mark mode is enabled and the mark is active."
  834. (declare (interactive-only "use `(goto-char (point-min))' instead."))
  835. (interactive "^P")
  836. (or (consp arg)
  837. (region-active-p)
  838. (push-mark))
  839. (let ((size (- (point-max) (point-min))))
  840. (goto-char (if (and arg (not (consp arg)))
  841. (+ (point-min)
  842. (if (> size 10000)
  843. ;; Avoid overflow for large buffer sizes!
  844. (* (prefix-numeric-value arg)
  845. (/ size 10))
  846. (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
  847. (point-min))))
  848. (if (and arg (not (consp arg))) (forward-line 1)))
  849. (defun end-of-buffer (&optional arg)
  850. "Move point to the end of the buffer.
  851. With numeric arg N, put point N/10 of the way from the end.
  852. If the buffer is narrowed, this command uses the end of the
  853. accessible part of the buffer.
  854. Push mark at previous position, unless either a \\[universal-argument] prefix
  855. is supplied, or Transient Mark mode is enabled and the mark is active."
  856. (declare (interactive-only "use `(goto-char (point-max))' instead."))
  857. (interactive "^P")
  858. (or (consp arg) (region-active-p) (push-mark))
  859. (let ((size (- (point-max) (point-min))))
  860. (goto-char (if (and arg (not (consp arg)))
  861. (- (point-max)
  862. (if (> size 10000)
  863. ;; Avoid overflow for large buffer sizes!
  864. (* (prefix-numeric-value arg)
  865. (/ size 10))
  866. (/ (* size (prefix-numeric-value arg)) 10)))
  867. (point-max))))
  868. ;; If we went to a place in the middle of the buffer,
  869. ;; adjust it to the beginning of a line.
  870. (cond ((and arg (not (consp arg))) (forward-line 1))
  871. ((and (eq (current-buffer) (window-buffer))
  872. (> (point) (window-end nil t)))
  873. ;; If the end of the buffer is not already on the screen,
  874. ;; then scroll specially to put it near, but not at, the bottom.
  875. (overlay-recenter (point))
  876. (recenter -3))))
  877. (defcustom delete-active-region t
  878. "Whether single-char deletion commands delete an active region.
  879. This has an effect only if Transient Mark mode is enabled, and
  880. affects `delete-forward-char' and `delete-backward-char', though
  881. not `delete-char'.
  882. If the value is the symbol `kill', the active region is killed
  883. instead of deleted."
  884. :type '(choice (const :tag "Delete active region" t)
  885. (const :tag "Kill active region" kill)
  886. (const :tag "Do ordinary deletion" nil))
  887. :group 'killing
  888. :version "24.1")
  889. (defvar region-extract-function
  890. (lambda (method)
  891. (when (region-beginning)
  892. (cond
  893. ((eq method 'bounds)
  894. (list (cons (region-beginning) (region-end))))
  895. ((eq method 'delete-only)
  896. (delete-region (region-beginning) (region-end)))
  897. (t
  898. (filter-buffer-substring (region-beginning) (region-end) method)))))
  899. "Function to get the region's content.
  900. Called with one argument METHOD.
  901. If METHOD is `delete-only', then delete the region; the return value
  902. is undefined. If METHOD is nil, then return the content as a string.
  903. If METHOD is `bounds', then return the boundaries of the region
  904. as a list of the form (START . END).
  905. If METHOD is anything else, delete the region and return its content
  906. as a string, after filtering it with `filter-buffer-substring', which
  907. is called with METHOD as its 3rd argument.")
  908. (defvar region-insert-function
  909. (lambda (lines)
  910. (let ((first t))
  911. (while lines
  912. (or first
  913. (insert ?\n))
  914. (insert-for-yank (car lines))
  915. (setq lines (cdr lines)
  916. first nil))))
  917. "Function to insert the region's content.
  918. Called with one argument LINES.
  919. Insert the region as a list of lines.")
  920. (defun delete-backward-char (n &optional killflag)
  921. "Delete the previous N characters (following if N is negative).
  922. If Transient Mark mode is enabled, the mark is active, and N is 1,
  923. delete the text in the region and deactivate the mark instead.
  924. To disable this, set option `delete-active-region' to nil.
  925. Optional second arg KILLFLAG, if non-nil, means to kill (save in
  926. kill ring) instead of delete. Interactively, N is the prefix
  927. arg, and KILLFLAG is set if N is explicitly specified.
  928. When killing, the killed text is filtered by
  929. `filter-buffer-substring' before it is saved in the kill ring, so
  930. the actual saved text might be different from what was killed.
  931. In Overwrite mode, single character backward deletion may replace
  932. tabs with spaces so as to back over columns, unless point is at
  933. the end of the line."
  934. (declare (interactive-only delete-char))
  935. (interactive "p\nP")
  936. (unless (integerp n)
  937. (signal 'wrong-type-argument (list 'integerp n)))
  938. (cond ((and (use-region-p)
  939. delete-active-region
  940. (= n 1))
  941. ;; If a region is active, kill or delete it.
  942. (if (eq delete-active-region 'kill)
  943. (kill-region (region-beginning) (region-end) 'region)
  944. (funcall region-extract-function 'delete-only)))
  945. ;; In Overwrite mode, maybe untabify while deleting
  946. ((null (or (null overwrite-mode)
  947. (<= n 0)
  948. (memq (char-before) '(?\t ?\n))
  949. (eobp)
  950. (eq (char-after) ?\n)))
  951. (let ((ocol (current-column)))
  952. (delete-char (- n) killflag)
  953. (save-excursion
  954. (insert-char ?\s (- ocol (current-column)) nil))))
  955. ;; Otherwise, do simple deletion.
  956. (t (delete-char (- n) killflag))))
  957. (defun delete-forward-char (n &optional killflag)
  958. "Delete the following N characters (previous if N is negative).
  959. If Transient Mark mode is enabled, the mark is active, and N is 1,
  960. delete the text in the region and deactivate the mark instead.
  961. To disable this, set variable `delete-active-region' to nil.
  962. Optional second arg KILLFLAG non-nil means to kill (save in kill
  963. ring) instead of delete. Interactively, N is the prefix arg, and
  964. KILLFLAG is set if N was explicitly specified.
  965. When killing, the killed text is filtered by
  966. `filter-buffer-substring' before it is saved in the kill ring, so
  967. the actual saved text might be different from what was killed."
  968. (declare (interactive-only delete-char))
  969. (interactive "p\nP")
  970. (unless (integerp n)
  971. (signal 'wrong-type-argument (list 'integerp n)))
  972. (cond ((and (use-region-p)
  973. delete-active-region
  974. (= n 1))
  975. ;; If a region is active, kill or delete it.
  976. (if (eq delete-active-region 'kill)
  977. (kill-region (region-beginning) (region-end) 'region)
  978. (funcall region-extract-function 'delete-only)))
  979. ;; Otherwise, do simple deletion.
  980. (t (delete-char n killflag))))
  981. (defun mark-whole-buffer ()
  982. "Put point at beginning and mark at end of buffer.
  983. If narrowing is in effect, only uses the accessible part of the buffer.
  984. You probably should not use this function in Lisp programs;
  985. it is usually a mistake for a Lisp function to use any subroutine
  986. that uses or sets the mark."
  987. (declare (interactive-only t))
  988. (interactive)
  989. (push-mark)
  990. (push-mark (point-max) nil t)
  991. ;; This is really `point-min' in most cases, but if we're in the
  992. ;; minibuffer, this is at the end of the prompt.
  993. (goto-char (minibuffer-prompt-end)))
  994. ;; Counting lines, one way or another.
  995. (defun goto-line (line &optional buffer)
  996. "Go to LINE, counting from line 1 at beginning of buffer.
  997. If called interactively, a numeric prefix argument specifies
  998. LINE; without a numeric prefix argument, read LINE from the
  999. minibuffer.
  1000. If optional argument BUFFER is non-nil, switch to that buffer and
  1001. move to line LINE there. If called interactively with \\[universal-argument]
  1002. as argument, BUFFER is the most recently selected other buffer.
  1003. Prior to moving point, this function sets the mark (without
  1004. activating it), unless Transient Mark mode is enabled and the
  1005. mark is already active.
  1006. This function is usually the wrong thing to use in a Lisp program.
  1007. What you probably want instead is something like:
  1008. (goto-char (point-min))
  1009. (forward-line (1- N))
  1010. If at all possible, an even better solution is to use char counts
  1011. rather than line counts."
  1012. (declare (interactive-only forward-line))
  1013. (interactive
  1014. (if (and current-prefix-arg (not (consp current-prefix-arg)))
  1015. (list (prefix-numeric-value current-prefix-arg))
  1016. ;; Look for a default, a number in the buffer at point.
  1017. (let* ((default
  1018. (save-excursion
  1019. (skip-chars-backward "0-9")
  1020. (if (looking-at "[0-9]")
  1021. (string-to-number
  1022. (buffer-substring-no-properties
  1023. (point)
  1024. (progn (skip-chars-forward "0-9")
  1025. (point)))))))
  1026. ;; Decide if we're switching buffers.
  1027. (buffer
  1028. (if (consp current-prefix-arg)
  1029. (other-buffer (current-buffer) t)))
  1030. (buffer-prompt
  1031. (if buffer
  1032. (concat " in " (buffer-name buffer))
  1033. "")))
  1034. ;; Read the argument, offering that number (if any) as default.
  1035. (list (read-number (format "Goto line%s: " buffer-prompt)
  1036. (list default (line-number-at-pos)))
  1037. buffer))))
  1038. ;; Switch to the desired buffer, one way or another.
  1039. (if buffer
  1040. (let ((window (get-buffer-window buffer)))
  1041. (if window (select-window window)
  1042. (switch-to-buffer-other-window buffer))))
  1043. ;; Leave mark at previous position
  1044. (or (region-active-p) (push-mark))
  1045. ;; Move to the specified line number in that buffer.
  1046. (save-restriction
  1047. (widen)
  1048. (goto-char (point-min))
  1049. (if (eq selective-display t)
  1050. (re-search-forward "[\n\C-m]" nil 'end (1- line))
  1051. (forward-line (1- line)))))
  1052. (defun count-words-region (start end &optional arg)
  1053. "Count the number of words in the region.
  1054. If called interactively, print a message reporting the number of
  1055. lines, words, and characters in the region (whether or not the
  1056. region is active); with prefix ARG, report for the entire buffer
  1057. rather than the region.
  1058. If called from Lisp, return the number of words between positions
  1059. START and END."
  1060. (interactive (if current-prefix-arg
  1061. (list nil nil current-prefix-arg)
  1062. (list (region-beginning) (region-end) nil)))
  1063. (cond ((not (called-interactively-p 'any))
  1064. (count-words start end))
  1065. (arg
  1066. (count-words--buffer-message))
  1067. (t
  1068. (count-words--message "Region" start end))))
  1069. (defun count-words (start end)
  1070. "Count words between START and END.
  1071. If called interactively, START and END are normally the start and
  1072. end of the buffer; but if the region is active, START and END are
  1073. the start and end of the region. Print a message reporting the
  1074. number of lines, words, and chars.
  1075. If called from Lisp, return the number of words between START and
  1076. END, without printing any message."
  1077. (interactive (list nil nil))
  1078. (cond ((not (called-interactively-p 'any))
  1079. (let ((words 0))
  1080. (save-excursion
  1081. (save-restriction
  1082. (narrow-to-region start end)
  1083. (goto-char (point-min))
  1084. (while (forward-word-strictly 1)
  1085. (setq words (1+ words)))))
  1086. words))
  1087. ((use-region-p)
  1088. (call-interactively 'count-words-region))
  1089. (t
  1090. (count-words--buffer-message))))
  1091. (defun count-words--buffer-message ()
  1092. (count-words--message
  1093. (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
  1094. (point-min) (point-max)))
  1095. (defun count-words--message (str start end)
  1096. (let ((lines (count-lines start end))
  1097. (words (count-words start end))
  1098. (chars (- end start)))
  1099. (message "%s has %d line%s, %d word%s, and %d character%s."
  1100. str
  1101. lines (if (= lines 1) "" "s")
  1102. words (if (= words 1) "" "s")
  1103. chars (if (= chars 1) "" "s"))))
  1104. (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
  1105. (defun what-line ()
  1106. "Print the current buffer line number and narrowed line number of point."
  1107. (interactive)
  1108. (let ((start (point-min))
  1109. (n (line-number-at-pos)))
  1110. (if (= start 1)
  1111. (message "Line %d" n)
  1112. (save-excursion
  1113. (save-restriction
  1114. (widen)
  1115. (message "line %d (narrowed line %d)"
  1116. (+ n (line-number-at-pos start) -1) n))))))
  1117. (defun count-lines (start end)
  1118. "Return number of lines between START and END.
  1119. This is usually the number of newlines between them,
  1120. but can be one more if START is not equal to END
  1121. and the greater of them is not at the start of a line."
  1122. (save-excursion
  1123. (save-restriction
  1124. (narrow-to-region start end)
  1125. (goto-char (point-min))
  1126. (if (eq selective-display t)
  1127. (save-match-data
  1128. (let ((done 0))
  1129. (while (re-search-forward "[\n\C-m]" nil t 40)
  1130. (setq done (+ 40 done)))
  1131. (while (re-search-forward "[\n\C-m]" nil t 1)
  1132. (setq done (+ 1 done)))
  1133. (goto-char (point-max))
  1134. (if (and (/= start end)
  1135. (not (bolp)))
  1136. (1+ done)
  1137. done)))
  1138. (- (buffer-size) (forward-line (buffer-size)))))))
  1139. (defun line-number-at-pos (&optional pos absolute)
  1140. "Return buffer line number at position POS.
  1141. If POS is nil, use current buffer location.
  1142. If ABSOLUTE is nil, the default, counting starts
  1143. at (point-min), so the value refers to the contents of the
  1144. accessible portion of the (potentially narrowed) buffer. If
  1145. ABSOLUTE is non-nil, ignore any narrowing and return the
  1146. absolute line number."
  1147. (save-restriction
  1148. (when absolute
  1149. (widen))
  1150. (let ((opoint (or pos (point))) start)
  1151. (save-excursion
  1152. (goto-char (point-min))
  1153. (setq start (point))
  1154. (goto-char opoint)
  1155. (forward-line 0)
  1156. (1+ (count-lines start (point)))))))
  1157. (defun what-cursor-position (&optional detail)
  1158. "Print info on cursor position (on screen and within buffer).
  1159. Also describe the character after point, and give its character code
  1160. in octal, decimal and hex.
  1161. For a non-ASCII multibyte character, also give its encoding in the
  1162. buffer's selected coding system if the coding system encodes the
  1163. character safely. If the character is encoded into one byte, that
  1164. code is shown in hex. If the character is encoded into more than one
  1165. byte, just \"...\" is shown.
  1166. In addition, with prefix argument, show details about that character
  1167. in *Help* buffer. See also the command `describe-char'."
  1168. (interactive "P")
  1169. (let* ((char (following-char))
  1170. (bidi-fixer
  1171. ;; If the character is one of LRE, LRO, RLE, RLO, it will
  1172. ;; start a directional embedding, which could completely
  1173. ;; disrupt the rest of the line (e.g., RLO will display the
  1174. ;; rest of the line right-to-left). So we put an invisible
  1175. ;; PDF character after these characters, to end the
  1176. ;; embedding, which eliminates any effects on the rest of
  1177. ;; the line. For RLE and RLO we also append an invisible
  1178. ;; LRM, to avoid reordering the following numerical
  1179. ;; characters. For LRI/RLI/FSI we append a PDI.
  1180. (cond ((memq char '(?\x202a ?\x202d))
  1181. (propertize (string ?\x202c) 'invisible t))
  1182. ((memq char '(?\x202b ?\x202e))
  1183. (propertize (string ?\x202c ?\x200e) 'invisible t))
  1184. ((memq char '(?\x2066 ?\x2067 ?\x2068))
  1185. (propertize (string ?\x2069) 'invisible t))
  1186. ;; Strong right-to-left characters cause reordering of
  1187. ;; the following numerical characters which show the
  1188. ;; codepoint, so append LRM to countermand that.
  1189. ((memq (get-char-code-property char 'bidi-class) '(R AL))
  1190. (propertize (string ?\x200e) 'invisible t))
  1191. (t
  1192. "")))
  1193. (beg (point-min))
  1194. (end (point-max))
  1195. (pos (point))
  1196. (total (buffer-size))
  1197. (percent (round (* 100.0 (1- pos)) (max 1 total)))
  1198. (hscroll (if (= (window-hscroll) 0)
  1199. ""
  1200. (format " Hscroll=%d" (window-hscroll))))
  1201. (col (current-column)))
  1202. (if (= pos end)
  1203. (if (or (/= beg 1) (/= end (1+ total)))
  1204. (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
  1205. pos total percent beg end col hscroll)
  1206. (message "point=%d of %d (EOB) column=%d%s"
  1207. pos total col hscroll))
  1208. (let ((coding buffer-file-coding-system)
  1209. encoded encoding-msg display-prop under-display)
  1210. (if (or (not coding)
  1211. (eq (coding-system-type coding) t))
  1212. (setq coding (default-value 'buffer-file-coding-system)))
  1213. (if (eq (char-charset char) 'eight-bit)
  1214. (setq encoding-msg
  1215. (format "(%d, #o%o, #x%x, raw-byte)" char char char))
  1216. ;; Check if the character is displayed with some `display'
  1217. ;; text property. In that case, set under-display to the
  1218. ;; buffer substring covered by that property.
  1219. (setq display-prop (get-char-property pos 'display))
  1220. (if display-prop
  1221. (let ((to (or (next-single-char-property-change pos 'display)
  1222. (point-max))))
  1223. (if (< to (+ pos 4))
  1224. (setq under-display "")
  1225. (setq under-display "..."
  1226. to (+ pos 4)))
  1227. (setq under-display
  1228. (concat (buffer-substring-no-properties pos to)
  1229. under-display)))
  1230. (setq encoded (and (>= char 128) (encode-coding-char char coding))))
  1231. (setq encoding-msg
  1232. (if display-prop
  1233. (if (not (stringp display-prop))
  1234. (format "(%d, #o%o, #x%x, part of display \"%s\")"
  1235. char char char under-display)
  1236. (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
  1237. char char char under-display display-prop))
  1238. (if encoded
  1239. (format "(%d, #o%o, #x%x, file %s)"
  1240. char char char
  1241. (if (> (length encoded) 1)
  1242. "..."
  1243. (encoded-string-description encoded coding)))
  1244. (format "(%d, #o%o, #x%x)" char char char)))))
  1245. (if detail
  1246. ;; We show the detailed information about CHAR.
  1247. (describe-char (point)))
  1248. (if (or (/= beg 1) (/= end (1+ total)))
  1249. (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
  1250. (if (< char 256)
  1251. (single-key-description char)
  1252. (buffer-substring-no-properties (point) (1+ (point))))
  1253. bidi-fixer
  1254. encoding-msg pos total percent beg end col hscroll)
  1255. (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
  1256. (if enable-multibyte-characters
  1257. (if (< char 128)
  1258. (single-key-description char)
  1259. (buffer-substring-no-properties (point) (1+ (point))))
  1260. (single-key-description char))
  1261. bidi-fixer encoding-msg pos total percent col hscroll))))))
  1262. ;; Initialize read-expression-map. It is defined at C level.
  1263. (defvar read-expression-map
  1264. (let ((m (make-sparse-keymap)))
  1265. (define-key m "\M-\t" 'completion-at-point)
  1266. ;; Might as well bind TAB to completion, since inserting a TAB char is
  1267. ;; much too rarely useful.
  1268. (define-key m "\t" 'completion-at-point)
  1269. (set-keymap-parent m minibuffer-local-map)
  1270. m))
  1271. (defun read-minibuffer (prompt &optional initial-contents)
  1272. "Return a Lisp object read using the minibuffer, unevaluated.
  1273. Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
  1274. is a string to insert in the minibuffer before reading.
  1275. \(INITIAL-CONTENTS can also be a cons of a string and an integer.
  1276. Such arguments are used as in `read-from-minibuffer'.)"
  1277. ;; Used for interactive spec `x'.
  1278. (read-from-minibuffer prompt initial-contents minibuffer-local-map
  1279. t 'minibuffer-history))
  1280. (defun eval-minibuffer (prompt &optional initial-contents)
  1281. "Return value of Lisp expression read using the minibuffer.
  1282. Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
  1283. is a string to insert in the minibuffer before reading.
  1284. \(INITIAL-CONTENTS can also be a cons of a string and an integer.
  1285. Such arguments are used as in `read-from-minibuffer'.)"
  1286. ;; Used for interactive spec `X'.
  1287. (eval (read--expression prompt initial-contents)))
  1288. (defvar minibuffer-completing-symbol nil
  1289. "Non-nil means completing a Lisp symbol in the minibuffer.")
  1290. (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
  1291. (defvar minibuffer-default nil
  1292. "The current default value or list of default values in the minibuffer.
  1293. The functions `read-from-minibuffer' and `completing-read' bind
  1294. this variable locally.")
  1295. (defcustom eval-expression-print-level 4
  1296. "Value for `print-level' while printing value in `eval-expression'.
  1297. A value of nil means no limit."
  1298. :group 'lisp
  1299. :type '(choice (const :tag "No Limit" nil) integer)
  1300. :version "21.1")
  1301. (defcustom eval-expression-print-length 12
  1302. "Value for `print-length' while printing value in `eval-expression'.
  1303. A value of nil means no limit."
  1304. :group 'lisp
  1305. :type '(choice (const :tag "No Limit" nil) integer)
  1306. :version "21.1")
  1307. (defcustom eval-expression-debug-on-error t
  1308. "If non-nil set `debug-on-error' to t in `eval-expression'.
  1309. If nil, don't change the value of `debug-on-error'."
  1310. :group 'lisp
  1311. :type 'boolean
  1312. :version "21.1")
  1313. (defcustom eval-expression-print-maximum-character 127
  1314. "The largest integer that will be displayed as a character.
  1315. This affects printing by `eval-expression' (via
  1316. `eval-expression-print-format')."
  1317. :group 'lisp
  1318. :type 'integer
  1319. :version "26.1")
  1320. (defun eval-expression-print-format (value)
  1321. "If VALUE in an integer, return a specially formatted string.
  1322. This string will typically look like \" (#o1, #x1, ?\\C-a)\".
  1323. If VALUE is not an integer, nil is returned.
  1324. This function is used by commands like `eval-expression' that
  1325. display the result of expression evaluation."
  1326. (when (integerp value)
  1327. (let ((char-string
  1328. (and (characterp value)
  1329. (<= value eval-expression-print-maximum-character)
  1330. (char-displayable-p value)
  1331. (prin1-char value))))
  1332. (if char-string
  1333. (format " (#o%o, #x%x, %s)" value value char-string)
  1334. (format " (#o%o, #x%x)" value value)))))
  1335. (defvar eval-expression-minibuffer-setup-hook nil
  1336. "Hook run by `eval-expression' when entering the minibuffer.")
  1337. (defun read--expression (prompt &optional initial-contents)
  1338. (let ((minibuffer-completing-symbol t))
  1339. (minibuffer-with-setup-hook
  1340. (lambda ()
  1341. ;; FIXME: call emacs-lisp-mode?
  1342. (add-function :before-until (local 'eldoc-documentation-function)
  1343. #'elisp-eldoc-documentation-function)
  1344. (eldoc-mode 1)
  1345. (add-hook 'completion-at-point-functions
  1346. #'elisp-completion-at-point nil t)
  1347. (run-hooks 'eval-expression-minibuffer-setup-hook))
  1348. (read-from-minibuffer prompt initial-contents
  1349. read-expression-map t
  1350. 'read-expression-history))))
  1351. (defun eval-expression-get-print-arguments (prefix-argument)
  1352. "Get arguments for commands that print an expression result.
  1353. Returns a list (INSERT-VALUE NO-TRUNCATE CHAR-PRINT-LIMIT)
  1354. based on PREFIX-ARG. This function determines the interpretation
  1355. of the prefix argument for `eval-expression' and
  1356. `eval-last-sexp'."
  1357. (let ((num (prefix-numeric-value prefix-argument)))
  1358. (list (not (memq prefix-argument '(- nil)))
  1359. (= num 0)
  1360. (cond ((not (memq prefix-argument '(0 -1 - nil))) nil)
  1361. ((= num -1) most-positive-fixnum)
  1362. (t eval-expression-print-maximum-character)))))
  1363. ;; We define this, rather than making `eval' interactive,
  1364. ;; for the sake of completion of names like eval-region, eval-buffer.
  1365. (defun eval-expression (exp &optional insert-value no-truncate char-print-limit)
  1366. "Evaluate EXP and print value in the echo area.
  1367. When called interactively, read an Emacs Lisp expression and
  1368. evaluate it. Value is also consed on to front of the variable
  1369. `values'. Optional argument INSERT-VALUE non-nil (interactively,
  1370. with a non `-' prefix argument) means insert the result into the
  1371. current buffer instead of printing it in the echo area.
  1372. Normally, this function truncates long output according to the
  1373. value of the variables `eval-expression-print-length' and
  1374. `eval-expression-print-level'. When NO-TRUNCATE is
  1375. non-nil (interactively, with a prefix argument of zero), however,
  1376. there is no such truncation.
  1377. If the resulting value is an integer, and CHAR-PRINT-LIMIT is
  1378. non-nil (interactively, unless given a positive prefix argument)
  1379. it will be printed in several additional formats (octal,
  1380. hexadecimal, and character). The character format is only used
  1381. if the value is below CHAR-PRINT-LIMIT (interactively, if the
  1382. prefix argument is -1 or the value is below
  1383. `eval-expression-print-maximum-character').
  1384. Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
  1385. minibuffer.
  1386. If `eval-expression-debug-on-error' is non-nil, which is the default,
  1387. this command arranges for all errors to enter the debugger."
  1388. (interactive
  1389. (cons (read--expression "Eval: ")
  1390. (eval-expression-get-print-arguments current-prefix-arg)))
  1391. (if (null eval-expression-debug-on-error)
  1392. (push (eval exp lexical-binding) values)
  1393. (let ((old-value (make-symbol "t")) new-value)
  1394. ;; Bind debug-on-error to something unique so that we can
  1395. ;; detect when evalled code changes it.
  1396. (let ((debug-on-error old-value))
  1397. (push (eval (macroexpand-all exp) lexical-binding) values)
  1398. (setq new-value debug-on-error))
  1399. ;; If evalled code has changed the value of debug-on-error,
  1400. ;; propagate that change to the global binding.
  1401. (unless (eq old-value new-value)
  1402. (setq debug-on-error new-value))))
  1403. (let ((print-length (unless no-truncate eval-expression-print-length))
  1404. (print-level (unless no-truncate eval-expression-print-level))
  1405. (eval-expression-print-maximum-character char-print-limit)
  1406. (deactivate-mark))
  1407. (let ((out (if insert-value (current-buffer) t)))
  1408. (prog1
  1409. (prin1 (car values) out)
  1410. (let ((str (and char-print-limit
  1411. (eval-expression-print-format (car values)))))
  1412. (when str (princ str out)))))))
  1413. (defun edit-and-eval-command (prompt command)
  1414. "Prompting with PROMPT, let user edit COMMAND and eval result.
  1415. COMMAND is a Lisp expression. Let user edit that expression in
  1416. the minibuffer, then read and evaluate the result."
  1417. (let ((command
  1418. (let ((print-level nil)
  1419. (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
  1420. (unwind-protect
  1421. (read-from-minibuffer prompt
  1422. (prin1-to-string command)
  1423. read-expression-map t
  1424. 'command-history)
  1425. ;; If command was added to command-history as a string,
  1426. ;; get rid of that. We want only evaluable expressions there.
  1427. (if (stringp (car command-history))
  1428. (setq command-history (cdr command-history)))))))
  1429. ;; If command to be redone does not match front of history,
  1430. ;; add it to the history.
  1431. (or (equal command (car command-history))
  1432. (setq command-history (cons command command-history)))
  1433. (eval command)))
  1434. (defun repeat-complex-command (arg)
  1435. "Edit and re-evaluate last complex command, or ARGth from last.
  1436. A complex command is one which used the minibuffer.
  1437. The command is placed in the minibuffer as a Lisp form for editing.
  1438. The result is executed, repeating the command as changed.
  1439. If the command has been changed or is not the most recent previous
  1440. command it is added to the front of the command history.
  1441. You can use the minibuffer history commands \
  1442. \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
  1443. to get different commands to edit and resubmit."
  1444. (interactive "p")
  1445. (let ((elt (nth (1- arg) command-history))
  1446. newcmd)
  1447. (if elt
  1448. (progn
  1449. (setq newcmd
  1450. (let ((print-level nil)
  1451. (minibuffer-history-position arg)
  1452. (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
  1453. (unwind-protect
  1454. (read-from-minibuffer
  1455. "Redo: " (prin1-to-string elt) read-expression-map t
  1456. (cons 'command-history arg))
  1457. ;; If command was added to command-history as a
  1458. ;; string, get rid of that. We want only
  1459. ;; evaluable expressions there.
  1460. (if (stringp (car command-history))
  1461. (setq command-history (cdr command-history))))))
  1462. ;; If command to be redone does not match front of history,
  1463. ;; add it to the history.
  1464. (or (equal newcmd (car command-history))
  1465. (setq command-history (cons newcmd command-history)))
  1466. (apply #'funcall-interactively
  1467. (car newcmd)
  1468. (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
  1469. (if command-history
  1470. (error "Argument %d is beyond length of command history" arg)
  1471. (error "There are no previous complex commands to repeat")))))
  1472. (defvar extended-command-history nil)
  1473. (defvar execute-extended-command--last-typed nil)
  1474. (defun read-extended-command ()
  1475. "Read command name to invoke in `execute-extended-command'."
  1476. (minibuffer-with-setup-hook
  1477. (lambda ()
  1478. (add-hook 'post-self-insert-hook
  1479. (lambda ()
  1480. (setq execute-extended-command--last-typed
  1481. (minibuffer-contents)))
  1482. nil 'local)
  1483. (set (make-local-variable 'minibuffer-default-add-function)
  1484. (lambda ()
  1485. ;; Get a command name at point in the original buffer
  1486. ;; to propose it after M-n.
  1487. (with-current-buffer (window-buffer (minibuffer-selected-window))
  1488. (and (commandp (function-called-at-point))
  1489. (format "%S" (function-called-at-point)))))))
  1490. ;; Read a string, completing from and restricting to the set of
  1491. ;; all defined commands. Don't provide any initial input.
  1492. ;; Save the command read on the extended-command history list.
  1493. (completing-read
  1494. (concat (cond
  1495. ((eq current-prefix-arg '-) "- ")
  1496. ((and (consp current-prefix-arg)
  1497. (eq (car current-prefix-arg) 4)) "C-u ")
  1498. ((and (consp current-prefix-arg)
  1499. (integerp (car current-prefix-arg)))
  1500. (format "%d " (car current-prefix-arg)))
  1501. ((integerp current-prefix-arg)
  1502. (format "%d " current-prefix-arg)))
  1503. ;; This isn't strictly correct if `execute-extended-command'
  1504. ;; is bound to anything else (e.g. [menu]).
  1505. ;; It could use (key-description (this-single-command-keys)),
  1506. ;; but actually a prompt other than "M-x" would be confusing,
  1507. ;; because "M-x" is a well-known prompt to read a command
  1508. ;; and it serves as a shorthand for "Extended command: ".
  1509. "M-x ")
  1510. (lambda (string pred action)
  1511. (let ((pred
  1512. (if (memq action '(nil t))
  1513. ;; Exclude obsolete commands from completions.
  1514. (lambda (sym)
  1515. (and (funcall pred sym)
  1516. (or (equal string (symbol-name sym))
  1517. (not (get sym 'byte-obsolete-info)))))
  1518. pred)))
  1519. (complete-with-action action obarray string pred)))
  1520. #'commandp t nil 'extended-command-history)))
  1521. (defcustom suggest-key-bindings t
  1522. "Non-nil means show the equivalent key-binding when M-x command has one.
  1523. The value can be a length of time to show the message for.
  1524. If the value is non-nil and not a number, we wait 2 seconds."
  1525. :group 'keyboard
  1526. :type '(choice (const :tag "off" nil)
  1527. (integer :tag "time" 2)
  1528. (other :tag "on")))
  1529. (defcustom extended-command-suggest-shorter t
  1530. "If non-nil, show a shorter M-x invocation when there is one."
  1531. :group 'keyboard
  1532. :type 'boolean
  1533. :version "26.1")
  1534. (defun execute-extended-command--shorter-1 (name length)
  1535. (cond
  1536. ((zerop length) (list ""))
  1537. ((equal name "") nil)
  1538. (t
  1539. (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
  1540. (execute-extended-command--shorter-1
  1541. (substring name 1) (1- length)))
  1542. (when (string-match "\\`\\(-\\)?[^-]*" name)
  1543. (execute-extended-command--shorter-1
  1544. (substring name (match-end 0)) length))))))
  1545. (defun execute-extended-command--shorter (name typed)
  1546. (let ((candidates '())
  1547. (max (length typed))
  1548. (len 1)
  1549. binding)
  1550. (while (and (not binding)
  1551. (progn
  1552. (unless candidates
  1553. (setq len (1+ len))
  1554. (setq candidates (execute-extended-command--shorter-1
  1555. name len)))
  1556. ;; Don't show the help message if the binding isn't
  1557. ;; significantly shorter than the M-x command the user typed.
  1558. (< len (- max 5))))
  1559. (input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
  1560. (let ((candidate (pop candidates)))
  1561. (when (equal name
  1562. (car-safe (completion-try-completion
  1563. candidate obarray 'commandp len)))
  1564. (setq binding candidate))))
  1565. binding))
  1566. (defun execute-extended-command (prefixarg &optional command-name typed)
  1567. ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
  1568. ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
  1569. "Read a command name, then read the arguments and call the command.
  1570. To pass a prefix argument to the command you are
  1571. invoking, give a prefix argument to `execute-extended-command'."
  1572. (declare (interactive-only command-execute))
  1573. ;; FIXME: Remember the actual text typed by the user before completion,
  1574. ;; so that we don't later on suggest the same shortening.
  1575. (interactive
  1576. (let ((execute-extended-command--last-typed nil))
  1577. (list current-prefix-arg
  1578. (read-extended-command)
  1579. execute-extended-command--last-typed)))
  1580. ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
  1581. (unless command-name
  1582. (let ((current-prefix-arg prefixarg) ; for prompt
  1583. (execute-extended-command--last-typed nil))
  1584. (setq command-name (read-extended-command))
  1585. (setq typed execute-extended-command--last-typed)))
  1586. (let* ((function (and (stringp command-name) (intern-soft command-name)))
  1587. (binding (and suggest-key-bindings
  1588. (not executing-kbd-macro)
  1589. (where-is-internal function overriding-local-map t))))
  1590. (unless (commandp function)
  1591. (error "`%s' is not a valid command name" command-name))
  1592. ;; Some features, such as novice.el, rely on this-command-keys
  1593. ;; including M-x COMMAND-NAME RET.
  1594. (set--this-command-keys (concat "\M-x" (symbol-name function) "\r"))
  1595. (setq this-command function)
  1596. ;; Normally `real-this-command' should never be changed, but here we really
  1597. ;; want to pretend that M-x <cmd> RET is nothing more than a "key
  1598. ;; binding" for <cmd>, so the command the user really wanted to run is
  1599. ;; `function' and not `execute-extended-command'. The difference is
  1600. ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
  1601. (setq real-this-command function)
  1602. (let ((prefix-arg prefixarg))
  1603. (command-execute function 'record))
  1604. ;; If enabled, show which key runs this command.
  1605. ;; But first wait, and skip the message if there is input.
  1606. (let* ((waited
  1607. ;; If this command displayed something in the echo area;
  1608. ;; wait a few seconds, then display our suggestion message.
  1609. ;; FIXME: Wait *after* running post-command-hook!
  1610. ;; FIXME: Don't wait if execute-extended-command--shorter won't
  1611. ;; find a better answer anyway!
  1612. (when suggest-key-bindings
  1613. (sit-for (cond
  1614. ((zerop (length (current-message))) 0)
  1615. ((numberp suggest-key-bindings) suggest-key-bindings)
  1616. (t 2))))))
  1617. (when (and waited (not (consp unread-command-events)))
  1618. (unless (or (not extended-command-suggest-shorter)
  1619. binding executing-kbd-macro (not (symbolp function))
  1620. (<= (length (symbol-name function)) 2))
  1621. ;; There's no binding for CMD. Let's try and find the shortest
  1622. ;; string to use in M-x.
  1623. ;; FIXME: Can be slow. Cache it maybe?
  1624. (while-no-input
  1625. (setq binding (execute-extended-command--shorter
  1626. (symbol-name function) typed))))
  1627. (when binding
  1628. (with-temp-message
  1629. (format-message "You can run the command `%s' with %s"
  1630. function
  1631. (if (stringp binding)
  1632. (concat "M-x " binding " RET")
  1633. (key-description binding)))
  1634. (sit-for (if (numberp suggest-key-bindings)
  1635. suggest-key-bindings
  1636. 2))))))))
  1637. (defun command-execute (cmd &optional record-flag keys special)
  1638. ;; BEWARE: Called directly from the C code.
  1639. "Execute CMD as an editor command.
  1640. CMD must be a symbol that satisfies the `commandp' predicate.
  1641. Optional second arg RECORD-FLAG non-nil
  1642. means unconditionally put this command in the variable `command-history'.
  1643. Otherwise, that is done only if an arg is read using the minibuffer.
  1644. The argument KEYS specifies the value to use instead of (this-command-keys)
  1645. when reading the arguments; if it is nil, (this-command-keys) is used.
  1646. The argument SPECIAL, if non-nil, means that this command is executing
  1647. a special event, so ignore the prefix argument and don't clear it."
  1648. (setq debug-on-next-call nil)
  1649. (let ((prefixarg (unless special
  1650. ;; FIXME: This should probably be done around
  1651. ;; pre-command-hook rather than here!
  1652. (prog1 prefix-arg
  1653. (setq current-prefix-arg prefix-arg)
  1654. (setq prefix-arg nil)
  1655. (when current-prefix-arg
  1656. (prefix-command-update))))))
  1657. (if (and (symbolp cmd)
  1658. (get cmd 'disabled)
  1659. disabled-command-function)
  1660. ;; FIXME: Weird calling convention!
  1661. (run-hooks 'disabled-command-function)
  1662. (let ((final cmd))
  1663. (while
  1664. (progn
  1665. (setq final (indirect-function final))
  1666. (if (autoloadp final)
  1667. (setq final (autoload-do-load final cmd)))))
  1668. (cond
  1669. ((arrayp final)
  1670. ;; If requested, place the macro in the command history. For
  1671. ;; other sorts of commands, call-interactively takes care of this.
  1672. (when record-flag
  1673. (push `(execute-kbd-macro ,final ,prefixarg) command-history)
  1674. ;; Don't keep command history around forever.
  1675. (when (and (numberp history-length) (> history-length 0))
  1676. (let ((cell (nthcdr history-length command-history)))
  1677. (if (consp cell) (setcdr cell nil)))))
  1678. (execute-kbd-macro final prefixarg))
  1679. (t
  1680. ;; Pass `cmd' rather than `final', for the backtrace's sake.
  1681. (prog1 (call-interactively cmd record-flag keys)
  1682. (when (and (symbolp cmd)
  1683. (get cmd 'byte-obsolete-info)
  1684. (not (get cmd 'command-execute-obsolete-warned)))
  1685. (put cmd 'command-execute-obsolete-warned t)
  1686. (message "%s" (macroexp--obsolete-warning
  1687. cmd (get cmd 'byte-obsolete-info) "command"))))))))))
  1688. (defvar minibuffer-history nil
  1689. "Default minibuffer history list.
  1690. This is used for all minibuffer input
  1691. except when an alternate history list is specified.
  1692. Maximum length of the history list is determined by the value
  1693. of `history-length', which see.")
  1694. (defvar minibuffer-history-sexp-flag nil
  1695. "Control whether history list elements are expressions or strings.
  1696. If the value of this variable equals current minibuffer depth,
  1697. they are expressions; otherwise they are strings.
  1698. \(That convention is designed to do the right thing for
  1699. recursive uses of the minibuffer.)")
  1700. (setq minibuffer-history-variable 'minibuffer-history)
  1701. (setq minibuffer-history-position nil) ;; Defvar is in C code.
  1702. (defvar minibuffer-history-search-history nil)
  1703. (defvar minibuffer-text-before-history nil
  1704. "Text that was in this minibuffer before any history commands.
  1705. This is nil if there have not yet been any history commands
  1706. in this use of the minibuffer.")
  1707. (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
  1708. (defun minibuffer-history-initialize ()
  1709. (setq minibuffer-text-before-history nil))
  1710. (defun minibuffer-avoid-prompt (_new _old)
  1711. "A point-motion hook for the minibuffer, that moves point out of the prompt."
  1712. (declare (obsolete cursor-intangible-mode "25.1"))
  1713. (constrain-to-field nil (point-max)))
  1714. (defcustom minibuffer-history-case-insensitive-variables nil
  1715. "Minibuffer history variables for which matching should ignore case.
  1716. If a history variable is a member of this list, then the
  1717. \\[previous-matching-history-element] and \\[next-matching-history-element]\
  1718. commands ignore case when searching it, regardless of `case-fold-search'."
  1719. :type '(repeat variable)
  1720. :group 'minibuffer)
  1721. (defun previous-matching-history-element (regexp n)
  1722. "Find the previous history element that matches REGEXP.
  1723. \(Previous history elements refer to earlier actions.)
  1724. With prefix argument N, search for Nth previous match.
  1725. If N is negative, find the next or Nth next match.
  1726. Normally, history elements are matched case-insensitively if
  1727. `case-fold-search' is non-nil, but an uppercase letter in REGEXP
  1728. makes the search case-sensitive.
  1729. See also `minibuffer-history-case-insensitive-variables'."
  1730. (interactive
  1731. (let* ((enable-recursive-minibuffers t)
  1732. (regexp (read-from-minibuffer "Previous element matching (regexp): "
  1733. nil
  1734. minibuffer-local-map
  1735. nil
  1736. 'minibuffer-history-search-history
  1737. (car minibuffer-history-search-history))))
  1738. ;; Use the last regexp specified, by default, if input is empty.
  1739. (list (if (string= regexp "")
  1740. (if minibuffer-history-search-history
  1741. (car minibuffer-history-search-history)
  1742. (user-error "No previous history search regexp"))
  1743. regexp)
  1744. (prefix-numeric-value current-prefix-arg))))
  1745. (unless (zerop n)
  1746. (if (and (zerop minibuffer-history-position)
  1747. (null minibuffer-text-before-history))
  1748. (setq minibuffer-text-before-history
  1749. (minibuffer-contents-no-properties)))
  1750. (let ((history (symbol-value minibuffer-history-variable))
  1751. (case-fold-search
  1752. (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
  1753. ;; On some systems, ignore case for file names.
  1754. (if (memq minibuffer-history-variable
  1755. minibuffer-history-case-insensitive-variables)
  1756. t
  1757. ;; Respect the user's setting for case-fold-search:
  1758. case-fold-search)
  1759. nil))
  1760. prevpos
  1761. match-string
  1762. match-offset
  1763. (pos minibuffer-history-position))
  1764. (while (/= n 0)
  1765. (setq prevpos pos)
  1766. (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
  1767. (when (= pos prevpos)
  1768. (user-error (if (= pos 1)
  1769. "No later matching history item"
  1770. "No earlier matching history item")))
  1771. (setq match-string
  1772. (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
  1773. (let ((print-level nil))
  1774. (prin1-to-string (nth (1- pos) history)))
  1775. (nth (1- pos) history)))
  1776. (setq match-offset
  1777. (if (< n 0)
  1778. (and (string-match regexp match-string)
  1779. (match-end 0))
  1780. (and (string-match (concat ".*\\(" regexp "\\)") match-string)
  1781. (match-beginning 1))))
  1782. (when match-offset
  1783. (setq n (+ n (if (< n 0) 1 -1)))))
  1784. (setq minibuffer-history-position pos)
  1785. (goto-char (point-max))
  1786. (delete-minibuffer-contents)
  1787. (insert match-string)
  1788. (goto-char (+ (minibuffer-prompt-end) match-offset))))
  1789. (if (memq (car (car command-history)) '(previous-matching-history-element
  1790. next-matching-history-element))
  1791. (setq command-history (cdr command-history))))
  1792. (defun next-matching-history-element (regexp n)
  1793. "Find the next history element that matches REGEXP.
  1794. \(The next history element refers to a more recent action.)
  1795. With prefix argument N, search for Nth next match.
  1796. If N is negative, find the previous or Nth previous match.
  1797. Normally, history elements are matched case-insensitively if
  1798. `case-fold-search' is non-nil, but an uppercase letter in REGEXP
  1799. makes the search case-sensitive."
  1800. (interactive
  1801. (let* ((enable-recursive-minibuffers t)
  1802. (regexp (read-from-minibuffer "Next element matching (regexp): "
  1803. nil
  1804. minibuffer-local-map
  1805. nil
  1806. 'minibuffer-history-search-history
  1807. (car minibuffer-history-search-history))))
  1808. ;; Use the last regexp specified, by default, if input is empty.
  1809. (list (if (string= regexp "")
  1810. (if minibuffer-history-search-history
  1811. (car minibuffer-history-search-history)
  1812. (user-error "No previous history search regexp"))
  1813. regexp)
  1814. (prefix-numeric-value current-prefix-arg))))
  1815. (previous-matching-history-element regexp (- n)))
  1816. (defvar minibuffer-temporary-goal-position nil)
  1817. (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
  1818. "Function run by `goto-history-element' before consuming default values.
  1819. This is useful to dynamically add more elements to the list of default values
  1820. when `goto-history-element' reaches the end of this list.
  1821. Before calling this function `goto-history-element' sets the variable
  1822. `minibuffer-default-add-done' to t, so it will call this function only
  1823. once. In special cases, when this function needs to be called more
  1824. than once, it can set `minibuffer-default-add-done' to nil explicitly,
  1825. overriding the setting of this variable to t in `goto-history-element'.")
  1826. (defvar minibuffer-default-add-done nil
  1827. "When nil, add more elements to the end of the list of default values.
  1828. The value nil causes `goto-history-element' to add more elements to
  1829. the list of defaults when it reaches the end of this list. It does
  1830. this by calling a function defined by `minibuffer-default-add-function'.")
  1831. (make-variable-buffer-local 'minibuffer-default-add-done)
  1832. (defun minibuffer-default-add-completions ()
  1833. "Return a list of all completions without the default value.
  1834. This function is used to add all elements of the completion table to
  1835. the end of the list of defaults just after the default value."
  1836. (let ((def minibuffer-default)
  1837. (all (all-completions ""
  1838. minibuffer-completion-table
  1839. minibuffer-completion-predicate)))
  1840. (if (listp def)
  1841. (append def all)
  1842. (cons def (delete def all)))))
  1843. (defun goto-history-element (nabs)
  1844. "Puts element of the minibuffer history in the minibuffer.
  1845. The argument NABS specifies the absolute history position."
  1846. (interactive "p")
  1847. (when (and (not minibuffer-default-add-done)
  1848. (functionp minibuffer-default-add-function)
  1849. (< nabs (- (if (listp minibuffer-default)
  1850. (length minibuffer-default)
  1851. 1))))
  1852. (setq minibuffer-default-add-done t
  1853. minibuffer-default (funcall minibuffer-default-add-function)))
  1854. (let ((minimum (if minibuffer-default
  1855. (- (if (listp minibuffer-default)
  1856. (length minibuffer-default)
  1857. 1))
  1858. 0))
  1859. elt minibuffer-returned-to-present)
  1860. (if (and (zerop minibuffer-history-position)
  1861. (null minibuffer-text-before-history))
  1862. (setq minibuffer-text-before-history
  1863. (minibuffer-contents-no-properties)))
  1864. (if (< nabs minimum)
  1865. (user-error (if minibuffer-default
  1866. "End of defaults; no next item"
  1867. "End of history; no default available")))
  1868. (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
  1869. (length (symbol-value minibuffer-history-variable))
  1870. 0))
  1871. (user-error "Beginning of history; no preceding item"))
  1872. (unless (memq last-command '(next-history-element
  1873. previous-history-element))
  1874. (let ((prompt-end (minibuffer-prompt-end)))
  1875. (set (make-local-variable 'minibuffer-temporary-goal-position)
  1876. (cond ((<= (point) prompt-end) prompt-end)
  1877. ((eobp) nil)
  1878. (t (point))))))
  1879. (goto-char (point-max))
  1880. (delete-minibuffer-contents)
  1881. (setq minibuffer-history-position nabs)
  1882. (cond ((< nabs 0)
  1883. (setq elt (if (listp minibuffer-default)
  1884. (nth (1- (abs nabs)) minibuffer-default)
  1885. minibuffer-default)))
  1886. ((= nabs 0)
  1887. (setq elt (or minibuffer-text-before-history ""))
  1888. (setq minibuffer-returned-to-present t)
  1889. (setq minibuffer-text-before-history nil))
  1890. (t (setq elt (nth (1- minibuffer-history-position)
  1891. (symbol-value minibuffer-history-variable)))))
  1892. (insert
  1893. (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
  1894. (not minibuffer-returned-to-present))
  1895. (let ((print-level nil))
  1896. (prin1-to-string elt))
  1897. elt))
  1898. (goto-char (or minibuffer-temporary-goal-position (point-max)))))
  1899. (defun next-history-element (n)
  1900. "Puts next element of the minibuffer history in the minibuffer.
  1901. With argument N, it uses the Nth following element."
  1902. (interactive "p")
  1903. (or (zerop n)
  1904. (goto-history-element (- minibuffer-history-position n))))
  1905. (defun previous-history-element (n)
  1906. "Puts previous element of the minibuffer history in the minibuffer.
  1907. With argument N, it uses the Nth previous element."
  1908. (interactive "p")
  1909. (or (zerop n)
  1910. (goto-history-element (+ minibuffer-history-position n))))
  1911. (defun next-line-or-history-element (&optional arg)
  1912. "Move cursor vertically down ARG lines, or to the next history element.
  1913. When point moves over the bottom line of multi-line minibuffer, puts ARGth
  1914. next element of the minibuffer history in the minibuffer."
  1915. (interactive "^p")
  1916. (or arg (setq arg 1))
  1917. (let* ((old-point (point))
  1918. ;; Remember the original goal column of possibly multi-line input
  1919. ;; excluding the length of the prompt on the first line.
  1920. (prompt-end (minibuffer-prompt-end))
  1921. (old-column (unless (and (eolp) (> (point) prompt-end))
  1922. (if (= (line-number-at-pos) 1)
  1923. (max (- (current-column) (1- prompt-end)) 0)
  1924. (current-column)))))
  1925. (condition-case nil
  1926. (with-no-warnings
  1927. (next-line arg))
  1928. (end-of-buffer
  1929. ;; Restore old position since `line-move-visual' moves point to
  1930. ;; the end of the line when it fails to go to the next line.
  1931. (goto-char old-point)
  1932. (next-history-element arg)
  1933. ;; Reset `temporary-goal-column' because a correct value is not
  1934. ;; calculated when `next-line' above fails by bumping against
  1935. ;; the bottom of the minibuffer (bug#22544).
  1936. (setq temporary-goal-column 0)
  1937. ;; Restore the original goal column on the last line
  1938. ;; of possibly multi-line input.
  1939. (goto-char (point-max))
  1940. (when old-column
  1941. (if (= (line-number-at-pos) 1)
  1942. (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
  1943. (move-to-column old-column)))))))
  1944. (defun previous-line-or-history-element (&optional arg)
  1945. "Move cursor vertically up ARG lines, or to the previous history element.
  1946. When point moves over the top line of multi-line minibuffer, puts ARGth
  1947. previous element of the minibuffer history in the minibuffer."
  1948. (interactive "^p")
  1949. (or arg (setq arg 1))
  1950. (let* ((old-point (point))
  1951. ;; Remember the original goal column of possibly multi-line input
  1952. ;; excluding the length of the prompt on the first line.
  1953. (prompt-end (minibuffer-prompt-end))
  1954. (old-column (unless (and (eolp) (> (point) prompt-end))
  1955. (if (= (line-number-at-pos) 1)
  1956. (max (- (current-column) (1- prompt-end)) 0)
  1957. (current-column)))))
  1958. (condition-case nil
  1959. (with-no-warnings
  1960. (previous-line arg))
  1961. (beginning-of-buffer
  1962. ;; Restore old position since `line-move-visual' moves point to
  1963. ;; the beginning of the line when it fails to go to the previous line.
  1964. (goto-char old-point)
  1965. (previous-history-element arg)
  1966. ;; Reset `temporary-goal-column' because a correct value is not
  1967. ;; calculated when `previous-line' above fails by bumping against
  1968. ;; the top of the minibuffer (bug#22544).
  1969. (setq temporary-goal-column 0)
  1970. ;; Restore the original goal column on the first line
  1971. ;; of possibly multi-line input.
  1972. (goto-char (minibuffer-prompt-end))
  1973. (if old-column
  1974. (if (= (line-number-at-pos) 1)
  1975. (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
  1976. (move-to-column old-column))
  1977. ;; Put the cursor at the end of the visual line instead of the
  1978. ;; logical line, so the next `previous-line-or-history-element'
  1979. ;; would move to the previous history element, not to a possible upper
  1980. ;; visual line from the end of logical line in `line-move-visual' mode.
  1981. (end-of-visual-line)
  1982. ;; Since `end-of-visual-line' puts the cursor at the beginning
  1983. ;; of the next visual line, move it one char back to the end
  1984. ;; of the first visual line (bug#22544).
  1985. (unless (eolp) (backward-char 1)))))))
  1986. (defun next-complete-history-element (n)
  1987. "Get next history element which completes the minibuffer before the point.
  1988. The contents of the minibuffer after the point are deleted, and replaced
  1989. by the new completion."
  1990. (interactive "p")
  1991. (let ((point-at-start (point)))
  1992. (next-matching-history-element
  1993. (concat
  1994. "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
  1995. n)
  1996. ;; next-matching-history-element always puts us at (point-min).
  1997. ;; Move to the position we were at before changing the buffer contents.
  1998. ;; This is still sensible, because the text before point has not changed.
  1999. (goto-char point-at-start)))
  2000. (defun previous-complete-history-element (n)
  2001. "\
  2002. Get previous history element which completes the minibuffer before the point.
  2003. The contents of the minibuffer after the point are deleted, and replaced
  2004. by the new completion."
  2005. (interactive "p")
  2006. (next-complete-history-element (- n)))
  2007. ;; For compatibility with the old subr of the same name.
  2008. (defun minibuffer-prompt-width ()
  2009. "Return the display width of the minibuffer prompt.
  2010. Return 0 if current buffer is not a minibuffer."
  2011. ;; Return the width of everything before the field at the end of
  2012. ;; the buffer; this should be 0 for normal buffers.
  2013. (1- (minibuffer-prompt-end)))
  2014. ;; isearch minibuffer history
  2015. (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
  2016. (defvar minibuffer-history-isearch-message-overlay)
  2017. (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
  2018. (defun minibuffer-history-isearch-setup ()
  2019. "Set up a minibuffer for using isearch to search the minibuffer history.
  2020. Intended to be added to `minibuffer-setup-hook'."
  2021. (set (make-local-variable 'isearch-search-fun-function)
  2022. 'minibuffer-history-isearch-search)
  2023. (set (make-local-variable 'isearch-message-function)
  2024. 'minibuffer-history-isearch-message)
  2025. (set (make-local-variable 'isearch-wrap-function)
  2026. 'minibuffer-history-isearch-wrap)
  2027. (set (make-local-variable 'isearch-push-state-function)
  2028. 'minibuffer-history-isearch-push-state)
  2029. (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
  2030. (defun minibuffer-history-isearch-end ()
  2031. "Clean up the minibuffer after terminating isearch in the minibuffer."
  2032. (if minibuffer-history-isearch-message-overlay
  2033. (delete-overlay minibuffer-history-isearch-message-overlay)))
  2034. (defun minibuffer-history-isearch-search ()
  2035. "Return the proper search function, for isearch in minibuffer history."
  2036. (lambda (string bound noerror)
  2037. (let ((search-fun
  2038. ;; Use standard functions to search within minibuffer text
  2039. (isearch-search-fun-default))
  2040. found)
  2041. ;; Avoid lazy-highlighting matches in the minibuffer prompt when
  2042. ;; searching forward. Lazy-highlight calls this lambda with the
  2043. ;; bound arg, so skip the minibuffer prompt.
  2044. (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
  2045. (goto-char (minibuffer-prompt-end)))
  2046. (or
  2047. ;; 1. First try searching in the initial minibuffer text
  2048. (funcall search-fun string
  2049. (if isearch-forward bound (minibuffer-prompt-end))
  2050. noerror)
  2051. ;; 2. If the above search fails, start putting next/prev history
  2052. ;; elements in the minibuffer successively, and search the string
  2053. ;; in them. Do this only when bound is nil (i.e. not while
  2054. ;; lazy-highlighting search strings in the current minibuffer text).
  2055. (unless bound
  2056. (condition-case nil
  2057. (progn
  2058. (while (not found)
  2059. (cond (isearch-forward
  2060. (next-history-element 1)
  2061. (goto-char (minibuffer-prompt-end)))
  2062. (t
  2063. (previous-history-element 1)
  2064. (goto-char (point-max))))
  2065. (setq isearch-barrier (point) isearch-opoint (point))
  2066. ;; After putting the next/prev history element, search
  2067. ;; the string in them again, until next-history-element
  2068. ;; or previous-history-element raises an error at the
  2069. ;; beginning/end of history.
  2070. (setq found (funcall search-fun string
  2071. (unless isearch-forward
  2072. ;; For backward search, don't search
  2073. ;; in the minibuffer prompt
  2074. (minibuffer-prompt-end))
  2075. noerror)))
  2076. ;; Return point of the new search result
  2077. (point))
  2078. ;; Return nil when next(prev)-history-element fails
  2079. (error nil)))))))
  2080. (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
  2081. "Display the minibuffer history search prompt.
  2082. If there are no search errors, this function displays an overlay with
  2083. the isearch prompt which replaces the original minibuffer prompt.
  2084. Otherwise, it displays the standard isearch message returned from
  2085. the function `isearch-message'."
  2086. (if (not (and (minibufferp) isearch-success (not isearch-error)))
  2087. ;; Use standard function `isearch-message' when not in the minibuffer,
  2088. ;; or search fails, or has an error (like incomplete regexp).
  2089. ;; This function overwrites minibuffer text with isearch message,
  2090. ;; so it's possible to see what is wrong in the search string.
  2091. (isearch-message c-q-hack ellipsis)
  2092. ;; Otherwise, put the overlay with the standard isearch prompt over
  2093. ;; the initial minibuffer prompt.
  2094. (if (overlayp minibuffer-history-isearch-message-overlay)
  2095. (move-overlay minibuffer-history-isearch-message-overlay
  2096. (point-min) (minibuffer-prompt-end))
  2097. (setq minibuffer-history-isearch-message-overlay
  2098. (make-overlay (point-min) (minibuffer-prompt-end)))
  2099. (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
  2100. (overlay-put minibuffer-history-isearch-message-overlay
  2101. 'display (isearch-message-prefix c-q-hack ellipsis))
  2102. ;; And clear any previous isearch message.
  2103. (message "")))
  2104. (defun minibuffer-history-isearch-wrap ()
  2105. "Wrap the minibuffer history search when search fails.
  2106. Move point to the first history element for a forward search,
  2107. or to the last history element for a backward search."
  2108. ;; When `minibuffer-history-isearch-search' fails on reaching the
  2109. ;; beginning/end of the history, wrap the search to the first/last
  2110. ;; minibuffer history element.
  2111. (if isearch-forward
  2112. (goto-history-element (length (symbol-value minibuffer-history-variable)))
  2113. (goto-history-element 0))
  2114. (setq isearch-success t)
  2115. (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
  2116. (defun minibuffer-history-isearch-push-state ()
  2117. "Save a function restoring the state of minibuffer history search.
  2118. Save `minibuffer-history-position' to the additional state parameter
  2119. in the search status stack."
  2120. (let ((pos minibuffer-history-position))
  2121. (lambda (cmd)
  2122. (minibuffer-history-isearch-pop-state cmd pos))))
  2123. (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
  2124. "Restore the minibuffer history search state.
  2125. Go to the history element by the absolute history position HIST-POS."
  2126. (goto-history-element hist-pos))
  2127. ;Put this on C-x u, so we can force that rather than C-_ into startup msg
  2128. (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
  2129. (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
  2130. "Table mapping redo records to the corresponding undo one.
  2131. A redo record for undo-in-region maps to t.
  2132. A redo record for ordinary undo maps to the following (earlier) undo.")
  2133. (defvar undo-in-region nil
  2134. "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
  2135. (defvar undo-no-redo nil
  2136. "If t, `undo' doesn't go through redo entries.")
  2137. (defvar pending-undo-list nil
  2138. "Within a run of consecutive undo commands, list remaining to be undone.
  2139. If t, we undid all the way to the end of it.")
  2140. (defun undo (&optional arg)
  2141. "Undo some previous changes.
  2142. Repeat this command to undo more changes.
  2143. A numeric ARG serves as a repeat count.
  2144. In Transient Mark mode when the mark is active, only undo changes within
  2145. the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
  2146. as an argument limits undo to changes within the current region."
  2147. (interactive "*P")
  2148. ;; Make last-command indicate for the next command that this was an undo.
  2149. ;; That way, another undo will undo more.
  2150. ;; If we get to the end of the undo history and get an error,
  2151. ;; another undo command will find the undo history empty
  2152. ;; and will get another error. To begin undoing the undos,
  2153. ;; you must type some other command.
  2154. (let* ((modified (buffer-modified-p))
  2155. ;; For an indirect buffer, look in the base buffer for the
  2156. ;; auto-save data.
  2157. (base-buffer (or (buffer-base-buffer) (current-buffer)))
  2158. (recent-save (with-current-buffer base-buffer
  2159. (recent-auto-save-p)))
  2160. message)
  2161. ;; If we get an error in undo-start,
  2162. ;; the next command should not be a "consecutive undo".
  2163. ;; So set `this-command' to something other than `undo'.
  2164. (setq this-command 'undo-start)
  2165. (unless (and (eq last-command 'undo)
  2166. (or (eq pending-undo-list t)
  2167. ;; If something (a timer or filter?) changed the buffer
  2168. ;; since the previous command, don't continue the undo seq.
  2169. (let ((list buffer-undo-list))
  2170. (while (eq (car list) nil)
  2171. (setq list (cdr list)))
  2172. ;; If the last undo record made was made by undo
  2173. ;; it shows nothing else happened in between.
  2174. (gethash list undo-equiv-table))))
  2175. (setq undo-in-region
  2176. (or (region-active-p) (and arg (not (numberp arg)))))
  2177. (if undo-in-region
  2178. (undo-start (region-beginning) (region-end))
  2179. (undo-start))
  2180. ;; get rid of initial undo boundary
  2181. (undo-more 1))
  2182. ;; If we got this far, the next command should be a consecutive undo.
  2183. (setq this-command 'undo)
  2184. ;; Check to see whether we're hitting a redo record, and if
  2185. ;; so, ask the user whether she wants to skip the redo/undo pair.
  2186. (let ((equiv (gethash pending-undo-list undo-equiv-table)))
  2187. (or (eq (selected-window) (minibuffer-window))
  2188. (setq message (format "%s%s!"
  2189. (if (or undo-no-redo (not equiv))
  2190. "Undo" "Redo")
  2191. (if undo-in-region " in region" ""))))
  2192. (when (and (consp equiv) undo-no-redo)
  2193. ;; The equiv entry might point to another redo record if we have done
  2194. ;; undo-redo-undo-redo-... so skip to the very last equiv.
  2195. (while (let ((next (gethash equiv undo-equiv-table)))
  2196. (if next (setq equiv next))))
  2197. (setq pending-undo-list equiv)))
  2198. (undo-more
  2199. (if (numberp arg)
  2200. (prefix-numeric-value arg)
  2201. 1))
  2202. ;; Record the fact that the just-generated undo records come from an
  2203. ;; undo operation--that is, they are redo records.
  2204. ;; In the ordinary case (not within a region), map the redo
  2205. ;; record to the following undos.
  2206. ;; I don't know how to do that in the undo-in-region case.
  2207. (let ((list buffer-undo-list))
  2208. ;; Strip any leading undo boundaries there might be, like we do
  2209. ;; above when checking.
  2210. (while (eq (car list) nil)
  2211. (setq list (cdr list)))
  2212. (puthash list
  2213. ;; Prevent identity mapping. This can happen if
  2214. ;; consecutive nils are erroneously in undo list.
  2215. (if (or undo-in-region (eq list pending-undo-list))
  2216. t
  2217. pending-undo-list)
  2218. undo-equiv-table))
  2219. ;; Don't specify a position in the undo record for the undo command.
  2220. ;; Instead, undoing this should move point to where the change is.
  2221. (let ((tail buffer-undo-list)
  2222. (prev nil))
  2223. (while (car tail)
  2224. (when (integerp (car tail))
  2225. (let ((pos (car tail)))
  2226. (if prev
  2227. (setcdr prev (cdr tail))
  2228. (setq buffer-undo-list (cdr tail)))
  2229. (setq tail (cdr tail))
  2230. (while (car tail)
  2231. (if (eq pos (car tail))
  2232. (if prev
  2233. (setcdr prev (cdr tail))
  2234. (setq buffer-undo-list (cdr tail)))
  2235. (setq prev tail))
  2236. (setq tail (cdr tail)))
  2237. (setq tail nil)))
  2238. (setq prev tail tail (cdr tail))))
  2239. ;; Record what the current undo list says,
  2240. ;; so the next command can tell if the buffer was modified in between.
  2241. (and modified (not (buffer-modified-p))
  2242. (with-current-buffer base-buffer
  2243. (delete-auto-save-file-if-necessary recent-save)))
  2244. ;; Display a message announcing success.
  2245. (if message
  2246. (message "%s" message))))
  2247. (defun buffer-disable-undo (&optional buffer)
  2248. "Make BUFFER stop keeping undo information.
  2249. No argument or nil as argument means do this for the current buffer."
  2250. (interactive)
  2251. (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
  2252. (setq buffer-undo-list t)))
  2253. (defun undo-only (&optional arg)
  2254. "Undo some previous changes.
  2255. Repeat this command to undo more changes.
  2256. A numeric ARG serves as a repeat count.
  2257. Contrary to `undo', this will not redo a previous undo."
  2258. (interactive "*p")
  2259. (let ((undo-no-redo t)) (undo arg)))
  2260. (defvar undo-in-progress nil
  2261. "Non-nil while performing an undo.
  2262. Some change-hooks test this variable to do something different.")
  2263. (defun undo-more (n)
  2264. "Undo back N undo-boundaries beyond what was already undone recently.
  2265. Call `undo-start' to get ready to undo recent changes,
  2266. then call `undo-more' one or more times to undo them."
  2267. (or (listp pending-undo-list)
  2268. (user-error (concat "No further undo information"
  2269. (and undo-in-region " for region"))))
  2270. (let ((undo-in-progress t))
  2271. ;; Note: The following, while pulling elements off
  2272. ;; `pending-undo-list' will call primitive change functions which
  2273. ;; will push more elements onto `buffer-undo-list'.
  2274. (setq pending-undo-list (primitive-undo n pending-undo-list))
  2275. (if (null pending-undo-list)
  2276. (setq pending-undo-list t))))
  2277. (defun primitive-undo (n list)
  2278. "Undo N records from the front of the list LIST.
  2279. Return what remains of the list."
  2280. ;; This is a good feature, but would make undo-start
  2281. ;; unable to do what is expected.
  2282. ;;(when (null (car (list)))
  2283. ;; ;; If the head of the list is a boundary, it is the boundary
  2284. ;; ;; preceding this command. Get rid of it and don't count it.
  2285. ;; (setq list (cdr list))))
  2286. (let ((arg n)
  2287. ;; In a writable buffer, enable undoing read-only text that is
  2288. ;; so because of text properties.
  2289. (inhibit-read-only t)
  2290. ;; Don't let `intangible' properties interfere with undo.
  2291. (inhibit-point-motion-hooks t)
  2292. ;; We use oldlist only to check for EQ. ++kfs
  2293. (oldlist buffer-undo-list)
  2294. (did-apply nil)
  2295. (next nil))
  2296. (while (> arg 0)
  2297. (while (setq next (pop list)) ;Exit inner loop at undo boundary.
  2298. ;; Handle an integer by setting point to that value.
  2299. (pcase next
  2300. ((pred integerp) (goto-char next))
  2301. ;; Element (t . TIME) records previous modtime.
  2302. ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
  2303. ;; UNKNOWN_MODTIME_NSECS.
  2304. (`(t . ,time)
  2305. ;; If this records an obsolete save
  2306. ;; (not matching the actual disk file)
  2307. ;; then don't mark unmodified.
  2308. (when (or (equal time (visited-file-modtime))
  2309. (and (consp time)
  2310. (equal (list (car time) (cdr time))
  2311. (visited-file-modtime))))
  2312. (when (fboundp 'unlock-buffer)
  2313. (unlock-buffer))
  2314. (set-buffer-modified-p nil)))
  2315. ;; Element (nil PROP VAL BEG . END) is property change.
  2316. (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
  2317. (when (or (> (point-min) beg) (< (point-max) end))
  2318. (error "Changes to be undone are outside visible portion of buffer"))
  2319. (put-text-property beg end prop val))
  2320. ;; Element (BEG . END) means range was inserted.
  2321. (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
  2322. ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
  2323. ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
  2324. (when (or (> (point-min) beg) (< (point-max) end))
  2325. (error "Changes to be undone are outside visible portion of buffer"))
  2326. ;; Set point first thing, so that undoing this undo
  2327. ;; does not send point back to where it is now.
  2328. (goto-char beg)
  2329. (delete-region beg end))
  2330. ;; Element (apply FUN . ARGS) means call FUN to undo.
  2331. (`(apply . ,fun-args)
  2332. (let ((currbuff (current-buffer)))
  2333. (if (integerp (car fun-args))
  2334. ;; Long format: (apply DELTA START END FUN . ARGS).
  2335. (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
  2336. (start-mark (copy-marker start nil))
  2337. (end-mark (copy-marker end t)))
  2338. (when (or (> (point-min) start) (< (point-max) end))
  2339. (error "Changes to be undone are outside visible portion of buffer"))
  2340. (apply fun args) ;; Use `save-current-buffer'?
  2341. ;; Check that the function did what the entry
  2342. ;; said it would do.
  2343. (unless (and (= start start-mark)
  2344. (= (+ delta end) end-mark))
  2345. (error "Changes to be undone by function different than announced"))
  2346. (set-marker start-mark nil)
  2347. (set-marker end-mark nil))
  2348. (apply fun-args))
  2349. (unless (eq currbuff (current-buffer))
  2350. (error "Undo function switched buffer"))
  2351. (setq did-apply t)))
  2352. ;; Element (STRING . POS) means STRING was deleted.
  2353. (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
  2354. (when (let ((apos (abs pos)))
  2355. (or (< apos (point-min)) (> apos (point-max))))
  2356. (error "Changes to be undone are outside visible portion of buffer"))
  2357. (let (valid-marker-adjustments)
  2358. ;; Check that marker adjustments which were recorded
  2359. ;; with the (STRING . POS) record are still valid, ie
  2360. ;; the markers haven't moved. We check their validity
  2361. ;; before reinserting the string so as we don't need to
  2362. ;; mind marker insertion-type.
  2363. (while (and (markerp (car-safe (car list)))
  2364. (integerp (cdr-safe (car list))))
  2365. (let* ((marker-adj (pop list))
  2366. (m (car marker-adj)))
  2367. (and (eq (marker-buffer m) (current-buffer))
  2368. (= pos m)
  2369. (push marker-adj valid-marker-adjustments))))
  2370. ;; Insert string and adjust point
  2371. (if (< pos 0)
  2372. (progn
  2373. (goto-char (- pos))
  2374. (insert string))
  2375. (goto-char pos)
  2376. (insert string)
  2377. (goto-char pos))
  2378. ;; Adjust the valid marker adjustments
  2379. (dolist (adj valid-marker-adjustments)
  2380. ;; Insert might have invalidated some of the markers
  2381. ;; via modification hooks. Update only the currently
  2382. ;; valid ones (bug#25599).
  2383. (if (marker-buffer (car adj))
  2384. (set-marker (car adj)
  2385. (- (car adj) (cdr adj)))))))
  2386. ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
  2387. (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
  2388. (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
  2389. next)
  2390. ;; Even though these elements are not expected in the undo
  2391. ;; list, adjust them to be conservative for the 24.4
  2392. ;; release. (Bug#16818)
  2393. (when (marker-buffer marker)
  2394. (set-marker marker
  2395. (- marker offset)
  2396. (marker-buffer marker))))
  2397. (_ (error "Unrecognized entry in undo list %S" next))))
  2398. (setq arg (1- arg)))
  2399. ;; Make sure an apply entry produces at least one undo entry,
  2400. ;; so the test in `undo' for continuing an undo series
  2401. ;; will work right.
  2402. (if (and did-apply
  2403. (eq oldlist buffer-undo-list))
  2404. (setq buffer-undo-list
  2405. (cons (list 'apply 'cdr nil) buffer-undo-list))))
  2406. list)
  2407. ;; Deep copy of a list
  2408. (defun undo-copy-list (list)
  2409. "Make a copy of undo list LIST."
  2410. (mapcar 'undo-copy-list-1 list))
  2411. (defun undo-copy-list-1 (elt)
  2412. (if (consp elt)
  2413. (cons (car elt) (undo-copy-list-1 (cdr elt)))
  2414. elt))
  2415. (defun undo-start (&optional beg end)
  2416. "Set `pending-undo-list' to the front of the undo list.
  2417. The next call to `undo-more' will undo the most recently made change.
  2418. If BEG and END are specified, then only undo elements
  2419. that apply to text between BEG and END are used; other undo elements
  2420. are ignored. If BEG and END are nil, all undo elements are used."
  2421. (if (eq buffer-undo-list t)
  2422. (user-error "No undo information in this buffer"))
  2423. (setq pending-undo-list
  2424. (if (and beg end (not (= beg end)))
  2425. (undo-make-selective-list (min beg end) (max beg end))
  2426. buffer-undo-list)))
  2427. ;; The positions given in elements of the undo list are the positions
  2428. ;; as of the time that element was recorded to undo history. In
  2429. ;; general, subsequent buffer edits render those positions invalid in
  2430. ;; the current buffer, unless adjusted according to the intervening
  2431. ;; undo elements.
  2432. ;;
  2433. ;; Undo in region is a use case that requires adjustments to undo
  2434. ;; elements. It must adjust positions of elements in the region based
  2435. ;; on newer elements not in the region so as they may be correctly
  2436. ;; applied in the current buffer. undo-make-selective-list
  2437. ;; accomplishes this with its undo-deltas list of adjustments. An
  2438. ;; example undo history from oldest to newest:
  2439. ;;
  2440. ;; buf pos:
  2441. ;; 123456789 buffer-undo-list undo-deltas
  2442. ;; --------- ---------------- -----------
  2443. ;; aaa (1 . 4) (1 . -3)
  2444. ;; aaba (3 . 4) N/A (in region)
  2445. ;; ccaaba (1 . 3) (1 . -2)
  2446. ;; ccaabaddd (7 . 10) (7 . -3)
  2447. ;; ccaabdd ("ad" . 6) (6 . 2)
  2448. ;; ccaabaddd (6 . 8) (6 . -2)
  2449. ;; | |<-- region: "caab", from 2 to 6
  2450. ;;
  2451. ;; When the user starts a run of undos in region,
  2452. ;; undo-make-selective-list is called to create the full list of in
  2453. ;; region elements. Each element is adjusted forward chronologically
  2454. ;; through undo-deltas to determine if it is in the region.
  2455. ;;
  2456. ;; In the above example, the insertion of "b" is (3 . 4) in the
  2457. ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
  2458. ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
  2459. ;; . 6) is assessed as in the region and placed in the selective list.
  2460. ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
  2461. ;; due to the selected element. The "b" insertion is the only element
  2462. ;; fully in the region, so in this example undo-make-selective-list
  2463. ;; returns (nil (5 . 6)).
  2464. ;;
  2465. ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
  2466. ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
  2467. ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
  2468. ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
  2469. ;; . 10) adjusts to (6 . 8) due to the first undo delta.
  2470. ;;
  2471. ;; More interesting is how to adjust the "ddd" insertion due to the
  2472. ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
  2473. ;; If the reinsertion was a manual retyping of "ad", then the total
  2474. ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
  2475. ;; the reinsertion was due to undo, one might expect the first "d"
  2476. ;; character would again be a part of the "ddd" text, meaning its
  2477. ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
  2478. ;;
  2479. ;; undo-make-selective-list assumes in this situation that "ad" was a
  2480. ;; new edit, even if it was inserted because of an undo.
  2481. ;; Consequently, if the user undos in region "8 to 10" of the
  2482. ;; "ccaabaddd" buffer, they could be surprised that it becomes
  2483. ;; "ccaabad", as though the first "d" became detached from the
  2484. ;; original "ddd" insertion. This quirk is a FIXME.
  2485. (defun undo-make-selective-list (start end)
  2486. "Return a list of undo elements for the region START to END.
  2487. The elements come from `buffer-undo-list', but we keep only the
  2488. elements inside this region, and discard those outside this
  2489. region. The elements' positions are adjusted so as the returned
  2490. list can be applied to the current buffer."
  2491. (let ((ulist buffer-undo-list)
  2492. ;; A list of position adjusted undo elements in the region.
  2493. (selective-list (list nil))
  2494. ;; A list of undo-deltas for out of region undo elements.
  2495. undo-deltas
  2496. undo-elt)
  2497. (while ulist
  2498. (when undo-no-redo
  2499. (while (gethash ulist undo-equiv-table)
  2500. (setq ulist (gethash ulist undo-equiv-table))))
  2501. (setq undo-elt (car ulist))
  2502. (cond
  2503. ((null undo-elt)
  2504. ;; Don't put two nils together in the list
  2505. (when (car selective-list)
  2506. (push nil selective-list)))
  2507. ((and (consp undo-elt) (eq (car undo-elt) t))
  2508. ;; This is a "was unmodified" element. Keep it
  2509. ;; if we have kept everything thus far.
  2510. (when (not undo-deltas)
  2511. (push undo-elt selective-list)))
  2512. ;; Skip over marker adjustments, instead relying
  2513. ;; on finding them after (TEXT . POS) elements
  2514. ((markerp (car-safe undo-elt))
  2515. nil)
  2516. (t
  2517. (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
  2518. undo-deltas)))
  2519. (if (undo-elt-in-region adjusted-undo-elt start end)
  2520. (progn
  2521. (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
  2522. (push adjusted-undo-elt selective-list)
  2523. ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
  2524. ;; kept. primitive-undo may discard them later.
  2525. (when (and (stringp (car-safe adjusted-undo-elt))
  2526. (integerp (cdr-safe adjusted-undo-elt)))
  2527. (let ((list-i (cdr ulist)))
  2528. (while (markerp (car-safe (car list-i)))
  2529. (push (pop list-i) selective-list)))))
  2530. (let ((delta (undo-delta undo-elt)))
  2531. (when (/= 0 (cdr delta))
  2532. (push delta undo-deltas)))))))
  2533. (pop ulist))
  2534. (nreverse selective-list)))
  2535. (defun undo-elt-in-region (undo-elt start end)
  2536. "Determine whether UNDO-ELT falls inside the region START ... END.
  2537. If it crosses the edge, we return nil.
  2538. Generally this function is not useful for determining
  2539. whether (MARKER . ADJUSTMENT) undo elements are in the region,
  2540. because markers can be arbitrarily relocated. Instead, pass the
  2541. marker adjustment's corresponding (TEXT . POS) element."
  2542. (cond ((integerp undo-elt)
  2543. (and (>= undo-elt start)
  2544. (<= undo-elt end)))
  2545. ((eq undo-elt nil)
  2546. t)
  2547. ((atom undo-elt)
  2548. nil)
  2549. ((stringp (car undo-elt))
  2550. ;; (TEXT . POSITION)
  2551. (and (>= (abs (cdr undo-elt)) start)
  2552. (<= (abs (cdr undo-elt)) end)))
  2553. ((and (consp undo-elt) (markerp (car undo-elt)))
  2554. ;; (MARKER . ADJUSTMENT)
  2555. (<= start (car undo-elt) end))
  2556. ((null (car undo-elt))
  2557. ;; (nil PROPERTY VALUE BEG . END)
  2558. (let ((tail (nthcdr 3 undo-elt)))
  2559. (and (>= (car tail) start)
  2560. (<= (cdr tail) end))))
  2561. ((integerp (car undo-elt))
  2562. ;; (BEGIN . END)
  2563. (and (>= (car undo-elt) start)
  2564. (<= (cdr undo-elt) end)))))
  2565. (defun undo-elt-crosses-region (undo-elt start end)
  2566. "Test whether UNDO-ELT crosses one edge of that region START ... END.
  2567. This assumes we have already decided that UNDO-ELT
  2568. is not *inside* the region START...END."
  2569. (declare (obsolete nil "25.1"))
  2570. (cond ((atom undo-elt) nil)
  2571. ((null (car undo-elt))
  2572. ;; (nil PROPERTY VALUE BEG . END)
  2573. (let ((tail (nthcdr 3 undo-elt)))
  2574. (and (< (car tail) end)
  2575. (> (cdr tail) start))))
  2576. ((integerp (car undo-elt))
  2577. ;; (BEGIN . END)
  2578. (and (< (car undo-elt) end)
  2579. (> (cdr undo-elt) start)))))
  2580. (defun undo-adjust-elt (elt deltas)
  2581. "Return adjustment of undo element ELT by the undo DELTAS
  2582. list."
  2583. (pcase elt
  2584. ;; POSITION
  2585. ((pred integerp)
  2586. (undo-adjust-pos elt deltas))
  2587. ;; (BEG . END)
  2588. (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
  2589. (undo-adjust-beg-end beg end deltas))
  2590. ;; (TEXT . POSITION)
  2591. (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
  2592. (cons text (* (if (< pos 0) -1 1)
  2593. (undo-adjust-pos (abs pos) deltas))))
  2594. ;; (nil PROPERTY VALUE BEG . END)
  2595. (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
  2596. `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
  2597. ;; (apply DELTA START END FUN . ARGS)
  2598. ;; FIXME
  2599. ;; All others return same elt
  2600. (_ elt)))
  2601. ;; (BEG . END) can adjust to the same positions, commonly when an
  2602. ;; insertion was undone and they are out of region, for example:
  2603. ;;
  2604. ;; buf pos:
  2605. ;; 123456789 buffer-undo-list undo-deltas
  2606. ;; --------- ---------------- -----------
  2607. ;; [...]
  2608. ;; abbaa (2 . 4) (2 . -2)
  2609. ;; aaa ("bb" . 2) (2 . 2)
  2610. ;; [...]
  2611. ;;
  2612. ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
  2613. ;; undo. Further adjustments to such an element should be the same as
  2614. ;; for (TEXT . POSITION) elements. The options are:
  2615. ;;
  2616. ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
  2617. ;; analogous to marker insertion-type t.
  2618. ;;
  2619. ;; 2: POSITION adjusts using <, resulting in behavior analogous to
  2620. ;; marker insertion-type nil.
  2621. ;;
  2622. ;; There was no strong reason to prefer one or the other, except that
  2623. ;; the first is more consistent with prior undo in region behavior.
  2624. (defun undo-adjust-beg-end (beg end deltas)
  2625. "Return cons of adjustments to BEG and END by the undo DELTAS
  2626. list."
  2627. (let ((adj-beg (undo-adjust-pos beg deltas)))
  2628. ;; Note: option 2 above would be like (cons (min ...) adj-end)
  2629. (cons adj-beg
  2630. (max adj-beg (undo-adjust-pos end deltas t)))))
  2631. (defun undo-adjust-pos (pos deltas &optional use-<)
  2632. "Return adjustment of POS by the undo DELTAS list, comparing
  2633. with < or <= based on USE-<."
  2634. (dolist (d deltas pos)
  2635. (when (if use-<
  2636. (< (car d) pos)
  2637. (<= (car d) pos))
  2638. (setq pos
  2639. ;; Don't allow pos to become less than the undo-delta
  2640. ;; position. This edge case is described in the overview
  2641. ;; comments.
  2642. (max (car d) (- pos (cdr d)))))))
  2643. ;; Return the first affected buffer position and the delta for an undo element
  2644. ;; delta is defined as the change in subsequent buffer positions if we *did*
  2645. ;; the undo.
  2646. (defun undo-delta (undo-elt)
  2647. (if (consp undo-elt)
  2648. (cond ((stringp (car undo-elt))
  2649. ;; (TEXT . POSITION)
  2650. (cons (abs (cdr undo-elt)) (length (car undo-elt))))
  2651. ((integerp (car undo-elt))
  2652. ;; (BEGIN . END)
  2653. (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
  2654. (t
  2655. '(0 . 0)))
  2656. '(0 . 0)))
  2657. ;;; Default undo-boundary addition
  2658. ;;
  2659. ;; This section adds a new undo-boundary at either after a command is
  2660. ;; called or in some cases on a timer called after a change is made in
  2661. ;; any buffer.
  2662. (defvar-local undo-auto--last-boundary-cause nil
  2663. "Describe the cause of the last undo-boundary.
  2664. If `explicit', the last boundary was caused by an explicit call to
  2665. `undo-boundary', that is one not called by the code in this
  2666. section.
  2667. If it is equal to `timer', then the last boundary was inserted
  2668. by `undo-auto--boundary-timer'.
  2669. If it is equal to `command', then the last boundary was inserted
  2670. automatically after a command, that is by the code defined in
  2671. this section.
  2672. If it is equal to a list, then the last boundary was inserted by
  2673. an amalgamating command. The car of the list is the number of
  2674. times an amalgamating command has been called, and the cdr are the
  2675. buffers that were changed during the last command.")
  2676. (defvar undo-auto-current-boundary-timer nil
  2677. "Current timer which will run `undo-auto--boundary-timer' or nil.
  2678. If set to non-nil, this will effectively disable the timer.")
  2679. (defvar undo-auto--this-command-amalgamating nil
  2680. "Non-nil if `this-command' should be amalgamated.
  2681. This variable is set to nil by `undo-auto--boundaries' and is set
  2682. by `undo-auto-amalgamate'." )
  2683. (defun undo-auto--needs-boundary-p ()
  2684. "Return non-nil if `buffer-undo-list' needs a boundary at the start."
  2685. (car-safe buffer-undo-list))
  2686. (defun undo-auto--last-boundary-amalgamating-number ()
  2687. "Return the number of amalgamating last commands or nil.
  2688. Amalgamating commands are, by default, either
  2689. `self-insert-command' and `delete-char', but can be any command
  2690. that calls `undo-auto-amalgamate'."
  2691. (car-safe undo-auto--last-boundary-cause))
  2692. (defun undo-auto--ensure-boundary (cause)
  2693. "Add an `undo-boundary' to the current buffer if needed.
  2694. REASON describes the reason that the boundary is being added; see
  2695. `undo-auto--last-boundary' for more information."
  2696. (when (and
  2697. (undo-auto--needs-boundary-p))
  2698. (let ((last-amalgamating
  2699. (undo-auto--last-boundary-amalgamating-number)))
  2700. (undo-boundary)
  2701. (setq undo-auto--last-boundary-cause
  2702. (if (eq 'amalgamate cause)
  2703. (cons
  2704. (if last-amalgamating (1+ last-amalgamating) 0)
  2705. undo-auto--undoably-changed-buffers)
  2706. cause)))))
  2707. (defun undo-auto--boundaries (cause)
  2708. "Check recently changed buffers and add a boundary if necessary.
  2709. REASON describes the reason that the boundary is being added; see
  2710. `undo-last-boundary' for more information."
  2711. ;; (Bug #23785) All commands should ensure that there is an undo
  2712. ;; boundary whether they have changed the current buffer or not.
  2713. (when (eq cause 'command)
  2714. (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
  2715. (dolist (b undo-auto--undoably-changed-buffers)
  2716. (when (buffer-live-p b)
  2717. (with-current-buffer b
  2718. (undo-auto--ensure-boundary cause))))
  2719. (setq undo-auto--undoably-changed-buffers nil))
  2720. (defun undo-auto--boundary-timer ()
  2721. "Timer which will run `undo--auto-boundary-timer'."
  2722. (setq undo-auto-current-boundary-timer nil)
  2723. (undo-auto--boundaries 'timer))
  2724. (defun undo-auto--boundary-ensure-timer ()
  2725. "Ensure that the `undo-auto-boundary-timer' is set."
  2726. (unless undo-auto-current-boundary-timer
  2727. (setq undo-auto-current-boundary-timer
  2728. (run-at-time 10 nil #'undo-auto--boundary-timer))))
  2729. (defvar undo-auto--undoably-changed-buffers nil
  2730. "List of buffers that have changed recently.
  2731. This list is maintained by `undo-auto--undoable-change' and
  2732. `undo-auto--boundaries' and can be affected by changes to their
  2733. default values.")
  2734. (defun undo-auto--add-boundary ()
  2735. "Add an `undo-boundary' in appropriate buffers."
  2736. (undo-auto--boundaries
  2737. (let ((amal undo-auto--this-command-amalgamating))
  2738. (setq undo-auto--this-command-amalgamating nil)
  2739. (if amal
  2740. 'amalgamate
  2741. 'command))))
  2742. (defun undo-auto-amalgamate ()
  2743. "Amalgamate undo if necessary.
  2744. This function can be called before an amalgamating command. It
  2745. removes the previous `undo-boundary' if a series of such calls
  2746. have been made. By default `self-insert-command' and
  2747. `delete-char' are the only amalgamating commands, although this
  2748. function could be called by any command wishing to have this
  2749. behavior."
  2750. (let ((last-amalgamating-count
  2751. (undo-auto--last-boundary-amalgamating-number)))
  2752. (setq undo-auto--this-command-amalgamating t)
  2753. (when
  2754. last-amalgamating-count
  2755. (if
  2756. (and
  2757. (< last-amalgamating-count 20)
  2758. (eq this-command last-command))
  2759. ;; Amalgamate all buffers that have changed.
  2760. (dolist (b (cdr undo-auto--last-boundary-cause))
  2761. (when (buffer-live-p b)
  2762. (with-current-buffer
  2763. b
  2764. (when
  2765. ;; The head of `buffer-undo-list' is nil.
  2766. ;; `car-safe' doesn't work because
  2767. ;; `buffer-undo-list' need not be a list!
  2768. (and (listp buffer-undo-list)
  2769. (not (car buffer-undo-list)))
  2770. (setq buffer-undo-list
  2771. (cdr buffer-undo-list))))))
  2772. (setq undo-auto--last-boundary-cause 0)))))
  2773. (defun undo-auto--undoable-change ()
  2774. "Called after every undoable buffer change."
  2775. (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
  2776. (undo-auto--boundary-ensure-timer))
  2777. ;; End auto-boundary section
  2778. (defun undo-amalgamate-change-group (handle)
  2779. "Amalgamate changes in change-group since HANDLE.
  2780. Remove all undo boundaries between the state of HANDLE and now.
  2781. HANDLE is as returned by `prepare-change-group'."
  2782. (dolist (elt handle)
  2783. (with-current-buffer (car elt)
  2784. (setq elt (cdr elt))
  2785. (when (consp buffer-undo-list)
  2786. (let ((old-car (car-safe elt))
  2787. (old-cdr (cdr-safe elt)))
  2788. (unwind-protect
  2789. (progn
  2790. ;; Temporarily truncate the undo log at ELT.
  2791. (when (consp elt)
  2792. (setcar elt t) (setcdr elt nil))
  2793. (when
  2794. (or (null elt) ;The undo-log was empty.
  2795. ;; `elt' is still in the log: normal case.
  2796. (eq elt (last buffer-undo-list))
  2797. ;; `elt' is not in the log any more, but that's because
  2798. ;; the log is "all new", so we should remove all
  2799. ;; boundaries from it.
  2800. (not (eq (last buffer-undo-list) (last old-cdr))))
  2801. (cl-callf (lambda (x) (delq nil x))
  2802. (if (car buffer-undo-list)
  2803. buffer-undo-list
  2804. ;; Preserve the undo-boundaries at either ends of the
  2805. ;; change-groups.
  2806. (cdr buffer-undo-list)))))
  2807. ;; Reset the modified cons cell ELT to its original content.
  2808. (when (consp elt)
  2809. (setcar elt old-car)
  2810. (setcdr elt old-cdr))))))))
  2811. (defcustom undo-ask-before-discard nil
  2812. "If non-nil ask about discarding undo info for the current command.
  2813. Normally, Emacs discards the undo info for the current command if
  2814. it exceeds `undo-outer-limit'. But if you set this option
  2815. non-nil, it asks in the echo area whether to discard the info.
  2816. If you answer no, there is a slight risk that Emacs might crash, so
  2817. only do it if you really want to undo the command.
  2818. This option is mainly intended for debugging. You have to be
  2819. careful if you use it for other purposes. Garbage collection is
  2820. inhibited while the question is asked, meaning that Emacs might
  2821. leak memory. So you should make sure that you do not wait
  2822. excessively long before answering the question."
  2823. :type 'boolean
  2824. :group 'undo
  2825. :version "22.1")
  2826. (defvar undo-extra-outer-limit nil
  2827. "If non-nil, an extra level of size that's ok in an undo item.
  2828. We don't ask the user about truncating the undo list until the
  2829. current item gets bigger than this amount.
  2830. This variable only matters if `undo-ask-before-discard' is non-nil.")
  2831. (make-variable-buffer-local 'undo-extra-outer-limit)
  2832. ;; When the first undo batch in an undo list is longer than
  2833. ;; undo-outer-limit, this function gets called to warn the user that
  2834. ;; the undo info for the current command was discarded. Garbage
  2835. ;; collection is inhibited around the call, so it had better not do a
  2836. ;; lot of consing.
  2837. (setq undo-outer-limit-function 'undo-outer-limit-truncate)
  2838. (defun undo-outer-limit-truncate (size)
  2839. (if undo-ask-before-discard
  2840. (when (or (null undo-extra-outer-limit)
  2841. (> size undo-extra-outer-limit))
  2842. ;; Don't ask the question again unless it gets even bigger.
  2843. ;; This applies, in particular, if the user quits from the question.
  2844. ;; Such a quit quits out of GC, but something else will call GC
  2845. ;; again momentarily. It will call this function again,
  2846. ;; but we don't want to ask the question again.
  2847. (setq undo-extra-outer-limit (+ size 50000))
  2848. (if (let (use-dialog-box track-mouse executing-kbd-macro )
  2849. (yes-or-no-p (format-message
  2850. "Buffer `%s' undo info is %d bytes long; discard it? "
  2851. (buffer-name) size)))
  2852. (progn (setq buffer-undo-list nil)
  2853. (setq undo-extra-outer-limit nil)
  2854. t)
  2855. nil))
  2856. (display-warning '(undo discard-info)
  2857. (concat
  2858. (format-message
  2859. "Buffer `%s' undo info was %d bytes long.\n"
  2860. (buffer-name) size)
  2861. "The undo info was discarded because it exceeded \
  2862. `undo-outer-limit'.
  2863. This is normal if you executed a command that made a huge change
  2864. to the buffer. In that case, to prevent similar problems in the
  2865. future, set `undo-outer-limit' to a value that is large enough to
  2866. cover the maximum size of normal changes you expect a single
  2867. command to make, but not so large that it might exceed the
  2868. maximum memory allotted to Emacs.
  2869. If you did not execute any such command, the situation is
  2870. probably due to a bug and you should report it.
  2871. You can disable the popping up of this buffer by adding the entry
  2872. \(undo discard-info) to the user option `warning-suppress-types',
  2873. which is defined in the `warnings' library.\n")
  2874. :warning)
  2875. (setq buffer-undo-list nil)
  2876. t))
  2877. (defcustom password-word-equivalents
  2878. '("password" "passcode" "passphrase" "pass phrase"
  2879. ; These are sorted according to the GNU en_US locale.
  2880. "암호" ; ko
  2881. "パスワード" ; ja
  2882. "ପ୍ରବେଶ ସଙ୍କେତ" ; or
  2883. "ពាក្យសម្ងាត់" ; km
  2884. "adgangskode" ; da
  2885. "contraseña" ; es
  2886. "contrasenya" ; ca
  2887. "geslo" ; sl
  2888. "hasło" ; pl
  2889. "heslo" ; cs, sk
  2890. "iphasiwedi" ; zu
  2891. "jelszó" ; hu
  2892. "lösenord" ; sv
  2893. "lozinka" ; hr, sr
  2894. "mật khẩu" ; vi
  2895. "mot de passe" ; fr
  2896. "parola" ; tr
  2897. "pasahitza" ; eu
  2898. "passord" ; nb
  2899. "passwort" ; de
  2900. "pasvorto" ; eo
  2901. "salasana" ; fi
  2902. "senha" ; pt
  2903. "slaptažodis" ; lt
  2904. "wachtwoord" ; nl
  2905. "كلمة السر" ; ar
  2906. "ססמה" ; he
  2907. "лозинка" ; sr
  2908. "пароль" ; kk, ru, uk
  2909. "गुप्तशब्द" ; mr
  2910. "शब्दकूट" ; hi
  2911. "પાસવર્ડ" ; gu
  2912. "సంకేతపదము" ; te
  2913. "ਪਾਸਵਰਡ" ; pa
  2914. "ಗುಪ್ತಪದ" ; kn
  2915. "கடவுச்சொல்" ; ta
  2916. "അടയാളവാക്ക്" ; ml
  2917. "গুপ্তশব্দ" ; as
  2918. "পাসওয়ার্ড" ; bn_IN
  2919. "රහස්පදය" ; si
  2920. "密码" ; zh_CN
  2921. "密碼" ; zh_TW
  2922. )
  2923. "List of words equivalent to \"password\".
  2924. This is used by Shell mode and other parts of Emacs to recognize
  2925. password prompts, including prompts in languages other than
  2926. English. Different case choices should not be assumed to be
  2927. included; callers should bind `case-fold-search' to t."
  2928. :type '(repeat string)
  2929. :version "24.4"
  2930. :group 'processes)
  2931. (defvar shell-command-history nil
  2932. "History list for some commands that read shell commands.
  2933. Maximum length of the history list is determined by the value
  2934. of `history-length', which see.")
  2935. (defvar shell-command-switch (purecopy "-c")
  2936. "Switch used to have the shell execute its command line argument.")
  2937. (defvar shell-command-default-error-buffer nil
  2938. "Buffer name for `shell-command' and `shell-command-on-region' error output.
  2939. This buffer is used when `shell-command' or `shell-command-on-region'
  2940. is run interactively. A value of nil means that output to stderr and
  2941. stdout will be intermixed in the output stream.")
  2942. (declare-function mailcap-file-default-commands "mailcap" (files))
  2943. (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
  2944. (defun minibuffer-default-add-shell-commands ()
  2945. "Return a list of all commands associated with the current file.
  2946. This function is used to add all related commands retrieved by `mailcap'
  2947. to the end of the list of defaults just after the default value."
  2948. (interactive)
  2949. (let* ((filename (if (listp minibuffer-default)
  2950. (car minibuffer-default)
  2951. minibuffer-default))
  2952. (commands (and filename (require 'mailcap nil t)
  2953. (mailcap-file-default-commands (list filename)))))
  2954. (setq commands (mapcar (lambda (command)
  2955. (concat command " " filename))
  2956. commands))
  2957. (if (listp minibuffer-default)
  2958. (append minibuffer-default commands)
  2959. (cons minibuffer-default commands))))
  2960. (declare-function shell-completion-vars "shell" ())
  2961. (defvar minibuffer-local-shell-command-map
  2962. (let ((map (make-sparse-keymap)))
  2963. (set-keymap-parent map minibuffer-local-map)
  2964. (define-key map "\t" 'completion-at-point)
  2965. map)
  2966. "Keymap used for completing shell commands in minibuffer.")
  2967. (defun read-shell-command (prompt &optional initial-contents hist &rest args)
  2968. "Read a shell command from the minibuffer.
  2969. The arguments are the same as the ones of `read-from-minibuffer',
  2970. except READ and KEYMAP are missing and HIST defaults
  2971. to `shell-command-history'."
  2972. (require 'shell)
  2973. (minibuffer-with-setup-hook
  2974. (lambda ()
  2975. (shell-completion-vars)
  2976. (set (make-local-variable 'minibuffer-default-add-function)
  2977. 'minibuffer-default-add-shell-commands))
  2978. (apply 'read-from-minibuffer prompt initial-contents
  2979. minibuffer-local-shell-command-map
  2980. nil
  2981. (or hist 'shell-command-history)
  2982. args)))
  2983. (defcustom async-shell-command-buffer 'confirm-new-buffer
  2984. "What to do when the output buffer is used by another shell command.
  2985. This option specifies how to resolve the conflict where a new command
  2986. wants to direct its output to the buffer `*Async Shell Command*',
  2987. but this buffer is already taken by another running shell command.
  2988. The value `confirm-kill-process' is used to ask for confirmation before
  2989. killing the already running process and running a new process
  2990. in the same buffer, `confirm-new-buffer' for confirmation before running
  2991. the command in a new buffer with a name other than the default buffer name,
  2992. `new-buffer' for doing the same without confirmation,
  2993. `confirm-rename-buffer' for confirmation before renaming the existing
  2994. output buffer and running a new command in the default buffer,
  2995. `rename-buffer' for doing the same without confirmation."
  2996. :type '(choice (const :tag "Confirm killing of running command"
  2997. confirm-kill-process)
  2998. (const :tag "Confirm creation of a new buffer"
  2999. confirm-new-buffer)
  3000. (const :tag "Create a new buffer"
  3001. new-buffer)
  3002. (const :tag "Confirm renaming of existing buffer"
  3003. confirm-rename-buffer)
  3004. (const :tag "Rename the existing buffer"
  3005. rename-buffer))
  3006. :group 'shell
  3007. :version "24.3")
  3008. (defcustom async-shell-command-display-buffer t
  3009. "Whether to display the command buffer immediately.
  3010. If t, display the buffer immediately; if nil, wait until there
  3011. is output."
  3012. :type '(choice (const :tag "Display buffer immediately"
  3013. t)
  3014. (const :tag "Display buffer on output"
  3015. nil))
  3016. :group 'shell
  3017. :version "26.1")
  3018. (defun shell-command--save-pos-or-erase ()
  3019. "Store a buffer position or erase the buffer.
  3020. See `shell-command-dont-erase-buffer'."
  3021. (let ((sym shell-command-dont-erase-buffer)
  3022. pos)
  3023. (setq buffer-read-only nil)
  3024. ;; Setting buffer-read-only to nil doesn't suffice
  3025. ;; if some text has a non-nil read-only property,
  3026. ;; which comint sometimes adds for prompts.
  3027. (setq pos
  3028. (cond ((eq sym 'save-point) (point))
  3029. ((eq sym 'beg-last-out) (point-max))
  3030. ((not sym)
  3031. (let ((inhibit-read-only t))
  3032. (erase-buffer) nil))))
  3033. (when pos
  3034. (goto-char (point-max))
  3035. (push (cons (current-buffer) pos)
  3036. shell-command-saved-pos))))
  3037. (defun shell-command--set-point-after-cmd (&optional buffer)
  3038. "Set point in BUFFER after command complete.
  3039. BUFFER is the output buffer of the command; if nil, then defaults
  3040. to the current BUFFER.
  3041. Set point to the `cdr' of the element in `shell-command-saved-pos'
  3042. whose `car' is BUFFER."
  3043. (when shell-command-dont-erase-buffer
  3044. (let* ((sym shell-command-dont-erase-buffer)
  3045. (buf (or buffer (current-buffer)))
  3046. (pos (alist-get buf shell-command-saved-pos)))
  3047. (setq shell-command-saved-pos
  3048. (assq-delete-all buf shell-command-saved-pos))
  3049. (when (buffer-live-p buf)
  3050. (let ((win (car (get-buffer-window-list buf)))
  3051. (pmax (with-current-buffer buf (point-max))))
  3052. (unless (and pos (memq sym '(save-point beg-last-out)))
  3053. (setq pos pmax))
  3054. ;; Set point in the window displaying buf, if any; otherwise
  3055. ;; display buf temporary in selected frame and set the point.
  3056. (if win
  3057. (set-window-point win pos)
  3058. (save-window-excursion
  3059. (let ((win (display-buffer
  3060. buf
  3061. '(nil (inhibit-switch-frame . t)))))
  3062. (set-window-point win pos)))))))))
  3063. (defun async-shell-command (command &optional output-buffer error-buffer)
  3064. "Execute string COMMAND asynchronously in background.
  3065. Like `shell-command', but adds `&' at the end of COMMAND
  3066. to execute it asynchronously.
  3067. The output appears in the buffer `*Async Shell Command*'.
  3068. That buffer is in shell mode.
  3069. You can configure `async-shell-command-buffer' to specify what to do in
  3070. case when `*Async Shell Command*' buffer is already taken by another
  3071. running shell command. To run COMMAND without displaying the output
  3072. in a window you can configure `display-buffer-alist' to use the action
  3073. `display-buffer-no-window' for the buffer `*Async Shell Command*'.
  3074. In Elisp, you will often be better served by calling `start-process'
  3075. directly, since it offers more control and does not impose the use of a
  3076. shell (with its need to quote arguments)."
  3077. (interactive
  3078. (list
  3079. (read-shell-command "Async shell command: " nil nil
  3080. (let ((filename
  3081. (cond
  3082. (buffer-file-name)
  3083. ((eq major-mode 'dired-mode)
  3084. (dired-get-filename nil t)))))
  3085. (and filename (file-relative-name filename))))
  3086. current-prefix-arg
  3087. shell-command-default-error-buffer))
  3088. (unless (string-match "&[ \t]*\\'" command)
  3089. (setq command (concat command " &")))
  3090. (shell-command command output-buffer error-buffer))
  3091. (defun shell-command (command &optional output-buffer error-buffer)
  3092. "Execute string COMMAND in inferior shell; display output, if any.
  3093. With prefix argument, insert the COMMAND's output at point.
  3094. Interactively, prompt for COMMAND in the minibuffer.
  3095. If COMMAND ends in `&', execute it asynchronously.
  3096. The output appears in the buffer `*Async Shell Command*'.
  3097. That buffer is in shell mode. You can also use
  3098. `async-shell-command' that automatically adds `&'.
  3099. Otherwise, COMMAND is executed synchronously. The output appears in
  3100. the buffer `*Shell Command Output*'. If the output is short enough to
  3101. display in the echo area (which is determined by the variables
  3102. `resize-mini-windows' and `max-mini-window-height'), it is shown
  3103. there, but it is nonetheless available in buffer `*Shell Command
  3104. Output*' even though that buffer is not automatically displayed.
  3105. To specify a coding system for converting non-ASCII characters
  3106. in the shell command output, use \\[universal-coding-system-argument] \
  3107. before this command.
  3108. Noninteractive callers can specify coding systems by binding
  3109. `coding-system-for-read' and `coding-system-for-write'.
  3110. The optional second argument OUTPUT-BUFFER, if non-nil,
  3111. says to put the output in some other buffer.
  3112. If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
  3113. and insert the output there; a non-nil value of
  3114. `shell-command-dont-erase-buffer' prevent to erase the buffer.
  3115. If OUTPUT-BUFFER is not a buffer and not nil, insert the output
  3116. in current buffer after point leaving mark after it.
  3117. This cannot be done asynchronously.
  3118. If the command terminates without error, but generates output,
  3119. and you did not specify \"insert it in the current buffer\",
  3120. the output can be displayed in the echo area or in its buffer.
  3121. If the output is short enough to display in the echo area
  3122. \(determined by the variable `max-mini-window-height' if
  3123. `resize-mini-windows' is non-nil), it is shown there.
  3124. Otherwise,the buffer containing the output is displayed.
  3125. If there is output and an error, and you did not specify \"insert it
  3126. in the current buffer\", a message about the error goes at the end
  3127. of the output.
  3128. If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
  3129. or buffer name to which to direct the command's standard error output.
  3130. If it is nil, error output is mingled with regular output.
  3131. In an interactive call, the variable `shell-command-default-error-buffer'
  3132. specifies the value of ERROR-BUFFER.
  3133. In Elisp, you will often be better served by calling `call-process' or
  3134. `start-process' directly, since it offers more control and does not impose
  3135. the use of a shell (with its need to quote arguments)."
  3136. (interactive
  3137. (list
  3138. (read-shell-command "Shell command: " nil nil
  3139. (let ((filename
  3140. (cond
  3141. (buffer-file-name)
  3142. ((eq major-mode 'dired-mode)
  3143. (dired-get-filename nil t)))))
  3144. (and filename (file-relative-name filename))))
  3145. current-prefix-arg
  3146. shell-command-default-error-buffer))
  3147. ;; Look for a handler in case default-directory is a remote file name.
  3148. (let ((handler
  3149. (find-file-name-handler (directory-file-name default-directory)
  3150. 'shell-command)))
  3151. (if handler
  3152. (funcall handler 'shell-command command output-buffer error-buffer)
  3153. (if (and output-buffer
  3154. (not (or (bufferp output-buffer) (stringp output-buffer))))
  3155. ;; Output goes in current buffer.
  3156. (let ((error-file
  3157. (if error-buffer
  3158. (make-temp-file
  3159. (expand-file-name "scor"
  3160. (or small-temporary-file-directory
  3161. temporary-file-directory)))
  3162. nil)))
  3163. (barf-if-buffer-read-only)
  3164. (push-mark nil t)
  3165. ;; We do not use -f for csh; we will not support broken use of
  3166. ;; .cshrcs. Even the BSD csh manual says to use
  3167. ;; "if ($?prompt) exit" before things which are not useful
  3168. ;; non-interactively. Besides, if someone wants their other
  3169. ;; aliases for shell commands then they can still have them.
  3170. (call-process shell-file-name nil
  3171. (if error-file
  3172. (list t error-file)
  3173. t)
  3174. nil shell-command-switch command)
  3175. (when (and error-file (file-exists-p error-file))
  3176. (if (< 0 (nth 7 (file-attributes error-file)))
  3177. (with-current-buffer (get-buffer-create error-buffer)
  3178. (let ((pos-from-end (- (point-max) (point))))
  3179. (or (bobp)
  3180. (insert "\f\n"))
  3181. ;; Do no formatting while reading error file,
  3182. ;; because that can run a shell command, and we
  3183. ;; don't want that to cause an infinite recursion.
  3184. (format-insert-file error-file nil)
  3185. ;; Put point after the inserted errors.
  3186. (goto-char (- (point-max) pos-from-end)))
  3187. (display-buffer (current-buffer))))
  3188. (delete-file error-file))
  3189. ;; This is like exchange-point-and-mark, but doesn't
  3190. ;; activate the mark. It is cleaner to avoid activation,
  3191. ;; even though the command loop would deactivate the mark
  3192. ;; because we inserted text.
  3193. (goto-char (prog1 (mark t)
  3194. (set-marker (mark-marker) (point)
  3195. (current-buffer)))))
  3196. ;; Output goes in a separate buffer.
  3197. ;; Preserve the match data in case called from a program.
  3198. ;; FIXME: It'd be ridiculous for an Elisp function to call
  3199. ;; shell-command and assume that it won't mess the match-data!
  3200. (save-match-data
  3201. (if (string-match "[ \t]*&[ \t]*\\'" command)
  3202. ;; Command ending with ampersand means asynchronous.
  3203. (let ((buffer (get-buffer-create
  3204. (or output-buffer "*Async Shell Command*")))
  3205. (directory default-directory)
  3206. proc)
  3207. ;; Remove the ampersand.
  3208. (setq command (substring command 0 (match-beginning 0)))
  3209. ;; Ask the user what to do with already running process.
  3210. (setq proc (get-buffer-process buffer))
  3211. (when proc
  3212. (cond
  3213. ((eq async-shell-command-buffer 'confirm-kill-process)
  3214. ;; If will kill a process, query first.
  3215. (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
  3216. (kill-process proc)
  3217. (error "Shell command in progress")))
  3218. ((eq async-shell-command-buffer 'confirm-new-buffer)
  3219. ;; If will create a new buffer, query first.
  3220. (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
  3221. (setq buffer (generate-new-buffer
  3222. (or (and (bufferp output-buffer) (buffer-name output-buffer))
  3223. output-buffer "*Async Shell Command*")))
  3224. (error "Shell command in progress")))
  3225. ((eq async-shell-command-buffer 'new-buffer)
  3226. ;; It will create a new buffer.
  3227. (setq buffer (generate-new-buffer
  3228. (or (and (bufferp output-buffer) (buffer-name output-buffer))
  3229. output-buffer "*Async Shell Command*"))))
  3230. ((eq async-shell-command-buffer 'confirm-rename-buffer)
  3231. ;; If will rename the buffer, query first.
  3232. (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
  3233. (progn
  3234. (with-current-buffer buffer
  3235. (rename-uniquely))
  3236. (setq buffer (get-buffer-create
  3237. (or output-buffer "*Async Shell Command*"))))
  3238. (error "Shell command in progress")))
  3239. ((eq async-shell-command-buffer 'rename-buffer)
  3240. ;; It will rename the buffer.
  3241. (with-current-buffer buffer
  3242. (rename-uniquely))
  3243. (setq buffer (get-buffer-create
  3244. (or output-buffer "*Async Shell Command*"))))))
  3245. (with-current-buffer buffer
  3246. (shell-command--save-pos-or-erase)
  3247. (setq default-directory directory)
  3248. (setq proc (start-process "Shell" buffer shell-file-name
  3249. shell-command-switch command))
  3250. (setq mode-line-process '(":%s"))
  3251. (require 'shell) (shell-mode)
  3252. (set-process-sentinel proc 'shell-command-sentinel)
  3253. ;; Use the comint filter for proper handling of carriage motion
  3254. ;; (see `comint-inhibit-carriage-motion'),.
  3255. (set-process-filter proc 'comint-output-filter)
  3256. (if async-shell-command-display-buffer
  3257. (display-buffer buffer '(nil (allow-no-window . t)))
  3258. (add-function :before (process-filter proc)
  3259. `(lambda (process string)
  3260. (when (and (= 0 (buffer-size (process-buffer process)))
  3261. (string= (buffer-name (process-buffer process))
  3262. ,(or output-buffer "*Async Shell Command*")))
  3263. (display-buffer (process-buffer process))))
  3264. ))
  3265. ))
  3266. ;; Otherwise, command is executed synchronously.
  3267. (shell-command-on-region (point) (point) command
  3268. output-buffer nil error-buffer)))))))
  3269. (defun display-message-or-buffer (message &optional buffer-name action frame)
  3270. "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
  3271. MESSAGE may be either a string or a buffer.
  3272. A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
  3273. for maximum height of the echo area, as defined by `max-mini-window-height'
  3274. if `resize-mini-windows' is non-nil.
  3275. Returns either the string shown in the echo area, or when a pop-up
  3276. buffer is used, the window used to display it.
  3277. If MESSAGE is a string, then the optional argument BUFFER-NAME is the
  3278. name of the buffer used to display it in the case where a pop-up buffer
  3279. is used, defaulting to `*Message*'. In the case where MESSAGE is a
  3280. string and it is displayed in the echo area, it is not specified whether
  3281. the contents are inserted into the buffer anyway.
  3282. Optional arguments ACTION and FRAME are as for `display-buffer',
  3283. and are only used if a pop-up buffer is displayed."
  3284. (cond ((and (stringp message) (not (string-match "\n" message)))
  3285. ;; Trivial case where we can use the echo area
  3286. (message "%s" message))
  3287. ((and (stringp message)
  3288. (= (string-match "\n" message) (1- (length message))))
  3289. ;; Trivial case where we can just remove single trailing newline
  3290. (message "%s" (substring message 0 (1- (length message)))))
  3291. (t
  3292. ;; General case
  3293. (with-current-buffer
  3294. (if (bufferp message)
  3295. message
  3296. (get-buffer-create (or buffer-name "*Message*")))
  3297. (unless (bufferp message)
  3298. (erase-buffer)
  3299. (insert message))
  3300. (let ((lines
  3301. (if (= (buffer-size) 0)
  3302. 0
  3303. (count-screen-lines nil nil nil (minibuffer-window)))))
  3304. (cond ((= lines 0))
  3305. ((and (or (<= lines 1)
  3306. (<= lines
  3307. (if resize-mini-windows
  3308. (cond ((floatp max-mini-window-height)
  3309. (* (frame-height)
  3310. max-mini-window-height))
  3311. ((integerp max-mini-window-height)
  3312. max-mini-window-height)
  3313. (t
  3314. 1))
  3315. 1)))
  3316. ;; Don't use the echo area if the output buffer is
  3317. ;; already displayed in the selected frame.
  3318. (not (get-buffer-window (current-buffer))))
  3319. ;; Echo area
  3320. (goto-char (point-max))
  3321. (when (bolp)
  3322. (backward-char 1))
  3323. (message "%s" (buffer-substring (point-min) (point))))
  3324. (t
  3325. ;; Buffer
  3326. (goto-char (point-min))
  3327. (display-buffer (current-buffer) action frame))))))))
  3328. ;; We have a sentinel to prevent insertion of a termination message
  3329. ;; in the buffer itself, and to set the point in the buffer when
  3330. ;; `shell-command-dont-erase-buffer' is non-nil.
  3331. (defun shell-command-sentinel (process signal)
  3332. (when (memq (process-status process) '(exit signal))
  3333. (shell-command--set-point-after-cmd (process-buffer process))
  3334. (message "%s: %s."
  3335. (car (cdr (cdr (process-command process))))
  3336. (substring signal 0 -1))))
  3337. (defun shell-command-on-region (start end command
  3338. &optional output-buffer replace
  3339. error-buffer display-error-buffer
  3340. region-noncontiguous-p)
  3341. "Execute string COMMAND in inferior shell with region as input.
  3342. Normally display output (if any) in temp buffer `*Shell Command Output*';
  3343. Prefix arg means replace the region with it. Return the exit code of
  3344. COMMAND.
  3345. To specify a coding system for converting non-ASCII characters
  3346. in the input and output to the shell command, use \\[universal-coding-system-argument]
  3347. before this command. By default, the input (from the current buffer)
  3348. is encoded using coding-system specified by `process-coding-system-alist',
  3349. falling back to `default-process-coding-system' if no match for COMMAND
  3350. is found in `process-coding-system-alist'.
  3351. Noninteractive callers can specify coding systems by binding
  3352. `coding-system-for-read' and `coding-system-for-write'.
  3353. If the command generates output, the output may be displayed
  3354. in the echo area or in a buffer.
  3355. If the output is short enough to display in the echo area
  3356. \(determined by the variable `max-mini-window-height' if
  3357. `resize-mini-windows' is non-nil), it is shown there.
  3358. Otherwise it is displayed in the buffer `*Shell Command Output*'.
  3359. The output is available in that buffer in both cases.
  3360. If there is output and an error, a message about the error
  3361. appears at the end of the output.
  3362. Optional fourth arg OUTPUT-BUFFER specifies where to put the
  3363. command's output. If the value is a buffer or buffer name,
  3364. erase that buffer and insert the output there; a non-nil value of
  3365. `shell-command-dont-erase-buffer' prevent to erase the buffer.
  3366. If the value is nil, use the buffer `*Shell Command Output*'.
  3367. Any other non-nil value means to insert the output in the
  3368. current buffer after START.
  3369. Optional fifth arg REPLACE, if non-nil, means to insert the
  3370. output in place of text from START to END, putting point and mark
  3371. around it.
  3372. Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
  3373. or buffer name to which to direct the command's standard error
  3374. output. If nil, error output is mingled with regular output.
  3375. When called interactively, `shell-command-default-error-buffer'
  3376. is used for ERROR-BUFFER.
  3377. Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
  3378. display the error buffer if there were any errors. When called
  3379. interactively, this is t."
  3380. (interactive (let (string)
  3381. (unless (mark)
  3382. (user-error "The mark is not set now, so there is no region"))
  3383. ;; Do this before calling region-beginning
  3384. ;; and region-end, in case subprocess output
  3385. ;; relocates them while we are in the minibuffer.
  3386. (setq string (read-shell-command "Shell command on region: "))
  3387. ;; call-interactively recognizes region-beginning and
  3388. ;; region-end specially, leaving them in the history.
  3389. (list (region-beginning) (region-end)
  3390. string
  3391. current-prefix-arg
  3392. current-prefix-arg
  3393. shell-command-default-error-buffer
  3394. t
  3395. (region-noncontiguous-p))))
  3396. (let ((error-file
  3397. (if error-buffer
  3398. (make-temp-file
  3399. (expand-file-name "scor"
  3400. (or small-temporary-file-directory
  3401. temporary-file-directory)))
  3402. nil))
  3403. exit-status)
  3404. ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
  3405. (if region-noncontiguous-p
  3406. (let ((input (concat (funcall region-extract-function 'delete) "\n"))
  3407. output)
  3408. (with-temp-buffer
  3409. (insert input)
  3410. (call-process-region (point-min) (point-max)
  3411. shell-file-name t t
  3412. nil shell-command-switch
  3413. command)
  3414. (setq output (split-string (buffer-string) "\n")))
  3415. (goto-char start)
  3416. (funcall region-insert-function output))
  3417. (if (or replace
  3418. (and output-buffer
  3419. (not (or (bufferp output-buffer) (stringp output-buffer)))))
  3420. ;; Replace specified region with output from command.
  3421. (let ((swap (and replace (< start end))))
  3422. ;; Don't muck with mark unless REPLACE says we should.
  3423. (goto-char start)
  3424. (and replace (push-mark (point) 'nomsg))
  3425. (setq exit-status
  3426. (call-shell-region start end command replace
  3427. (if error-file
  3428. (list t error-file)
  3429. t)))
  3430. ;; It is rude to delete a buffer which the command is not using.
  3431. ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
  3432. ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
  3433. ;; (kill-buffer shell-buffer)))
  3434. ;; Don't muck with mark unless REPLACE says we should.
  3435. (and replace swap (exchange-point-and-mark)))
  3436. ;; No prefix argument: put the output in a temp buffer,
  3437. ;; replacing its entire contents.
  3438. (let ((buffer (get-buffer-create
  3439. (or output-buffer "*Shell Command Output*"))))
  3440. (unwind-protect
  3441. (if (and (eq buffer (current-buffer))
  3442. (or (not shell-command-dont-erase-buffer)
  3443. (and (not (eq buffer (get-buffer "*Shell Command Output*")))
  3444. (not (region-active-p)))))
  3445. ;; If the input is the same buffer as the output,
  3446. ;; delete everything but the specified region,
  3447. ;; then replace that region with the output.
  3448. (progn (setq buffer-read-only nil)
  3449. (delete-region (max start end) (point-max))
  3450. (delete-region (point-min) (min start end))
  3451. (setq exit-status
  3452. (call-process-region (point-min) (point-max)
  3453. shell-file-name t
  3454. (if error-file
  3455. (list t error-file)
  3456. t)
  3457. nil shell-command-switch
  3458. command)))
  3459. ;; Clear the output buffer, then run the command with
  3460. ;; output there.
  3461. (let ((directory default-directory))
  3462. (with-current-buffer buffer
  3463. (if (not output-buffer)
  3464. (setq default-directory directory))
  3465. (shell-command--save-pos-or-erase)))
  3466. (setq exit-status
  3467. (call-shell-region start end command nil
  3468. (if error-file
  3469. (list buffer error-file)
  3470. buffer))))
  3471. ;; Report the output.
  3472. (with-current-buffer buffer
  3473. (setq mode-line-process
  3474. (cond ((null exit-status)
  3475. " - Error")
  3476. ((stringp exit-status)
  3477. (format " - Signal [%s]" exit-status))
  3478. ((not (equal 0 exit-status))
  3479. (format " - Exit [%d]" exit-status)))))
  3480. (if (with-current-buffer buffer (> (point-max) (point-min)))
  3481. ;; There's some output, display it
  3482. (progn
  3483. (display-message-or-buffer buffer)
  3484. (shell-command--set-point-after-cmd buffer))
  3485. ;; No output; error?
  3486. (let ((output
  3487. (if (and error-file
  3488. (< 0 (nth 7 (file-attributes error-file))))
  3489. (format "some error output%s"
  3490. (if shell-command-default-error-buffer
  3491. (format " to the \"%s\" buffer"
  3492. shell-command-default-error-buffer)
  3493. ""))
  3494. "no output")))
  3495. (cond ((null exit-status)
  3496. (message "(Shell command failed with error)"))
  3497. ((equal 0 exit-status)
  3498. (message "(Shell command succeeded with %s)"
  3499. output))
  3500. ((stringp exit-status)
  3501. (message "(Shell command killed by signal %s)"
  3502. exit-status))
  3503. (t
  3504. (message "(Shell command failed with code %d and %s)"
  3505. exit-status output))))
  3506. ;; Don't kill: there might be useful info in the undo-log.
  3507. ;; (kill-buffer buffer)
  3508. )))))
  3509. (when (and error-file (file-exists-p error-file))
  3510. (if (< 0 (nth 7 (file-attributes error-file)))
  3511. (with-current-buffer (get-buffer-create error-buffer)
  3512. (let ((pos-from-end (- (point-max) (point))))
  3513. (or (bobp)
  3514. (insert "\f\n"))
  3515. ;; Do no formatting while reading error file,
  3516. ;; because that can run a shell command, and we
  3517. ;; don't want that to cause an infinite recursion.
  3518. (format-insert-file error-file nil)
  3519. ;; Put point after the inserted errors.
  3520. (goto-char (- (point-max) pos-from-end)))
  3521. (and display-error-buffer
  3522. (display-buffer (current-buffer)))))
  3523. (delete-file error-file))
  3524. exit-status))
  3525. (defun shell-command-to-string (command)
  3526. "Execute shell command COMMAND and return its output as a string."
  3527. (with-output-to-string
  3528. (with-current-buffer
  3529. standard-output
  3530. (process-file shell-file-name nil t nil shell-command-switch command))))
  3531. (defun process-file (program &optional infile buffer display &rest args)
  3532. "Process files synchronously in a separate process.
  3533. Similar to `call-process', but may invoke a file handler based on
  3534. `default-directory'. The current working directory of the
  3535. subprocess is `default-directory'.
  3536. File names in INFILE and BUFFER are handled normally, but file
  3537. names in ARGS should be relative to `default-directory', as they
  3538. are passed to the process verbatim. (This is a difference to
  3539. `call-process' which does not support file handlers for INFILE
  3540. and BUFFER.)
  3541. Some file handlers might not support all variants, for example
  3542. they might behave as if DISPLAY was nil, regardless of the actual
  3543. value passed."
  3544. (let ((fh (find-file-name-handler default-directory 'process-file))
  3545. lc stderr-file)
  3546. (unwind-protect
  3547. (if fh (apply fh 'process-file program infile buffer display args)
  3548. (when infile (setq lc (file-local-copy infile)))
  3549. (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
  3550. (make-temp-file "emacs")))
  3551. (prog1
  3552. (apply 'call-process program
  3553. (or lc infile)
  3554. (if stderr-file (list (car buffer) stderr-file) buffer)
  3555. display args)
  3556. (when stderr-file (copy-file stderr-file (cadr buffer) t))))
  3557. (when stderr-file (delete-file stderr-file))
  3558. (when lc (delete-file lc)))))
  3559. (defvar process-file-side-effects t
  3560. "Whether a call of `process-file' changes remote files.
  3561. By default, this variable is always set to t, meaning that a
  3562. call of `process-file' could potentially change any file on a
  3563. remote host. When set to nil, a file handler could optimize
  3564. its behavior with respect to remote file attribute caching.
  3565. You should only ever change this variable with a let-binding;
  3566. never with `setq'.")
  3567. (defun start-file-process (name buffer program &rest program-args)
  3568. "Start a program in a subprocess. Return the process object for it.
  3569. Similar to `start-process', but may invoke a file handler based on
  3570. `default-directory'. See Info node `(elisp)Magic File Names'.
  3571. This handler ought to run PROGRAM, perhaps on the local host,
  3572. perhaps on a remote host that corresponds to `default-directory'.
  3573. In the latter case, the local part of `default-directory' becomes
  3574. the working directory of the process.
  3575. PROGRAM and PROGRAM-ARGS might be file names. They are not
  3576. objects of file handler invocation. File handlers might not
  3577. support pty association, if PROGRAM is nil."
  3578. (let ((fh (find-file-name-handler default-directory 'start-file-process)))
  3579. (if fh (apply fh 'start-file-process name buffer program program-args)
  3580. (apply 'start-process name buffer program program-args))))
  3581. ;;;; Process menu
  3582. (defvar tabulated-list-format)
  3583. (defvar tabulated-list-entries)
  3584. (defvar tabulated-list-sort-key)
  3585. (declare-function tabulated-list-init-header "tabulated-list" ())
  3586. (declare-function tabulated-list-print "tabulated-list"
  3587. (&optional remember-pos update))
  3588. (defvar process-menu-query-only nil)
  3589. (defvar process-menu-mode-map
  3590. (let ((map (make-sparse-keymap)))
  3591. (define-key map [?d] 'process-menu-delete-process)
  3592. map))
  3593. (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
  3594. "Major mode for listing the processes called by Emacs."
  3595. (setq tabulated-list-format [("Process" 15 t)
  3596. ("PID" 7 t)
  3597. ("Status" 7 t)
  3598. ("Buffer" 15 t)
  3599. ("TTY" 12 t)
  3600. ("Command" 0 t)])
  3601. (make-local-variable 'process-menu-query-only)
  3602. (setq tabulated-list-sort-key (cons "Process" nil))
  3603. (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t))
  3604. (defun process-menu-delete-process ()
  3605. "Kill process at point in a `list-processes' buffer."
  3606. (interactive)
  3607. (let ((pos (point)))
  3608. (delete-process (tabulated-list-get-id))
  3609. (revert-buffer)
  3610. (goto-char (min pos (point-max)))
  3611. (if (eobp)
  3612. (forward-line -1)
  3613. (beginning-of-line))))
  3614. (defun list-processes--refresh ()
  3615. "Recompute the list of processes for the Process List buffer.
  3616. Also, delete any process that is exited or signaled."
  3617. (setq tabulated-list-entries nil)
  3618. (dolist (p (process-list))
  3619. (cond ((memq (process-status p) '(exit signal closed))
  3620. (delete-process p))
  3621. ((or (not process-menu-query-only)
  3622. (process-query-on-exit-flag p))
  3623. (let* ((buf (process-buffer p))
  3624. (type (process-type p))
  3625. (pid (if (process-id p) (format "%d" (process-id p)) "--"))
  3626. (name (process-name p))
  3627. (status (symbol-name (process-status p)))
  3628. (buf-label (if (buffer-live-p buf)
  3629. `(,(buffer-name buf)
  3630. face link
  3631. help-echo ,(format-message
  3632. "Visit buffer `%s'"
  3633. (buffer-name buf))
  3634. follow-link t
  3635. process-buffer ,buf
  3636. action process-menu-visit-buffer)
  3637. "--"))
  3638. (tty (or (process-tty-name p) "--"))
  3639. (cmd
  3640. (if (memq type '(network serial))
  3641. (let ((contact (process-contact p t)))
  3642. (if (eq type 'network)
  3643. (format "(%s %s)"
  3644. (if (plist-get contact :type)
  3645. "datagram"
  3646. "network")
  3647. (if (plist-get contact :server)
  3648. (format "server on %s"
  3649. (or
  3650. (plist-get contact :host)
  3651. (plist-get contact :local)))
  3652. (format "connection to %s"
  3653. (plist-get contact :host))))
  3654. (format "(serial port %s%s)"
  3655. (or (plist-get contact :port) "?")
  3656. (let ((speed (plist-get contact :speed)))
  3657. (if speed
  3658. (format " at %s b/s" speed)
  3659. "")))))
  3660. (mapconcat 'identity (process-command p) " "))))
  3661. (push (list p (vector name pid status buf-label tty cmd))
  3662. tabulated-list-entries)))))
  3663. (tabulated-list-init-header))
  3664. (defun process-menu-visit-buffer (button)
  3665. (display-buffer (button-get button 'process-buffer)))
  3666. (defun list-processes (&optional query-only buffer)
  3667. "Display a list of all processes that are Emacs sub-processes.
  3668. If optional argument QUERY-ONLY is non-nil, only processes with
  3669. the query-on-exit flag set are listed.
  3670. Any process listed as exited or signaled is actually eliminated
  3671. after the listing is made.
  3672. Optional argument BUFFER specifies a buffer to use, instead of
  3673. \"*Process List*\".
  3674. The return value is always nil.
  3675. This function lists only processes that were launched by Emacs. To
  3676. see other processes running on the system, use `list-system-processes'."
  3677. (interactive)
  3678. (or (fboundp 'process-list)
  3679. (error "Asynchronous subprocesses are not supported on this system"))
  3680. (unless (bufferp buffer)
  3681. (setq buffer (get-buffer-create "*Process List*")))
  3682. (with-current-buffer buffer
  3683. (process-menu-mode)
  3684. (setq process-menu-query-only query-only)
  3685. (list-processes--refresh)
  3686. (tabulated-list-print))
  3687. (display-buffer buffer)
  3688. nil)
  3689. ;;;; Prefix commands
  3690. (setq prefix-command--needs-update nil)
  3691. (setq prefix-command--last-echo nil)
  3692. (defun internal-echo-keystrokes-prefix ()
  3693. ;; BEWARE: Called directly from C code.
  3694. ;; If the return value is non-nil, it means we are in the middle of
  3695. ;; a command with prefix, such as a command invoked with prefix-arg.
  3696. (if (not prefix-command--needs-update)
  3697. prefix-command--last-echo
  3698. (setq prefix-command--last-echo
  3699. (let ((strs nil))
  3700. (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
  3701. (lambda (fun) (push (funcall fun) strs)))
  3702. (setq strs (delq nil strs))
  3703. (when strs (mapconcat #'identity strs " "))))))
  3704. (defvar prefix-command-echo-keystrokes-functions nil
  3705. "Abnormal hook which constructs the description of the current prefix state.
  3706. Each function is called with no argument, should return a string or nil.")
  3707. (defun prefix-command-update ()
  3708. "Update state of prefix commands.
  3709. Call it whenever you change the \"prefix command state\"."
  3710. (setq prefix-command--needs-update t))
  3711. (defvar prefix-command-preserve-state-hook nil
  3712. "Normal hook run when a command needs to preserve the prefix.")
  3713. (defun prefix-command-preserve-state ()
  3714. "Pass the current prefix command state to the next command.
  3715. Should be called by all prefix commands.
  3716. Runs `prefix-command-preserve-state-hook'."
  3717. (run-hooks 'prefix-command-preserve-state-hook)
  3718. ;; If the current command is a prefix command, we don't want the next (real)
  3719. ;; command to have `last-command' set to, say, `universal-argument'.
  3720. (setq this-command last-command)
  3721. (setq real-this-command real-last-command)
  3722. (prefix-command-update))
  3723. (defun reset-this-command-lengths ()
  3724. (declare (obsolete prefix-command-preserve-state "25.1"))
  3725. nil)
  3726. ;;;;; The main prefix command.
  3727. ;; FIXME: Declaration of `prefix-arg' should be moved here!?
  3728. (add-hook 'prefix-command-echo-keystrokes-functions
  3729. #'universal-argument--description)
  3730. (defun universal-argument--description ()
  3731. (when prefix-arg
  3732. (concat "C-u"
  3733. (pcase prefix-arg
  3734. (`(-) " -")
  3735. (`(,(and (pred integerp) n))
  3736. (let ((str ""))
  3737. (while (and (> n 4) (= (mod n 4) 0))
  3738. (setq str (concat str " C-u"))
  3739. (setq n (/ n 4)))
  3740. (if (= n 4) str (format " %s" prefix-arg))))
  3741. (_ (format " %s" prefix-arg))))))
  3742. (add-hook 'prefix-command-preserve-state-hook
  3743. #'universal-argument--preserve)
  3744. (defun universal-argument--preserve ()
  3745. (setq prefix-arg current-prefix-arg))
  3746. (defvar universal-argument-map
  3747. (let ((map (make-sparse-keymap))
  3748. (universal-argument-minus
  3749. ;; For backward compatibility, minus with no modifiers is an ordinary
  3750. ;; command if digits have already been entered.
  3751. `(menu-item "" negative-argument
  3752. :filter ,(lambda (cmd)
  3753. (if (integerp prefix-arg) nil cmd)))))
  3754. (define-key map [switch-frame]
  3755. (lambda (e) (interactive "e")
  3756. (handle-switch-frame e) (universal-argument--mode)))
  3757. (define-key map [?\C-u] 'universal-argument-more)
  3758. (define-key map [?-] universal-argument-minus)
  3759. (define-key map [?0] 'digit-argument)
  3760. (define-key map [?1] 'digit-argument)
  3761. (define-key map [?2] 'digit-argument)
  3762. (define-key map [?3] 'digit-argument)
  3763. (define-key map [?4] 'digit-argument)
  3764. (define-key map [?5] 'digit-argument)
  3765. (define-key map [?6] 'digit-argument)
  3766. (define-key map [?7] 'digit-argument)
  3767. (define-key map [?8] 'digit-argument)
  3768. (define-key map [?9] 'digit-argument)
  3769. (define-key map [kp-0] 'digit-argument)
  3770. (define-key map [kp-1] 'digit-argument)
  3771. (define-key map [kp-2] 'digit-argument)
  3772. (define-key map [kp-3] 'digit-argument)
  3773. (define-key map [kp-4] 'digit-argument)
  3774. (define-key map [kp-5] 'digit-argument)
  3775. (define-key map [kp-6] 'digit-argument)
  3776. (define-key map [kp-7] 'digit-argument)
  3777. (define-key map [kp-8] 'digit-argument)
  3778. (define-key map [kp-9] 'digit-argument)
  3779. (define-key map [kp-subtract] universal-argument-minus)
  3780. map)
  3781. "Keymap used while processing \\[universal-argument].")
  3782. (defun universal-argument--mode ()
  3783. (prefix-command-update)
  3784. (set-transient-map universal-argument-map nil))
  3785. (defun universal-argument ()
  3786. "Begin a numeric argument for the following command.
  3787. Digits or minus sign following \\[universal-argument] make up the numeric argument.
  3788. \\[universal-argument] following the digits or minus sign ends the argument.
  3789. \\[universal-argument] without digits or minus sign provides 4 as argument.
  3790. Repeating \\[universal-argument] without digits or minus sign
  3791. multiplies the argument by 4 each time.
  3792. For some commands, just \\[universal-argument] by itself serves as a flag
  3793. which is different in effect from any particular numeric argument.
  3794. These commands include \\[set-mark-command] and \\[start-kbd-macro]."
  3795. (interactive)
  3796. (prefix-command-preserve-state)
  3797. (setq prefix-arg (list 4))
  3798. (universal-argument--mode))
  3799. (defun universal-argument-more (arg)
  3800. ;; A subsequent C-u means to multiply the factor by 4 if we've typed
  3801. ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
  3802. (interactive "P")
  3803. (prefix-command-preserve-state)
  3804. (setq prefix-arg (if (consp arg)
  3805. (list (* 4 (car arg)))
  3806. (if (eq arg '-)
  3807. (list -4)
  3808. arg)))
  3809. (when (consp prefix-arg) (universal-argument--mode)))
  3810. (defun negative-argument (arg)
  3811. "Begin a negative numeric argument for the next command.
  3812. \\[universal-argument] following digits or minus sign ends the argument."
  3813. (interactive "P")
  3814. (prefix-command-preserve-state)
  3815. (setq prefix-arg (cond ((integerp arg) (- arg))
  3816. ((eq arg '-) nil)
  3817. (t '-)))
  3818. (universal-argument--mode))
  3819. (defun digit-argument (arg)
  3820. "Part of the numeric argument for the next command.
  3821. \\[universal-argument] following digits or minus sign ends the argument."
  3822. (interactive "P")
  3823. (prefix-command-preserve-state)
  3824. (let* ((char (if (integerp last-command-event)
  3825. last-command-event
  3826. (get last-command-event 'ascii-character)))
  3827. (digit (- (logand char ?\177) ?0)))
  3828. (setq prefix-arg (cond ((integerp arg)
  3829. (+ (* arg 10)
  3830. (if (< arg 0) (- digit) digit)))
  3831. ((eq arg '-)
  3832. ;; Treat -0 as just -, so that -01 will work.
  3833. (if (zerop digit) '- (- digit)))
  3834. (t
  3835. digit))))
  3836. (universal-argument--mode))
  3837. (defvar filter-buffer-substring-functions nil
  3838. "This variable is a wrapper hook around `buffer-substring--filter'.
  3839. \(See `with-wrapper-hook' for details about wrapper hooks.)")
  3840. (make-obsolete-variable 'filter-buffer-substring-functions
  3841. 'filter-buffer-substring-function "24.4")
  3842. (defvar filter-buffer-substring-function #'buffer-substring--filter
  3843. "Function to perform the filtering in `filter-buffer-substring'.
  3844. The function is called with the same 3 arguments (BEG END DELETE)
  3845. that `filter-buffer-substring' received. It should return the
  3846. buffer substring between BEG and END, after filtering. If DELETE is
  3847. non-nil, it should delete the text between BEG and END from the buffer.")
  3848. (defvar buffer-substring-filters nil
  3849. "List of filter functions for `buffer-substring--filter'.
  3850. Each function must accept a single argument, a string, and return a string.
  3851. The buffer substring is passed to the first function in the list,
  3852. and the return value of each function is passed to the next.
  3853. As a special convention, point is set to the start of the buffer text
  3854. being operated on (i.e., the first argument of `buffer-substring--filter')
  3855. before these functions are called.")
  3856. (make-obsolete-variable 'buffer-substring-filters
  3857. 'filter-buffer-substring-function "24.1")
  3858. (defun filter-buffer-substring (beg end &optional delete)
  3859. "Return the buffer substring between BEG and END, after filtering.
  3860. If DELETE is non-nil, delete the text between BEG and END from the buffer.
  3861. This calls the function that `filter-buffer-substring-function' specifies
  3862. \(passing the same three arguments that it received) to do the work,
  3863. and returns whatever it does. The default function does no filtering,
  3864. unless a hook has been set.
  3865. Use `filter-buffer-substring' instead of `buffer-substring',
  3866. `buffer-substring-no-properties', or `delete-and-extract-region' when
  3867. you want to allow filtering to take place. For example, major or minor
  3868. modes can use `filter-buffer-substring-function' to extract characters
  3869. that are special to a buffer, and should not be copied into other buffers."
  3870. (funcall filter-buffer-substring-function beg end delete))
  3871. (defun buffer-substring--filter (beg end &optional delete)
  3872. "Default function to use for `filter-buffer-substring-function'.
  3873. Its arguments and return value are as specified for `filter-buffer-substring'.
  3874. Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
  3875. \(see `with-wrapper-hook' for details about wrapper hooks),
  3876. and the abnormal hook `buffer-substring-filters'.
  3877. No filtering is done unless a hook says to."
  3878. (subr--with-wrapper-hook-no-warnings
  3879. filter-buffer-substring-functions (beg end delete)
  3880. (cond
  3881. ((or delete buffer-substring-filters)
  3882. (save-excursion
  3883. (goto-char beg)
  3884. (let ((string (if delete (delete-and-extract-region beg end)
  3885. (buffer-substring beg end))))
  3886. (dolist (filter buffer-substring-filters)
  3887. (setq string (funcall filter string)))
  3888. string)))
  3889. (t
  3890. (buffer-substring beg end)))))
  3891. ;;;; Window system cut and paste hooks.
  3892. (defvar interprogram-cut-function #'gui-select-text
  3893. "Function to call to make a killed region available to other programs.
  3894. Most window systems provide a facility for cutting and pasting
  3895. text between different programs, such as the clipboard on X and
  3896. MS-Windows, or the pasteboard on Nextstep/Mac OS.
  3897. This variable holds a function that Emacs calls whenever text is
  3898. put in the kill ring, to make the new kill available to other
  3899. programs. The function takes one argument, TEXT, which is a
  3900. string containing the text which should be made available.")
  3901. (defvar interprogram-paste-function #'gui-selection-value
  3902. "Function to call to get text cut from other programs.
  3903. Most window systems provide a facility for cutting and pasting
  3904. text between different programs, such as the clipboard on X and
  3905. MS-Windows, or the pasteboard on Nextstep/Mac OS.
  3906. This variable holds a function that Emacs calls to obtain text
  3907. that other programs have provided for pasting. The function is
  3908. called with no arguments. If no other program has provided text
  3909. to paste, the function should return nil (in which case the
  3910. caller, usually `current-kill', should use the top of the Emacs
  3911. kill ring). If another program has provided text to paste, the
  3912. function should return that text as a string (in which case the
  3913. caller should put this string in the kill ring as the latest
  3914. kill).
  3915. The function may also return a list of strings if the window
  3916. system supports multiple selections. The first string will be
  3917. used as the pasted text, but the other will be placed in the kill
  3918. ring for easy access via `yank-pop'.
  3919. Note that the function should return a string only if a program
  3920. other than Emacs has provided a string for pasting; if Emacs
  3921. provided the most recent string, the function should return nil.
  3922. If it is difficult to tell whether Emacs or some other program
  3923. provided the current string, it is probably good enough to return
  3924. nil if the string is equal (according to `string=') to the last
  3925. text Emacs provided.")
  3926. ;;;; The kill ring data structure.
  3927. (defvar kill-ring nil
  3928. "List of killed text sequences.
  3929. Since the kill ring is supposed to interact nicely with cut-and-paste
  3930. facilities offered by window systems, use of this variable should
  3931. interact nicely with `interprogram-cut-function' and
  3932. `interprogram-paste-function'. The functions `kill-new',
  3933. `kill-append', and `current-kill' are supposed to implement this
  3934. interaction; you may want to use them instead of manipulating the kill
  3935. ring directly.")
  3936. (defcustom kill-ring-max 60
  3937. "Maximum length of kill ring before oldest elements are thrown away."
  3938. :type 'integer
  3939. :group 'killing)
  3940. (defvar kill-ring-yank-pointer nil
  3941. "The tail of the kill ring whose car is the last thing yanked.")
  3942. (defcustom save-interprogram-paste-before-kill nil
  3943. "Save clipboard strings into kill ring before replacing them.
  3944. When one selects something in another program to paste it into Emacs,
  3945. but kills something in Emacs before actually pasting it,
  3946. this selection is gone unless this variable is non-nil,
  3947. in which case the other program's selection is saved in the `kill-ring'
  3948. before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
  3949. :type 'boolean
  3950. :group 'killing
  3951. :version "23.2")
  3952. (defcustom kill-do-not-save-duplicates nil
  3953. "Do not add a new string to `kill-ring' if it duplicates the last one.
  3954. The comparison is done using `equal-including-properties'."
  3955. :type 'boolean
  3956. :group 'killing
  3957. :version "23.2")
  3958. (defun kill-new (string &optional replace)
  3959. "Make STRING the latest kill in the kill ring.
  3960. Set `kill-ring-yank-pointer' to point to it.
  3961. If `interprogram-cut-function' is non-nil, apply it to STRING.
  3962. Optional second argument REPLACE non-nil means that STRING will replace
  3963. the front of the kill ring, rather than being added to the list.
  3964. When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
  3965. are non-nil, saves the interprogram paste string(s) into `kill-ring' before
  3966. STRING.
  3967. When the yank handler has a non-nil PARAM element, the original STRING
  3968. argument is not used by `insert-for-yank'. However, since Lisp code
  3969. may access and use elements from the kill ring directly, the STRING
  3970. argument should still be a \"useful\" string for such uses."
  3971. (unless (and kill-do-not-save-duplicates
  3972. ;; Due to text properties such as 'yank-handler that
  3973. ;; can alter the contents to yank, comparison using
  3974. ;; `equal' is unsafe.
  3975. (equal-including-properties string (car kill-ring)))
  3976. (if (fboundp 'menu-bar-update-yank-menu)
  3977. (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
  3978. (when save-interprogram-paste-before-kill
  3979. (let ((interprogram-paste (and interprogram-paste-function
  3980. (funcall interprogram-paste-function))))
  3981. (when interprogram-paste
  3982. (dolist (s (if (listp interprogram-paste)
  3983. (nreverse interprogram-paste)
  3984. (list interprogram-paste)))
  3985. (unless (and kill-do-not-save-duplicates
  3986. (equal-including-properties s (car kill-ring)))
  3987. (push s kill-ring))))))
  3988. (unless (and kill-do-not-save-duplicates
  3989. (equal-including-properties string (car kill-ring)))
  3990. (if (and replace kill-ring)
  3991. (setcar kill-ring string)
  3992. (push string kill-ring)
  3993. (if (> (length kill-ring) kill-ring-max)
  3994. (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
  3995. (setq kill-ring-yank-pointer kill-ring)
  3996. (if interprogram-cut-function
  3997. (funcall interprogram-cut-function string)))
  3998. ;; It has been argued that this should work similar to `self-insert-command'
  3999. ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
  4000. (defcustom kill-append-merge-undo nil
  4001. "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
  4002. :type 'boolean
  4003. :group 'killing
  4004. :version "25.1")
  4005. (defun kill-append (string before-p)
  4006. "Append STRING to the end of the latest kill in the kill ring.
  4007. If BEFORE-P is non-nil, prepend STRING to the kill.
  4008. Also removes the last undo boundary in the current buffer,
  4009. depending on `kill-append-merge-undo'.
  4010. If `interprogram-cut-function' is set, pass the resulting kill to it."
  4011. (let* ((cur (car kill-ring)))
  4012. (kill-new (if before-p (concat string cur) (concat cur string))
  4013. (or (= (length cur) 0)
  4014. (equal nil (get-text-property 0 'yank-handler cur))))
  4015. (when (and kill-append-merge-undo (not buffer-read-only))
  4016. (let ((prev buffer-undo-list)
  4017. (next (cdr buffer-undo-list)))
  4018. ;; find the next undo boundary
  4019. (while (car next)
  4020. (pop next)
  4021. (pop prev))
  4022. ;; remove this undo boundary
  4023. (when prev
  4024. (setcdr prev (cdr next)))))))
  4025. (defcustom yank-pop-change-selection nil
  4026. "Whether rotating the kill ring changes the window system selection.
  4027. If non-nil, whenever the kill ring is rotated (usually via the
  4028. `yank-pop' command), Emacs also calls `interprogram-cut-function'
  4029. to copy the new kill to the window system selection."
  4030. :type 'boolean
  4031. :group 'killing
  4032. :version "23.1")
  4033. (defun current-kill (n &optional do-not-move)
  4034. "Rotate the yanking point by N places, and then return that kill.
  4035. If N is zero and `interprogram-paste-function' is set to a
  4036. function that returns a string or a list of strings, and if that
  4037. function doesn't return nil, then that string (or list) is added
  4038. to the front of the kill ring and the string (or first string in
  4039. the list) is returned as the latest kill.
  4040. If N is not zero, and if `yank-pop-change-selection' is
  4041. non-nil, use `interprogram-cut-function' to transfer the
  4042. kill at the new yank point into the window system selection.
  4043. If optional arg DO-NOT-MOVE is non-nil, then don't actually
  4044. move the yanking point; just return the Nth kill forward."
  4045. (let ((interprogram-paste (and (= n 0)
  4046. interprogram-paste-function
  4047. (funcall interprogram-paste-function))))
  4048. (if interprogram-paste
  4049. (progn
  4050. ;; Disable the interprogram cut function when we add the new
  4051. ;; text to the kill ring, so Emacs doesn't try to own the
  4052. ;; selection, with identical text.
  4053. (let ((interprogram-cut-function nil))
  4054. (if (listp interprogram-paste)
  4055. (mapc 'kill-new (nreverse interprogram-paste))
  4056. (kill-new interprogram-paste)))
  4057. (car kill-ring))
  4058. (or kill-ring (error "Kill ring is empty"))
  4059. (let ((ARGth-kill-element
  4060. (nthcdr (mod (- n (length kill-ring-yank-pointer))
  4061. (length kill-ring))
  4062. kill-ring)))
  4063. (unless do-not-move
  4064. (setq kill-ring-yank-pointer ARGth-kill-element)
  4065. (when (and yank-pop-change-selection
  4066. (> n 0)
  4067. interprogram-cut-function)
  4068. (funcall interprogram-cut-function (car ARGth-kill-element))))
  4069. (car ARGth-kill-element)))))
  4070. ;;;; Commands for manipulating the kill ring.
  4071. (defcustom kill-read-only-ok nil
  4072. "Non-nil means don't signal an error for killing read-only text."
  4073. :type 'boolean
  4074. :group 'killing)
  4075. (defun kill-region (beg end &optional region)
  4076. "Kill (\"cut\") text between point and mark.
  4077. This deletes the text from the buffer and saves it in the kill ring.
  4078. The command \\[yank] can retrieve it from there.
  4079. \(If you want to save the region without killing it, use \\[kill-ring-save].)
  4080. If you want to append the killed region to the last killed text,
  4081. use \\[append-next-kill] before \\[kill-region].
  4082. Any command that calls this function is a \"kill command\".
  4083. If the previous command was also a kill command,
  4084. the text killed this time appends to the text killed last time
  4085. to make one entry in the kill ring.
  4086. The killed text is filtered by `filter-buffer-substring' before it is
  4087. saved in the kill ring, so the actual saved text might be different
  4088. from what was killed.
  4089. If the buffer is read-only, Emacs will beep and refrain from deleting
  4090. the text, but put the text in the kill ring anyway. This means that
  4091. you can use the killing commands to copy text from a read-only buffer.
  4092. Lisp programs should use this function for killing text.
  4093. (To delete text, use `delete-region'.)
  4094. Supply two arguments, character positions BEG and END indicating the
  4095. stretch of text to be killed. If the optional argument REGION is
  4096. non-nil, the function ignores BEG and END, and kills the current
  4097. region instead."
  4098. ;; Pass mark first, then point, because the order matters when
  4099. ;; calling `kill-append'.
  4100. (interactive (list (mark) (point) 'region))
  4101. (unless (and beg end)
  4102. (user-error "The mark is not set now, so there is no region"))
  4103. (condition-case nil
  4104. (let ((string (if region
  4105. (funcall region-extract-function 'delete)
  4106. (filter-buffer-substring beg end 'delete))))
  4107. (when string ;STRING is nil if BEG = END
  4108. ;; Add that string to the kill ring, one way or another.
  4109. (if (eq last-command 'kill-region)
  4110. (kill-append string (< end beg))
  4111. (kill-new string)))
  4112. (when (or string (eq last-command 'kill-region))
  4113. (setq this-command 'kill-region))
  4114. (setq deactivate-mark t)
  4115. nil)
  4116. ((buffer-read-only text-read-only)
  4117. ;; The code above failed because the buffer, or some of the characters
  4118. ;; in the region, are read-only.
  4119. ;; We should beep, in case the user just isn't aware of this.
  4120. ;; However, there's no harm in putting
  4121. ;; the region's text in the kill ring, anyway.
  4122. (copy-region-as-kill beg end region)
  4123. ;; Set this-command now, so it will be set even if we get an error.
  4124. (setq this-command 'kill-region)
  4125. ;; This should barf, if appropriate, and give us the correct error.
  4126. (if kill-read-only-ok
  4127. (progn (message "Read only text copied to kill ring") nil)
  4128. ;; Signal an error if the buffer is read-only.
  4129. (barf-if-buffer-read-only)
  4130. ;; If the buffer isn't read-only, the text is.
  4131. (signal 'text-read-only (list (current-buffer)))))))
  4132. ;; copy-region-as-kill no longer sets this-command, because it's confusing
  4133. ;; to get two copies of the text when the user accidentally types M-w and
  4134. ;; then corrects it with the intended C-w.
  4135. (defun copy-region-as-kill (beg end &optional region)
  4136. "Save the region as if killed, but don't kill it.
  4137. In Transient Mark mode, deactivate the mark.
  4138. If `interprogram-cut-function' is non-nil, also save the text for a window
  4139. system cut and paste.
  4140. The copied text is filtered by `filter-buffer-substring' before it is
  4141. saved in the kill ring, so the actual saved text might be different
  4142. from what was in the buffer.
  4143. When called from Lisp, save in the kill ring the stretch of text
  4144. between BEG and END, unless the optional argument REGION is
  4145. non-nil, in which case ignore BEG and END, and save the current
  4146. region instead.
  4147. This command's old key binding has been given to `kill-ring-save'."
  4148. ;; Pass mark first, then point, because the order matters when
  4149. ;; calling `kill-append'.
  4150. (interactive (list (mark) (point)
  4151. (prefix-numeric-value current-prefix-arg)))
  4152. (let ((str (if region
  4153. (funcall region-extract-function nil)
  4154. (filter-buffer-substring beg end))))
  4155. (if (eq last-command 'kill-region)
  4156. (kill-append str (< end beg))
  4157. (kill-new str)))
  4158. (setq deactivate-mark t)
  4159. nil)
  4160. (defun kill-ring-save (beg end &optional region)
  4161. "Save the region as if killed, but don't kill it.
  4162. In Transient Mark mode, deactivate the mark.
  4163. If `interprogram-cut-function' is non-nil, also save the text for a window
  4164. system cut and paste.
  4165. If you want to append the killed line to the last killed text,
  4166. use \\[append-next-kill] before \\[kill-ring-save].
  4167. The copied text is filtered by `filter-buffer-substring' before it is
  4168. saved in the kill ring, so the actual saved text might be different
  4169. from what was in the buffer.
  4170. When called from Lisp, save in the kill ring the stretch of text
  4171. between BEG and END, unless the optional argument REGION is
  4172. non-nil, in which case ignore BEG and END, and save the current
  4173. region instead.
  4174. This command is similar to `copy-region-as-kill', except that it gives
  4175. visual feedback indicating the extent of the region being copied."
  4176. ;; Pass mark first, then point, because the order matters when
  4177. ;; calling `kill-append'.
  4178. (interactive (list (mark) (point)
  4179. (prefix-numeric-value current-prefix-arg)))
  4180. (copy-region-as-kill beg end region)
  4181. ;; This use of called-interactively-p is correct because the code it
  4182. ;; controls just gives the user visual feedback.
  4183. (if (called-interactively-p 'interactive)
  4184. (indicate-copied-region)))
  4185. (defun indicate-copied-region (&optional message-len)
  4186. "Indicate that the region text has been copied interactively.
  4187. If the mark is visible in the selected window, blink the cursor
  4188. between point and mark if there is currently no active region
  4189. highlighting.
  4190. If the mark lies outside the selected window, display an
  4191. informative message containing a sample of the copied text. The
  4192. optional argument MESSAGE-LEN, if non-nil, specifies the length
  4193. of this sample text; it defaults to 40."
  4194. (let ((mark (mark t))
  4195. (point (point))
  4196. ;; Inhibit quitting so we can make a quit here
  4197. ;; look like a C-g typed as a command.
  4198. (inhibit-quit t))
  4199. (if (pos-visible-in-window-p mark (selected-window))
  4200. ;; Swap point-and-mark quickly so as to show the region that
  4201. ;; was selected. Don't do it if the region is highlighted.
  4202. (unless (and (region-active-p)
  4203. (face-background 'region))
  4204. ;; Swap point and mark.
  4205. (set-marker (mark-marker) (point) (current-buffer))
  4206. (goto-char mark)
  4207. (sit-for blink-matching-delay)
  4208. ;; Swap back.
  4209. (set-marker (mark-marker) mark (current-buffer))
  4210. (goto-char point)
  4211. ;; If user quit, deactivate the mark
  4212. ;; as C-g would as a command.
  4213. (and quit-flag (region-active-p)
  4214. (deactivate-mark)))
  4215. (let ((len (min (abs (- mark point))
  4216. (or message-len 40))))
  4217. (if (< point mark)
  4218. ;; Don't say "killed"; that is misleading.
  4219. (message "Saved text until \"%s\""
  4220. (buffer-substring-no-properties (- mark len) mark))
  4221. (message "Saved text from \"%s\""
  4222. (buffer-substring-no-properties mark (+ mark len))))))))
  4223. (defun append-next-kill (&optional interactive)
  4224. "Cause following command, if it kills, to add to previous kill.
  4225. If the next command kills forward from point, the kill is
  4226. appended to the previous killed text. If the command kills
  4227. backward, the kill is prepended. Kill commands that act on the
  4228. region, such as `kill-region', are regarded as killing forward if
  4229. point is after mark, and killing backward if point is before
  4230. mark.
  4231. If the next command is not a kill command, `append-next-kill' has
  4232. no effect.
  4233. The argument is used for internal purposes; do not supply one."
  4234. (interactive "p")
  4235. ;; We don't use (interactive-p), since that breaks kbd macros.
  4236. (if interactive
  4237. (progn
  4238. (setq this-command 'kill-region)
  4239. (message "If the next command is a kill, it will append"))
  4240. (setq last-command 'kill-region)))
  4241. (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
  4242. "Character set that matches bidirectional formatting control characters.")
  4243. (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
  4244. "Character set that matches any character except bidirectional controls.")
  4245. (defun squeeze-bidi-context-1 (from to category replacement)
  4246. "A subroutine of `squeeze-bidi-context'.
  4247. FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
  4248. (let ((pt (copy-marker from))
  4249. (limit (copy-marker to))
  4250. (old-pt 0)
  4251. lim1)
  4252. (setq lim1 limit)
  4253. (goto-char pt)
  4254. (while (< pt limit)
  4255. (if (> pt old-pt)
  4256. (move-marker lim1
  4257. (save-excursion
  4258. ;; L and R categories include embedding and
  4259. ;; override controls, but we don't want to
  4260. ;; replace them, because that might change
  4261. ;; the visual order. Likewise with PDF and
  4262. ;; isolate controls.
  4263. (+ pt (skip-chars-forward
  4264. bidi-directional-non-controls-chars
  4265. limit)))))
  4266. ;; Replace any run of non-RTL characters by a single LRM.
  4267. (if (null (re-search-forward category lim1 t))
  4268. ;; No more characters of CATEGORY, we are done.
  4269. (setq pt limit)
  4270. (replace-match replacement nil t)
  4271. (move-marker pt (point)))
  4272. (setq old-pt pt)
  4273. ;; Skip directional controls, if any.
  4274. (move-marker
  4275. pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
  4276. (defun squeeze-bidi-context (from to)
  4277. "Replace characters between FROM and TO while keeping bidi context.
  4278. This function replaces the region of text with as few characters
  4279. as possible, while preserving the effect that region will have on
  4280. bidirectional display before and after the region."
  4281. (let ((start (set-marker (make-marker)
  4282. (if (> from 0) from (+ (point-max) from))))
  4283. (end (set-marker (make-marker) to))
  4284. ;; This is for when they copy text with read-only text
  4285. ;; properties.
  4286. (inhibit-read-only t))
  4287. (if (null (marker-position end))
  4288. (setq end (point-max-marker)))
  4289. ;; Replace each run of non-RTL characters with a single LRM.
  4290. (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
  4291. ;; Replace each run of non-LTR characters with a single RLM. Note
  4292. ;; that the \cR category includes both the Arabic Letter (AL) and
  4293. ;; R characters; here we ignore the distinction between them,
  4294. ;; because that distinction only affects Arabic Number (AN)
  4295. ;; characters, which are weak and don't affect the reordering.
  4296. (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
  4297. (defun line-substring-with-bidi-context (start end &optional no-properties)
  4298. "Return buffer text between START and END with its bidi context.
  4299. START and END are assumed to belong to the same physical line
  4300. of buffer text. This function prepends and appends to the text
  4301. between START and END bidi control characters that preserve the
  4302. visual order of that text when it is inserted at some other place."
  4303. (if (or (< start (point-min))
  4304. (> end (point-max)))
  4305. (signal 'args-out-of-range (list (current-buffer) start end)))
  4306. (let ((buf (current-buffer))
  4307. substr para-dir from to)
  4308. (save-excursion
  4309. (goto-char start)
  4310. (setq para-dir (current-bidi-paragraph-direction))
  4311. (setq from (line-beginning-position)
  4312. to (line-end-position))
  4313. (goto-char from)
  4314. ;; If we don't have any mixed directional characters in the
  4315. ;; entire line, we can just copy the substring without adding
  4316. ;; any context.
  4317. (if (or (looking-at-p "\\CR*$")
  4318. (looking-at-p "\\CL*$"))
  4319. (setq substr (if no-properties
  4320. (buffer-substring-no-properties start end)
  4321. (buffer-substring start end)))
  4322. (setq substr
  4323. (with-temp-buffer
  4324. (if no-properties
  4325. (insert-buffer-substring-no-properties buf from to)
  4326. (insert-buffer-substring buf from to))
  4327. (squeeze-bidi-context 1 (1+ (- start from)))
  4328. (squeeze-bidi-context (- end to) nil)
  4329. (buffer-substring 1 (point-max)))))
  4330. ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
  4331. ;; (1) force the string to have the same base embedding
  4332. ;; direction as the paragraph direction at the source, no matter
  4333. ;; what is the paragraph direction at destination; and (2) avoid
  4334. ;; affecting the visual order of the surrounding text at
  4335. ;; destination if there are characters of different
  4336. ;; directionality there.
  4337. (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
  4338. substr "\x2069"))))
  4339. (defun buffer-substring-with-bidi-context (start end &optional no-properties)
  4340. "Return portion of current buffer between START and END with bidi context.
  4341. This function works similar to `buffer-substring', but it prepends and
  4342. appends to the text bidi directional control characters necessary to
  4343. preserve the visual appearance of the text if it is inserted at another
  4344. place. This is useful when the buffer substring includes bidirectional
  4345. text and control characters that cause non-trivial reordering on display.
  4346. If copied verbatim, such text can have a very different visual appearance,
  4347. and can also change the visual appearance of the surrounding text at the
  4348. destination of the copy.
  4349. Optional argument NO-PROPERTIES, if non-nil, means copy the text without
  4350. the text properties."
  4351. (let (line-end substr)
  4352. (if (or (< start (point-min))
  4353. (> end (point-max)))
  4354. (signal 'args-out-of-range (list (current-buffer) start end)))
  4355. (save-excursion
  4356. (goto-char start)
  4357. (setq line-end (min end (line-end-position)))
  4358. (while (< start end)
  4359. (setq substr
  4360. (concat substr
  4361. (if substr "\n" "")
  4362. (line-substring-with-bidi-context start line-end
  4363. no-properties)))
  4364. (forward-line 1)
  4365. (setq start (point))
  4366. (setq line-end (min end (line-end-position))))
  4367. substr)))
  4368. ;; Yanking.
  4369. (defcustom yank-handled-properties
  4370. '((font-lock-face . yank-handle-font-lock-face-property)
  4371. (category . yank-handle-category-property))
  4372. "List of special text property handling conditions for yanking.
  4373. Each element should have the form (PROP . FUN), where PROP is a
  4374. property symbol and FUN is a function. When the `yank' command
  4375. inserts text into the buffer, it scans the inserted text for
  4376. stretches of text that have `eq' values of the text property
  4377. PROP; for each such stretch of text, FUN is called with three
  4378. arguments: the property's value in that text, and the start and
  4379. end positions of the text.
  4380. This is done prior to removing the properties specified by
  4381. `yank-excluded-properties'."
  4382. :group 'killing
  4383. :type '(repeat (cons (symbol :tag "property symbol")
  4384. function))
  4385. :version "24.3")
  4386. ;; This is actually used in subr.el but defcustom does not work there.
  4387. (defcustom yank-excluded-properties
  4388. '(category field follow-link fontified font-lock-face help-echo
  4389. intangible invisible keymap local-map mouse-face read-only
  4390. yank-handler)
  4391. "Text properties to discard when yanking.
  4392. The value should be a list of text properties to discard or t,
  4393. which means to discard all text properties.
  4394. See also `yank-handled-properties'."
  4395. :type '(choice (const :tag "All" t) (repeat symbol))
  4396. :group 'killing
  4397. :version "24.3")
  4398. (defvar yank-window-start nil)
  4399. (defvar yank-undo-function nil
  4400. "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
  4401. Function is called with two parameters, START and END corresponding to
  4402. the value of the mark and point; it is guaranteed that START <= END.
  4403. Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
  4404. (defun yank-pop (&optional arg)
  4405. "Replace just-yanked stretch of killed text with a different stretch.
  4406. This command is allowed only immediately after a `yank' or a `yank-pop'.
  4407. At such a time, the region contains a stretch of reinserted
  4408. previously-killed text. `yank-pop' deletes that text and inserts in its
  4409. place a different stretch of killed text.
  4410. With no argument, the previous kill is inserted.
  4411. With argument N, insert the Nth previous kill.
  4412. If N is negative, this is a more recent kill.
  4413. The sequence of kills wraps around, so that after the oldest one
  4414. comes the newest one.
  4415. This command honors the `yank-handled-properties' and
  4416. `yank-excluded-properties' variables, and the `yank-handler' text
  4417. property, in the way that `yank' does."
  4418. (interactive "*p")
  4419. (if (not (eq last-command 'yank))
  4420. (user-error "Previous command was not a yank"))
  4421. (setq this-command 'yank)
  4422. (unless arg (setq arg 1))
  4423. (let ((inhibit-read-only t)
  4424. (before (< (point) (mark t))))
  4425. (if before
  4426. (funcall (or yank-undo-function 'delete-region) (point) (mark t))
  4427. (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
  4428. (setq yank-undo-function nil)
  4429. (set-marker (mark-marker) (point) (current-buffer))
  4430. (insert-for-yank (current-kill arg))
  4431. ;; Set the window start back where it was in the yank command,
  4432. ;; if possible.
  4433. (set-window-start (selected-window) yank-window-start t)
  4434. (if before
  4435. ;; This is like exchange-point-and-mark, but doesn't activate the mark.
  4436. ;; It is cleaner to avoid activation, even though the command
  4437. ;; loop would deactivate the mark because we inserted text.
  4438. (goto-char (prog1 (mark t)
  4439. (set-marker (mark-marker) (point) (current-buffer))))))
  4440. nil)
  4441. (defun yank (&optional arg)
  4442. "Reinsert (\"paste\") the last stretch of killed text.
  4443. More precisely, reinsert the most recent kill, which is the
  4444. stretch of killed text most recently killed OR yanked. Put point
  4445. at the end, and set mark at the beginning without activating it.
  4446. With just \\[universal-argument] as argument, put point at beginning, and mark at end.
  4447. With argument N, reinsert the Nth most recent kill.
  4448. This command honors the `yank-handled-properties' and
  4449. `yank-excluded-properties' variables, and the `yank-handler' text
  4450. property, as described below.
  4451. Properties listed in `yank-handled-properties' are processed,
  4452. then those listed in `yank-excluded-properties' are discarded.
  4453. If STRING has a non-nil `yank-handler' property anywhere, the
  4454. normal insert behavior is altered, and instead, for each contiguous
  4455. segment of STRING that has a given value of the `yank-handler'
  4456. property, that value is used as follows:
  4457. The value of a `yank-handler' property must be a list of one to four
  4458. elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
  4459. FUNCTION, if non-nil, should be a function of one argument (the
  4460. object to insert); FUNCTION is called instead of `insert'.
  4461. PARAM, if present and non-nil, is passed to FUNCTION (to be handled
  4462. in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
  4463. PARAM may be a list of strings to insert as a rectangle). If PARAM
  4464. is nil, then the current segment of STRING is used.
  4465. If NOEXCLUDE is present and non-nil, the normal removal of
  4466. `yank-excluded-properties' is not performed; instead FUNCTION is
  4467. responsible for the removal. This may be necessary if FUNCTION
  4468. adjusts point before or after inserting the object.
  4469. UNDO, if present and non-nil, should be a function to be called
  4470. by `yank-pop' to undo the insertion of the current PARAM. It is
  4471. given two arguments, the start and end of the region. FUNCTION
  4472. may set `yank-undo-function' to override UNDO.
  4473. See also the command `yank-pop' (\\[yank-pop])."
  4474. (interactive "*P")
  4475. (setq yank-window-start (window-start))
  4476. ;; If we don't get all the way thru, make last-command indicate that
  4477. ;; for the following command.
  4478. (setq this-command t)
  4479. (push-mark)
  4480. (insert-for-yank (current-kill (cond
  4481. ((listp arg) 0)
  4482. ((eq arg '-) -2)
  4483. (t (1- arg)))))
  4484. (if (consp arg)
  4485. ;; This is like exchange-point-and-mark, but doesn't activate the mark.
  4486. ;; It is cleaner to avoid activation, even though the command
  4487. ;; loop would deactivate the mark because we inserted text.
  4488. (goto-char (prog1 (mark t)
  4489. (set-marker (mark-marker) (point) (current-buffer)))))
  4490. ;; If we do get all the way thru, make this-command indicate that.
  4491. (if (eq this-command t)
  4492. (setq this-command 'yank))
  4493. nil)
  4494. (defun rotate-yank-pointer (arg)
  4495. "Rotate the yanking point in the kill ring.
  4496. With ARG, rotate that many kills forward (or backward, if negative)."
  4497. (interactive "p")
  4498. (current-kill arg))
  4499. ;; Some kill commands.
  4500. ;; Internal subroutine of delete-char
  4501. (defun kill-forward-chars (arg)
  4502. (if (listp arg) (setq arg (car arg)))
  4503. (if (eq arg '-) (setq arg -1))
  4504. (kill-region (point) (+ (point) arg)))
  4505. ;; Internal subroutine of backward-delete-char
  4506. (defun kill-backward-chars (arg)
  4507. (if (listp arg) (setq arg (car arg)))
  4508. (if (eq arg '-) (setq arg -1))
  4509. (kill-region (point) (- (point) arg)))
  4510. (defcustom backward-delete-char-untabify-method 'untabify
  4511. "The method for untabifying when deleting backward.
  4512. Can be `untabify' -- turn a tab to many spaces, then delete one space;
  4513. `hungry' -- delete all whitespace, both tabs and spaces;
  4514. `all' -- delete all whitespace, including tabs, spaces and newlines;
  4515. nil -- just delete one character."
  4516. :type '(choice (const untabify) (const hungry) (const all) (const nil))
  4517. :version "20.3"
  4518. :group 'killing)
  4519. (defun backward-delete-char-untabify (arg &optional killp)
  4520. "Delete characters backward, changing tabs into spaces.
  4521. The exact behavior depends on `backward-delete-char-untabify-method'.
  4522. Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
  4523. Interactively, ARG is the prefix arg (default 1)
  4524. and KILLP is t if a prefix arg was specified."
  4525. (interactive "*p\nP")
  4526. (when (eq backward-delete-char-untabify-method 'untabify)
  4527. (let ((count arg))
  4528. (save-excursion
  4529. (while (and (> count 0) (not (bobp)))
  4530. (if (= (preceding-char) ?\t)
  4531. (let ((col (current-column)))
  4532. (forward-char -1)
  4533. (setq col (- col (current-column)))
  4534. (insert-char ?\s col)
  4535. (delete-char 1)))
  4536. (forward-char -1)
  4537. (setq count (1- count))))))
  4538. (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
  4539. ((eq backward-delete-char-untabify-method 'all)
  4540. " \t\n\r")))
  4541. (n (if skip
  4542. (let* ((oldpt (point))
  4543. (wh (- oldpt (save-excursion
  4544. (skip-chars-backward skip)
  4545. (constrain-to-field nil oldpt)))))
  4546. (+ arg (if (zerop wh) 0 (1- wh))))
  4547. arg)))
  4548. ;; Avoid warning about delete-backward-char
  4549. (with-no-warnings (delete-backward-char n killp))))
  4550. (defun zap-to-char (arg char)
  4551. "Kill up to and including ARGth occurrence of CHAR.
  4552. Case is ignored if `case-fold-search' is non-nil in the current buffer.
  4553. Goes backward if ARG is negative; error if CHAR not found."
  4554. (interactive (list (prefix-numeric-value current-prefix-arg)
  4555. (read-char "Zap to char: " t)))
  4556. ;; Avoid "obsolete" warnings for translation-table-for-input.
  4557. (with-no-warnings
  4558. (if (char-table-p translation-table-for-input)
  4559. (setq char (or (aref translation-table-for-input char) char))))
  4560. (kill-region (point) (progn
  4561. (search-forward (char-to-string char) nil nil arg)
  4562. (point))))
  4563. ;; kill-line and its subroutines.
  4564. (defcustom kill-whole-line nil
  4565. "If non-nil, `kill-line' with no arg at start of line kills the whole line."
  4566. :type 'boolean
  4567. :group 'killing)
  4568. (defun kill-line (&optional arg)
  4569. "Kill the rest of the current line; if no nonblanks there, kill thru newline.
  4570. With prefix argument ARG, kill that many lines from point.
  4571. Negative arguments kill lines backward.
  4572. With zero argument, kills the text before point on the current line.
  4573. When calling from a program, nil means \"no arg\",
  4574. a number counts as a prefix arg.
  4575. To kill a whole line, when point is not at the beginning, type \
  4576. \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
  4577. If `show-trailing-whitespace' is non-nil, this command will just
  4578. kill the rest of the current line, even if there are no nonblanks
  4579. there.
  4580. If option `kill-whole-line' is non-nil, then this command kills the whole line
  4581. including its terminating newline, when used at the beginning of a line
  4582. with no argument. As a consequence, you can always kill a whole line
  4583. by typing \\[move-beginning-of-line] \\[kill-line].
  4584. If you want to append the killed line to the last killed text,
  4585. use \\[append-next-kill] before \\[kill-line].
  4586. If the buffer is read-only, Emacs will beep and refrain from deleting
  4587. the line, but put the line in the kill ring anyway. This means that
  4588. you can use this command to copy text from a read-only buffer.
  4589. \(If the variable `kill-read-only-ok' is non-nil, then this won't
  4590. even beep.)"
  4591. (interactive "P")
  4592. (kill-region (point)
  4593. ;; It is better to move point to the other end of the kill
  4594. ;; before killing. That way, in a read-only buffer, point
  4595. ;; moves across the text that is copied to the kill ring.
  4596. ;; The choice has no effect on undo now that undo records
  4597. ;; the value of point from before the command was run.
  4598. (progn
  4599. (if arg
  4600. (forward-visible-line (prefix-numeric-value arg))
  4601. (if (eobp)
  4602. (signal 'end-of-buffer nil))
  4603. (let ((end
  4604. (save-excursion
  4605. (end-of-visible-line) (point))))
  4606. (if (or (save-excursion
  4607. ;; If trailing whitespace is visible,
  4608. ;; don't treat it as nothing.
  4609. (unless show-trailing-whitespace
  4610. (skip-chars-forward " \t" end))
  4611. (= (point) end))
  4612. (and kill-whole-line (bolp)))
  4613. (forward-visible-line 1)
  4614. (goto-char end))))
  4615. (point))))
  4616. (defun kill-whole-line (&optional arg)
  4617. "Kill current line.
  4618. With prefix ARG, kill that many lines starting from the current line.
  4619. If ARG is negative, kill backward. Also kill the preceding newline.
  4620. \(This is meant to make \\[repeat] work well with negative arguments.)
  4621. If ARG is zero, kill current line but exclude the trailing newline."
  4622. (interactive "p")
  4623. (or arg (setq arg 1))
  4624. (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
  4625. (signal 'end-of-buffer nil))
  4626. (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
  4627. (signal 'beginning-of-buffer nil))
  4628. (unless (eq last-command 'kill-region)
  4629. (kill-new "")
  4630. (setq last-command 'kill-region))
  4631. (cond ((zerop arg)
  4632. ;; We need to kill in two steps, because the previous command
  4633. ;; could have been a kill command, in which case the text
  4634. ;; before point needs to be prepended to the current kill
  4635. ;; ring entry and the text after point appended. Also, we
  4636. ;; need to use save-excursion to avoid copying the same text
  4637. ;; twice to the kill ring in read-only buffers.
  4638. (save-excursion
  4639. (kill-region (point) (progn (forward-visible-line 0) (point))))
  4640. (kill-region (point) (progn (end-of-visible-line) (point))))
  4641. ((< arg 0)
  4642. (save-excursion
  4643. (kill-region (point) (progn (end-of-visible-line) (point))))
  4644. (kill-region (point)
  4645. (progn (forward-visible-line (1+ arg))
  4646. (unless (bobp) (backward-char))
  4647. (point))))
  4648. (t
  4649. (save-excursion
  4650. (kill-region (point) (progn (forward-visible-line 0) (point))))
  4651. (kill-region (point)
  4652. (progn (forward-visible-line arg) (point))))))
  4653. (defun forward-visible-line (arg)
  4654. "Move forward by ARG lines, ignoring currently invisible newlines only.
  4655. If ARG is negative, move backward -ARG lines.
  4656. If ARG is zero, move to the beginning of the current line."
  4657. (condition-case nil
  4658. (if (> arg 0)
  4659. (progn
  4660. (while (> arg 0)
  4661. (or (zerop (forward-line 1))
  4662. (signal 'end-of-buffer nil))
  4663. ;; If the newline we just skipped is invisible,
  4664. ;; don't count it.
  4665. (let ((prop
  4666. (get-char-property (1- (point)) 'invisible)))
  4667. (if (if (eq buffer-invisibility-spec t)
  4668. prop
  4669. (or (memq prop buffer-invisibility-spec)
  4670. (assq prop buffer-invisibility-spec)))
  4671. (setq arg (1+ arg))))
  4672. (setq arg (1- arg)))
  4673. ;; If invisible text follows, and it is a number of complete lines,
  4674. ;; skip it.
  4675. (let ((opoint (point)))
  4676. (while (and (not (eobp))
  4677. (let ((prop
  4678. (get-char-property (point) 'invisible)))
  4679. (if (eq buffer-invisibility-spec t)
  4680. prop
  4681. (or (memq prop buffer-invisibility-spec)
  4682. (assq prop buffer-invisibility-spec)))))
  4683. (goto-char
  4684. (if (get-text-property (point) 'invisible)
  4685. (or (next-single-property-change (point) 'invisible)
  4686. (point-max))
  4687. (next-overlay-change (point)))))
  4688. (unless (bolp)
  4689. (goto-char opoint))))
  4690. (let ((first t))
  4691. (while (or first (<= arg 0))
  4692. (if first
  4693. (beginning-of-line)
  4694. (or (zerop (forward-line -1))
  4695. (signal 'beginning-of-buffer nil)))
  4696. ;; If the newline we just moved to is invisible,
  4697. ;; don't count it.
  4698. (unless (bobp)
  4699. (let ((prop
  4700. (get-char-property (1- (point)) 'invisible)))
  4701. (unless (if (eq buffer-invisibility-spec t)
  4702. prop
  4703. (or (memq prop buffer-invisibility-spec)
  4704. (assq prop buffer-invisibility-spec)))
  4705. (setq arg (1+ arg)))))
  4706. (setq first nil))
  4707. ;; If invisible text follows, and it is a number of complete lines,
  4708. ;; skip it.
  4709. (let ((opoint (point)))
  4710. (while (and (not (bobp))
  4711. (let ((prop
  4712. (get-char-property (1- (point)) 'invisible)))
  4713. (if (eq buffer-invisibility-spec t)
  4714. prop
  4715. (or (memq prop buffer-invisibility-spec)
  4716. (assq prop buffer-invisibility-spec)))))
  4717. (goto-char
  4718. (if (get-text-property (1- (point)) 'invisible)
  4719. (or (previous-single-property-change (point) 'invisible)
  4720. (point-min))
  4721. (previous-overlay-change (point)))))
  4722. (unless (bolp)
  4723. (goto-char opoint)))))
  4724. ((beginning-of-buffer end-of-buffer)
  4725. nil)))
  4726. (defun end-of-visible-line ()
  4727. "Move to end of current visible line."
  4728. (end-of-line)
  4729. ;; If the following character is currently invisible,
  4730. ;; skip all characters with that same `invisible' property value,
  4731. ;; then find the next newline.
  4732. (while (and (not (eobp))
  4733. (save-excursion
  4734. (skip-chars-forward "^\n")
  4735. (let ((prop
  4736. (get-char-property (point) 'invisible)))
  4737. (if (eq buffer-invisibility-spec t)
  4738. prop
  4739. (or (memq prop buffer-invisibility-spec)
  4740. (assq prop buffer-invisibility-spec))))))
  4741. (skip-chars-forward "^\n")
  4742. (if (get-text-property (point) 'invisible)
  4743. (goto-char (or (next-single-property-change (point) 'invisible)
  4744. (point-max)))
  4745. (goto-char (next-overlay-change (point))))
  4746. (end-of-line)))
  4747. (defun kill-current-buffer ()
  4748. "Kill the current buffer.
  4749. When called in the minibuffer, get out of the minibuffer
  4750. using `abort-recursive-edit'.
  4751. This is like `kill-this-buffer', but it doesn't have to be invoked
  4752. via the menu bar, and pays no attention to the menu-bar's frame."
  4753. (interactive)
  4754. (let ((frame (selected-frame)))
  4755. (if (and (frame-live-p frame)
  4756. (not (window-minibuffer-p (frame-selected-window frame))))
  4757. (kill-buffer (current-buffer))
  4758. (abort-recursive-edit))))
  4759. (defun insert-buffer (buffer)
  4760. "Insert after point the contents of BUFFER.
  4761. Puts mark after the inserted text.
  4762. BUFFER may be a buffer or a buffer name."
  4763. (declare (interactive-only insert-buffer-substring))
  4764. (interactive
  4765. (list
  4766. (progn
  4767. (barf-if-buffer-read-only)
  4768. (read-buffer "Insert buffer: "
  4769. (if (eq (selected-window) (next-window))
  4770. (other-buffer (current-buffer))
  4771. (window-buffer (next-window)))
  4772. t))))
  4773. (push-mark
  4774. (save-excursion
  4775. (insert-buffer-substring (get-buffer buffer))
  4776. (point)))
  4777. nil)
  4778. (defun append-to-buffer (buffer start end)
  4779. "Append to specified buffer the text of the region.
  4780. It is inserted into that buffer before its point.
  4781. When calling from a program, give three arguments:
  4782. BUFFER (or buffer name), START and END.
  4783. START and END specify the portion of the current buffer to be copied."
  4784. (interactive
  4785. (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
  4786. (region-beginning) (region-end)))
  4787. (let* ((oldbuf (current-buffer))
  4788. (append-to (get-buffer-create buffer))
  4789. (windows (get-buffer-window-list append-to t t))
  4790. point)
  4791. (save-excursion
  4792. (with-current-buffer append-to
  4793. (setq point (point))
  4794. (barf-if-buffer-read-only)
  4795. (insert-buffer-substring oldbuf start end)
  4796. (dolist (window windows)
  4797. (when (= (window-point window) point)
  4798. (set-window-point window (point))))))))
  4799. (defun prepend-to-buffer (buffer start end)
  4800. "Prepend to specified buffer the text of the region.
  4801. It is inserted into that buffer after its point.
  4802. When calling from a program, give three arguments:
  4803. BUFFER (or buffer name), START and END.
  4804. START and END specify the portion of the current buffer to be copied."
  4805. (interactive "BPrepend to buffer: \nr")
  4806. (let ((oldbuf (current-buffer)))
  4807. (with-current-buffer (get-buffer-create buffer)
  4808. (barf-if-buffer-read-only)
  4809. (save-excursion
  4810. (insert-buffer-substring oldbuf start end)))))
  4811. (defun copy-to-buffer (buffer start end)
  4812. "Copy to specified buffer the text of the region.
  4813. It is inserted into that buffer, replacing existing text there.
  4814. When calling from a program, give three arguments:
  4815. BUFFER (or buffer name), START and END.
  4816. START and END specify the portion of the current buffer to be copied."
  4817. (interactive "BCopy to buffer: \nr")
  4818. (let ((oldbuf (current-buffer)))
  4819. (with-current-buffer (get-buffer-create buffer)
  4820. (barf-if-buffer-read-only)
  4821. (erase-buffer)
  4822. (save-excursion
  4823. (insert-buffer-substring oldbuf start end)))))
  4824. (define-error 'mark-inactive (purecopy "The mark is not active now"))
  4825. (defvar activate-mark-hook nil
  4826. "Hook run when the mark becomes active.
  4827. It is also run at the end of a command, if the mark is active and
  4828. it is possible that the region may have changed.")
  4829. (defvar deactivate-mark-hook nil
  4830. "Hook run when the mark becomes inactive.")
  4831. (defun mark (&optional force)
  4832. "Return this buffer's mark value as integer, or nil if never set.
  4833. In Transient Mark mode, this function signals an error if
  4834. the mark is not active. However, if `mark-even-if-inactive' is non-nil,
  4835. or the argument FORCE is non-nil, it disregards whether the mark
  4836. is active, and returns an integer or nil in the usual way.
  4837. If you are using this in an editing command, you are most likely making
  4838. a mistake; see the documentation of `set-mark'."
  4839. (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
  4840. (marker-position (mark-marker))
  4841. (signal 'mark-inactive nil)))
  4842. ;; Behind display-selections-p.
  4843. (defun deactivate-mark (&optional force)
  4844. "Deactivate the mark.
  4845. If Transient Mark mode is disabled, this function normally does
  4846. nothing; but if FORCE is non-nil, it deactivates the mark anyway.
  4847. Deactivating the mark sets `mark-active' to nil, updates the
  4848. primary selection according to `select-active-regions', and runs
  4849. `deactivate-mark-hook'.
  4850. If Transient Mark mode was temporarily enabled, reset the value
  4851. of the variable `transient-mark-mode'; if this causes Transient
  4852. Mark mode to be disabled, don't change `mark-active' to nil or
  4853. run `deactivate-mark-hook'."
  4854. (when (or (region-active-p) force)
  4855. (when (and (if (eq select-active-regions 'only)
  4856. (eq (car-safe transient-mark-mode) 'only)
  4857. select-active-regions)
  4858. (region-active-p)
  4859. (display-selections-p))
  4860. ;; The var `saved-region-selection', if non-nil, is the text in
  4861. ;; the region prior to the last command modifying the buffer.
  4862. ;; Set the selection to that, or to the current region.
  4863. (cond (saved-region-selection
  4864. (if (gui-backend-selection-owner-p 'PRIMARY)
  4865. (gui-set-selection 'PRIMARY saved-region-selection))
  4866. (setq saved-region-selection nil))
  4867. ;; If another program has acquired the selection, region
  4868. ;; deactivation should not clobber it (Bug#11772).
  4869. ((and (/= (region-beginning) (region-end))
  4870. (or (gui-backend-selection-owner-p 'PRIMARY)
  4871. (null (gui-backend-selection-exists-p 'PRIMARY))))
  4872. (gui-set-selection 'PRIMARY
  4873. (funcall region-extract-function nil)))))
  4874. (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
  4875. (cond
  4876. ((eq (car-safe transient-mark-mode) 'only)
  4877. (setq transient-mark-mode (cdr transient-mark-mode))
  4878. (if (eq transient-mark-mode (default-value 'transient-mark-mode))
  4879. (kill-local-variable 'transient-mark-mode)))
  4880. ((eq transient-mark-mode 'lambda)
  4881. (kill-local-variable 'transient-mark-mode)))
  4882. (setq mark-active nil)
  4883. (run-hooks 'deactivate-mark-hook)
  4884. (redisplay--update-region-highlight (selected-window))))
  4885. (defun activate-mark (&optional no-tmm)
  4886. "Activate the mark.
  4887. If NO-TMM is non-nil, leave `transient-mark-mode' alone."
  4888. (when (mark t)
  4889. (unless (region-active-p)
  4890. (force-mode-line-update) ;Refresh toolbar (bug#16382).
  4891. (setq mark-active t)
  4892. (unless (or transient-mark-mode no-tmm)
  4893. (setq-local transient-mark-mode 'lambda))
  4894. (run-hooks 'activate-mark-hook))))
  4895. (defun set-mark (pos)
  4896. "Set this buffer's mark to POS. Don't use this function!
  4897. That is to say, don't use this function unless you want
  4898. the user to see that the mark has moved, and you want the previous
  4899. mark position to be lost.
  4900. Normally, when a new mark is set, the old one should go on the stack.
  4901. This is why most applications should use `push-mark', not `set-mark'.
  4902. Novice Emacs Lisp programmers often try to use the mark for the wrong
  4903. purposes. The mark saves a location for the user's convenience.
  4904. Most editing commands should not alter the mark.
  4905. To remember a location for internal use in the Lisp program,
  4906. store it in a Lisp variable. Example:
  4907. (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
  4908. (if pos
  4909. (progn
  4910. (set-marker (mark-marker) pos (current-buffer))
  4911. (activate-mark 'no-tmm))
  4912. ;; Normally we never clear mark-active except in Transient Mark mode.
  4913. ;; But when we actually clear out the mark value too, we must
  4914. ;; clear mark-active in any mode.
  4915. (deactivate-mark t)
  4916. ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
  4917. ;; it should never be nil if the mark is nil.
  4918. (setq mark-active nil)
  4919. (set-marker (mark-marker) nil)))
  4920. (defun save-mark-and-excursion--save ()
  4921. (cons
  4922. (let ((mark (mark-marker)))
  4923. (and (marker-position mark) (copy-marker mark)))
  4924. mark-active))
  4925. (defun save-mark-and-excursion--restore (saved-mark-info)
  4926. (let ((saved-mark (car saved-mark-info))
  4927. (omark (marker-position (mark-marker)))
  4928. (nmark nil)
  4929. (saved-mark-active (cdr saved-mark-info)))
  4930. ;; Mark marker
  4931. (if (null saved-mark)
  4932. (set-marker (mark-marker) nil)
  4933. (setf nmark (marker-position saved-mark))
  4934. (set-marker (mark-marker) nmark)
  4935. (set-marker saved-mark nil))
  4936. ;; Mark active
  4937. (let ((cur-mark-active mark-active))
  4938. (setq mark-active saved-mark-active)
  4939. ;; If mark is active now, and either was not active or was at a
  4940. ;; different place, run the activate hook.
  4941. (if saved-mark-active
  4942. (when (or (not cur-mark-active)
  4943. (not (eq omark nmark)))
  4944. (run-hooks 'activate-mark-hook))
  4945. ;; If mark has ceased to be active, run deactivate hook.
  4946. (when cur-mark-active
  4947. (run-hooks 'deactivate-mark-hook))))))
  4948. (defmacro save-mark-and-excursion (&rest body)
  4949. "Like `save-excursion', but also save and restore the mark state.
  4950. This macro does what `save-excursion' did before Emacs 25.1."
  4951. (declare (indent 0) (debug t))
  4952. (let ((saved-marker-sym (make-symbol "saved-marker")))
  4953. `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
  4954. (unwind-protect
  4955. (save-excursion ,@body)
  4956. (save-mark-and-excursion--restore ,saved-marker-sym)))))
  4957. (defcustom use-empty-active-region nil
  4958. "Whether \"region-aware\" commands should act on empty regions.
  4959. If nil, region-aware commands treat the empty region as inactive.
  4960. If non-nil, region-aware commands treat the region as active as
  4961. long as the mark is active, even if the region is empty.
  4962. Region-aware commands are those that act on the region if it is
  4963. active and Transient Mark mode is enabled, and on the text near
  4964. point otherwise."
  4965. :type 'boolean
  4966. :version "23.1"
  4967. :group 'editing-basics)
  4968. (defun use-region-p ()
  4969. "Return t if the region is active and it is appropriate to act on it.
  4970. This is used by commands that act specially on the region under
  4971. Transient Mark mode.
  4972. The return value is t if Transient Mark mode is enabled and the
  4973. mark is active; furthermore, if `use-empty-active-region' is nil,
  4974. the region must not be empty. Otherwise, the return value is nil.
  4975. For some commands, it may be appropriate to ignore the value of
  4976. `use-empty-active-region'; in that case, use `region-active-p'."
  4977. (and (region-active-p)
  4978. (or use-empty-active-region (> (region-end) (region-beginning)))))
  4979. (defun region-active-p ()
  4980. "Return non-nil if Transient Mark mode is enabled and the mark is active.
  4981. Some commands act specially on the region when Transient Mark
  4982. mode is enabled. Usually, such commands should use
  4983. `use-region-p' instead of this function, because `use-region-p'
  4984. also checks the value of `use-empty-active-region'."
  4985. (and transient-mark-mode mark-active
  4986. ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
  4987. ;; without the mark being set (e.g. bug#17324). We really should fix
  4988. ;; that problem, but in the mean time, let's make sure we don't say the
  4989. ;; region is active when there's no mark.
  4990. (progn (cl-assert (mark)) t)))
  4991. (defun region-bounds ()
  4992. "Return the boundaries of the region as a list of (START . END) positions."
  4993. (funcall region-extract-function 'bounds))
  4994. (defun region-noncontiguous-p ()
  4995. "Return non-nil if the region contains several pieces.
  4996. An example is a rectangular region handled as a list of
  4997. separate contiguous regions for each line."
  4998. (> (length (region-bounds)) 1))
  4999. (defvar redisplay-unhighlight-region-function
  5000. (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
  5001. (defvar redisplay-highlight-region-function
  5002. (lambda (start end window rol)
  5003. (if (not (overlayp rol))
  5004. (let ((nrol (make-overlay start end)))
  5005. (funcall redisplay-unhighlight-region-function rol)
  5006. (overlay-put nrol 'window window)
  5007. (overlay-put nrol 'face 'region)
  5008. ;; Normal priority so that a large region doesn't hide all the
  5009. ;; overlays within it, but high secondary priority so that if it
  5010. ;; ends/starts in the middle of a small overlay, that small overlay
  5011. ;; won't hide the region's boundaries.
  5012. (overlay-put nrol 'priority '(nil . 100))
  5013. nrol)
  5014. (unless (and (eq (overlay-buffer rol) (current-buffer))
  5015. (eq (overlay-start rol) start)
  5016. (eq (overlay-end rol) end))
  5017. (move-overlay rol start end (current-buffer)))
  5018. rol)))
  5019. (defun redisplay--update-region-highlight (window)
  5020. (let ((rol (window-parameter window 'internal-region-overlay)))
  5021. (if (not (and (region-active-p)
  5022. (or highlight-nonselected-windows
  5023. (eq window (selected-window))
  5024. (and (window-minibuffer-p)
  5025. (eq window (minibuffer-selected-window))))))
  5026. (funcall redisplay-unhighlight-region-function rol)
  5027. (let* ((pt (window-point window))
  5028. (mark (mark))
  5029. (start (min pt mark))
  5030. (end (max pt mark))
  5031. (new
  5032. (funcall redisplay-highlight-region-function
  5033. start end window rol)))
  5034. (unless (equal new rol)
  5035. (set-window-parameter window 'internal-region-overlay
  5036. new))))))
  5037. (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
  5038. "Hook run just before redisplay.
  5039. It is called in each window that is to be redisplayed. It takes one argument,
  5040. which is the window that will be redisplayed. When run, the `current-buffer'
  5041. is set to the buffer displayed in that window.")
  5042. (defun redisplay--pre-redisplay-functions (windows)
  5043. (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
  5044. (if (null windows)
  5045. (with-current-buffer (window-buffer (selected-window))
  5046. (run-hook-with-args 'pre-redisplay-functions (selected-window)))
  5047. (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
  5048. (with-current-buffer (window-buffer win)
  5049. (run-hook-with-args 'pre-redisplay-functions win))))))
  5050. (add-function :before pre-redisplay-function
  5051. #'redisplay--pre-redisplay-functions)
  5052. (defvar-local mark-ring nil
  5053. "The list of former marks of the current buffer, most recent first.")
  5054. (put 'mark-ring 'permanent-local t)
  5055. (defcustom mark-ring-max 16
  5056. "Maximum size of mark ring. Start discarding off end if gets this big."
  5057. :type 'integer
  5058. :group 'editing-basics)
  5059. (defvar global-mark-ring nil
  5060. "The list of saved global marks, most recent first.")
  5061. (defcustom global-mark-ring-max 16
  5062. "Maximum size of global mark ring. \
  5063. Start discarding off end if gets this big."
  5064. :type 'integer
  5065. :group 'editing-basics)
  5066. (defun pop-to-mark-command ()
  5067. "Jump to mark, and pop a new position for mark off the ring.
  5068. \(Does not affect global mark ring)."
  5069. (interactive)
  5070. (if (null (mark t))
  5071. (user-error "No mark set in this buffer")
  5072. (if (= (point) (mark t))
  5073. (message "Mark popped"))
  5074. (goto-char (mark t))
  5075. (pop-mark)))
  5076. (defun push-mark-command (arg &optional nomsg)
  5077. "Set mark at where point is.
  5078. If no prefix ARG and mark is already set there, just activate it.
  5079. Display `Mark set' unless the optional second arg NOMSG is non-nil."
  5080. (interactive "P")
  5081. (let ((mark (mark t)))
  5082. (if (or arg (null mark) (/= mark (point)))
  5083. (push-mark nil nomsg t)
  5084. (activate-mark 'no-tmm)
  5085. (unless nomsg
  5086. (message "Mark activated")))))
  5087. (defcustom set-mark-command-repeat-pop nil
  5088. "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
  5089. That means that C-u \\[set-mark-command] \\[set-mark-command]
  5090. will pop the mark twice, and
  5091. C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
  5092. will pop the mark three times.
  5093. A value of nil means \\[set-mark-command]'s behavior does not change
  5094. after C-u \\[set-mark-command]."
  5095. :type 'boolean
  5096. :group 'editing-basics)
  5097. (defun set-mark-command (arg)
  5098. "Set the mark where point is, and activate it; or jump to the mark.
  5099. Setting the mark also alters the region, which is the text
  5100. between point and mark; this is the closest equivalent in
  5101. Emacs to what some editors call the \"selection\".
  5102. With no prefix argument, set the mark at point, and push the
  5103. old mark position on local mark ring. Also push the new mark on
  5104. global mark ring, if the previous mark was set in another buffer.
  5105. When Transient Mark Mode is off, immediately repeating this
  5106. command activates `transient-mark-mode' temporarily.
  5107. With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
  5108. jump to the mark, and set the mark from
  5109. position popped off the local mark ring (this does not affect the global
  5110. mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
  5111. mark ring (see `pop-global-mark').
  5112. If `set-mark-command-repeat-pop' is non-nil, repeating
  5113. the \\[set-mark-command] command with no prefix argument pops the next position
  5114. off the local (or global) mark ring and jumps there.
  5115. With \\[universal-argument] \\[universal-argument] as prefix
  5116. argument, unconditionally set mark where point is, even if
  5117. `set-mark-command-repeat-pop' is non-nil.
  5118. Novice Emacs Lisp programmers often try to use the mark for the wrong
  5119. purposes. See the documentation of `set-mark' for more information."
  5120. (interactive "P")
  5121. (cond ((eq transient-mark-mode 'lambda)
  5122. (kill-local-variable 'transient-mark-mode))
  5123. ((eq (car-safe transient-mark-mode) 'only)
  5124. (deactivate-mark)))
  5125. (cond
  5126. ((and (consp arg) (> (prefix-numeric-value arg) 4))
  5127. (push-mark-command nil))
  5128. ((not (eq this-command 'set-mark-command))
  5129. (if arg
  5130. (pop-to-mark-command)
  5131. (push-mark-command t)))
  5132. ((and set-mark-command-repeat-pop
  5133. (eq last-command 'pop-global-mark)
  5134. (not arg))
  5135. (setq this-command 'pop-global-mark)
  5136. (pop-global-mark))
  5137. ((or (and set-mark-command-repeat-pop
  5138. (eq last-command 'pop-to-mark-command))
  5139. arg)
  5140. (setq this-command 'pop-to-mark-command)
  5141. (pop-to-mark-command))
  5142. ((eq last-command 'set-mark-command)
  5143. (if (region-active-p)
  5144. (progn
  5145. (deactivate-mark)
  5146. (message "Mark deactivated"))
  5147. (activate-mark)
  5148. (message "Mark activated")))
  5149. (t
  5150. (push-mark-command nil))))
  5151. (defun push-mark (&optional location nomsg activate)
  5152. "Set mark at LOCATION (point, by default) and push old mark on mark ring.
  5153. If the last global mark pushed was not in the current buffer,
  5154. also push LOCATION on the global mark ring.
  5155. Display `Mark set' unless the optional second arg NOMSG is non-nil.
  5156. Novice Emacs Lisp programmers often try to use the mark for the wrong
  5157. purposes. See the documentation of `set-mark' for more information.
  5158. In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
  5159. (unless (null (mark t))
  5160. (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
  5161. (when (> (length mark-ring) mark-ring-max)
  5162. (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
  5163. (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
  5164. (set-marker (mark-marker) (or location (point)) (current-buffer))
  5165. ;; Now push the mark on the global mark ring.
  5166. (if (and global-mark-ring
  5167. (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
  5168. ;; The last global mark pushed was in this same buffer.
  5169. ;; Don't push another one.
  5170. nil
  5171. (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
  5172. (when (> (length global-mark-ring) global-mark-ring-max)
  5173. (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
  5174. (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
  5175. (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
  5176. (message "Mark set"))
  5177. (if (or activate (not transient-mark-mode))
  5178. (set-mark (mark t)))
  5179. nil)
  5180. (defun pop-mark ()
  5181. "Pop off mark ring into the buffer's actual mark.
  5182. Does not set point. Does nothing if mark ring is empty."
  5183. (when mark-ring
  5184. (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
  5185. (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
  5186. (move-marker (car mark-ring) nil)
  5187. (if (null (mark t)) (ding))
  5188. (setq mark-ring (cdr mark-ring)))
  5189. (deactivate-mark))
  5190. (define-obsolete-function-alias
  5191. 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
  5192. (defun exchange-point-and-mark (&optional arg)
  5193. "Put the mark where point is now, and point where the mark is now.
  5194. This command works even when the mark is not active,
  5195. and it reactivates the mark.
  5196. If Transient Mark mode is on, a prefix ARG deactivates the mark
  5197. if it is active, and otherwise avoids reactivating it. If
  5198. Transient Mark mode is off, a prefix ARG enables Transient Mark
  5199. mode temporarily."
  5200. (interactive "P")
  5201. (let ((omark (mark t))
  5202. (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
  5203. (if (null omark)
  5204. (user-error "No mark set in this buffer"))
  5205. (set-mark (point))
  5206. (goto-char omark)
  5207. (cond (temp-highlight
  5208. (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
  5209. ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
  5210. (not (or arg (region-active-p))))
  5211. (deactivate-mark))
  5212. (t (activate-mark)))
  5213. nil))
  5214. (defcustom shift-select-mode t
  5215. "When non-nil, shifted motion keys activate the mark momentarily.
  5216. While the mark is activated in this way, any shift-translated point
  5217. motion key extends the region, and if Transient Mark mode was off, it
  5218. is temporarily turned on. Furthermore, the mark will be deactivated
  5219. by any subsequent point motion key that was not shift-translated, or
  5220. by any action that normally deactivates the mark in Transient Mark mode.
  5221. See `this-command-keys-shift-translated' for the meaning of
  5222. shift-translation."
  5223. :type 'boolean
  5224. :group 'editing-basics)
  5225. (defun handle-shift-selection ()
  5226. "Activate/deactivate mark depending on invocation thru shift translation.
  5227. This function is called by `call-interactively' when a command
  5228. with a `^' character in its `interactive' spec is invoked, before
  5229. running the command itself.
  5230. If `shift-select-mode' is enabled and the command was invoked
  5231. through shift translation, set the mark and activate the region
  5232. temporarily, unless it was already set in this way. See
  5233. `this-command-keys-shift-translated' for the meaning of shift
  5234. translation.
  5235. Otherwise, if the region has been activated temporarily,
  5236. deactivate it, and restore the variable `transient-mark-mode' to
  5237. its earlier value."
  5238. (cond ((and shift-select-mode this-command-keys-shift-translated)
  5239. (unless (and mark-active
  5240. (eq (car-safe transient-mark-mode) 'only))
  5241. (setq-local transient-mark-mode
  5242. (cons 'only
  5243. (unless (eq transient-mark-mode 'lambda)
  5244. transient-mark-mode)))
  5245. (push-mark nil nil t)))
  5246. ((eq (car-safe transient-mark-mode) 'only)
  5247. (setq transient-mark-mode (cdr transient-mark-mode))
  5248. (if (eq transient-mark-mode (default-value 'transient-mark-mode))
  5249. (kill-local-variable 'transient-mark-mode))
  5250. (deactivate-mark))))
  5251. (define-minor-mode transient-mark-mode
  5252. "Toggle Transient Mark mode.
  5253. With a prefix argument ARG, enable Transient Mark mode if ARG is
  5254. positive, and disable it otherwise. If called from Lisp, enable
  5255. Transient Mark mode if ARG is omitted or nil.
  5256. Transient Mark mode is a global minor mode. When enabled, the
  5257. region is highlighted with the `region' face whenever the mark
  5258. is active. The mark is \"deactivated\" by changing the buffer,
  5259. and after certain other operations that set the mark but whose
  5260. main purpose is something else--for example, incremental search,
  5261. \\[beginning-of-buffer], and \\[end-of-buffer].
  5262. You can also deactivate the mark by typing \\[keyboard-quit] or
  5263. \\[keyboard-escape-quit].
  5264. Many commands change their behavior when Transient Mark mode is
  5265. in effect and the mark is active, by acting on the region instead
  5266. of their usual default part of the buffer's text. Examples of
  5267. such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
  5268. \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
  5269. To see the documentation of commands which are sensitive to the
  5270. Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
  5271. or \"mark.*active\" at the prompt."
  5272. :global t
  5273. ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
  5274. :variable (default-value 'transient-mark-mode))
  5275. (defvar widen-automatically t
  5276. "Non-nil means it is ok for commands to call `widen' when they want to.
  5277. Some commands will do this in order to go to positions outside
  5278. the current accessible part of the buffer.
  5279. If `widen-automatically' is nil, these commands will do something else
  5280. as a fallback, and won't change the buffer bounds.")
  5281. (defvar non-essential nil
  5282. "Whether the currently executing code is performing an essential task.
  5283. This variable should be non-nil only when running code which should not
  5284. disturb the user. E.g. it can be used to prevent Tramp from prompting the
  5285. user for a password when we are simply scanning a set of files in the
  5286. background or displaying possible completions before the user even asked
  5287. for it.")
  5288. (defun pop-global-mark ()
  5289. "Pop off global mark ring and jump to the top location."
  5290. (interactive)
  5291. ;; Pop entries which refer to non-existent buffers.
  5292. (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
  5293. (setq global-mark-ring (cdr global-mark-ring)))
  5294. (or global-mark-ring
  5295. (error "No global mark set"))
  5296. (let* ((marker (car global-mark-ring))
  5297. (buffer (marker-buffer marker))
  5298. (position (marker-position marker)))
  5299. (setq global-mark-ring (nconc (cdr global-mark-ring)
  5300. (list (car global-mark-ring))))
  5301. (set-buffer buffer)
  5302. (or (and (>= position (point-min))
  5303. (<= position (point-max)))
  5304. (if widen-automatically
  5305. (widen)
  5306. (error "Global mark position is outside accessible part of buffer")))
  5307. (goto-char position)
  5308. (switch-to-buffer buffer)))
  5309. (defcustom next-line-add-newlines nil
  5310. "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
  5311. :type 'boolean
  5312. :version "21.1"
  5313. :group 'editing-basics)
  5314. (defun next-line (&optional arg try-vscroll)
  5315. "Move cursor vertically down ARG lines.
  5316. Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
  5317. Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
  5318. lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
  5319. function will not vscroll.
  5320. ARG defaults to 1.
  5321. If there is no character in the target line exactly under the current column,
  5322. the cursor is positioned after the character in that line which spans this
  5323. column, or at the end of the line if it is not long enough.
  5324. If there is no line in the buffer after this one, behavior depends on the
  5325. value of `next-line-add-newlines'. If non-nil, it inserts a newline character
  5326. to create a line, and moves the cursor to that line. Otherwise it moves the
  5327. cursor to the end of the buffer.
  5328. If the variable `line-move-visual' is non-nil, this command moves
  5329. by display lines. Otherwise, it moves by buffer lines, without
  5330. taking variable-width characters or continued lines into account.
  5331. See \\[next-logical-line] for a command that always moves by buffer lines.
  5332. The command \\[set-goal-column] can be used to create
  5333. a semipermanent goal column for this command.
  5334. Then instead of trying to move exactly vertically (or as close as possible),
  5335. this command moves to the specified goal column (or as close as possible).
  5336. The goal column is stored in the variable `goal-column', which is nil
  5337. when there is no goal column. Note that setting `goal-column'
  5338. overrides `line-move-visual' and causes this command to move by buffer
  5339. lines rather than by display lines."
  5340. (declare (interactive-only forward-line))
  5341. (interactive "^p\np")
  5342. (or arg (setq arg 1))
  5343. (if (and next-line-add-newlines (= arg 1))
  5344. (if (save-excursion (end-of-line) (eobp))
  5345. ;; When adding a newline, don't expand an abbrev.
  5346. (let ((abbrev-mode nil))
  5347. (end-of-line)
  5348. (insert (if use-hard-newlines hard-newline "\n")))
  5349. (line-move arg nil nil try-vscroll))
  5350. (if (called-interactively-p 'interactive)
  5351. (condition-case err
  5352. (line-move arg nil nil try-vscroll)
  5353. ((beginning-of-buffer end-of-buffer)
  5354. (signal (car err) (cdr err))))
  5355. (line-move arg nil nil try-vscroll)))
  5356. nil)
  5357. (defun previous-line (&optional arg try-vscroll)
  5358. "Move cursor vertically up ARG lines.
  5359. Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
  5360. Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
  5361. lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
  5362. function will not vscroll.
  5363. ARG defaults to 1.
  5364. If there is no character in the target line exactly over the current column,
  5365. the cursor is positioned after the character in that line which spans this
  5366. column, or at the end of the line if it is not long enough.
  5367. If the variable `line-move-visual' is non-nil, this command moves
  5368. by display lines. Otherwise, it moves by buffer lines, without
  5369. taking variable-width characters or continued lines into account.
  5370. See \\[previous-logical-line] for a command that always moves by buffer lines.
  5371. The command \\[set-goal-column] can be used to create
  5372. a semipermanent goal column for this command.
  5373. Then instead of trying to move exactly vertically (or as close as possible),
  5374. this command moves to the specified goal column (or as close as possible).
  5375. The goal column is stored in the variable `goal-column', which is nil
  5376. when there is no goal column. Note that setting `goal-column'
  5377. overrides `line-move-visual' and causes this command to move by buffer
  5378. lines rather than by display lines."
  5379. (declare (interactive-only
  5380. "use `forward-line' with negative argument instead."))
  5381. (interactive "^p\np")
  5382. (or arg (setq arg 1))
  5383. (if (called-interactively-p 'interactive)
  5384. (condition-case err
  5385. (line-move (- arg) nil nil try-vscroll)
  5386. ((beginning-of-buffer end-of-buffer)
  5387. (signal (car err) (cdr err))))
  5388. (line-move (- arg) nil nil try-vscroll))
  5389. nil)
  5390. (defcustom track-eol nil
  5391. "Non-nil means vertical motion starting at end of line keeps to ends of lines.
  5392. This means moving to the end of each line moved onto.
  5393. The beginning of a blank line does not count as the end of a line.
  5394. This has no effect when the variable `line-move-visual' is non-nil."
  5395. :type 'boolean
  5396. :group 'editing-basics)
  5397. (defcustom goal-column nil
  5398. "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
  5399. A non-nil setting overrides the variable `line-move-visual', which see."
  5400. :type '(choice integer
  5401. (const :tag "None" nil))
  5402. :group 'editing-basics)
  5403. (make-variable-buffer-local 'goal-column)
  5404. (defvar temporary-goal-column 0
  5405. "Current goal column for vertical motion.
  5406. It is the column where point was at the start of the current run
  5407. of vertical motion commands.
  5408. When moving by visual lines via the function `line-move-visual', it is a cons
  5409. cell (COL . HSCROLL), where COL is the x-position, in pixels,
  5410. divided by the default column width, and HSCROLL is the number of
  5411. columns by which window is scrolled from left margin.
  5412. When the `track-eol' feature is doing its job, the value is
  5413. `most-positive-fixnum'.")
  5414. (defvar last--line-number-width 0
  5415. "Last value of width used for displaying line numbers.
  5416. Used internally by `line-move-visual'.")
  5417. (defcustom line-move-ignore-invisible t
  5418. "Non-nil means commands that move by lines ignore invisible newlines.
  5419. When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
  5420. as if newlines that are invisible didn't exist, and count
  5421. only visible newlines. Thus, moving across across 2 newlines
  5422. one of which is invisible will be counted as a one-line move.
  5423. Also, a non-nil value causes invisible text to be ignored when
  5424. counting columns for the purposes of keeping point in the same
  5425. column by \\[next-line] and \\[previous-line].
  5426. Outline mode sets this."
  5427. :type 'boolean
  5428. :group 'editing-basics)
  5429. (defcustom line-move-visual t
  5430. "When non-nil, `line-move' moves point by visual lines.
  5431. This movement is based on where the cursor is displayed on the
  5432. screen, instead of relying on buffer contents alone. It takes
  5433. into account variable-width characters and line continuation.
  5434. If nil, `line-move' moves point by logical lines.
  5435. A non-nil setting of `goal-column' overrides the value of this variable
  5436. and forces movement by logical lines.
  5437. A window that is horizontally scrolled also forces movement by logical
  5438. lines."
  5439. :type 'boolean
  5440. :group 'editing-basics
  5441. :version "23.1")
  5442. ;; Only used if display-graphic-p.
  5443. (declare-function font-info "font.c" (name &optional frame))
  5444. (defun default-font-height ()
  5445. "Return the height in pixels of the current buffer's default face font.
  5446. If the default font is remapped (see `face-remapping-alist'), the
  5447. function returns the height of the remapped face."
  5448. (let ((default-font (face-font 'default)))
  5449. (cond
  5450. ((and (display-multi-font-p)
  5451. ;; Avoid calling font-info if the frame's default font was
  5452. ;; not changed since the frame was created. That's because
  5453. ;; font-info is expensive for some fonts, see bug #14838.
  5454. (not (string= (frame-parameter nil 'font) default-font)))
  5455. (aref (font-info default-font) 3))
  5456. (t (frame-char-height)))))
  5457. (defun default-font-width ()
  5458. "Return the width in pixels of the current buffer's default face font.
  5459. If the default font is remapped (see `face-remapping-alist'), the
  5460. function returns the width of the remapped face."
  5461. (let ((default-font (face-font 'default)))
  5462. (cond
  5463. ((and (display-multi-font-p)
  5464. ;; Avoid calling font-info if the frame's default font was
  5465. ;; not changed since the frame was created. That's because
  5466. ;; font-info is expensive for some fonts, see bug #14838.
  5467. (not (string= (frame-parameter nil 'font) default-font)))
  5468. (let* ((info (font-info (face-font 'default)))
  5469. (width (aref info 11)))
  5470. (if (> width 0)
  5471. width
  5472. (aref info 10))))
  5473. (t (frame-char-width)))))
  5474. (defun default-line-height ()
  5475. "Return the pixel height of current buffer's default-face text line.
  5476. The value includes `line-spacing', if any, defined for the buffer
  5477. or the frame."
  5478. (let ((dfh (default-font-height))
  5479. (lsp (if (display-graphic-p)
  5480. (or line-spacing
  5481. (default-value 'line-spacing)
  5482. (frame-parameter nil 'line-spacing)
  5483. 0)
  5484. 0)))
  5485. (if (floatp lsp)
  5486. (setq lsp (truncate (* (frame-char-height) lsp))))
  5487. (+ dfh lsp)))
  5488. (defun window-screen-lines ()
  5489. "Return the number of screen lines in the text area of the selected window.
  5490. This is different from `window-text-height' in that this function counts
  5491. lines in units of the height of the font used by the default face displayed
  5492. in the window, not in units of the frame's default font, and also accounts
  5493. for `line-spacing', if any, defined for the window's buffer or frame.
  5494. The value is a floating-point number."
  5495. (let ((edges (window-inside-pixel-edges))
  5496. (dlh (default-line-height)))
  5497. (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
  5498. ;; Returns non-nil if partial move was done.
  5499. (defun line-move-partial (arg noerror &optional _to-end)
  5500. (if (< arg 0)
  5501. ;; Move backward (up).
  5502. ;; If already vscrolled, reduce vscroll
  5503. (let ((vs (window-vscroll nil t))
  5504. (dlh (default-line-height)))
  5505. (when (> vs dlh)
  5506. (set-window-vscroll nil (- vs dlh) t)))
  5507. ;; Move forward (down).
  5508. (let* ((lh (window-line-height -1))
  5509. (rowh (car lh))
  5510. (vpos (nth 1 lh))
  5511. (ypos (nth 2 lh))
  5512. (rbot (nth 3 lh))
  5513. (this-lh (window-line-height))
  5514. (this-height (car this-lh))
  5515. (this-ypos (nth 2 this-lh))
  5516. (dlh (default-line-height))
  5517. (wslines (window-screen-lines))
  5518. (edges (window-inside-pixel-edges))
  5519. (winh (- (nth 3 edges) (nth 1 edges) 1))
  5520. py vs last-line)
  5521. (if (> (mod wslines 1.0) 0.0)
  5522. (setq wslines (round (+ wslines 0.5))))
  5523. (when (or (null lh)
  5524. (>= rbot dlh)
  5525. (<= ypos (- dlh))
  5526. (null this-lh)
  5527. (<= this-ypos (- dlh)))
  5528. (unless lh
  5529. (let ((wend (pos-visible-in-window-p t nil t)))
  5530. (setq rbot (nth 3 wend)
  5531. rowh (nth 4 wend)
  5532. vpos (nth 5 wend))))
  5533. (unless this-lh
  5534. (let ((wstart (pos-visible-in-window-p nil nil t)))
  5535. (setq this-ypos (nth 2 wstart)
  5536. this-height (nth 4 wstart))))
  5537. (setq py
  5538. (or (nth 1 this-lh)
  5539. (let ((ppos (posn-at-point))
  5540. col-row)
  5541. (setq col-row (posn-actual-col-row ppos))
  5542. (if col-row
  5543. (- (cdr col-row) (window-vscroll))
  5544. (cdr (posn-col-row ppos))))))
  5545. ;; VPOS > 0 means the last line is only partially visible.
  5546. ;; But if the part that is visible is at least as tall as the
  5547. ;; default font, that means the line is actually fully
  5548. ;; readable, and something like line-spacing is hidden. So in
  5549. ;; that case we accept the last line in the window as still
  5550. ;; visible, and consider the margin as starting one line
  5551. ;; later.
  5552. (if (and vpos (> vpos 0))
  5553. (if (and rowh
  5554. (>= rowh (default-font-height))
  5555. (< rowh dlh))
  5556. (setq last-line (min (- wslines scroll-margin) vpos))
  5557. (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
  5558. (cond
  5559. ;; If last line of window is fully visible, and vscrolling
  5560. ;; more would make this line invisible, move forward.
  5561. ((and (or (< (setq vs (window-vscroll nil t)) dlh)
  5562. (null this-height)
  5563. (<= this-height dlh))
  5564. (or (null rbot) (= rbot 0)))
  5565. nil)
  5566. ;; If cursor is not in the bottom scroll margin, and the
  5567. ;; current line is is not too tall, move forward.
  5568. ((and (or (null this-height) (<= this-height winh))
  5569. vpos
  5570. (> vpos 0)
  5571. (< py last-line))
  5572. nil)
  5573. ;; When already vscrolled, we vscroll some more if we can,
  5574. ;; or clear vscroll and move forward at end of tall image.
  5575. ((> vs 0)
  5576. (when (or (and rbot (> rbot 0))
  5577. (and this-height (> this-height dlh)))
  5578. (set-window-vscroll nil (+ vs dlh) t)))
  5579. ;; If cursor just entered the bottom scroll margin, move forward,
  5580. ;; but also optionally vscroll one line so redisplay won't recenter.
  5581. ((and vpos
  5582. (> vpos 0)
  5583. (= py last-line))
  5584. ;; Don't vscroll if the partially-visible line at window
  5585. ;; bottom is not too tall (a.k.a. "just one more text
  5586. ;; line"): in that case, we do want redisplay to behave
  5587. ;; normally, i.e. recenter or whatever.
  5588. ;;
  5589. ;; Note: ROWH + RBOT from the value returned by
  5590. ;; pos-visible-in-window-p give the total height of the
  5591. ;; partially-visible glyph row at the end of the window. As
  5592. ;; we are dealing with floats, we disregard sub-pixel
  5593. ;; discrepancies between that and DLH.
  5594. (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
  5595. (set-window-vscroll nil dlh t))
  5596. (line-move-1 arg noerror)
  5597. t)
  5598. ;; If there are lines above the last line, scroll-up one line.
  5599. ((and vpos (> vpos 0))
  5600. (scroll-up 1)
  5601. t)
  5602. ;; Finally, start vscroll.
  5603. (t
  5604. (set-window-vscroll nil dlh t)))))))
  5605. ;; This is like line-move-1 except that it also performs
  5606. ;; vertical scrolling of tall images if appropriate.
  5607. ;; That is not really a clean thing to do, since it mixes
  5608. ;; scrolling with cursor motion. But so far we don't have
  5609. ;; a cleaner solution to the problem of making C-n do something
  5610. ;; useful given a tall image.
  5611. (defun line-move (arg &optional noerror _to-end try-vscroll)
  5612. "Move forward ARG lines.
  5613. If NOERROR, don't signal an error if we can't move ARG lines.
  5614. TO-END is unused.
  5615. TRY-VSCROLL controls whether to vscroll tall lines: if either
  5616. `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
  5617. not vscroll."
  5618. (if noninteractive
  5619. (line-move-1 arg noerror)
  5620. (unless (and auto-window-vscroll try-vscroll
  5621. ;; Only vscroll for single line moves
  5622. (= (abs arg) 1)
  5623. ;; Under scroll-conservatively, the display engine
  5624. ;; does this better.
  5625. (zerop scroll-conservatively)
  5626. ;; But don't vscroll in a keyboard macro.
  5627. (not defining-kbd-macro)
  5628. (not executing-kbd-macro)
  5629. (line-move-partial arg noerror))
  5630. (set-window-vscroll nil 0 t)
  5631. (if (and line-move-visual
  5632. ;; Display-based column are incompatible with goal-column.
  5633. (not goal-column)
  5634. ;; When the text in the window is scrolled to the left,
  5635. ;; display-based motion doesn't make sense (because each
  5636. ;; logical line occupies exactly one screen line).
  5637. (not (> (window-hscroll) 0))
  5638. ;; Likewise when the text _was_ scrolled to the left
  5639. ;; when the current run of vertical motion commands
  5640. ;; started.
  5641. (not (and (memq last-command
  5642. `(next-line previous-line ,this-command))
  5643. auto-hscroll-mode
  5644. (numberp temporary-goal-column)
  5645. (>= temporary-goal-column
  5646. (- (window-width) hscroll-margin)))))
  5647. (prog1 (line-move-visual arg noerror)
  5648. ;; If we moved into a tall line, set vscroll to make
  5649. ;; scrolling through tall images more smooth.
  5650. (let ((lh (line-pixel-height))
  5651. (edges (window-inside-pixel-edges))
  5652. (dlh (default-line-height))
  5653. winh)
  5654. (setq winh (- (nth 3 edges) (nth 1 edges) 1))
  5655. (if (and (< arg 0)
  5656. (< (point) (window-start))
  5657. (> lh winh))
  5658. (set-window-vscroll
  5659. nil
  5660. (- lh dlh) t))))
  5661. (line-move-1 arg noerror)))))
  5662. ;; Display-based alternative to line-move-1.
  5663. ;; Arg says how many lines to move. The value is t if we can move the
  5664. ;; specified number of lines.
  5665. (defun line-move-visual (arg &optional noerror)
  5666. "Move ARG lines forward.
  5667. If NOERROR, don't signal an error if we can't move that many lines."
  5668. (let ((opoint (point))
  5669. (hscroll (window-hscroll))
  5670. (lnum-width (line-number-display-width t))
  5671. target-hscroll)
  5672. ;; Check if the previous command was a line-motion command, or if
  5673. ;; we were called from some other command.
  5674. (if (and (consp temporary-goal-column)
  5675. (memq last-command `(next-line previous-line ,this-command)))
  5676. ;; If so, there's no need to reset `temporary-goal-column',
  5677. ;; but we may need to hscroll.
  5678. (progn
  5679. (if (or (/= (cdr temporary-goal-column) hscroll)
  5680. (> (cdr temporary-goal-column) 0))
  5681. (setq target-hscroll (cdr temporary-goal-column)))
  5682. ;; Update the COLUMN part of temporary-goal-column if the
  5683. ;; line-number display changed its width since the last
  5684. ;; time.
  5685. (setq temporary-goal-column
  5686. (cons (+ (car temporary-goal-column)
  5687. (/ (float (- lnum-width last--line-number-width))
  5688. (frame-char-width)))
  5689. (cdr temporary-goal-column)))
  5690. (setq last--line-number-width lnum-width))
  5691. ;; Otherwise, we should reset `temporary-goal-column'.
  5692. (let ((posn (posn-at-point))
  5693. x-pos)
  5694. (cond
  5695. ;; Handle the `overflow-newline-into-fringe' case
  5696. ;; (left-fringe is for the R2L case):
  5697. ((memq (nth 1 posn) '(right-fringe left-fringe))
  5698. (setq temporary-goal-column (cons (window-width) hscroll)))
  5699. ((car (posn-x-y posn))
  5700. (setq x-pos (car (posn-x-y posn)))
  5701. ;; In R2L lines, the X pixel coordinate is measured from the
  5702. ;; left edge of the window, but columns are still counted
  5703. ;; from the logical-order beginning of the line, i.e. from
  5704. ;; the right edge in this case. We need to adjust for that.
  5705. (if (eq (current-bidi-paragraph-direction) 'right-to-left)
  5706. (setq x-pos (- (window-body-width nil t) 1 x-pos)))
  5707. (setq temporary-goal-column
  5708. (cons (/ (float x-pos)
  5709. (frame-char-width))
  5710. hscroll)))
  5711. (executing-kbd-macro
  5712. ;; When we move beyond the first/last character visible in
  5713. ;; the window, posn-at-point will return nil, so we need to
  5714. ;; approximate the goal column as below.
  5715. (setq temporary-goal-column
  5716. (mod (current-column) (window-text-width)))))))
  5717. (if target-hscroll
  5718. (set-window-hscroll (selected-window) target-hscroll))
  5719. ;; vertical-motion can move more than it was asked to if it moves
  5720. ;; across display strings with newlines. We don't want to ring
  5721. ;; the bell and announce beginning/end of buffer in that case.
  5722. (or (and (or (and (>= arg 0)
  5723. (>= (vertical-motion
  5724. (cons (or goal-column
  5725. (if (consp temporary-goal-column)
  5726. (car temporary-goal-column)
  5727. temporary-goal-column))
  5728. arg))
  5729. arg))
  5730. (and (< arg 0)
  5731. (<= (vertical-motion
  5732. (cons (or goal-column
  5733. (if (consp temporary-goal-column)
  5734. (car temporary-goal-column)
  5735. temporary-goal-column))
  5736. arg))
  5737. arg)))
  5738. (or (>= arg 0)
  5739. (/= (point) opoint)
  5740. ;; If the goal column lies on a display string,
  5741. ;; `vertical-motion' advances the cursor to the end
  5742. ;; of the string. For arg < 0, this can cause the
  5743. ;; cursor to get stuck. (Bug#3020).
  5744. (= (vertical-motion arg) arg)))
  5745. (unless noerror
  5746. (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
  5747. nil)))))
  5748. ;; This is the guts of next-line and previous-line.
  5749. ;; Arg says how many lines to move.
  5750. ;; The value is t if we can move the specified number of lines.
  5751. (defun line-move-1 (arg &optional noerror _to-end)
  5752. ;; Don't run any point-motion hooks, and disregard intangibility,
  5753. ;; for intermediate positions.
  5754. (let ((inhibit-point-motion-hooks t)
  5755. (opoint (point))
  5756. (orig-arg arg))
  5757. (if (consp temporary-goal-column)
  5758. (setq temporary-goal-column (+ (car temporary-goal-column)
  5759. (cdr temporary-goal-column))))
  5760. (unwind-protect
  5761. (progn
  5762. (if (not (memq last-command '(next-line previous-line)))
  5763. (setq temporary-goal-column
  5764. (if (and track-eol (eolp)
  5765. ;; Don't count beg of empty line as end of line
  5766. ;; unless we just did explicit end-of-line.
  5767. (or (not (bolp)) (eq last-command 'move-end-of-line)))
  5768. most-positive-fixnum
  5769. (current-column))))
  5770. (if (not (or (integerp selective-display)
  5771. line-move-ignore-invisible))
  5772. ;; Use just newline characters.
  5773. ;; Set ARG to 0 if we move as many lines as requested.
  5774. (or (if (> arg 0)
  5775. (progn (if (> arg 1) (forward-line (1- arg)))
  5776. ;; This way of moving forward ARG lines
  5777. ;; verifies that we have a newline after the last one.
  5778. ;; It doesn't get confused by intangible text.
  5779. (end-of-line)
  5780. (if (zerop (forward-line 1))
  5781. (setq arg 0)))
  5782. (and (zerop (forward-line arg))
  5783. (bolp)
  5784. (setq arg 0)))
  5785. (unless noerror
  5786. (signal (if (< arg 0)
  5787. 'beginning-of-buffer
  5788. 'end-of-buffer)
  5789. nil)))
  5790. ;; Move by arg lines, but ignore invisible ones.
  5791. (let (done)
  5792. (while (and (> arg 0) (not done))
  5793. ;; If the following character is currently invisible,
  5794. ;; skip all characters with that same `invisible' property value.
  5795. (while (and (not (eobp)) (invisible-p (point)))
  5796. (goto-char (next-char-property-change (point))))
  5797. ;; Move a line.
  5798. ;; We don't use `end-of-line', since we want to escape
  5799. ;; from field boundaries occurring exactly at point.
  5800. (goto-char (constrain-to-field
  5801. (let ((inhibit-field-text-motion t))
  5802. (line-end-position))
  5803. (point) t t
  5804. 'inhibit-line-move-field-capture))
  5805. ;; If there's no invisibility here, move over the newline.
  5806. (cond
  5807. ((eobp)
  5808. (if (not noerror)
  5809. (signal 'end-of-buffer nil)
  5810. (setq done t)))
  5811. ((and (> arg 1) ;; Use vertical-motion for last move
  5812. (not (integerp selective-display))
  5813. (not (invisible-p (point))))
  5814. ;; We avoid vertical-motion when possible
  5815. ;; because that has to fontify.
  5816. (forward-line 1))
  5817. ;; Otherwise move a more sophisticated way.
  5818. ((zerop (vertical-motion 1))
  5819. (if (not noerror)
  5820. (signal 'end-of-buffer nil)
  5821. (setq done t))))
  5822. (unless done
  5823. (setq arg (1- arg))))
  5824. ;; The logic of this is the same as the loop above,
  5825. ;; it just goes in the other direction.
  5826. (while (and (< arg 0) (not done))
  5827. ;; For completely consistency with the forward-motion
  5828. ;; case, we should call beginning-of-line here.
  5829. ;; However, if point is inside a field and on a
  5830. ;; continued line, the call to (vertical-motion -1)
  5831. ;; below won't move us back far enough; then we return
  5832. ;; to the same column in line-move-finish, and point
  5833. ;; gets stuck -- cyd
  5834. (forward-line 0)
  5835. (cond
  5836. ((bobp)
  5837. (if (not noerror)
  5838. (signal 'beginning-of-buffer nil)
  5839. (setq done t)))
  5840. ((and (< arg -1) ;; Use vertical-motion for last move
  5841. (not (integerp selective-display))
  5842. (not (invisible-p (1- (point)))))
  5843. (forward-line -1))
  5844. ((zerop (vertical-motion -1))
  5845. (if (not noerror)
  5846. (signal 'beginning-of-buffer nil)
  5847. (setq done t))))
  5848. (unless done
  5849. (setq arg (1+ arg))
  5850. (while (and ;; Don't move over previous invis lines
  5851. ;; if our target is the middle of this line.
  5852. (or (zerop (or goal-column temporary-goal-column))
  5853. (< arg 0))
  5854. (not (bobp)) (invisible-p (1- (point))))
  5855. (goto-char (previous-char-property-change (point))))))))
  5856. ;; This is the value the function returns.
  5857. (= arg 0))
  5858. (cond ((> arg 0)
  5859. ;; If we did not move down as far as desired, at least go
  5860. ;; to end of line. Be sure to call point-entered and
  5861. ;; point-left-hooks.
  5862. (let* ((npoint (prog1 (line-end-position)
  5863. (goto-char opoint)))
  5864. (inhibit-point-motion-hooks nil))
  5865. (goto-char npoint)))
  5866. ((< arg 0)
  5867. ;; If we did not move up as far as desired,
  5868. ;; at least go to beginning of line.
  5869. (let* ((npoint (prog1 (line-beginning-position)
  5870. (goto-char opoint)))
  5871. (inhibit-point-motion-hooks nil))
  5872. (goto-char npoint)))
  5873. (t
  5874. (line-move-finish (or goal-column temporary-goal-column)
  5875. opoint (> orig-arg 0)))))))
  5876. (defun line-move-finish (column opoint forward)
  5877. (let ((repeat t))
  5878. (while repeat
  5879. ;; Set REPEAT to t to repeat the whole thing.
  5880. (setq repeat nil)
  5881. (let (new
  5882. (old (point))
  5883. (line-beg (line-beginning-position))
  5884. (line-end
  5885. ;; Compute the end of the line
  5886. ;; ignoring effectively invisible newlines.
  5887. (save-excursion
  5888. ;; Like end-of-line but ignores fields.
  5889. (skip-chars-forward "^\n")
  5890. (while (and (not (eobp)) (invisible-p (point)))
  5891. (goto-char (next-char-property-change (point)))
  5892. (skip-chars-forward "^\n"))
  5893. (point))))
  5894. ;; Move to the desired column.
  5895. (if (and line-move-visual
  5896. (not (or truncate-lines truncate-partial-width-windows)))
  5897. ;; Under line-move-visual, goal-column should be
  5898. ;; interpreted in units of the frame's canonical character
  5899. ;; width, which is exactly what vertical-motion does.
  5900. (vertical-motion (cons column 0))
  5901. (line-move-to-column (truncate column)))
  5902. ;; Corner case: suppose we start out in a field boundary in
  5903. ;; the middle of a continued line. When we get to
  5904. ;; line-move-finish, point is at the start of a new *screen*
  5905. ;; line but the same text line; then line-move-to-column would
  5906. ;; move us backwards. Test using C-n with point on the "x" in
  5907. ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
  5908. (and forward
  5909. (< (point) old)
  5910. (goto-char old))
  5911. (setq new (point))
  5912. ;; Process intangibility within a line.
  5913. ;; With inhibit-point-motion-hooks bound to nil, a call to
  5914. ;; goto-char moves point past intangible text.
  5915. ;; However, inhibit-point-motion-hooks controls both the
  5916. ;; intangibility and the point-entered/point-left hooks. The
  5917. ;; following hack avoids calling the point-* hooks
  5918. ;; unnecessarily. Note that we move *forward* past intangible
  5919. ;; text when the initial and final points are the same.
  5920. (goto-char new)
  5921. (let ((inhibit-point-motion-hooks nil))
  5922. (goto-char new)
  5923. ;; If intangibility moves us to a different (later) place
  5924. ;; in the same line, use that as the destination.
  5925. (if (<= (point) line-end)
  5926. (setq new (point))
  5927. ;; If that position is "too late",
  5928. ;; try the previous allowable position.
  5929. ;; See if it is ok.
  5930. (backward-char)
  5931. (if (if forward
  5932. ;; If going forward, don't accept the previous
  5933. ;; allowable position if it is before the target line.
  5934. (< line-beg (point))
  5935. ;; If going backward, don't accept the previous
  5936. ;; allowable position if it is still after the target line.
  5937. (<= (point) line-end))
  5938. (setq new (point))
  5939. ;; As a last resort, use the end of the line.
  5940. (setq new line-end))))
  5941. ;; Now move to the updated destination, processing fields
  5942. ;; as well as intangibility.
  5943. (goto-char opoint)
  5944. (let ((inhibit-point-motion-hooks nil))
  5945. (goto-char
  5946. ;; Ignore field boundaries if the initial and final
  5947. ;; positions have the same `field' property, even if the
  5948. ;; fields are non-contiguous. This seems to be "nicer"
  5949. ;; behavior in many situations.
  5950. (if (eq (get-char-property new 'field)
  5951. (get-char-property opoint 'field))
  5952. new
  5953. (constrain-to-field new opoint t t
  5954. 'inhibit-line-move-field-capture))))
  5955. ;; If all this moved us to a different line,
  5956. ;; retry everything within that new line.
  5957. (when (or (< (point) line-beg) (> (point) line-end))
  5958. ;; Repeat the intangibility and field processing.
  5959. (setq repeat t))))))
  5960. (defun line-move-to-column (col)
  5961. "Try to find column COL, considering invisibility.
  5962. This function works only in certain cases,
  5963. because what we really need is for `move-to-column'
  5964. and `current-column' to be able to ignore invisible text."
  5965. (if (zerop col)
  5966. (beginning-of-line)
  5967. (move-to-column col))
  5968. (when (and line-move-ignore-invisible
  5969. (not (bolp)) (invisible-p (1- (point))))
  5970. (let ((normal-location (point))
  5971. (normal-column (current-column)))
  5972. ;; If the following character is currently invisible,
  5973. ;; skip all characters with that same `invisible' property value.
  5974. (while (and (not (eobp))
  5975. (invisible-p (point)))
  5976. (goto-char (next-char-property-change (point))))
  5977. ;; Have we advanced to a larger column position?
  5978. (if (> (current-column) normal-column)
  5979. ;; We have made some progress towards the desired column.
  5980. ;; See if we can make any further progress.
  5981. (line-move-to-column (+ (current-column) (- col normal-column)))
  5982. ;; Otherwise, go to the place we originally found
  5983. ;; and move back over invisible text.
  5984. ;; that will get us to the same place on the screen
  5985. ;; but with a more reasonable buffer position.
  5986. (goto-char normal-location)
  5987. (let ((line-beg
  5988. ;; We want the real line beginning, so it's consistent
  5989. ;; with bolp below, otherwise we might infloop.
  5990. (let ((inhibit-field-text-motion t))
  5991. (line-beginning-position))))
  5992. (while (and (not (bolp)) (invisible-p (1- (point))))
  5993. (goto-char (previous-char-property-change (point) line-beg))))))))
  5994. (defun move-end-of-line (arg)
  5995. "Move point to end of current line as displayed.
  5996. With argument ARG not nil or 1, move forward ARG - 1 lines first.
  5997. If point reaches the beginning or end of buffer, it stops there.
  5998. To ignore the effects of the `intangible' text or overlay
  5999. property, bind `inhibit-point-motion-hooks' to t.
  6000. If there is an image in the current line, this function
  6001. disregards newlines that are part of the text on which the image
  6002. rests."
  6003. (interactive "^p")
  6004. (or arg (setq arg 1))
  6005. (let (done)
  6006. (while (not done)
  6007. (let ((newpos
  6008. (save-excursion
  6009. (let ((goal-column 0)
  6010. (line-move-visual nil))
  6011. (and (line-move arg t)
  6012. ;; With bidi reordering, we may not be at bol,
  6013. ;; so make sure we are.
  6014. (skip-chars-backward "^\n")
  6015. (not (bobp))
  6016. (progn
  6017. (while (and (not (bobp)) (invisible-p (1- (point))))
  6018. (goto-char (previous-single-char-property-change
  6019. (point) 'invisible)))
  6020. (backward-char 1)))
  6021. (point)))))
  6022. (goto-char newpos)
  6023. (if (and (> (point) newpos)
  6024. (eq (preceding-char) ?\n))
  6025. (backward-char 1)
  6026. (if (and (> (point) newpos) (not (eobp))
  6027. (not (eq (following-char) ?\n)))
  6028. ;; If we skipped something intangible and now we're not
  6029. ;; really at eol, keep going.
  6030. (setq arg 1)
  6031. (setq done t)))))))
  6032. (defun move-beginning-of-line (arg)
  6033. "Move point to beginning of current line as displayed.
  6034. \(If there's an image in the line, this disregards newlines
  6035. which are part of the text that the image rests on.)
  6036. With argument ARG not nil or 1, move forward ARG - 1 lines first.
  6037. If point reaches the beginning or end of buffer, it stops there.
  6038. \(But if the buffer doesn't end in a newline, it stops at the
  6039. beginning of the last line.)
  6040. To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
  6041. (interactive "^p")
  6042. (or arg (setq arg 1))
  6043. (let ((orig (point))
  6044. first-vis first-vis-field-value)
  6045. ;; Move by lines, if ARG is not 1 (the default).
  6046. (if (/= arg 1)
  6047. (let ((line-move-visual nil))
  6048. (line-move (1- arg) t)))
  6049. ;; Move to beginning-of-line, ignoring fields and invisible text.
  6050. (skip-chars-backward "^\n")
  6051. (while (and (not (bobp)) (invisible-p (1- (point))))
  6052. (goto-char (previous-char-property-change (point)))
  6053. (skip-chars-backward "^\n"))
  6054. ;; Now find first visible char in the line.
  6055. (while (and (< (point) orig) (invisible-p (point)))
  6056. (goto-char (next-char-property-change (point) orig)))
  6057. (setq first-vis (point))
  6058. ;; See if fields would stop us from reaching FIRST-VIS.
  6059. (setq first-vis-field-value
  6060. (constrain-to-field first-vis orig (/= arg 1) t nil))
  6061. (goto-char (if (/= first-vis-field-value first-vis)
  6062. ;; If yes, obey them.
  6063. first-vis-field-value
  6064. ;; Otherwise, move to START with attention to fields.
  6065. ;; (It is possible that fields never matter in this case.)
  6066. (constrain-to-field (point) orig
  6067. (/= arg 1) t nil)))))
  6068. ;; Many people have said they rarely use this feature, and often type
  6069. ;; it by accident. Maybe it shouldn't even be on a key.
  6070. (put 'set-goal-column 'disabled t)
  6071. (defun set-goal-column (arg)
  6072. "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
  6073. Those commands will move to this position in the line moved to
  6074. rather than trying to keep the same horizontal position.
  6075. With a non-nil argument ARG, clears out the goal column
  6076. so that \\[next-line] and \\[previous-line] resume vertical motion.
  6077. The goal column is stored in the variable `goal-column'.
  6078. This is a buffer-local setting."
  6079. (interactive "P")
  6080. (if arg
  6081. (progn
  6082. (setq goal-column nil)
  6083. (message "No goal column"))
  6084. (setq goal-column (current-column))
  6085. ;; The older method below can be erroneous if `set-goal-column' is bound
  6086. ;; to a sequence containing %
  6087. ;;(message (substitute-command-keys
  6088. ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
  6089. ;;goal-column)
  6090. (message "%s"
  6091. (concat
  6092. (format "Goal column %d " goal-column)
  6093. (substitute-command-keys
  6094. "(use \\[set-goal-column] with an arg to unset it)")))
  6095. )
  6096. nil)
  6097. ;;; Editing based on visual lines, as opposed to logical lines.
  6098. (defun end-of-visual-line (&optional n)
  6099. "Move point to end of current visual line.
  6100. With argument N not nil or 1, move forward N - 1 visual lines first.
  6101. If point reaches the beginning or end of buffer, it stops there.
  6102. To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
  6103. (interactive "^p")
  6104. (or n (setq n 1))
  6105. (if (/= n 1)
  6106. (let ((line-move-visual t))
  6107. (line-move (1- n) t)))
  6108. ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
  6109. ;; constrain to field boundaries, so we don't either.
  6110. (vertical-motion (cons (window-width) 0)))
  6111. (defun beginning-of-visual-line (&optional n)
  6112. "Move point to beginning of current visual line.
  6113. With argument N not nil or 1, move forward N - 1 visual lines first.
  6114. If point reaches the beginning or end of buffer, it stops there.
  6115. \(But if the buffer doesn't end in a newline, it stops at the
  6116. beginning of the last visual line.)
  6117. To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
  6118. (interactive "^p")
  6119. (or n (setq n 1))
  6120. (let ((opoint (point)))
  6121. (if (/= n 1)
  6122. (let ((line-move-visual t))
  6123. (line-move (1- n) t)))
  6124. (vertical-motion 0)
  6125. ;; Constrain to field boundaries, like `move-beginning-of-line'.
  6126. (goto-char (constrain-to-field (point) opoint (/= n 1)))))
  6127. (defun kill-visual-line (&optional arg)
  6128. "Kill the rest of the visual line.
  6129. With prefix argument ARG, kill that many visual lines from point.
  6130. If ARG is negative, kill visual lines backward.
  6131. If ARG is zero, kill the text before point on the current visual
  6132. line.
  6133. If you want to append the killed line to the last killed text,
  6134. use \\[append-next-kill] before \\[kill-line].
  6135. If the buffer is read-only, Emacs will beep and refrain from deleting
  6136. the line, but put the line in the kill ring anyway. This means that
  6137. you can use this command to copy text from a read-only buffer.
  6138. \(If the variable `kill-read-only-ok' is non-nil, then this won't
  6139. even beep.)"
  6140. (interactive "P")
  6141. ;; Like in `kill-line', it's better to move point to the other end
  6142. ;; of the kill before killing.
  6143. (let ((opoint (point))
  6144. (kill-whole-line (and kill-whole-line (bolp))))
  6145. (if arg
  6146. (vertical-motion (prefix-numeric-value arg))
  6147. (end-of-visual-line 1)
  6148. (if (= (point) opoint)
  6149. (vertical-motion 1)
  6150. ;; Skip any trailing whitespace at the end of the visual line.
  6151. ;; We used to do this only if `show-trailing-whitespace' is
  6152. ;; nil, but that's wrong; the correct thing would be to check
  6153. ;; whether the trailing whitespace is highlighted. But, it's
  6154. ;; OK to just do this unconditionally.
  6155. (skip-chars-forward " \t")))
  6156. (kill-region opoint (if (and kill-whole-line (= (following-char) ?\n))
  6157. (1+ (point))
  6158. (point)))))
  6159. (defun next-logical-line (&optional arg try-vscroll)
  6160. "Move cursor vertically down ARG lines.
  6161. This is identical to `next-line', except that it always moves
  6162. by logical lines instead of visual lines, ignoring the value of
  6163. the variable `line-move-visual'."
  6164. (interactive "^p\np")
  6165. (let ((line-move-visual nil))
  6166. (with-no-warnings
  6167. (next-line arg try-vscroll))))
  6168. (defun previous-logical-line (&optional arg try-vscroll)
  6169. "Move cursor vertically up ARG lines.
  6170. This is identical to `previous-line', except that it always moves
  6171. by logical lines instead of visual lines, ignoring the value of
  6172. the variable `line-move-visual'."
  6173. (interactive "^p\np")
  6174. (let ((line-move-visual nil))
  6175. (with-no-warnings
  6176. (previous-line arg try-vscroll))))
  6177. (defgroup visual-line nil
  6178. "Editing based on visual lines."
  6179. :group 'convenience
  6180. :version "23.1")
  6181. (defvar visual-line-mode-map
  6182. (let ((map (make-sparse-keymap)))
  6183. (define-key map [remap kill-line] 'kill-visual-line)
  6184. (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
  6185. (define-key map [remap move-end-of-line] 'end-of-visual-line)
  6186. ;; These keybindings interfere with xterm function keys. Are
  6187. ;; there any other suitable bindings?
  6188. ;; (define-key map "\M-[" 'previous-logical-line)
  6189. ;; (define-key map "\M-]" 'next-logical-line)
  6190. map))
  6191. (defcustom visual-line-fringe-indicators '(nil nil)
  6192. "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
  6193. The value should be a list of the form (LEFT RIGHT), where LEFT
  6194. and RIGHT are symbols representing the bitmaps to display, to
  6195. indicate wrapped lines, in the left and right fringes respectively.
  6196. See also `fringe-indicator-alist'.
  6197. The default is not to display fringe indicators for wrapped lines.
  6198. This variable does not affect fringe indicators displayed for
  6199. other purposes."
  6200. :type '(list (choice (const :tag "Hide left indicator" nil)
  6201. (const :tag "Left curly arrow" left-curly-arrow)
  6202. (symbol :tag "Other bitmap"))
  6203. (choice (const :tag "Hide right indicator" nil)
  6204. (const :tag "Right curly arrow" right-curly-arrow)
  6205. (symbol :tag "Other bitmap")))
  6206. :set (lambda (symbol value)
  6207. (dolist (buf (buffer-list))
  6208. (with-current-buffer buf
  6209. (when (and (boundp 'visual-line-mode)
  6210. (symbol-value 'visual-line-mode))
  6211. (setq fringe-indicator-alist
  6212. (cons (cons 'continuation value)
  6213. (assq-delete-all
  6214. 'continuation
  6215. (copy-tree fringe-indicator-alist)))))))
  6216. (set-default symbol value)))
  6217. (defvar visual-line--saved-state nil)
  6218. (define-minor-mode visual-line-mode
  6219. "Toggle visual line based editing (Visual Line mode).
  6220. Interactively, with a prefix argument, enable
  6221. Visual Line mode if the prefix argument is positive,
  6222. and disable it otherwise. If called from Lisp, toggle
  6223. the mode if ARG is `toggle', disable the mode if ARG is
  6224. a non-positive integer, and enable the mode otherwise
  6225. \(including if ARG is omitted or nil or a positive integer).
  6226. When Visual Line mode is enabled, `word-wrap' is turned on in
  6227. this buffer, and simple editing commands are redefined to act on
  6228. visual lines, not logical lines. See Info node `Visual Line
  6229. Mode' for details."
  6230. :keymap visual-line-mode-map
  6231. :group 'visual-line
  6232. :lighter " Wrap"
  6233. (if visual-line-mode
  6234. (progn
  6235. (set (make-local-variable 'visual-line--saved-state) nil)
  6236. ;; Save the local values of some variables, to be restored if
  6237. ;; visual-line-mode is turned off.
  6238. (dolist (var '(line-move-visual truncate-lines
  6239. truncate-partial-width-windows
  6240. word-wrap fringe-indicator-alist))
  6241. (if (local-variable-p var)
  6242. (push (cons var (symbol-value var))
  6243. visual-line--saved-state)))
  6244. (set (make-local-variable 'line-move-visual) t)
  6245. (set (make-local-variable 'truncate-partial-width-windows) nil)
  6246. (setq truncate-lines nil
  6247. word-wrap t
  6248. fringe-indicator-alist
  6249. (cons (cons 'continuation visual-line-fringe-indicators)
  6250. fringe-indicator-alist)))
  6251. (kill-local-variable 'line-move-visual)
  6252. (kill-local-variable 'word-wrap)
  6253. (kill-local-variable 'truncate-lines)
  6254. (kill-local-variable 'truncate-partial-width-windows)
  6255. (kill-local-variable 'fringe-indicator-alist)
  6256. (dolist (saved visual-line--saved-state)
  6257. (set (make-local-variable (car saved)) (cdr saved)))
  6258. (kill-local-variable 'visual-line--saved-state)))
  6259. (defun turn-on-visual-line-mode ()
  6260. (visual-line-mode 1))
  6261. (define-globalized-minor-mode global-visual-line-mode
  6262. visual-line-mode turn-on-visual-line-mode)
  6263. (defun transpose-chars (arg)
  6264. "Interchange characters around point, moving forward one character.
  6265. With prefix arg ARG, effect is to take character before point
  6266. and drag it forward past ARG other characters (backward if ARG negative).
  6267. If no argument and at end of line, the previous two chars are exchanged."
  6268. (interactive "*P")
  6269. (when (and (null arg) (eolp) (not (bobp))
  6270. (not (get-text-property (1- (point)) 'read-only)))
  6271. (forward-char -1))
  6272. (transpose-subr 'forward-char (prefix-numeric-value arg)))
  6273. (defun transpose-words (arg)
  6274. "Interchange words around point, leaving point at end of them.
  6275. With prefix arg ARG, effect is to take word before or around point
  6276. and drag it forward past ARG other words (backward if ARG negative).
  6277. If ARG is zero, the words around or after point and around or after mark
  6278. are interchanged."
  6279. ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
  6280. (interactive "*p")
  6281. (transpose-subr 'forward-word arg))
  6282. (defun transpose-sexps (arg)
  6283. "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
  6284. Unlike `transpose-words', point must be between the two sexps and not
  6285. in the middle of a sexp to be transposed.
  6286. With non-zero prefix arg ARG, effect is to take the sexp before point
  6287. and drag it forward past ARG other sexps (backward if ARG is negative).
  6288. If ARG is zero, the sexps ending at or after point and at or after mark
  6289. are interchanged."
  6290. (interactive "*p")
  6291. (transpose-subr
  6292. (lambda (arg)
  6293. ;; Here we should try to simulate the behavior of
  6294. ;; (cons (progn (forward-sexp x) (point))
  6295. ;; (progn (forward-sexp (- x)) (point)))
  6296. ;; Except that we don't want to rely on the second forward-sexp
  6297. ;; putting us back to where we want to be, since forward-sexp-function
  6298. ;; might do funny things like infix-precedence.
  6299. (if (if (> arg 0)
  6300. (looking-at "\\sw\\|\\s_")
  6301. (and (not (bobp))
  6302. (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
  6303. ;; Jumping over a symbol. We might be inside it, mind you.
  6304. (progn (funcall (if (> arg 0)
  6305. 'skip-syntax-backward 'skip-syntax-forward)
  6306. "w_")
  6307. (cons (save-excursion (forward-sexp arg) (point)) (point)))
  6308. ;; Otherwise, we're between sexps. Take a step back before jumping
  6309. ;; to make sure we'll obey the same precedence no matter which direction
  6310. ;; we're going.
  6311. (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
  6312. (cons (save-excursion (forward-sexp arg) (point))
  6313. (progn (while (or (forward-comment (if (> arg 0) 1 -1))
  6314. (not (zerop (funcall (if (> arg 0)
  6315. 'skip-syntax-forward
  6316. 'skip-syntax-backward)
  6317. ".")))))
  6318. (point)))))
  6319. arg 'special))
  6320. (defun transpose-lines (arg)
  6321. "Exchange current line and previous line, leaving point after both.
  6322. With argument ARG, takes previous line and moves it past ARG lines.
  6323. With argument 0, interchanges line point is in with line mark is in."
  6324. (interactive "*p")
  6325. (transpose-subr (function
  6326. (lambda (arg)
  6327. (if (> arg 0)
  6328. (progn
  6329. ;; Move forward over ARG lines,
  6330. ;; but create newlines if necessary.
  6331. (setq arg (forward-line arg))
  6332. (if (/= (preceding-char) ?\n)
  6333. (setq arg (1+ arg)))
  6334. (if (> arg 0)
  6335. (newline arg)))
  6336. (forward-line arg))))
  6337. arg))
  6338. ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
  6339. ;; which seems inconsistent with the ARG /= 0 case.
  6340. ;; FIXME document SPECIAL.
  6341. (defun transpose-subr (mover arg &optional special)
  6342. "Subroutine to do the work of transposing objects.
  6343. Works for lines, sentences, paragraphs, etc. MOVER is a function that
  6344. moves forward by units of the given object (e.g. forward-sentence,
  6345. forward-paragraph). If ARG is zero, exchanges the current object
  6346. with the one containing mark. If ARG is an integer, moves the
  6347. current object past ARG following (if ARG is positive) or
  6348. preceding (if ARG is negative) objects, leaving point after the
  6349. current object."
  6350. (let ((aux (if special mover
  6351. (lambda (x)
  6352. (cons (progn (funcall mover x) (point))
  6353. (progn (funcall mover (- x)) (point))))))
  6354. pos1 pos2)
  6355. (cond
  6356. ((= arg 0)
  6357. (save-excursion
  6358. (setq pos1 (funcall aux 1))
  6359. (goto-char (or (mark) (error "No mark set in this buffer")))
  6360. (setq pos2 (funcall aux 1))
  6361. (transpose-subr-1 pos1 pos2))
  6362. (exchange-point-and-mark))
  6363. ((> arg 0)
  6364. (setq pos1 (funcall aux -1))
  6365. (setq pos2 (funcall aux arg))
  6366. (transpose-subr-1 pos1 pos2)
  6367. (goto-char (car pos2)))
  6368. (t
  6369. (setq pos1 (funcall aux -1))
  6370. (goto-char (car pos1))
  6371. (setq pos2 (funcall aux arg))
  6372. (transpose-subr-1 pos1 pos2)
  6373. (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
  6374. (defun transpose-subr-1 (pos1 pos2)
  6375. (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
  6376. (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
  6377. (when (> (car pos1) (car pos2))
  6378. (let ((swap pos1))
  6379. (setq pos1 pos2 pos2 swap)))
  6380. (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
  6381. (atomic-change-group
  6382. ;; This sequence of insertions attempts to preserve marker
  6383. ;; positions at the start and end of the transposed objects.
  6384. (let* ((word (buffer-substring (car pos2) (cdr pos2)))
  6385. (len1 (- (cdr pos1) (car pos1)))
  6386. (len2 (length word))
  6387. (boundary (make-marker)))
  6388. (set-marker boundary (car pos2))
  6389. (goto-char (cdr pos1))
  6390. (insert-before-markers word)
  6391. (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
  6392. (goto-char boundary)
  6393. (insert word)
  6394. (goto-char (+ boundary len1))
  6395. (delete-region (point) (+ (point) len2))
  6396. (set-marker boundary nil))))
  6397. (defun backward-word (&optional arg)
  6398. "Move backward until encountering the beginning of a word.
  6399. With argument ARG, do this that many times.
  6400. If ARG is omitted or nil, move point backward one word.
  6401. The word boundaries are normally determined by the buffer's syntax
  6402. table, but `find-word-boundary-function-table', such as set up
  6403. by `subword-mode', can change that. If a Lisp program needs to
  6404. move by words determined strictly by the syntax table, it should
  6405. use `backward-word-strictly' instead."
  6406. (interactive "^p")
  6407. (forward-word (- (or arg 1))))
  6408. (defun mark-word (&optional arg allow-extend)
  6409. "Set mark ARG words away from point.
  6410. The place mark goes is the same place \\[forward-word] would
  6411. move to with the same argument.
  6412. Interactively, if this command is repeated
  6413. or (in Transient Mark mode) if the mark is active,
  6414. it marks the next ARG words after the ones already marked."
  6415. (interactive "P\np")
  6416. (cond ((and allow-extend
  6417. (or (and (eq last-command this-command) (mark t))
  6418. (region-active-p)))
  6419. (setq arg (if arg (prefix-numeric-value arg)
  6420. (if (< (mark) (point)) -1 1)))
  6421. (set-mark
  6422. (save-excursion
  6423. (goto-char (mark))
  6424. (forward-word arg)
  6425. (point))))
  6426. (t
  6427. (push-mark
  6428. (save-excursion
  6429. (forward-word (prefix-numeric-value arg))
  6430. (point))
  6431. nil t))))
  6432. (defun kill-word (arg)
  6433. "Kill characters forward until encountering the end of a word.
  6434. With argument ARG, do this that many times."
  6435. (interactive "p")
  6436. (kill-region (point) (progn (forward-word arg) (point))))
  6437. (defun backward-kill-word (arg)
  6438. "Kill characters backward until encountering the beginning of a word.
  6439. With argument ARG, do this that many times."
  6440. (interactive "p")
  6441. (kill-word (- arg)))
  6442. (defun current-word (&optional strict really-word)
  6443. "Return the word at or near point, as a string.
  6444. The return value includes no text properties.
  6445. If optional arg STRICT is non-nil, return nil unless point is
  6446. within or adjacent to a word, otherwise look for a word within
  6447. point's line. If there is no word anywhere on point's line, the
  6448. value is nil regardless of STRICT.
  6449. By default, this function treats as a single word any sequence of
  6450. characters that have either word or symbol syntax. If optional
  6451. arg REALLY-WORD is non-nil, only characters of word syntax can
  6452. constitute a word."
  6453. (save-excursion
  6454. (let* ((oldpoint (point)) (start (point)) (end (point))
  6455. (syntaxes (if really-word "w" "w_"))
  6456. (not-syntaxes (concat "^" syntaxes)))
  6457. (skip-syntax-backward syntaxes) (setq start (point))
  6458. (goto-char oldpoint)
  6459. (skip-syntax-forward syntaxes) (setq end (point))
  6460. (when (and (eq start oldpoint) (eq end oldpoint)
  6461. ;; Point is neither within nor adjacent to a word.
  6462. (not strict))
  6463. ;; Look for preceding word in same line.
  6464. (skip-syntax-backward not-syntaxes (line-beginning-position))
  6465. (if (bolp)
  6466. ;; No preceding word in same line.
  6467. ;; Look for following word in same line.
  6468. (progn
  6469. (skip-syntax-forward not-syntaxes (line-end-position))
  6470. (setq start (point))
  6471. (skip-syntax-forward syntaxes)
  6472. (setq end (point)))
  6473. (setq end (point))
  6474. (skip-syntax-backward syntaxes)
  6475. (setq start (point))))
  6476. ;; If we found something nonempty, return it as a string.
  6477. (unless (= start end)
  6478. (buffer-substring-no-properties start end)))))
  6479. (defcustom fill-prefix nil
  6480. "String for filling to insert at front of new line, or nil for none."
  6481. :type '(choice (const :tag "None" nil)
  6482. string)
  6483. :group 'fill)
  6484. (make-variable-buffer-local 'fill-prefix)
  6485. (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
  6486. (defcustom auto-fill-inhibit-regexp nil
  6487. "Regexp to match lines which should not be auto-filled."
  6488. :type '(choice (const :tag "None" nil)
  6489. regexp)
  6490. :group 'fill)
  6491. (defun do-auto-fill ()
  6492. "The default value for `normal-auto-fill-function'.
  6493. This is the default auto-fill function, some major modes use a different one.
  6494. Returns t if it really did any work."
  6495. (let (fc justify give-up
  6496. (fill-prefix fill-prefix))
  6497. (if (or (not (setq justify (current-justification)))
  6498. (null (setq fc (current-fill-column)))
  6499. (and (eq justify 'left)
  6500. (<= (current-column) fc))
  6501. (and auto-fill-inhibit-regexp
  6502. (save-excursion (beginning-of-line)
  6503. (looking-at auto-fill-inhibit-regexp))))
  6504. nil ;; Auto-filling not required
  6505. (if (memq justify '(full center right))
  6506. (save-excursion (unjustify-current-line)))
  6507. ;; Choose a fill-prefix automatically.
  6508. (when (and adaptive-fill-mode
  6509. (or (null fill-prefix) (string= fill-prefix "")))
  6510. (let ((prefix
  6511. (fill-context-prefix
  6512. (save-excursion (fill-forward-paragraph -1) (point))
  6513. (save-excursion (fill-forward-paragraph 1) (point)))))
  6514. (and prefix (not (equal prefix ""))
  6515. ;; Use auto-indentation rather than a guessed empty prefix.
  6516. (not (and fill-indent-according-to-mode
  6517. (string-match "\\`[ \t]*\\'" prefix)))
  6518. (setq fill-prefix prefix))))
  6519. (while (and (not give-up) (> (current-column) fc))
  6520. ;; Determine where to split the line.
  6521. (let* (after-prefix
  6522. (fill-point
  6523. (save-excursion
  6524. (beginning-of-line)
  6525. (setq after-prefix (point))
  6526. (and fill-prefix
  6527. (looking-at (regexp-quote fill-prefix))
  6528. (setq after-prefix (match-end 0)))
  6529. (move-to-column (1+ fc))
  6530. (fill-move-to-break-point after-prefix)
  6531. (point))))
  6532. ;; See whether the place we found is any good.
  6533. (if (save-excursion
  6534. (goto-char fill-point)
  6535. (or (bolp)
  6536. ;; There is no use breaking at end of line.
  6537. (save-excursion (skip-chars-forward " ") (eolp))
  6538. ;; It is futile to split at the end of the prefix
  6539. ;; since we would just insert the prefix again.
  6540. (and after-prefix (<= (point) after-prefix))
  6541. ;; Don't split right after a comment starter
  6542. ;; since we would just make another comment starter.
  6543. (and comment-start-skip
  6544. (let ((limit (point)))
  6545. (beginning-of-line)
  6546. (and (re-search-forward comment-start-skip
  6547. limit t)
  6548. (eq (point) limit))))))
  6549. ;; No good place to break => stop trying.
  6550. (setq give-up t)
  6551. ;; Ok, we have a useful place to break the line. Do it.
  6552. (let ((prev-column (current-column)))
  6553. ;; If point is at the fill-point, do not `save-excursion'.
  6554. ;; Otherwise, if a comment prefix or fill-prefix is inserted,
  6555. ;; point will end up before it rather than after it.
  6556. (if (save-excursion
  6557. (skip-chars-backward " \t")
  6558. (= (point) fill-point))
  6559. (default-indent-new-line t)
  6560. (save-excursion
  6561. (goto-char fill-point)
  6562. (default-indent-new-line t)))
  6563. ;; Now do justification, if required
  6564. (if (not (eq justify 'left))
  6565. (save-excursion
  6566. (end-of-line 0)
  6567. (justify-current-line justify nil t)))
  6568. ;; If making the new line didn't reduce the hpos of
  6569. ;; the end of the line, then give up now;
  6570. ;; trying again will not help.
  6571. (if (>= (current-column) prev-column)
  6572. (setq give-up t))))))
  6573. ;; Justify last line.
  6574. (justify-current-line justify t t)
  6575. t)))
  6576. (defvar comment-line-break-function 'comment-indent-new-line
  6577. "Mode-specific function which line breaks and continues a comment.
  6578. This function is called during auto-filling when a comment syntax
  6579. is defined.
  6580. The function should take a single optional argument, which is a flag
  6581. indicating whether it should use soft newlines.")
  6582. (defun default-indent-new-line (&optional soft)
  6583. "Break line at point and indent.
  6584. If a comment syntax is defined, call `comment-indent-new-line'.
  6585. The inserted newline is marked hard if variable `use-hard-newlines' is true,
  6586. unless optional argument SOFT is non-nil."
  6587. (interactive)
  6588. (if comment-start
  6589. (funcall comment-line-break-function soft)
  6590. ;; Insert the newline before removing empty space so that markers
  6591. ;; get preserved better.
  6592. (if soft (insert-and-inherit ?\n) (newline 1))
  6593. (save-excursion (forward-char -1) (delete-horizontal-space))
  6594. (delete-horizontal-space)
  6595. (if (and fill-prefix (not adaptive-fill-mode))
  6596. ;; Blindly trust a non-adaptive fill-prefix.
  6597. (progn
  6598. (indent-to-left-margin)
  6599. (insert-before-markers-and-inherit fill-prefix))
  6600. (cond
  6601. ;; If there's an adaptive prefix, use it unless we're inside
  6602. ;; a comment and the prefix is not a comment starter.
  6603. (fill-prefix
  6604. (indent-to-left-margin)
  6605. (insert-and-inherit fill-prefix))
  6606. ;; If we're not inside a comment, just try to indent.
  6607. (t (indent-according-to-mode))))))
  6608. (defun internal-auto-fill ()
  6609. "The function called by `self-insert-command' to perform auto-filling."
  6610. (when (or (not comment-start)
  6611. (not comment-auto-fill-only-comments)
  6612. (nth 4 (syntax-ppss)))
  6613. (funcall auto-fill-function)))
  6614. (defvar normal-auto-fill-function 'do-auto-fill
  6615. "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
  6616. Some major modes set this.")
  6617. (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
  6618. ;; `functions' and `hooks' are usually unsafe to set, but setting
  6619. ;; auto-fill-function to nil in a file-local setting is safe and
  6620. ;; can be useful to prevent auto-filling.
  6621. (put 'auto-fill-function 'safe-local-variable 'null)
  6622. (define-minor-mode auto-fill-mode
  6623. "Toggle automatic line breaking (Auto Fill mode).
  6624. Interactively, with a prefix argument, enable
  6625. Auto Fill mode if the prefix argument is positive,
  6626. and disable it otherwise. If called from Lisp, toggle
  6627. the mode if ARG is `toggle', disable the mode if ARG is
  6628. a non-positive integer, and enable the mode otherwise
  6629. \(including if ARG is omitted or nil or a positive integer).
  6630. When Auto Fill mode is enabled, inserting a space at a column
  6631. beyond `current-fill-column' automatically breaks the line at a
  6632. previous space.
  6633. When `auto-fill-mode' is on, the `auto-fill-function' variable is
  6634. non-nil.
  6635. The value of `normal-auto-fill-function' specifies the function to use
  6636. for `auto-fill-function' when turning Auto Fill mode on."
  6637. :variable (auto-fill-function
  6638. . (lambda (v) (setq auto-fill-function
  6639. (if v normal-auto-fill-function)))))
  6640. ;; This holds a document string used to document auto-fill-mode.
  6641. (defun auto-fill-function ()
  6642. "Automatically break line at a previous space, in insertion of text."
  6643. nil)
  6644. (defun turn-on-auto-fill ()
  6645. "Unconditionally turn on Auto Fill mode."
  6646. (auto-fill-mode 1))
  6647. (defun turn-off-auto-fill ()
  6648. "Unconditionally turn off Auto Fill mode."
  6649. (auto-fill-mode -1))
  6650. (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
  6651. (defun set-fill-column (arg)
  6652. "Set `fill-column' to specified argument.
  6653. Use \\[universal-argument] followed by a number to specify a column.
  6654. Just \\[universal-argument] as argument means to use the current column."
  6655. (interactive
  6656. (list (or current-prefix-arg
  6657. ;; We used to use current-column silently, but C-x f is too easily
  6658. ;; typed as a typo for C-x C-f, so we turned it into an error and
  6659. ;; now an interactive prompt.
  6660. (read-number "Set fill-column to: " (current-column)))))
  6661. (if (consp arg)
  6662. (setq arg (current-column)))
  6663. (if (not (integerp arg))
  6664. ;; Disallow missing argument; it's probably a typo for C-x C-f.
  6665. (error "set-fill-column requires an explicit argument")
  6666. (message "Fill column set to %d (was %d)" arg fill-column)
  6667. (setq fill-column arg)))
  6668. (defun set-selective-display (arg)
  6669. "Set `selective-display' to ARG; clear it if no arg.
  6670. When the value of `selective-display' is a number > 0,
  6671. lines whose indentation is >= that value are not displayed.
  6672. The variable `selective-display' has a separate value for each buffer."
  6673. (interactive "P")
  6674. (if (eq selective-display t)
  6675. (error "selective-display already in use for marked lines"))
  6676. (let ((current-vpos
  6677. (save-restriction
  6678. (narrow-to-region (point-min) (point))
  6679. (goto-char (window-start))
  6680. (vertical-motion (window-height)))))
  6681. (setq selective-display
  6682. (and arg (prefix-numeric-value arg)))
  6683. (recenter current-vpos))
  6684. (set-window-start (selected-window) (window-start))
  6685. (princ "selective-display set to " t)
  6686. (prin1 selective-display t)
  6687. (princ "." t))
  6688. (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
  6689. (defun toggle-truncate-lines (&optional arg)
  6690. "Toggle truncating of long lines for the current buffer.
  6691. When truncating is off, long lines are folded.
  6692. With prefix argument ARG, truncate long lines if ARG is positive,
  6693. otherwise fold them. Note that in side-by-side windows, this
  6694. command has no effect if `truncate-partial-width-windows' is
  6695. non-nil."
  6696. (interactive "P")
  6697. (setq truncate-lines
  6698. (if (null arg)
  6699. (not truncate-lines)
  6700. (> (prefix-numeric-value arg) 0)))
  6701. (force-mode-line-update)
  6702. (unless truncate-lines
  6703. (let ((buffer (current-buffer)))
  6704. (walk-windows (lambda (window)
  6705. (if (eq buffer (window-buffer window))
  6706. (set-window-hscroll window 0)))
  6707. nil t)))
  6708. (message "Truncate long lines %s"
  6709. (if truncate-lines "enabled" "disabled")))
  6710. (defun toggle-word-wrap (&optional arg)
  6711. "Toggle whether to use word-wrapping for continuation lines.
  6712. With prefix argument ARG, wrap continuation lines at word boundaries
  6713. if ARG is positive, otherwise wrap them at the right screen edge.
  6714. This command toggles the value of `word-wrap'. It has no effect
  6715. if long lines are truncated."
  6716. (interactive "P")
  6717. (setq word-wrap
  6718. (if (null arg)
  6719. (not word-wrap)
  6720. (> (prefix-numeric-value arg) 0)))
  6721. (force-mode-line-update)
  6722. (message "Word wrapping %s"
  6723. (if word-wrap "enabled" "disabled")))
  6724. (defvar overwrite-mode-textual (purecopy " Ovwrt")
  6725. "The string displayed in the mode line when in overwrite mode.")
  6726. (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
  6727. "The string displayed in the mode line when in binary overwrite mode.")
  6728. (define-minor-mode overwrite-mode
  6729. "Toggle Overwrite mode.
  6730. With a prefix argument ARG, enable Overwrite mode if ARG is
  6731. positive, and disable it otherwise. If called from Lisp, enable
  6732. the mode if ARG is omitted or nil.
  6733. When Overwrite mode is enabled, printing characters typed in
  6734. replace existing text on a one-for-one basis, rather than pushing
  6735. it to the right. At the end of a line, such characters extend
  6736. the line. Before a tab, such characters insert until the tab is
  6737. filled in. \\[quoted-insert] still inserts characters in
  6738. overwrite mode; this is supposed to make it easier to insert
  6739. characters when necessary."
  6740. :variable (overwrite-mode
  6741. . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
  6742. (define-minor-mode binary-overwrite-mode
  6743. "Toggle Binary Overwrite mode.
  6744. With a prefix argument ARG, enable Binary Overwrite mode if ARG
  6745. is positive, and disable it otherwise. If called from Lisp,
  6746. enable the mode if ARG is omitted or nil.
  6747. When Binary Overwrite mode is enabled, printing characters typed
  6748. in replace existing text. Newlines are not treated specially, so
  6749. typing at the end of a line joins the line to the next, with the
  6750. typed character between them. Typing before a tab character
  6751. simply replaces the tab with the character typed.
  6752. \\[quoted-insert] replaces the text at the cursor, just as
  6753. ordinary typing characters do.
  6754. Note that Binary Overwrite mode is not its own minor mode; it is
  6755. a specialization of overwrite mode, entered by setting the
  6756. `overwrite-mode' variable to `overwrite-mode-binary'."
  6757. :variable (overwrite-mode
  6758. . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
  6759. (define-minor-mode line-number-mode
  6760. "Toggle line number display in the mode line (Line Number mode).
  6761. With a prefix argument ARG, enable Line Number mode if ARG is
  6762. positive, and disable it otherwise. If called from Lisp, enable
  6763. the mode if ARG is omitted or nil.
  6764. Line numbers do not appear for very large buffers and buffers
  6765. with very long lines; see variables `line-number-display-limit'
  6766. and `line-number-display-limit-width'."
  6767. :init-value t :global t :group 'mode-line)
  6768. (define-minor-mode column-number-mode
  6769. "Toggle column number display in the mode line (Column Number mode).
  6770. With a prefix argument ARG, enable Column Number mode if ARG is
  6771. positive, and disable it otherwise.
  6772. If called from Lisp, enable the mode if ARG is omitted or nil."
  6773. :global t :group 'mode-line)
  6774. (define-minor-mode size-indication-mode
  6775. "Toggle buffer size display in the mode line (Size Indication mode).
  6776. With a prefix argument ARG, enable Size Indication mode if ARG is
  6777. positive, and disable it otherwise.
  6778. If called from Lisp, enable the mode if ARG is omitted or nil."
  6779. :global t :group 'mode-line)
  6780. (define-minor-mode auto-save-mode
  6781. "Toggle auto-saving in the current buffer (Auto Save mode).
  6782. With a prefix argument ARG, enable Auto Save mode if ARG is
  6783. positive, and disable it otherwise.
  6784. If called from Lisp, enable the mode if ARG is omitted or nil."
  6785. :variable ((and buffer-auto-save-file-name
  6786. ;; If auto-save is off because buffer has shrunk,
  6787. ;; then toggling should turn it on.
  6788. (>= buffer-saved-size 0))
  6789. . (lambda (val)
  6790. (setq buffer-auto-save-file-name
  6791. (cond
  6792. ((null val) nil)
  6793. ((and buffer-file-name auto-save-visited-file-name
  6794. (not buffer-read-only))
  6795. buffer-file-name)
  6796. (t (make-auto-save-file-name))))))
  6797. ;; If -1 was stored here, to temporarily turn off saving,
  6798. ;; turn it back on.
  6799. (and (< buffer-saved-size 0)
  6800. (setq buffer-saved-size 0)))
  6801. (defgroup paren-blinking nil
  6802. "Blinking matching of parens and expressions."
  6803. :prefix "blink-matching-"
  6804. :group 'paren-matching)
  6805. (defcustom blink-matching-paren t
  6806. "Non-nil means show matching open-paren when close-paren is inserted.
  6807. If t, highlight the paren. If `jump', briefly move cursor to its
  6808. position. If `jump-offscreen', move cursor there even if the
  6809. position is off screen. With any other non-nil value, the
  6810. off-screen position of the opening paren will be shown in the
  6811. echo area."
  6812. :type '(choice
  6813. (const :tag "Disable" nil)
  6814. (const :tag "Highlight" t)
  6815. (const :tag "Move cursor" jump)
  6816. (const :tag "Move cursor, even if off screen" jump-offscreen))
  6817. :group 'paren-blinking)
  6818. (defcustom blink-matching-paren-on-screen t
  6819. "Non-nil means show matching open-paren when it is on screen.
  6820. If nil, don't show it (but the open-paren can still be shown
  6821. in the echo area when it is off screen).
  6822. This variable has no effect if `blink-matching-paren' is nil.
  6823. \(In that case, the open-paren is never shown.)
  6824. It is also ignored if `show-paren-mode' is enabled."
  6825. :type 'boolean
  6826. :group 'paren-blinking)
  6827. (defcustom blink-matching-paren-distance (* 100 1024)
  6828. "If non-nil, maximum distance to search backwards for matching open-paren.
  6829. If nil, search stops at the beginning of the accessible portion of the buffer."
  6830. :version "23.2" ; 25->100k
  6831. :type '(choice (const nil) integer)
  6832. :group 'paren-blinking)
  6833. (defcustom blink-matching-delay 1
  6834. "Time in seconds to delay after showing a matching paren."
  6835. :type 'number
  6836. :group 'paren-blinking)
  6837. (defcustom blink-matching-paren-dont-ignore-comments nil
  6838. "If nil, `blink-matching-paren' ignores comments.
  6839. More precisely, when looking for the matching parenthesis,
  6840. it skips the contents of comments that end before point."
  6841. :type 'boolean
  6842. :group 'paren-blinking)
  6843. (defun blink-matching-check-mismatch (start end)
  6844. "Return whether or not START...END are matching parens.
  6845. END is the current point and START is the blink position.
  6846. START might be nil if no matching starter was found.
  6847. Returns non-nil if we find there is a mismatch."
  6848. (let* ((end-syntax (syntax-after (1- end)))
  6849. (matching-paren (and (consp end-syntax)
  6850. (eq (syntax-class end-syntax) 5)
  6851. (cdr end-syntax))))
  6852. ;; For self-matched chars like " and $, we can't know when they're
  6853. ;; mismatched or unmatched, so we can only do it for parens.
  6854. (when matching-paren
  6855. (not (and start
  6856. (or
  6857. (eq (char-after start) matching-paren)
  6858. ;; The cdr might hold a new paren-class info rather than
  6859. ;; a matching-char info, in which case the two CDRs
  6860. ;; should match.
  6861. (eq matching-paren (cdr-safe (syntax-after start)))))))))
  6862. (defvar blink-matching-check-function #'blink-matching-check-mismatch
  6863. "Function to check parentheses mismatches.
  6864. The function takes two arguments (START and END) where START is the
  6865. position just before the opening token and END is the position right after.
  6866. START can be nil, if it was not found.
  6867. The function should return non-nil if the two tokens do not match.")
  6868. (defvar blink-matching--overlay
  6869. (let ((ol (make-overlay (point) (point) nil t)))
  6870. (overlay-put ol 'face 'show-paren-match)
  6871. (delete-overlay ol)
  6872. ol)
  6873. "Overlay used to highlight the matching paren.")
  6874. (defun blink-matching-open ()
  6875. "Momentarily highlight the beginning of the sexp before point."
  6876. (interactive)
  6877. (when (and (not (bobp))
  6878. blink-matching-paren)
  6879. (let* ((oldpos (point))
  6880. (message-log-max nil) ; Don't log messages about paren matching.
  6881. (blinkpos
  6882. (save-excursion
  6883. (save-restriction
  6884. (if blink-matching-paren-distance
  6885. (narrow-to-region
  6886. (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
  6887. (- (point) blink-matching-paren-distance))
  6888. oldpos))
  6889. (let ((parse-sexp-ignore-comments
  6890. (and parse-sexp-ignore-comments
  6891. (not blink-matching-paren-dont-ignore-comments))))
  6892. (condition-case ()
  6893. (progn
  6894. (syntax-propertize (point))
  6895. (forward-sexp -1)
  6896. ;; backward-sexp skips backward over prefix chars,
  6897. ;; so move back to the matching paren.
  6898. (while (and (< (point) (1- oldpos))
  6899. (let ((code (syntax-after (point))))
  6900. (or (eq (syntax-class code) 6)
  6901. (eq (logand 1048576 (car code))
  6902. 1048576))))
  6903. (forward-char 1))
  6904. (point))
  6905. (error nil))))))
  6906. (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
  6907. (cond
  6908. (mismatch
  6909. (if blinkpos
  6910. (if (minibufferp)
  6911. (minibuffer-message "Mismatched parentheses")
  6912. (message "Mismatched parentheses"))
  6913. (if (minibufferp)
  6914. (minibuffer-message "No matching parenthesis found")
  6915. (message "No matching parenthesis found"))))
  6916. ((not blinkpos) nil)
  6917. ((or
  6918. (eq blink-matching-paren 'jump-offscreen)
  6919. (pos-visible-in-window-p blinkpos))
  6920. ;; Matching open within window, temporarily move to or highlight
  6921. ;; char after blinkpos but only if `blink-matching-paren-on-screen'
  6922. ;; is non-nil.
  6923. (and blink-matching-paren-on-screen
  6924. (not show-paren-mode)
  6925. (if (memq blink-matching-paren '(jump jump-offscreen))
  6926. (save-excursion
  6927. (goto-char blinkpos)
  6928. (sit-for blink-matching-delay))
  6929. (unwind-protect
  6930. (progn
  6931. (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
  6932. (current-buffer))
  6933. (sit-for blink-matching-delay))
  6934. (delete-overlay blink-matching--overlay)))))
  6935. (t
  6936. (let ((open-paren-line-string
  6937. (save-excursion
  6938. (goto-char blinkpos)
  6939. ;; Show what precedes the open in its line, if anything.
  6940. (cond
  6941. ((save-excursion (skip-chars-backward " \t") (not (bolp)))
  6942. (buffer-substring (line-beginning-position)
  6943. (1+ blinkpos)))
  6944. ;; Show what follows the open in its line, if anything.
  6945. ((save-excursion
  6946. (forward-char 1)
  6947. (skip-chars-forward " \t")
  6948. (not (eolp)))
  6949. (buffer-substring blinkpos
  6950. (line-end-position)))
  6951. ;; Otherwise show the previous nonblank line,
  6952. ;; if there is one.
  6953. ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
  6954. (concat
  6955. (buffer-substring (progn
  6956. (skip-chars-backward "\n \t")
  6957. (line-beginning-position))
  6958. (progn (end-of-line)
  6959. (skip-chars-backward " \t")
  6960. (point)))
  6961. ;; Replace the newline and other whitespace with `...'.
  6962. "..."
  6963. (buffer-substring blinkpos (1+ blinkpos))))
  6964. ;; There is nothing to show except the char itself.
  6965. (t (buffer-substring blinkpos (1+ blinkpos)))))))
  6966. (minibuffer-message
  6967. "Matches %s"
  6968. (substring-no-properties open-paren-line-string))))))))
  6969. (defvar blink-paren-function 'blink-matching-open
  6970. "Function called, if non-nil, whenever a close parenthesis is inserted.
  6971. More precisely, a char with closeparen syntax is self-inserted.")
  6972. (defun blink-paren-post-self-insert-function ()
  6973. (when (and (eq (char-before) last-command-event) ; Sanity check.
  6974. (memq (char-syntax last-command-event) '(?\) ?\$))
  6975. blink-paren-function
  6976. (not executing-kbd-macro)
  6977. (not noninteractive)
  6978. ;; Verify an even number of quoting characters precede the close.
  6979. ;; FIXME: Also check if this parenthesis closes a comment as
  6980. ;; can happen in Pascal and SML.
  6981. (= 1 (logand 1 (- (point)
  6982. (save-excursion
  6983. (forward-char -1)
  6984. (skip-syntax-backward "/\\")
  6985. (point))))))
  6986. (funcall blink-paren-function)))
  6987. (put 'blink-paren-post-self-insert-function 'priority 100)
  6988. (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
  6989. ;; Most likely, this hook is nil, so this arg doesn't matter,
  6990. ;; but I use it as a reminder that this function usually
  6991. ;; likes to be run after others since it does
  6992. ;; `sit-for'. That's also the reason it get a `priority' prop
  6993. ;; of 100.
  6994. 'append)
  6995. ;; This executes C-g typed while Emacs is waiting for a command.
  6996. ;; Quitting out of a program does not go through here;
  6997. ;; that happens in the maybe_quit function at the C code level.
  6998. (defun keyboard-quit ()
  6999. "Signal a `quit' condition.
  7000. During execution of Lisp code, this character causes a quit directly.
  7001. At top-level, as an editor command, this simply beeps."
  7002. (interactive)
  7003. ;; Avoid adding the region to the window selection.
  7004. (setq saved-region-selection nil)
  7005. (let (select-active-regions)
  7006. (deactivate-mark))
  7007. (if (fboundp 'kmacro-keyboard-quit)
  7008. (kmacro-keyboard-quit))
  7009. (when completion-in-region-mode
  7010. (completion-in-region-mode -1))
  7011. ;; Force the next redisplay cycle to remove the "Def" indicator from
  7012. ;; all the mode lines.
  7013. (if defining-kbd-macro
  7014. (force-mode-line-update t))
  7015. (setq defining-kbd-macro nil)
  7016. (let ((debug-on-quit nil))
  7017. (signal 'quit nil)))
  7018. (defvar buffer-quit-function nil
  7019. "Function to call to \"quit\" the current buffer, or nil if none.
  7020. \\[keyboard-escape-quit] calls this function when its more local actions
  7021. \(such as canceling a prefix argument, minibuffer or region) do not apply.")
  7022. (defun keyboard-escape-quit ()
  7023. "Exit the current \"mode\" (in a generalized sense of the word).
  7024. This command can exit an interactive command such as `query-replace',
  7025. can clear out a prefix argument or a region,
  7026. can get out of the minibuffer or other recursive edit,
  7027. cancel the use of the current buffer (for special-purpose buffers),
  7028. or go back to just one window (by deleting all but the selected window)."
  7029. (interactive)
  7030. (cond ((eq last-command 'mode-exited) nil)
  7031. ((region-active-p)
  7032. (deactivate-mark))
  7033. ((> (minibuffer-depth) 0)
  7034. (abort-recursive-edit))
  7035. (current-prefix-arg
  7036. nil)
  7037. ((> (recursion-depth) 0)
  7038. (exit-recursive-edit))
  7039. (buffer-quit-function
  7040. (funcall buffer-quit-function))
  7041. ((not (one-window-p t))
  7042. (delete-other-windows))
  7043. ((string-match "^ \\*" (buffer-name (current-buffer)))
  7044. (bury-buffer))))
  7045. (defun play-sound-file (file &optional volume device)
  7046. "Play sound stored in FILE.
  7047. VOLUME and DEVICE correspond to the keywords of the sound
  7048. specification for `play-sound'."
  7049. (interactive "fPlay sound file: ")
  7050. (let ((sound (list :file file)))
  7051. (if volume
  7052. (plist-put sound :volume volume))
  7053. (if device
  7054. (plist-put sound :device device))
  7055. (push 'sound sound)
  7056. (play-sound sound)))
  7057. (defcustom read-mail-command 'rmail
  7058. "Your preference for a mail reading package.
  7059. This is used by some keybindings which support reading mail.
  7060. See also `mail-user-agent' concerning sending mail."
  7061. :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
  7062. (function-item :tag "Gnus" :format "%t\n" gnus)
  7063. (function-item :tag "Emacs interface to MH"
  7064. :format "%t\n" mh-rmail)
  7065. (function :tag "Other"))
  7066. :version "21.1"
  7067. :group 'mail)
  7068. (defcustom mail-user-agent 'message-user-agent
  7069. "Your preference for a mail composition package.
  7070. Various Emacs Lisp packages (e.g. Reporter) require you to compose an
  7071. outgoing email message. This variable lets you specify which
  7072. mail-sending package you prefer.
  7073. Valid values include:
  7074. `message-user-agent' -- use the Message package.
  7075. See Info node `(message)'.
  7076. `sendmail-user-agent' -- use the Mail package.
  7077. See Info node `(emacs)Sending Mail'.
  7078. `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
  7079. See Info node `(mh-e)'.
  7080. `gnus-user-agent' -- like `message-user-agent', but with Gnus
  7081. paraphernalia if Gnus is running, particularly
  7082. the Gcc: header for archiving.
  7083. Additional valid symbols may be available; check with the author of
  7084. your package for details. The function should return non-nil if it
  7085. succeeds.
  7086. See also `read-mail-command' concerning reading mail."
  7087. :type '(radio (function-item :tag "Message package"
  7088. :format "%t\n"
  7089. message-user-agent)
  7090. (function-item :tag "Mail package"
  7091. :format "%t\n"
  7092. sendmail-user-agent)
  7093. (function-item :tag "Emacs interface to MH"
  7094. :format "%t\n"
  7095. mh-e-user-agent)
  7096. (function-item :tag "Message with full Gnus features"
  7097. :format "%t\n"
  7098. gnus-user-agent)
  7099. (function :tag "Other"))
  7100. :version "23.2" ; sendmail->message
  7101. :group 'mail)
  7102. (defcustom compose-mail-user-agent-warnings t
  7103. "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
  7104. If the value of `mail-user-agent' is the default, and the user
  7105. appears to have customizations applying to the old default,
  7106. `compose-mail' issues a warning."
  7107. :type 'boolean
  7108. :version "23.2"
  7109. :group 'mail)
  7110. (defun rfc822-goto-eoh ()
  7111. "If the buffer starts with a mail header, move point to the header's end.
  7112. Otherwise, moves to `point-min'.
  7113. The end of the header is the start of the next line, if there is one,
  7114. else the end of the last line. This function obeys RFC822."
  7115. (goto-char (point-min))
  7116. (when (re-search-forward
  7117. "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
  7118. (goto-char (match-beginning 0))))
  7119. ;; Used by Rmail (e.g., rmail-forward).
  7120. (defvar mail-encode-mml nil
  7121. "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
  7122. the outgoing message before sending it.")
  7123. (defun compose-mail (&optional to subject other-headers continue
  7124. switch-function yank-action send-actions
  7125. return-action)
  7126. "Start composing a mail message to send.
  7127. This uses the user's chosen mail composition package
  7128. as selected with the variable `mail-user-agent'.
  7129. The optional arguments TO and SUBJECT specify recipients
  7130. and the initial Subject field, respectively.
  7131. OTHER-HEADERS is an alist specifying additional
  7132. header fields. Elements look like (HEADER . VALUE) where both
  7133. HEADER and VALUE are strings.
  7134. CONTINUE, if non-nil, says to continue editing a message already
  7135. being composed. Interactively, CONTINUE is the prefix argument.
  7136. SWITCH-FUNCTION, if non-nil, is a function to use to
  7137. switch to and display the buffer used for mail composition.
  7138. YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
  7139. to insert the raw text of the message being replied to.
  7140. It has the form (FUNCTION . ARGS). The user agent will apply
  7141. FUNCTION to ARGS, to insert the raw text of the original message.
  7142. \(The user agent will also run `mail-citation-hook', *after* the
  7143. original text has been inserted in this way.)
  7144. SEND-ACTIONS is a list of actions to call when the message is sent.
  7145. Each action has the form (FUNCTION . ARGS).
  7146. RETURN-ACTION, if non-nil, is an action for returning to the
  7147. caller. It has the form (FUNCTION . ARGS). The function is
  7148. called after the mail has been sent or put aside, and the mail
  7149. buffer buried."
  7150. (interactive
  7151. (list nil nil nil current-prefix-arg))
  7152. ;; In Emacs 23.2, the default value of `mail-user-agent' changed
  7153. ;; from sendmail-user-agent to message-user-agent. Some users may
  7154. ;; encounter incompatibilities. This hack tries to detect problems
  7155. ;; and warn about them.
  7156. (and compose-mail-user-agent-warnings
  7157. (eq mail-user-agent 'message-user-agent)
  7158. (let (warn-vars)
  7159. (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
  7160. mail-yank-hooks mail-archive-file-name
  7161. mail-default-reply-to mail-mailing-lists
  7162. mail-self-blind))
  7163. (and (boundp var)
  7164. (symbol-value var)
  7165. (push var warn-vars)))
  7166. (when warn-vars
  7167. (display-warning 'mail
  7168. (format-message "\
  7169. The default mail mode is now Message mode.
  7170. You have the following Mail mode variable%s customized:
  7171. \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
  7172. To disable this warning, set `compose-mail-user-agent-warnings' to nil."
  7173. (if (> (length warn-vars) 1) "s" "")
  7174. (mapconcat 'symbol-name
  7175. warn-vars " "))))))
  7176. (let ((function (get mail-user-agent 'composefunc)))
  7177. (funcall function to subject other-headers continue switch-function
  7178. yank-action send-actions return-action)))
  7179. (defun compose-mail-other-window (&optional to subject other-headers continue
  7180. yank-action send-actions
  7181. return-action)
  7182. "Like \\[compose-mail], but edit the outgoing message in another window."
  7183. (interactive (list nil nil nil current-prefix-arg))
  7184. (compose-mail to subject other-headers continue
  7185. 'switch-to-buffer-other-window yank-action send-actions
  7186. return-action))
  7187. (defun compose-mail-other-frame (&optional to subject other-headers continue
  7188. yank-action send-actions
  7189. return-action)
  7190. "Like \\[compose-mail], but edit the outgoing message in another frame."
  7191. (interactive (list nil nil nil current-prefix-arg))
  7192. (compose-mail to subject other-headers continue
  7193. 'switch-to-buffer-other-frame yank-action send-actions
  7194. return-action))
  7195. (defvar set-variable-value-history nil
  7196. "History of values entered with `set-variable'.
  7197. Maximum length of the history list is determined by the value
  7198. of `history-length', which see.")
  7199. (defun set-variable (variable value &optional make-local)
  7200. "Set VARIABLE to VALUE. VALUE is a Lisp object.
  7201. VARIABLE should be a user option variable name, a Lisp variable
  7202. meant to be customized by users. You should enter VALUE in Lisp syntax,
  7203. so if you want VALUE to be a string, you must surround it with doublequotes.
  7204. VALUE is used literally, not evaluated.
  7205. If VARIABLE has a `variable-interactive' property, that is used as if
  7206. it were the arg to `interactive' (which see) to interactively read VALUE.
  7207. If VARIABLE has been defined with `defcustom', then the type information
  7208. in the definition is used to check that VALUE is valid.
  7209. Note that this function is at heart equivalent to the basic `set' function.
  7210. For a variable defined with `defcustom', it does not pay attention to
  7211. any :set property that the variable might have (if you want that, use
  7212. \\[customize-set-variable] instead).
  7213. With a prefix argument, set VARIABLE to VALUE buffer-locally."
  7214. (interactive
  7215. (let* ((default-var (variable-at-point))
  7216. (var (if (custom-variable-p default-var)
  7217. (read-variable (format "Set variable (default %s): " default-var)
  7218. default-var)
  7219. (read-variable "Set variable: ")))
  7220. (minibuffer-help-form '(describe-variable var))
  7221. (prop (get var 'variable-interactive))
  7222. (obsolete (car (get var 'byte-obsolete-variable)))
  7223. (prompt (format "Set %s %s to value: " var
  7224. (cond ((local-variable-p var)
  7225. "(buffer-local)")
  7226. ((or current-prefix-arg
  7227. (local-variable-if-set-p var))
  7228. "buffer-locally")
  7229. (t "globally"))))
  7230. (val (progn
  7231. (when obsolete
  7232. (message (concat "`%S' is obsolete; "
  7233. (if (symbolp obsolete) "use `%S' instead" "%s"))
  7234. var obsolete)
  7235. (sit-for 3))
  7236. (if prop
  7237. ;; Use VAR's `variable-interactive' property
  7238. ;; as an interactive spec for prompting.
  7239. (call-interactively `(lambda (arg)
  7240. (interactive ,prop)
  7241. arg))
  7242. (read-from-minibuffer prompt nil
  7243. read-expression-map t
  7244. 'set-variable-value-history
  7245. (format "%S" (symbol-value var)))))))
  7246. (list var val current-prefix-arg)))
  7247. (and (custom-variable-p variable)
  7248. (not (get variable 'custom-type))
  7249. (custom-load-symbol variable))
  7250. (let ((type (get variable 'custom-type)))
  7251. (when type
  7252. ;; Match with custom type.
  7253. (require 'cus-edit)
  7254. (setq type (widget-convert type))
  7255. (unless (widget-apply type :match value)
  7256. (user-error "Value `%S' does not match type %S of %S"
  7257. value (car type) variable))))
  7258. (if make-local
  7259. (make-local-variable variable))
  7260. (set variable value)
  7261. ;; Force a thorough redisplay for the case that the variable
  7262. ;; has an effect on the display, like `tab-width' has.
  7263. (force-mode-line-update))
  7264. ;; Define the major mode for lists of completions.
  7265. (defvar completion-list-mode-map
  7266. (let ((map (make-sparse-keymap)))
  7267. (define-key map [mouse-2] 'choose-completion)
  7268. (define-key map [follow-link] 'mouse-face)
  7269. (define-key map [down-mouse-2] nil)
  7270. (define-key map "\C-m" 'choose-completion)
  7271. (define-key map "\e\e\e" 'delete-completion-window)
  7272. (define-key map [left] 'previous-completion)
  7273. (define-key map [right] 'next-completion)
  7274. (define-key map [?\t] 'next-completion)
  7275. (define-key map [backtab] 'previous-completion)
  7276. (define-key map "q" 'quit-window)
  7277. (define-key map "z" 'kill-current-buffer)
  7278. map)
  7279. "Local map for completion list buffers.")
  7280. ;; Completion mode is suitable only for specially formatted data.
  7281. (put 'completion-list-mode 'mode-class 'special)
  7282. (defvar completion-reference-buffer nil
  7283. "Record the buffer that was current when the completion list was requested.
  7284. This is a local variable in the completion list buffer.
  7285. Initial value is nil to avoid some compiler warnings.")
  7286. (defvar completion-no-auto-exit nil
  7287. "Non-nil means `choose-completion-string' should never exit the minibuffer.
  7288. This also applies to other functions such as `choose-completion'.")
  7289. (defvar completion-base-position nil
  7290. "Position of the base of the text corresponding to the shown completions.
  7291. This variable is used in the *Completions* buffers.
  7292. Its value is a list of the form (START END) where START is the place
  7293. where the completion should be inserted and END (if non-nil) is the end
  7294. of the text to replace. If END is nil, point is used instead.")
  7295. (defvar completion-list-insert-choice-function #'completion--replace
  7296. "Function to use to insert the text chosen in *Completions*.
  7297. Called with three arguments (BEG END TEXT), it should replace the text
  7298. between BEG and END with TEXT. Expected to be set buffer-locally
  7299. in the *Completions* buffer.")
  7300. (defvar completion-base-size nil
  7301. "Number of chars before point not involved in completion.
  7302. This is a local variable in the completion list buffer.
  7303. It refers to the chars in the minibuffer if completing in the
  7304. minibuffer, or in `completion-reference-buffer' otherwise.
  7305. Only characters in the field at point are included.
  7306. If nil, Emacs determines which part of the tail end of the
  7307. buffer's text is involved in completion by comparing the text
  7308. directly.")
  7309. (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
  7310. (defun delete-completion-window ()
  7311. "Delete the completion list window.
  7312. Go to the window from which completion was requested."
  7313. (interactive)
  7314. (let ((buf completion-reference-buffer))
  7315. (if (one-window-p t)
  7316. (if (window-dedicated-p) (delete-frame))
  7317. (delete-window (selected-window))
  7318. (if (get-buffer-window buf)
  7319. (select-window (get-buffer-window buf))))))
  7320. (defun previous-completion (n)
  7321. "Move to the previous item in the completion list."
  7322. (interactive "p")
  7323. (next-completion (- n)))
  7324. (defun next-completion (n)
  7325. "Move to the next item in the completion list.
  7326. With prefix argument N, move N items (negative N means move backward)."
  7327. (interactive "p")
  7328. (let ((beg (point-min)) (end (point-max)))
  7329. (while (and (> n 0) (not (eobp)))
  7330. ;; If in a completion, move to the end of it.
  7331. (when (get-text-property (point) 'mouse-face)
  7332. (goto-char (next-single-property-change (point) 'mouse-face nil end)))
  7333. ;; Move to start of next one.
  7334. (unless (get-text-property (point) 'mouse-face)
  7335. (goto-char (next-single-property-change (point) 'mouse-face nil end)))
  7336. (setq n (1- n)))
  7337. (while (and (< n 0) (not (bobp)))
  7338. (let ((prop (get-text-property (1- (point)) 'mouse-face)))
  7339. ;; If in a completion, move to the start of it.
  7340. (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
  7341. (goto-char (previous-single-property-change
  7342. (point) 'mouse-face nil beg)))
  7343. ;; Move to end of the previous completion.
  7344. (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
  7345. (goto-char (previous-single-property-change
  7346. (point) 'mouse-face nil beg)))
  7347. ;; Move to the start of that one.
  7348. (goto-char (previous-single-property-change
  7349. (point) 'mouse-face nil beg))
  7350. (setq n (1+ n))))))
  7351. (defun choose-completion (&optional event)
  7352. "Choose the completion at point.
  7353. If EVENT, use EVENT's position to determine the starting position."
  7354. (interactive (list last-nonmenu-event))
  7355. ;; In case this is run via the mouse, give temporary modes such as
  7356. ;; isearch a chance to turn off.
  7357. (run-hooks 'mouse-leave-buffer-hook)
  7358. (with-current-buffer (window-buffer (posn-window (event-start event)))
  7359. (let ((buffer completion-reference-buffer)
  7360. (base-size completion-base-size)
  7361. (base-position completion-base-position)
  7362. (insert-function completion-list-insert-choice-function)
  7363. (choice
  7364. (save-excursion
  7365. (goto-char (posn-point (event-start event)))
  7366. (let (beg end)
  7367. (cond
  7368. ((and (not (eobp)) (get-text-property (point) 'mouse-face))
  7369. (setq end (point) beg (1+ (point))))
  7370. ((and (not (bobp))
  7371. (get-text-property (1- (point)) 'mouse-face))
  7372. (setq end (1- (point)) beg (point)))
  7373. (t (error "No completion here")))
  7374. (setq beg (previous-single-property-change beg 'mouse-face))
  7375. (setq end (or (next-single-property-change end 'mouse-face)
  7376. (point-max)))
  7377. (buffer-substring-no-properties beg end)))))
  7378. (unless (buffer-live-p buffer)
  7379. (error "Destination buffer is dead"))
  7380. (quit-window nil (posn-window (event-start event)))
  7381. (with-current-buffer buffer
  7382. (choose-completion-string
  7383. choice buffer
  7384. (or base-position
  7385. (when base-size
  7386. ;; Someone's using old completion code that doesn't know
  7387. ;; about base-position yet.
  7388. (list (+ base-size (field-beginning))))
  7389. ;; If all else fails, just guess.
  7390. (list (choose-completion-guess-base-position choice)))
  7391. insert-function)))))
  7392. ;; Delete the longest partial match for STRING
  7393. ;; that can be found before POINT.
  7394. (defun choose-completion-guess-base-position (string)
  7395. (save-excursion
  7396. (let ((opoint (point))
  7397. len)
  7398. ;; Try moving back by the length of the string.
  7399. (goto-char (max (- (point) (length string))
  7400. (minibuffer-prompt-end)))
  7401. ;; See how far back we were actually able to move. That is the
  7402. ;; upper bound on how much we can match and delete.
  7403. (setq len (- opoint (point)))
  7404. (if completion-ignore-case
  7405. (setq string (downcase string)))
  7406. (while (and (> len 0)
  7407. (let ((tail (buffer-substring (point) opoint)))
  7408. (if completion-ignore-case
  7409. (setq tail (downcase tail)))
  7410. (not (string= tail (substring string 0 len)))))
  7411. (setq len (1- len))
  7412. (forward-char 1))
  7413. (point))))
  7414. (defun choose-completion-delete-max-match (string)
  7415. (declare (obsolete choose-completion-guess-base-position "23.2"))
  7416. (delete-region (choose-completion-guess-base-position string) (point)))
  7417. (defvar choose-completion-string-functions nil
  7418. "Functions that may override the normal insertion of a completion choice.
  7419. These functions are called in order with three arguments:
  7420. CHOICE - the string to insert in the buffer,
  7421. BUFFER - the buffer in which the choice should be inserted,
  7422. BASE-POSITION - where to insert the completion.
  7423. If a function in the list returns non-nil, that function is supposed
  7424. to have inserted the CHOICE in the BUFFER, and possibly exited
  7425. the minibuffer; no further functions will be called.
  7426. If all functions in the list return nil, that means to use
  7427. the default method of inserting the completion in BUFFER.")
  7428. (defun choose-completion-string (choice &optional
  7429. buffer base-position insert-function)
  7430. "Switch to BUFFER and insert the completion choice CHOICE.
  7431. BASE-POSITION says where to insert the completion.
  7432. INSERT-FUNCTION says how to insert the completion and falls
  7433. back on `completion-list-insert-choice-function' when nil."
  7434. ;; If BUFFER is the minibuffer, exit the minibuffer
  7435. ;; unless it is reading a file name and CHOICE is a directory,
  7436. ;; or completion-no-auto-exit is non-nil.
  7437. ;; Some older code may call us passing `base-size' instead of
  7438. ;; `base-position'. It's difficult to make any use of `base-size',
  7439. ;; so we just ignore it.
  7440. (unless (consp base-position)
  7441. (message "Obsolete `base-size' passed to choose-completion-string")
  7442. (setq base-position nil))
  7443. (let* ((buffer (or buffer completion-reference-buffer))
  7444. (mini-p (minibufferp buffer)))
  7445. ;; If BUFFER is a minibuffer, barf unless it's the currently
  7446. ;; active minibuffer.
  7447. (if (and mini-p
  7448. (not (and (active-minibuffer-window)
  7449. (equal buffer
  7450. (window-buffer (active-minibuffer-window))))))
  7451. (error "Minibuffer is not active for completion")
  7452. ;; Set buffer so buffer-local choose-completion-string-functions works.
  7453. (set-buffer buffer)
  7454. (unless (run-hook-with-args-until-success
  7455. 'choose-completion-string-functions
  7456. ;; The fourth arg used to be `mini-p' but was useless
  7457. ;; (since minibufferp can be used on the `buffer' arg)
  7458. ;; and indeed unused. The last used to be `base-size', so we
  7459. ;; keep it to try and avoid breaking old code.
  7460. choice buffer base-position nil)
  7461. ;; This remove-text-properties should be unnecessary since `choice'
  7462. ;; comes from buffer-substring-no-properties.
  7463. ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
  7464. ;; Insert the completion into the buffer where it was requested.
  7465. (funcall (or insert-function completion-list-insert-choice-function)
  7466. (or (car base-position) (point))
  7467. (or (cadr base-position) (point))
  7468. choice)
  7469. ;; Update point in the window that BUFFER is showing in.
  7470. (let ((window (get-buffer-window buffer t)))
  7471. (set-window-point window (point)))
  7472. ;; If completing for the minibuffer, exit it with this choice.
  7473. (and (not completion-no-auto-exit)
  7474. (minibufferp buffer)
  7475. minibuffer-completion-table
  7476. ;; If this is reading a file name, and the file name chosen
  7477. ;; is a directory, don't exit the minibuffer.
  7478. (let* ((result (buffer-substring (field-beginning) (point)))
  7479. (bounds
  7480. (completion-boundaries result minibuffer-completion-table
  7481. minibuffer-completion-predicate
  7482. "")))
  7483. (if (eq (car bounds) (length result))
  7484. ;; The completion chosen leads to a new set of completions
  7485. ;; (e.g. it's a directory): don't exit the minibuffer yet.
  7486. (let ((mini (active-minibuffer-window)))
  7487. (select-window mini)
  7488. (when minibuffer-auto-raise
  7489. (raise-frame (window-frame mini))))
  7490. (exit-minibuffer))))))))
  7491. (define-derived-mode completion-list-mode nil "Completion List"
  7492. "Major mode for buffers showing lists of possible completions.
  7493. Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
  7494. to select the completion near point.
  7495. Or click to select one with the mouse.
  7496. \\{completion-list-mode-map}"
  7497. (set (make-local-variable 'completion-base-size) nil))
  7498. (defun completion-list-mode-finish ()
  7499. "Finish setup of the completions buffer.
  7500. Called from `temp-buffer-show-hook'."
  7501. (when (eq major-mode 'completion-list-mode)
  7502. (setq buffer-read-only t)))
  7503. (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
  7504. ;; Variables and faces used in `completion-setup-function'.
  7505. (defcustom completion-show-help t
  7506. "Non-nil means show help message in *Completions* buffer."
  7507. :type 'boolean
  7508. :version "22.1"
  7509. :group 'completion)
  7510. ;; This function goes in completion-setup-hook, so that it is called
  7511. ;; after the text of the completion list buffer is written.
  7512. (defun completion-setup-function ()
  7513. (let* ((mainbuf (current-buffer))
  7514. (base-dir
  7515. ;; FIXME: This is a bad hack. We try to set the default-directory
  7516. ;; in the *Completions* buffer so that the relative file names
  7517. ;; displayed there can be treated as valid file names, independently
  7518. ;; from the completion context. But this suffers from many problems:
  7519. ;; - It's not clear when the completions are file names. With some
  7520. ;; completion tables (e.g. bzr revision specs), the listed
  7521. ;; completions can mix file names and other things.
  7522. ;; - It doesn't pay attention to possible quoting.
  7523. ;; - With fancy completion styles, the code below will not always
  7524. ;; find the right base directory.
  7525. (if minibuffer-completing-file-name
  7526. (file-name-as-directory
  7527. (expand-file-name
  7528. (buffer-substring (minibuffer-prompt-end)
  7529. (- (point) (or completion-base-size 0))))))))
  7530. (with-current-buffer standard-output
  7531. (let ((base-size completion-base-size) ;Read before killing localvars.
  7532. (base-position completion-base-position)
  7533. (insert-fun completion-list-insert-choice-function))
  7534. (completion-list-mode)
  7535. (set (make-local-variable 'completion-base-size) base-size)
  7536. (set (make-local-variable 'completion-base-position) base-position)
  7537. (set (make-local-variable 'completion-list-insert-choice-function)
  7538. insert-fun))
  7539. (set (make-local-variable 'completion-reference-buffer) mainbuf)
  7540. (if base-dir (setq default-directory base-dir))
  7541. ;; Maybe insert help string.
  7542. (when completion-show-help
  7543. (goto-char (point-min))
  7544. (if (display-mouse-p)
  7545. (insert "Click on a completion to select it.\n"))
  7546. (insert (substitute-command-keys
  7547. "In this buffer, type \\[choose-completion] to \
  7548. select the completion near point.\n\n"))))))
  7549. (add-hook 'completion-setup-hook 'completion-setup-function)
  7550. (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
  7551. (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
  7552. (defun switch-to-completions ()
  7553. "Select the completion list window."
  7554. (interactive)
  7555. (let ((window (or (get-buffer-window "*Completions*" 0)
  7556. ;; Make sure we have a completions window.
  7557. (progn (minibuffer-completion-help)
  7558. (get-buffer-window "*Completions*" 0)))))
  7559. (when window
  7560. (select-window window)
  7561. ;; In the new buffer, go to the first completion.
  7562. ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
  7563. (when (bobp)
  7564. (next-completion 1)))))
  7565. ;;; Support keyboard commands to turn on various modifiers.
  7566. ;; These functions -- which are not commands -- each add one modifier
  7567. ;; to the following event.
  7568. (defun event-apply-alt-modifier (_ignore-prompt)
  7569. "\\<function-key-map>Add the Alt modifier to the following event.
  7570. For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
  7571. (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
  7572. (defun event-apply-super-modifier (_ignore-prompt)
  7573. "\\<function-key-map>Add the Super modifier to the following event.
  7574. For example, type \\[event-apply-super-modifier] & to enter Super-&."
  7575. (vector (event-apply-modifier (read-event) 'super 23 "s-")))
  7576. (defun event-apply-hyper-modifier (_ignore-prompt)
  7577. "\\<function-key-map>Add the Hyper modifier to the following event.
  7578. For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
  7579. (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
  7580. (defun event-apply-shift-modifier (_ignore-prompt)
  7581. "\\<function-key-map>Add the Shift modifier to the following event.
  7582. For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
  7583. (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
  7584. (defun event-apply-control-modifier (_ignore-prompt)
  7585. "\\<function-key-map>Add the Ctrl modifier to the following event.
  7586. For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
  7587. (vector (event-apply-modifier (read-event) 'control 26 "C-")))
  7588. (defun event-apply-meta-modifier (_ignore-prompt)
  7589. "\\<function-key-map>Add the Meta modifier to the following event.
  7590. For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
  7591. (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
  7592. (defun event-apply-modifier (event symbol lshiftby prefix)
  7593. "Apply a modifier flag to event EVENT.
  7594. SYMBOL is the name of this modifier, as a symbol.
  7595. LSHIFTBY is the numeric value of this modifier, in keyboard events.
  7596. PREFIX is the string that represents this modifier in an event type symbol."
  7597. (if (numberp event)
  7598. (cond ((eq symbol 'control)
  7599. (if (and (<= (downcase event) ?z)
  7600. (>= (downcase event) ?a))
  7601. (- (downcase event) ?a -1)
  7602. (if (and (<= (downcase event) ?Z)
  7603. (>= (downcase event) ?A))
  7604. (- (downcase event) ?A -1)
  7605. (logior (lsh 1 lshiftby) event))))
  7606. ((eq symbol 'shift)
  7607. (if (and (<= (downcase event) ?z)
  7608. (>= (downcase event) ?a))
  7609. (upcase event)
  7610. (logior (lsh 1 lshiftby) event)))
  7611. (t
  7612. (logior (lsh 1 lshiftby) event)))
  7613. (if (memq symbol (event-modifiers event))
  7614. event
  7615. (let ((event-type (if (symbolp event) event (car event))))
  7616. (setq event-type (intern (concat prefix (symbol-name event-type))))
  7617. (if (symbolp event)
  7618. event-type
  7619. (cons event-type (cdr event)))))))
  7620. (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
  7621. (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
  7622. (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
  7623. (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
  7624. (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
  7625. (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
  7626. ;;;; Keypad support.
  7627. ;; Make the keypad keys act like ordinary typing keys. If people add
  7628. ;; bindings for the function key symbols, then those bindings will
  7629. ;; override these, so this shouldn't interfere with any existing
  7630. ;; bindings.
  7631. ;; Also tell read-char how to handle these keys.
  7632. (mapc
  7633. (lambda (keypad-normal)
  7634. (let ((keypad (nth 0 keypad-normal))
  7635. (normal (nth 1 keypad-normal)))
  7636. (put keypad 'ascii-character normal)
  7637. (define-key function-key-map (vector keypad) (vector normal))))
  7638. ;; See also kp-keys bound in bindings.el.
  7639. '((kp-space ?\s)
  7640. (kp-tab ?\t)
  7641. (kp-enter ?\r)
  7642. (kp-separator ?,)
  7643. (kp-equal ?=)
  7644. ;; Do the same for various keys that are represented as symbols under
  7645. ;; GUIs but naturally correspond to characters.
  7646. (backspace 127)
  7647. (delete 127)
  7648. (tab ?\t)
  7649. (linefeed ?\n)
  7650. (clear ?\C-l)
  7651. (return ?\C-m)
  7652. (escape ?\e)
  7653. ))
  7654. ;;;;
  7655. ;;;; forking a twin copy of a buffer.
  7656. ;;;;
  7657. (defvar clone-buffer-hook nil
  7658. "Normal hook to run in the new buffer at the end of `clone-buffer'.")
  7659. (defvar clone-indirect-buffer-hook nil
  7660. "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
  7661. (defun clone-process (process &optional newname)
  7662. "Create a twin copy of PROCESS.
  7663. If NEWNAME is nil, it defaults to PROCESS' name;
  7664. NEWNAME is modified by adding or incrementing <N> at the end as necessary.
  7665. If PROCESS is associated with a buffer, the new process will be associated
  7666. with the current buffer instead.
  7667. Returns nil if PROCESS has already terminated."
  7668. (setq newname (or newname (process-name process)))
  7669. (if (string-match "<[0-9]+>\\'" newname)
  7670. (setq newname (substring newname 0 (match-beginning 0))))
  7671. (when (memq (process-status process) '(run stop open))
  7672. (let* ((process-connection-type (process-tty-name process))
  7673. (new-process
  7674. (if (memq (process-status process) '(open))
  7675. (let ((args (process-contact process t)))
  7676. (setq args (plist-put args :name newname))
  7677. (setq args (plist-put args :buffer
  7678. (if (process-buffer process)
  7679. (current-buffer))))
  7680. (apply 'make-network-process args))
  7681. (apply 'start-process newname
  7682. (if (process-buffer process) (current-buffer))
  7683. (process-command process)))))
  7684. (set-process-query-on-exit-flag
  7685. new-process (process-query-on-exit-flag process))
  7686. (set-process-inherit-coding-system-flag
  7687. new-process (process-inherit-coding-system-flag process))
  7688. (set-process-filter new-process (process-filter process))
  7689. (set-process-sentinel new-process (process-sentinel process))
  7690. (set-process-plist new-process (copy-sequence (process-plist process)))
  7691. new-process)))
  7692. ;; things to maybe add (currently partly covered by `funcall mode'):
  7693. ;; - syntax-table
  7694. ;; - overlays
  7695. (defun clone-buffer (&optional newname display-flag)
  7696. "Create and return a twin copy of the current buffer.
  7697. Unlike an indirect buffer, the new buffer can be edited
  7698. independently of the old one (if it is not read-only).
  7699. NEWNAME is the name of the new buffer. It may be modified by
  7700. adding or incrementing <N> at the end as necessary to create a
  7701. unique buffer name. If nil, it defaults to the name of the
  7702. current buffer, with the proper suffix. If DISPLAY-FLAG is
  7703. non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
  7704. clone a file-visiting buffer, or a buffer whose major mode symbol
  7705. has a non-nil `no-clone' property, results in an error.
  7706. Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
  7707. current buffer with appropriate suffix. However, if a prefix
  7708. argument is given, then the command prompts for NEWNAME in the
  7709. minibuffer.
  7710. This runs the normal hook `clone-buffer-hook' in the new buffer
  7711. after it has been set up properly in other respects."
  7712. (interactive
  7713. (progn
  7714. (if buffer-file-name
  7715. (error "Cannot clone a file-visiting buffer"))
  7716. (if (get major-mode 'no-clone)
  7717. (error "Cannot clone a buffer in %s mode" mode-name))
  7718. (list (if current-prefix-arg
  7719. (read-buffer "Name of new cloned buffer: " (current-buffer)))
  7720. t)))
  7721. (if buffer-file-name
  7722. (error "Cannot clone a file-visiting buffer"))
  7723. (if (get major-mode 'no-clone)
  7724. (error "Cannot clone a buffer in %s mode" mode-name))
  7725. (setq newname (or newname (buffer-name)))
  7726. (if (string-match "<[0-9]+>\\'" newname)
  7727. (setq newname (substring newname 0 (match-beginning 0))))
  7728. (let ((buf (current-buffer))
  7729. (ptmin (point-min))
  7730. (ptmax (point-max))
  7731. (pt (point))
  7732. (mk (if mark-active (mark t)))
  7733. (modified (buffer-modified-p))
  7734. (mode major-mode)
  7735. (lvars (buffer-local-variables))
  7736. (process (get-buffer-process (current-buffer)))
  7737. (new (generate-new-buffer (or newname (buffer-name)))))
  7738. (save-restriction
  7739. (widen)
  7740. (with-current-buffer new
  7741. (insert-buffer-substring buf)))
  7742. (with-current-buffer new
  7743. (narrow-to-region ptmin ptmax)
  7744. (goto-char pt)
  7745. (if mk (set-mark mk))
  7746. (set-buffer-modified-p modified)
  7747. ;; Clone the old buffer's process, if any.
  7748. (when process (clone-process process))
  7749. ;; Now set up the major mode.
  7750. (funcall mode)
  7751. ;; Set up other local variables.
  7752. (mapc (lambda (v)
  7753. (condition-case () ;in case var is read-only
  7754. (if (symbolp v)
  7755. (makunbound v)
  7756. (set (make-local-variable (car v)) (cdr v)))
  7757. (error nil)))
  7758. lvars)
  7759. ;; Run any hooks (typically set up by the major mode
  7760. ;; for cloning to work properly).
  7761. (run-hooks 'clone-buffer-hook))
  7762. (if display-flag
  7763. ;; Presumably the current buffer is shown in the selected frame, so
  7764. ;; we want to display the clone elsewhere.
  7765. (let ((same-window-regexps nil)
  7766. (same-window-buffer-names))
  7767. (pop-to-buffer new)))
  7768. new))
  7769. (defun clone-indirect-buffer (newname display-flag &optional norecord)
  7770. "Create an indirect buffer that is a twin copy of the current buffer.
  7771. Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
  7772. from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
  7773. or if not called with a prefix arg, NEWNAME defaults to the current
  7774. buffer's name. The name is modified by adding a `<N>' suffix to it
  7775. or by incrementing the N in an existing suffix. Trying to clone a
  7776. buffer whose major mode symbol has a non-nil `no-clone-indirect'
  7777. property results in an error.
  7778. DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
  7779. This is always done when called interactively.
  7780. Optional third arg NORECORD non-nil means do not put this buffer at the
  7781. front of the list of recently selected ones.
  7782. Returns the newly created indirect buffer."
  7783. (interactive
  7784. (progn
  7785. (if (get major-mode 'no-clone-indirect)
  7786. (error "Cannot indirectly clone a buffer in %s mode" mode-name))
  7787. (list (if current-prefix-arg
  7788. (read-buffer "Name of indirect buffer: " (current-buffer)))
  7789. t)))
  7790. (if (get major-mode 'no-clone-indirect)
  7791. (error "Cannot indirectly clone a buffer in %s mode" mode-name))
  7792. (setq newname (or newname (buffer-name)))
  7793. (if (string-match "<[0-9]+>\\'" newname)
  7794. (setq newname (substring newname 0 (match-beginning 0))))
  7795. (let* ((name (generate-new-buffer-name newname))
  7796. (buffer (make-indirect-buffer (current-buffer) name t)))
  7797. (with-current-buffer buffer
  7798. (run-hooks 'clone-indirect-buffer-hook))
  7799. (when display-flag
  7800. (pop-to-buffer buffer nil norecord))
  7801. buffer))
  7802. (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
  7803. "Like `clone-indirect-buffer' but display in another window."
  7804. (interactive
  7805. (progn
  7806. (if (get major-mode 'no-clone-indirect)
  7807. (error "Cannot indirectly clone a buffer in %s mode" mode-name))
  7808. (list (if current-prefix-arg
  7809. (read-buffer "Name of indirect buffer: " (current-buffer)))
  7810. t)))
  7811. (let ((pop-up-windows t))
  7812. (clone-indirect-buffer newname display-flag norecord)))
  7813. ;;; Handling of Backspace and Delete keys.
  7814. (defcustom normal-erase-is-backspace 'maybe
  7815. "Set the default behavior of the Delete and Backspace keys.
  7816. If set to t, Delete key deletes forward and Backspace key deletes
  7817. backward.
  7818. If set to nil, both Delete and Backspace keys delete backward.
  7819. If set to `maybe' (which is the default), Emacs automatically
  7820. selects a behavior. On window systems, the behavior depends on
  7821. the keyboard used. If the keyboard has both a Backspace key and
  7822. a Delete key, and both are mapped to their usual meanings, the
  7823. option's default value is set to t, so that Backspace can be used
  7824. to delete backward, and Delete can be used to delete forward.
  7825. If not running under a window system, customizing this option
  7826. accomplishes a similar effect by mapping C-h, which is usually
  7827. generated by the Backspace key, to DEL, and by mapping DEL to C-d
  7828. via `keyboard-translate'. The former functionality of C-h is
  7829. available on the F1 key. You should probably not use this
  7830. setting if you don't have both Backspace, Delete and F1 keys.
  7831. Setting this variable with setq doesn't take effect. Programmatically,
  7832. call `normal-erase-is-backspace-mode' (which see) instead."
  7833. :type '(choice (const :tag "Off" nil)
  7834. (const :tag "Maybe" maybe)
  7835. (other :tag "On" t))
  7836. :group 'editing-basics
  7837. :version "21.1"
  7838. :set (lambda (symbol value)
  7839. ;; The fboundp is because of a problem with :set when
  7840. ;; dumping Emacs. It doesn't really matter.
  7841. (if (fboundp 'normal-erase-is-backspace-mode)
  7842. (normal-erase-is-backspace-mode (or value 0))
  7843. (set-default symbol value))))
  7844. (defun normal-erase-is-backspace-setup-frame (&optional frame)
  7845. "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
  7846. (unless frame (setq frame (selected-frame)))
  7847. (with-selected-frame frame
  7848. (unless (terminal-parameter nil 'normal-erase-is-backspace)
  7849. (normal-erase-is-backspace-mode
  7850. (if (if (eq normal-erase-is-backspace 'maybe)
  7851. (and (not noninteractive)
  7852. (or (memq system-type '(ms-dos windows-nt))
  7853. (memq window-system '(w32 ns))
  7854. (and (memq window-system '(x))
  7855. (fboundp 'x-backspace-delete-keys-p)
  7856. (x-backspace-delete-keys-p))
  7857. ;; If the terminal Emacs is running on has erase char
  7858. ;; set to ^H, use the Backspace key for deleting
  7859. ;; backward, and the Delete key for deleting forward.
  7860. (and (null window-system)
  7861. (eq tty-erase-char ?\^H))))
  7862. normal-erase-is-backspace)
  7863. 1 0)))))
  7864. (define-minor-mode normal-erase-is-backspace-mode
  7865. "Toggle the Erase and Delete mode of the Backspace and Delete keys.
  7866. With a prefix argument ARG, enable this feature if ARG is
  7867. positive, and disable it otherwise. If called from Lisp, enable
  7868. the mode if ARG is omitted or nil.
  7869. On window systems, when this mode is on, Delete is mapped to C-d
  7870. and Backspace is mapped to DEL; when this mode is off, both
  7871. Delete and Backspace are mapped to DEL. (The remapping goes via
  7872. `local-function-key-map', so binding Delete or Backspace in the
  7873. global or local keymap will override that.)
  7874. In addition, on window systems, the bindings of C-Delete, M-Delete,
  7875. C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
  7876. the global keymap in accordance with the functionality of Delete and
  7877. Backspace. For example, if Delete is remapped to C-d, which deletes
  7878. forward, C-Delete is bound to `kill-word', but if Delete is remapped
  7879. to DEL, which deletes backward, C-Delete is bound to
  7880. `backward-kill-word'.
  7881. If not running on a window system, a similar effect is accomplished by
  7882. remapping C-h (normally produced by the Backspace key) and DEL via
  7883. `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
  7884. to C-d; if it's off, the keys are not remapped.
  7885. When not running on a window system, and this mode is turned on, the
  7886. former functionality of C-h is available on the F1 key. You should
  7887. probably not turn on this mode on a text-only terminal if you don't
  7888. have both Backspace, Delete and F1 keys.
  7889. See also `normal-erase-is-backspace'."
  7890. :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
  7891. . (lambda (v)
  7892. (setf (terminal-parameter nil 'normal-erase-is-backspace)
  7893. (if v 1 0))))
  7894. (let ((enabled (eq 1 (terminal-parameter
  7895. nil 'normal-erase-is-backspace))))
  7896. (cond ((or (memq window-system '(x w32 ns pc))
  7897. (memq system-type '(ms-dos windows-nt)))
  7898. (let ((bindings
  7899. `(([M-delete] [M-backspace])
  7900. ([C-M-delete] [C-M-backspace])
  7901. ([?\e C-delete] [?\e C-backspace]))))
  7902. (if enabled
  7903. (progn
  7904. (define-key local-function-key-map [delete] [deletechar])
  7905. (define-key local-function-key-map [kp-delete] [deletechar])
  7906. (define-key local-function-key-map [backspace] [?\C-?])
  7907. (dolist (b bindings)
  7908. ;; Not sure if input-decode-map is really right, but
  7909. ;; keyboard-translate-table (used below) only works
  7910. ;; for integer events, and key-translation-table is
  7911. ;; global (like the global-map, used earlier).
  7912. (define-key input-decode-map (car b) nil)
  7913. (define-key input-decode-map (cadr b) nil)))
  7914. (define-key local-function-key-map [delete] [?\C-?])
  7915. (define-key local-function-key-map [kp-delete] [?\C-?])
  7916. (define-key local-function-key-map [backspace] [?\C-?])
  7917. (dolist (b bindings)
  7918. (define-key input-decode-map (car b) (cadr b))
  7919. (define-key input-decode-map (cadr b) (car b))))))
  7920. (t
  7921. (if enabled
  7922. (progn
  7923. (keyboard-translate ?\C-h ?\C-?)
  7924. (keyboard-translate ?\C-? ?\C-d))
  7925. (keyboard-translate ?\C-h ?\C-h)
  7926. (keyboard-translate ?\C-? ?\C-?))))
  7927. (if (called-interactively-p 'interactive)
  7928. (message "Delete key deletes %s"
  7929. (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
  7930. "forward" "backward")))))
  7931. (defvar vis-mode-saved-buffer-invisibility-spec nil
  7932. "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
  7933. (define-minor-mode read-only-mode
  7934. "Change whether the current buffer is read-only.
  7935. With prefix argument ARG, make the buffer read-only if ARG is
  7936. positive, otherwise make it writable. If buffer is read-only
  7937. and `view-read-only' is non-nil, enter view mode.
  7938. Do not call this from a Lisp program unless you really intend to
  7939. do the same thing as the \\[read-only-mode] command, including
  7940. possibly enabling or disabling View mode. Also, note that this
  7941. command works by setting the variable `buffer-read-only', which
  7942. does not affect read-only regions caused by text properties. To
  7943. ignore read-only status in a Lisp program (whether due to text
  7944. properties or buffer state), bind `inhibit-read-only' temporarily
  7945. to a non-nil value."
  7946. :variable buffer-read-only
  7947. (cond
  7948. ((and (not buffer-read-only) view-mode)
  7949. (View-exit-and-edit)
  7950. (make-local-variable 'view-read-only)
  7951. (setq view-read-only t)) ; Must leave view mode.
  7952. ((and buffer-read-only view-read-only
  7953. ;; If view-mode is already active, `view-mode-enter' is a nop.
  7954. (not view-mode)
  7955. (not (eq (get major-mode 'mode-class) 'special)))
  7956. (view-mode-enter))))
  7957. (define-minor-mode visible-mode
  7958. "Toggle making all invisible text temporarily visible (Visible mode).
  7959. With a prefix argument ARG, enable Visible mode if ARG is
  7960. positive, and disable it otherwise. If called from Lisp, enable
  7961. the mode if ARG is omitted or nil.
  7962. This mode works by saving the value of `buffer-invisibility-spec'
  7963. and setting it to nil."
  7964. :lighter " Vis"
  7965. :group 'editing-basics
  7966. (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
  7967. (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
  7968. (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
  7969. (when visible-mode
  7970. (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
  7971. buffer-invisibility-spec)
  7972. (setq buffer-invisibility-spec nil)))
  7973. (defvar messages-buffer-mode-map
  7974. (let ((map (make-sparse-keymap)))
  7975. (set-keymap-parent map special-mode-map)
  7976. (define-key map "g" nil) ; nothing to revert
  7977. map))
  7978. (define-derived-mode messages-buffer-mode special-mode "Messages"
  7979. "Major mode used in the \"*Messages*\" buffer.")
  7980. (defun messages-buffer ()
  7981. "Return the \"*Messages*\" buffer.
  7982. If it does not exist, create and it switch it to `messages-buffer-mode'."
  7983. (or (get-buffer "*Messages*")
  7984. (with-current-buffer (get-buffer-create "*Messages*")
  7985. (messages-buffer-mode)
  7986. (current-buffer))))
  7987. ;; Minibuffer prompt stuff.
  7988. ;;(defun minibuffer-prompt-modification (start end)
  7989. ;; (error "You cannot modify the prompt"))
  7990. ;;
  7991. ;;
  7992. ;;(defun minibuffer-prompt-insertion (start end)
  7993. ;; (let ((inhibit-modification-hooks t))
  7994. ;; (delete-region start end)
  7995. ;; ;; Discard undo information for the text insertion itself
  7996. ;; ;; and for the text deletion.above.
  7997. ;; (when (consp buffer-undo-list)
  7998. ;; (setq buffer-undo-list (cddr buffer-undo-list)))
  7999. ;; (message "You cannot modify the prompt")))
  8000. ;;
  8001. ;;
  8002. ;;(setq minibuffer-prompt-properties
  8003. ;; (list 'modification-hooks '(minibuffer-prompt-modification)
  8004. ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
  8005. ;;;; Problematic external packages.
  8006. ;; rms says this should be done by specifying symbols that define
  8007. ;; versions together with bad values. This is therefore not as
  8008. ;; flexible as it could be. See the thread:
  8009. ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
  8010. (defconst bad-packages-alist
  8011. ;; Not sure exactly which semantic versions have problems.
  8012. ;; Definitely 2.0pre3, probably all 2.0pre's before this.
  8013. '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
  8014. "The version of `semantic' loaded does not work in Emacs 22.
  8015. It can cause constant high CPU load.
  8016. Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
  8017. ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
  8018. ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
  8019. ;; provided the `CUA-mode' feature. Since this is no longer true,
  8020. ;; we can warn the user if the `CUA-mode' feature is ever provided.
  8021. (CUA-mode t nil
  8022. "CUA-mode is now part of the standard GNU Emacs distribution,
  8023. so you can now enable CUA via the Options menu or by customizing `cua-mode'.
  8024. You have loaded an older version of CUA-mode which does not work
  8025. correctly with this version of Emacs. You should remove the old
  8026. version and use the one distributed with Emacs."))
  8027. "Alist of packages known to cause problems in this version of Emacs.
  8028. Each element has the form (PACKAGE SYMBOL REGEXP STRING).
  8029. PACKAGE is either a regular expression to match file names, or a
  8030. symbol (a feature name), like for `with-eval-after-load'.
  8031. SYMBOL is either the name of a string variable, or t. Upon
  8032. loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
  8033. warning using STRING as the message.")
  8034. (defun bad-package-check (package)
  8035. "Run a check using the element from `bad-packages-alist' matching PACKAGE."
  8036. (condition-case nil
  8037. (let* ((list (assoc package bad-packages-alist))
  8038. (symbol (nth 1 list)))
  8039. (and list
  8040. (boundp symbol)
  8041. (or (eq symbol t)
  8042. (and (stringp (setq symbol (eval symbol)))
  8043. (string-match-p (nth 2 list) symbol)))
  8044. (display-warning package (nth 3 list) :warning)))
  8045. (error nil)))
  8046. (dolist (elem bad-packages-alist)
  8047. (let ((pkg (car elem)))
  8048. (with-eval-after-load pkg
  8049. (bad-package-check pkg))))
  8050. ;;; Generic dispatcher commands
  8051. ;; Macro `define-alternatives' is used to create generic commands.
  8052. ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
  8053. ;; that can have different alternative implementations where choosing
  8054. ;; among them is exclusively a matter of user preference.
  8055. ;; (define-alternatives COMMAND) creates a new interactive command
  8056. ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
  8057. ;; Typically, the user will not need to customize this variable; packages
  8058. ;; wanting to add alternative implementations should use
  8059. ;;
  8060. ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
  8061. (defmacro define-alternatives (command &rest customizations)
  8062. "Define the new command `COMMAND'.
  8063. The argument `COMMAND' should be a symbol.
  8064. Running `M-x COMMAND RET' for the first time prompts for which
  8065. alternative to use and records the selected command as a custom
  8066. variable.
  8067. Running `C-u M-x COMMAND RET' prompts again for an alternative
  8068. and overwrites the previous choice.
  8069. The variable `COMMAND-alternatives' contains an alist with
  8070. alternative implementations of COMMAND. `define-alternatives'
  8071. does not have any effect until this variable is set.
  8072. CUSTOMIZATIONS, if non-nil, should be composed of alternating
  8073. `defcustom' keywords and values to add to the declaration of
  8074. `COMMAND-alternatives' (typically :group and :version)."
  8075. (let* ((command-name (symbol-name command))
  8076. (varalt-name (concat command-name "-alternatives"))
  8077. (varalt-sym (intern varalt-name))
  8078. (varimp-sym (intern (concat command-name "--implementation"))))
  8079. `(progn
  8080. (defcustom ,varalt-sym nil
  8081. ,(format "Alist of alternative implementations for the `%s' command.
  8082. Each entry must be a pair (ALTNAME . ALTFUN), where:
  8083. ALTNAME - The name shown at user to describe the alternative implementation.
  8084. ALTFUN - The function called to implement this alternative."
  8085. command-name)
  8086. :type '(alist :key-type string :value-type function)
  8087. ,@customizations)
  8088. (put ',varalt-sym 'definition-name ',command)
  8089. (defvar ,varimp-sym nil "Internal use only.")
  8090. (defun ,command (&optional arg)
  8091. ,(format "Run generic command `%s'.
  8092. If used for the first time, or with interactive ARG, ask the user which
  8093. implementation to use for `%s'. The variable `%s'
  8094. contains the list of implementations currently supported for this command."
  8095. command-name command-name varalt-name)
  8096. (interactive "P")
  8097. (when (or arg (null ,varimp-sym))
  8098. (let ((val (completing-read
  8099. ,(format-message
  8100. "Select implementation for command `%s': "
  8101. command-name)
  8102. ,varalt-sym nil t)))
  8103. (unless (string-equal val "")
  8104. (when (null ,varimp-sym)
  8105. (message
  8106. "Use C-u M-x %s RET`to select another implementation"
  8107. ,command-name)
  8108. (sit-for 3))
  8109. (customize-save-variable ',varimp-sym
  8110. (cdr (assoc-string val ,varalt-sym))))))
  8111. (if ,varimp-sym
  8112. (call-interactively ,varimp-sym)
  8113. (message "%s" ,(format-message
  8114. "No implementation selected for command `%s'"
  8115. command-name)))))))
  8116. ;;; Functions for changing capitalization that Do What I Mean
  8117. (defun upcase-dwim (arg)
  8118. "Upcase words in the region, if active; if not, upcase word at point.
  8119. If the region is active, this function calls `upcase-region'.
  8120. Otherwise, it calls `upcase-word', with prefix argument passed to it
  8121. to upcase ARG words."
  8122. (interactive "*p")
  8123. (if (use-region-p)
  8124. (upcase-region (region-beginning) (region-end))
  8125. (upcase-word arg)))
  8126. (defun downcase-dwim (arg)
  8127. "Downcase words in the region, if active; if not, downcase word at point.
  8128. If the region is active, this function calls `downcase-region'.
  8129. Otherwise, it calls `downcase-word', with prefix argument passed to it
  8130. to downcase ARG words."
  8131. (interactive "*p")
  8132. (if (use-region-p)
  8133. (downcase-region (region-beginning) (region-end))
  8134. (downcase-word arg)))
  8135. (defun capitalize-dwim (arg)
  8136. "Capitalize words in the region, if active; if not, capitalize word at point.
  8137. If the region is active, this function calls `capitalize-region'.
  8138. Otherwise, it calls `capitalize-word', with prefix argument passed to it
  8139. to capitalize ARG words."
  8140. (interactive "*p")
  8141. (if (use-region-p)
  8142. (capitalize-region (region-beginning) (region-end))
  8143. (capitalize-word arg)))
  8144. (provide 'simple)
  8145. ;;; simple.el ends here