files.el 290 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086
  1. ;;; files.el --- file input and output commands for Emacs -*- lexical-binding:t -*-
  2. ;; Copyright (C) 1985-1987, 1992-2015 Free Software Foundation, Inc.
  3. ;; Maintainer: emacs-devel@gnu.org
  4. ;; Package: emacs
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; Defines most of Emacs's file- and directory-handling functions,
  18. ;; including basic file visiting, backup generation, link handling,
  19. ;; ITS-id version control, load- and write-hook handling, and the like.
  20. ;;; Code:
  21. (defvar font-lock-keywords)
  22. (defgroup backup nil
  23. "Backups of edited data files."
  24. :group 'files)
  25. (defgroup find-file nil
  26. "Finding files."
  27. :group 'files)
  28. (defcustom delete-auto-save-files t
  29. "Non-nil means delete auto-save file when a buffer is saved or killed.
  30. Note that the auto-save file will not be deleted if the buffer is killed
  31. when it has unsaved changes."
  32. :type 'boolean
  33. :group 'auto-save)
  34. (defcustom directory-abbrev-alist
  35. nil
  36. "Alist of abbreviations for file directories.
  37. A list of elements of the form (FROM . TO), each meaning to replace
  38. FROM with TO when it appears in a directory name. This replacement is
  39. done when setting up the default directory of a newly visited file.
  40. FROM is matched against directory names anchored at the first
  41. character, so it should start with a \"\\\\\\=`\", or, if directory
  42. names cannot have embedded newlines, with a \"^\".
  43. FROM and TO should be equivalent names, which refer to the
  44. same directory. Do not use `~' in the TO strings;
  45. they should be ordinary absolute directory names.
  46. Use this feature when you have directories which you normally refer to
  47. via absolute symbolic links. Make TO the name of the link, and FROM
  48. the name it is linked to."
  49. :type '(repeat (cons :format "%v"
  50. :value ("\\`" . "")
  51. (regexp :tag "From")
  52. (string :tag "To")))
  53. :group 'abbrev
  54. :group 'find-file)
  55. (defcustom make-backup-files t
  56. "Non-nil means make a backup of a file the first time it is saved.
  57. This can be done by renaming the file or by copying.
  58. Renaming means that Emacs renames the existing file so that it is a
  59. backup file, then writes the buffer into a new file. Any other names
  60. that the old file had will now refer to the backup file. The new file
  61. is owned by you and its group is defaulted.
  62. Copying means that Emacs copies the existing file into the backup
  63. file, then writes the buffer on top of the existing file. Any other
  64. names that the old file had will now refer to the new (edited) file.
  65. The file's owner and group are unchanged.
  66. The choice of renaming or copying is controlled by the variables
  67. `backup-by-copying', `backup-by-copying-when-linked',
  68. `backup-by-copying-when-mismatch' and
  69. `backup-by-copying-when-privileged-mismatch'. See also `backup-inhibited'."
  70. :type 'boolean
  71. :group 'backup)
  72. ;; Do this so that local variables based on the file name
  73. ;; are not overridden by the major mode.
  74. (defvar backup-inhibited nil
  75. "If non-nil, backups will be inhibited.
  76. This variable is intended for use by making it local to a buffer,
  77. but it is not an automatically buffer-local variable.")
  78. (put 'backup-inhibited 'permanent-local t)
  79. (defcustom backup-by-copying nil
  80. "Non-nil means always use copying to create backup files.
  81. See documentation of variable `make-backup-files'."
  82. :type 'boolean
  83. :group 'backup)
  84. (defcustom backup-by-copying-when-linked nil
  85. "Non-nil means use copying to create backups for files with multiple names.
  86. This causes the alternate names to refer to the latest version as edited.
  87. This variable is relevant only if `backup-by-copying' is nil."
  88. :type 'boolean
  89. :group 'backup)
  90. (defcustom backup-by-copying-when-mismatch t
  91. "Non-nil means create backups by copying if this preserves owner or group.
  92. Renaming may still be used (subject to control of other variables)
  93. when it would not result in changing the owner or group of the file;
  94. that is, for files which are owned by you and whose group matches
  95. the default for a new file created there by you.
  96. This variable is relevant only if `backup-by-copying' is nil."
  97. :version "24.1"
  98. :type 'boolean
  99. :group 'backup)
  100. (put 'backup-by-copying-when-mismatch 'permanent-local t)
  101. (defcustom backup-by-copying-when-privileged-mismatch 200
  102. "Non-nil means create backups by copying to preserve a privileged owner.
  103. Renaming may still be used (subject to control of other variables)
  104. when it would not result in changing the owner of the file or if the owner
  105. has a user id greater than the value of this variable. This is useful
  106. when low-numbered uid's are used for special system users (such as root)
  107. that must maintain ownership of certain files.
  108. This variable is relevant only if `backup-by-copying' and
  109. `backup-by-copying-when-mismatch' are nil."
  110. :type '(choice (const nil) integer)
  111. :group 'backup)
  112. (defvar backup-enable-predicate 'normal-backup-enable-predicate
  113. "Predicate that looks at a file name and decides whether to make backups.
  114. Called with an absolute file name as argument, it returns t to enable backup.")
  115. (defcustom buffer-offer-save nil
  116. "Non-nil in a buffer means always offer to save buffer on exit.
  117. Do so even if the buffer is not visiting a file.
  118. Automatically local in all buffers."
  119. :type 'boolean
  120. :group 'backup)
  121. (make-variable-buffer-local 'buffer-offer-save)
  122. (put 'buffer-offer-save 'permanent-local t)
  123. (defcustom find-file-existing-other-name t
  124. "Non-nil means find a file under alternative names, in existing buffers.
  125. This means if any existing buffer is visiting the file you want
  126. under another name, you get the existing buffer instead of a new buffer."
  127. :type 'boolean
  128. :group 'find-file)
  129. (defcustom find-file-visit-truename nil
  130. "Non-nil means visiting a file uses its truename as the visited-file name.
  131. That is, the buffer visiting the file has the truename as the
  132. value of `buffer-file-name'. The truename of a file is found by
  133. chasing all links both at the file level and at the levels of the
  134. containing directories."
  135. :type 'boolean
  136. :group 'find-file)
  137. (put 'find-file-visit-truename 'safe-local-variable 'booleanp)
  138. (defcustom revert-without-query nil
  139. "Specify which files should be reverted without query.
  140. The value is a list of regular expressions.
  141. If the file name matches one of these regular expressions,
  142. then `revert-buffer' reverts the file without querying
  143. if the file has changed on disk and you have not edited the buffer."
  144. :type '(repeat regexp)
  145. :group 'find-file)
  146. (defvar buffer-file-number nil
  147. "The device number and file number of the file visited in the current buffer.
  148. The value is a list of the form (FILENUM DEVNUM).
  149. This pair of numbers uniquely identifies the file.
  150. If the buffer is visiting a new file, the value is nil.")
  151. (make-variable-buffer-local 'buffer-file-number)
  152. (put 'buffer-file-number 'permanent-local t)
  153. (defvar buffer-file-numbers-unique (not (memq system-type '(windows-nt)))
  154. "Non-nil means that `buffer-file-number' uniquely identifies files.")
  155. (defvar buffer-file-read-only nil
  156. "Non-nil if visited file was read-only when visited.")
  157. (make-variable-buffer-local 'buffer-file-read-only)
  158. (defcustom small-temporary-file-directory
  159. (if (eq system-type 'ms-dos) (getenv "TMPDIR"))
  160. "The directory for writing small temporary files.
  161. If non-nil, this directory is used instead of `temporary-file-directory'
  162. by programs that create small temporary files. This is for systems that
  163. have fast storage with limited space, such as a RAM disk."
  164. :group 'files
  165. :initialize 'custom-initialize-delay
  166. :type '(choice (const nil) directory))
  167. ;; The system null device. (Should reference NULL_DEVICE from C.)
  168. (defvar null-device (purecopy "/dev/null") "The system null device.")
  169. (declare-function msdos-long-file-names "msdos.c")
  170. (declare-function w32-long-file-name "w32proc.c")
  171. (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
  172. (declare-function dired-unmark "dired" (arg &optional interactive))
  173. (declare-function dired-do-flagged-delete "dired" (&optional nomessage))
  174. (declare-function dos-8+3-filename "dos-fns" (filename))
  175. (declare-function dosified-file-name "dos-fns" (file-name))
  176. (defvar file-name-invalid-regexp
  177. (cond ((and (eq system-type 'ms-dos) (not (msdos-long-file-names)))
  178. (purecopy
  179. (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
  180. "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
  181. "[\000-\037]\\|" ; control characters
  182. "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
  183. "\\(/[^/.]+\\.[^/.]*\\.\\)"))) ; more than a single dot
  184. ((memq system-type '(ms-dos windows-nt cygwin))
  185. (purecopy
  186. (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
  187. "[|<>\"?*\000-\037]"))) ; invalid characters
  188. (t (purecopy "[\000]")))
  189. "Regexp recognizing file names which aren't allowed by the filesystem.")
  190. (defcustom file-precious-flag nil
  191. "Non-nil means protect against I/O errors while saving files.
  192. Some modes set this non-nil in particular buffers.
  193. This feature works by writing the new contents into a temporary file
  194. and then renaming the temporary file to replace the original.
  195. In this way, any I/O error in writing leaves the original untouched,
  196. and there is never any instant where the file is nonexistent.
  197. Note that this feature forces backups to be made by copying.
  198. Yet, at the same time, saving a precious file
  199. breaks any hard links between it and other files.
  200. This feature is advisory: for example, if the directory in which the
  201. file is being saved is not writable, Emacs may ignore a non-nil value
  202. of `file-precious-flag' and write directly into the file.
  203. See also: `break-hardlink-on-save'."
  204. :type 'boolean
  205. :group 'backup)
  206. (defcustom break-hardlink-on-save nil
  207. "Whether to allow breaking hardlinks when saving files.
  208. If non-nil, then when saving a file that exists under several
  209. names \(i.e., has multiple hardlinks), break the hardlink
  210. associated with `buffer-file-name' and write to a new file, so
  211. that the other instances of the file are not affected by the
  212. save.
  213. If `buffer-file-name' refers to a symlink, do not break the symlink.
  214. Unlike `file-precious-flag', `break-hardlink-on-save' is not advisory.
  215. For example, if the directory in which a file is being saved is not
  216. itself writable, then error instead of saving in some
  217. hardlink-nonbreaking way.
  218. See also `backup-by-copying' and `backup-by-copying-when-linked'."
  219. :type 'boolean
  220. :group 'files
  221. :version "23.1")
  222. (defcustom version-control nil
  223. "Control use of version numbers for backup files.
  224. When t, make numeric backup versions unconditionally.
  225. When nil, make them for files that have some already.
  226. The value `never' means do not make them."
  227. :type '(choice (const :tag "Never" never)
  228. (const :tag "If existing" nil)
  229. (other :tag "Always" t))
  230. :group 'backup
  231. :group 'vc)
  232. (put 'version-control 'safe-local-variable
  233. (lambda (x) (or (booleanp x) (equal x 'never))))
  234. (defcustom dired-kept-versions 2
  235. "When cleaning directory, number of versions to keep."
  236. :type 'integer
  237. :group 'backup
  238. :group 'dired)
  239. (defcustom delete-old-versions nil
  240. "If t, delete excess backup versions silently.
  241. If nil, ask confirmation. Any other value prevents any trimming."
  242. :type '(choice (const :tag "Delete" t)
  243. (const :tag "Ask" nil)
  244. (other :tag "Leave" other))
  245. :group 'backup)
  246. (defcustom kept-old-versions 2
  247. "Number of oldest versions to keep when a new numbered backup is made."
  248. :type 'integer
  249. :group 'backup)
  250. (put 'kept-old-versions 'safe-local-variable 'integerp)
  251. (defcustom kept-new-versions 2
  252. "Number of newest versions to keep when a new numbered backup is made.
  253. Includes the new backup. Must be > 0"
  254. :type 'integer
  255. :group 'backup)
  256. (put 'kept-new-versions 'safe-local-variable 'integerp)
  257. (defcustom require-final-newline nil
  258. "Whether to add a newline automatically at the end of the file.
  259. A value of t means do this only when the file is about to be saved.
  260. A value of `visit' means do this right after the file is visited.
  261. A value of `visit-save' means do it at both of those times.
  262. Any other non-nil value means ask user whether to add a newline, when saving.
  263. A value of nil means don't add newlines.
  264. Certain major modes set this locally to the value obtained
  265. from `mode-require-final-newline'."
  266. :safe #'symbolp
  267. :type '(choice (const :tag "When visiting" visit)
  268. (const :tag "When saving" t)
  269. (const :tag "When visiting or saving" visit-save)
  270. (const :tag "Don't add newlines" nil)
  271. (other :tag "Ask each time" ask))
  272. :group 'editing-basics)
  273. (defcustom mode-require-final-newline t
  274. "Whether to add a newline at end of file, in certain major modes.
  275. Those modes set `require-final-newline' to this value when you enable them.
  276. They do so because they are often used for files that are supposed
  277. to end in newlines, and the question is how to arrange that.
  278. A value of t means do this only when the file is about to be saved.
  279. A value of `visit' means do this right after the file is visited.
  280. A value of `visit-save' means do it at both of those times.
  281. Any other non-nil value means ask user whether to add a newline, when saving.
  282. A value of nil means do not add newlines. That is a risky choice in this
  283. variable since this value is used for modes for files that ought to have
  284. final newlines. So if you set this to nil, you must explicitly check and
  285. add a final newline, whenever you save a file that really needs one."
  286. :type '(choice (const :tag "When visiting" visit)
  287. (const :tag "When saving" t)
  288. (const :tag "When visiting or saving" visit-save)
  289. (const :tag "Don't add newlines" nil)
  290. (other :tag "Ask each time" ask))
  291. :group 'editing-basics
  292. :version "22.1")
  293. (defcustom auto-save-default t
  294. "Non-nil says by default do auto-saving of every file-visiting buffer."
  295. :type 'boolean
  296. :group 'auto-save)
  297. (defcustom auto-save-file-name-transforms
  298. `(("\\`/[^/]*:\\([^/]*/\\)*\\([^/]*\\)\\'"
  299. ;; Don't put "\\2" inside expand-file-name, since it will be
  300. ;; transformed to "/2" on DOS/Windows.
  301. ,(concat temporary-file-directory "\\2") t))
  302. "Transforms to apply to buffer file name before making auto-save file name.
  303. Each transform is a list (REGEXP REPLACEMENT UNIQUIFY):
  304. REGEXP is a regular expression to match against the file name.
  305. If it matches, `replace-match' is used to replace the
  306. matching part with REPLACEMENT.
  307. If the optional element UNIQUIFY is non-nil, the auto-save file name is
  308. constructed by taking the directory part of the replaced file-name,
  309. concatenated with the buffer file name with all directory separators
  310. changed to `!' to prevent clashes. This will not work
  311. correctly if your filesystem truncates the resulting name.
  312. All the transforms in the list are tried, in the order they are listed.
  313. When one transform applies, its result is final;
  314. no further transforms are tried.
  315. The default value is set up to put the auto-save file into the
  316. temporary directory (see the variable `temporary-file-directory') for
  317. editing a remote file.
  318. On MS-DOS filesystems without long names this variable is always
  319. ignored."
  320. :group 'auto-save
  321. :type '(repeat (list (string :tag "Regexp") (string :tag "Replacement")
  322. (boolean :tag "Uniquify")))
  323. :initialize 'custom-initialize-delay
  324. :version "21.1")
  325. (defcustom save-abbrevs t
  326. "Non-nil means save word abbrevs too when files are saved.
  327. If `silently', don't ask the user before saving."
  328. :type '(choice (const t) (const nil) (const silently))
  329. :group 'abbrev)
  330. (defcustom find-file-run-dired t
  331. "Non-nil means allow `find-file' to visit directories.
  332. To visit the directory, `find-file' runs `find-directory-functions'."
  333. :type 'boolean
  334. :group 'find-file)
  335. (defcustom find-directory-functions '(cvs-dired-noselect dired-noselect)
  336. "List of functions to try in sequence to visit a directory.
  337. Each function is called with the directory name as the sole argument
  338. and should return either a buffer or nil."
  339. :type '(hook :options (cvs-dired-noselect dired-noselect))
  340. :group 'find-file)
  341. ;; FIXME: also add a hook for `(thing-at-point 'filename)'
  342. (defcustom file-name-at-point-functions '(ffap-guess-file-name-at-point)
  343. "List of functions to try in sequence to get a file name at point.
  344. Each function should return either nil or a file name found at the
  345. location of point in the current buffer."
  346. :type '(hook :options (ffap-guess-file-name-at-point))
  347. :group 'find-file)
  348. ;;;It is not useful to make this a local variable.
  349. ;;;(put 'find-file-not-found-hooks 'permanent-local t)
  350. (define-obsolete-variable-alias 'find-file-not-found-hooks
  351. 'find-file-not-found-functions "22.1")
  352. (defvar find-file-not-found-functions nil
  353. "List of functions to be called for `find-file' on nonexistent file.
  354. These functions are called as soon as the error is detected.
  355. Variable `buffer-file-name' is already set up.
  356. The functions are called in the order given until one of them returns non-nil.")
  357. ;;;It is not useful to make this a local variable.
  358. ;;;(put 'find-file-hooks 'permanent-local t)
  359. (define-obsolete-variable-alias 'find-file-hooks 'find-file-hook "22.1")
  360. (defcustom find-file-hook nil
  361. "List of functions to be called after a buffer is loaded from a file.
  362. The buffer's local variables (if any) will have been processed before the
  363. functions are called."
  364. :group 'find-file
  365. :type 'hook
  366. :options '(auto-insert)
  367. :version "22.1")
  368. (define-obsolete-variable-alias 'write-file-hooks 'write-file-functions "22.1")
  369. (defvar write-file-functions nil
  370. "List of functions to be called before writing out a buffer to a file.
  371. If one of them returns non-nil, the file is considered already written
  372. and the rest are not called.
  373. These hooks are considered to pertain to the visited file.
  374. So any buffer-local binding of this variable is discarded if you change
  375. the visited file name with \\[set-visited-file-name], but not when you
  376. change the major mode.
  377. This hook is not run if any of the functions in
  378. `write-contents-functions' returns non-nil. Both hooks pertain
  379. to how to save a buffer to file, for instance, choosing a suitable
  380. coding system and setting mode bits. (See Info
  381. node `(elisp)Saving Buffers'.) To perform various checks or
  382. updates before the buffer is saved, use `before-save-hook'.")
  383. (put 'write-file-functions 'permanent-local t)
  384. (defvar local-write-file-hooks nil)
  385. (make-variable-buffer-local 'local-write-file-hooks)
  386. (put 'local-write-file-hooks 'permanent-local t)
  387. (make-obsolete-variable 'local-write-file-hooks 'write-file-functions "22.1")
  388. (define-obsolete-variable-alias 'write-contents-hooks
  389. 'write-contents-functions "22.1")
  390. (defvar write-contents-functions nil
  391. "List of functions to be called before writing out a buffer to a file.
  392. If one of them returns non-nil, the file is considered already written
  393. and the rest are not called and neither are the functions in
  394. `write-file-functions'.
  395. This variable is meant to be used for hooks that pertain to the
  396. buffer's contents, not to the particular visited file; thus,
  397. `set-visited-file-name' does not clear this variable; but changing the
  398. major mode does clear it.
  399. For hooks that _do_ pertain to the particular visited file, use
  400. `write-file-functions'. Both this variable and
  401. `write-file-functions' relate to how a buffer is saved to file.
  402. To perform various checks or updates before the buffer is saved,
  403. use `before-save-hook'.")
  404. (make-variable-buffer-local 'write-contents-functions)
  405. (defcustom enable-local-variables t
  406. "Control use of local variables in files you visit.
  407. The value can be t, nil, :safe, :all, or something else.
  408. A value of t means file local variables specifications are obeyed
  409. if all the specified variable values are safe; if any values are
  410. not safe, Emacs queries you, once, whether to set them all.
  411. \(When you say yes to certain values, they are remembered as safe.)
  412. :safe means set the safe variables, and ignore the rest.
  413. :all means set all variables, whether safe or not.
  414. (Don't set it permanently to :all.)
  415. A value of nil means always ignore the file local variables.
  416. Any other value means always query you once whether to set them all.
  417. \(When you say yes to certain values, they are remembered as safe, but
  418. this has no effect when `enable-local-variables' is \"something else\".)
  419. This variable also controls use of major modes specified in
  420. a -*- line.
  421. The command \\[normal-mode], when used interactively,
  422. always obeys file local variable specifications and the -*- line,
  423. and ignores this variable."
  424. :risky t
  425. :type '(choice (const :tag "Query Unsafe" t)
  426. (const :tag "Safe Only" :safe)
  427. (const :tag "Do all" :all)
  428. (const :tag "Ignore" nil)
  429. (other :tag "Query" other))
  430. :group 'find-file)
  431. (defvar enable-dir-local-variables t
  432. "Non-nil means enable use of directory-local variables.
  433. Some modes may wish to set this to nil to prevent directory-local
  434. settings being applied, but still respect file-local ones.")
  435. ;; This is an odd variable IMO.
  436. ;; You might wonder why it is needed, when we could just do:
  437. ;; (set (make-local-variable 'enable-local-variables) nil)
  438. ;; These two are not precisely the same.
  439. ;; Setting this variable does not cause -*- mode settings to be
  440. ;; ignored, whereas setting enable-local-variables does.
  441. ;; Only three places in Emacs use this variable: tar and arc modes,
  442. ;; and rmail. The first two don't need it. They already use
  443. ;; inhibit-local-variables-regexps, which is probably enough, and
  444. ;; could also just set enable-local-variables locally to nil.
  445. ;; Them setting it has the side-effect that dir-locals cannot apply to
  446. ;; eg tar files (?). FIXME Is this appropriate?
  447. ;; AFAICS, rmail is the only thing that needs this, and the only
  448. ;; reason it uses it is for BABYL files (which are obsolete).
  449. ;; These contain "-*- rmail -*-" in the first line, which rmail wants
  450. ;; to respect, so that find-file on a BABYL file will switch to
  451. ;; rmail-mode automatically (this is nice, but hardly essential,
  452. ;; since most people are used to explicitly running a command to
  453. ;; access their mail; M-x gnus etc). Rmail files may happen to
  454. ;; contain Local Variables sections in messages, which Rmail wants to
  455. ;; ignore. So AFAICS the only reason this variable exists is for a
  456. ;; minor convenience feature for handling of an obsolete Rmail file format.
  457. (defvar local-enable-local-variables t
  458. "Like `enable-local-variables' but meant for buffer-local bindings.
  459. The meaningful values are nil and non-nil. The default is non-nil.
  460. If a major mode sets this to nil, buffer-locally, then any local
  461. variables list in a file visited in that mode will be ignored.
  462. This variable does not affect the use of major modes specified
  463. in a -*- line.")
  464. (defcustom enable-local-eval 'maybe
  465. "Control processing of the \"variable\" `eval' in a file's local variables.
  466. The value can be t, nil or something else.
  467. A value of t means obey `eval' variables.
  468. A value of nil means ignore them; anything else means query."
  469. :risky t
  470. :type '(choice (const :tag "Obey" t)
  471. (const :tag "Ignore" nil)
  472. (other :tag "Query" other))
  473. :group 'find-file)
  474. (defcustom view-read-only nil
  475. "Non-nil means buffers visiting files read-only do so in view mode.
  476. In fact, this means that all read-only buffers normally have
  477. View mode enabled, including buffers that are read-only because
  478. you visit a file you cannot alter, and buffers you make read-only
  479. using \\[read-only-mode]."
  480. :type 'boolean
  481. :group 'view)
  482. (defvar file-name-history nil
  483. "History list of file names entered in the minibuffer.
  484. Maximum length of the history list is determined by the value
  485. of `history-length', which see.")
  486. (defvar save-silently nil
  487. "If non-nil, avoid messages when saving files.
  488. Error-related messages will still be printed, but all other
  489. messages will not.")
  490. (put 'ange-ftp-completion-hook-function 'safe-magic t)
  491. (defun ange-ftp-completion-hook-function (op &rest args)
  492. "Provides support for ange-ftp host name completion.
  493. Runs the usual ange-ftp hook, but only for completion operations."
  494. ;; Having this here avoids the need to load ange-ftp when it's not
  495. ;; really in use.
  496. (if (memq op '(file-name-completion file-name-all-completions))
  497. (apply 'ange-ftp-hook-function op args)
  498. (let ((inhibit-file-name-handlers
  499. (cons 'ange-ftp-completion-hook-function
  500. (and (eq inhibit-file-name-operation op)
  501. inhibit-file-name-handlers)))
  502. (inhibit-file-name-operation op))
  503. (apply op args))))
  504. (declare-function dos-convert-standard-filename "dos-fns.el" (filename))
  505. (declare-function w32-convert-standard-filename "w32-fns.el" (filename))
  506. (defun convert-standard-filename (filename)
  507. "Convert a standard file's name to something suitable for the OS.
  508. This means to guarantee valid names and perhaps to canonicalize
  509. certain patterns.
  510. FILENAME should be an absolute file name since the conversion rules
  511. sometimes vary depending on the position in the file name. E.g. c:/foo
  512. is a valid DOS file name, but c:/bar/c:/foo is not.
  513. This function's standard definition is trivial; it just returns
  514. the argument. However, on Windows and DOS, replace invalid
  515. characters. On DOS, make sure to obey the 8.3 limitations.
  516. In the native Windows build, turn Cygwin names into native names,
  517. and also turn slashes into backslashes if the shell requires it (see
  518. `w32-shell-dos-semantics').
  519. See Info node `(elisp)Standard File Names' for more details."
  520. (cond
  521. ((eq system-type 'cygwin)
  522. (let ((name (copy-sequence filename))
  523. (start 0))
  524. ;; Replace invalid filename characters with !
  525. (while (string-match "[?*:<>|\"\000-\037]" name start)
  526. (aset name (match-beginning 0) ?!)
  527. (setq start (match-end 0)))
  528. name))
  529. ((eq system-type 'windows-nt)
  530. (w32-convert-standard-filename filename))
  531. ((eq system-type 'ms-dos)
  532. (dos-convert-standard-filename filename))
  533. (t filename)))
  534. (defun read-directory-name (prompt &optional dir default-dirname mustmatch initial)
  535. "Read directory name, prompting with PROMPT and completing in directory DIR.
  536. Value is not expanded---you must call `expand-file-name' yourself.
  537. Default name to DEFAULT-DIRNAME if user exits with the same
  538. non-empty string that was inserted by this function.
  539. (If DEFAULT-DIRNAME is omitted, DIR combined with INITIAL is used,
  540. or just DIR if INITIAL is nil.)
  541. If the user exits with an empty minibuffer, this function returns
  542. an empty string. (This can only happen if the user erased the
  543. pre-inserted contents or if `insert-default-directory' is nil.)
  544. Fourth arg MUSTMATCH non-nil means require existing directory's name.
  545. Non-nil and non-t means also require confirmation after completion.
  546. Fifth arg INITIAL specifies text to start with.
  547. DIR should be an absolute directory name. It defaults to
  548. the value of `default-directory'."
  549. (unless dir
  550. (setq dir default-directory))
  551. (read-file-name prompt dir (or default-dirname
  552. (if initial (expand-file-name initial dir)
  553. dir))
  554. mustmatch initial
  555. 'file-directory-p))
  556. (defun pwd (&optional insert)
  557. "Show the current default directory.
  558. With prefix argument INSERT, insert the current default directory
  559. at point instead."
  560. (interactive "P")
  561. (if insert
  562. (insert default-directory)
  563. (message "Directory %s" default-directory)))
  564. (defvar cd-path nil
  565. "Value of the CDPATH environment variable, as a list.
  566. Not actually set up until the first time you use it.")
  567. (defun parse-colon-path (search-path)
  568. "Explode a search path into a list of directory names.
  569. Directories are separated by `path-separator' (which is colon in
  570. GNU and Unix systems). Substitute environment variables into the
  571. resulting list of directory names. For an empty path element (i.e.,
  572. a leading or trailing separator, or two adjacent separators), return
  573. nil (meaning `default-directory') as the associated list element."
  574. (when (stringp search-path)
  575. (mapcar (lambda (f)
  576. (if (equal "" f) nil
  577. (substitute-in-file-name (file-name-as-directory f))))
  578. (split-string search-path path-separator))))
  579. (defun cd-absolute (dir)
  580. "Change current directory to given absolute file name DIR."
  581. ;; Put the name into directory syntax now,
  582. ;; because otherwise expand-file-name may give some bad results.
  583. (setq dir (file-name-as-directory dir))
  584. ;; We used to additionally call abbreviate-file-name here, for an
  585. ;; unknown reason. Problem is that most buffers are setup
  586. ;; without going through cd-absolute and don't call
  587. ;; abbreviate-file-name on their default-directory, so the few that
  588. ;; do end up using a superficially different directory.
  589. (setq dir (expand-file-name dir))
  590. (if (not (file-directory-p dir))
  591. (if (file-exists-p dir)
  592. (error "%s is not a directory" dir)
  593. (error "%s: no such directory" dir))
  594. (unless (file-accessible-directory-p dir)
  595. (error "Cannot cd to %s: Permission denied" dir))
  596. (setq default-directory dir)
  597. (setq list-buffers-directory dir)))
  598. (defun cd (dir)
  599. "Make DIR become the current buffer's default directory.
  600. If your environment includes a `CDPATH' variable, try each one of
  601. that list of directories (separated by occurrences of
  602. `path-separator') when resolving a relative directory name.
  603. The path separator is colon in GNU and GNU-like systems."
  604. (interactive
  605. (list
  606. ;; FIXME: There's a subtle bug in the completion below. Seems linked
  607. ;; to a fundamental difficulty of implementing `predicate' correctly.
  608. ;; The manifestation is that TAB may list non-directories in the case where
  609. ;; those files also correspond to valid directories (if your cd-path is (A/
  610. ;; B/) and you have A/a a file and B/a a directory, then both `a' and `a/'
  611. ;; will be listed as valid completions).
  612. ;; This is because `a' (listed because of A/a) is indeed a valid choice
  613. ;; (which will lead to the use of B/a).
  614. (minibuffer-with-setup-hook
  615. (lambda ()
  616. (setq minibuffer-completion-table
  617. (apply-partially #'locate-file-completion-table
  618. cd-path nil))
  619. (setq minibuffer-completion-predicate
  620. (lambda (dir)
  621. (locate-file dir cd-path nil
  622. (lambda (f) (and (file-directory-p f) 'dir-ok))))))
  623. (unless cd-path
  624. (setq cd-path (or (parse-colon-path (getenv "CDPATH"))
  625. (list "./"))))
  626. (read-directory-name "Change default directory: "
  627. default-directory default-directory
  628. t))))
  629. (unless cd-path
  630. (setq cd-path (or (parse-colon-path (getenv "CDPATH"))
  631. (list "./"))))
  632. (cd-absolute
  633. (or (locate-file dir cd-path nil
  634. (lambda (f) (and (file-directory-p f) 'dir-ok)))
  635. (error "No such directory found via CDPATH environment variable"))))
  636. (defsubst directory-name-p (name)
  637. "Return non-nil if NAME ends with a slash character."
  638. (and (> (length name) 0)
  639. (char-equal (aref name (1- (length name))) ?/)))
  640. (defun directory-files-recursively (dir match &optional include-directories)
  641. "Return all files under DIR that have file names matching MATCH (a regexp).
  642. This function works recursively. Files are returned in \"depth first\"
  643. and alphabetical order.
  644. If INCLUDE-DIRECTORIES, also include directories that have matching names."
  645. (let ((result nil)
  646. (files nil)
  647. ;; When DIR is "/", remote file names like "/method:" could
  648. ;; also be offered. We shall suppress them.
  649. (tramp-mode (and tramp-mode (file-remote-p dir))))
  650. (dolist (file (sort (file-name-all-completions "" dir)
  651. 'string<))
  652. (unless (member file '("./" "../"))
  653. (if (directory-name-p file)
  654. (let* ((leaf (substring file 0 (1- (length file))))
  655. (full-file (expand-file-name leaf dir)))
  656. ;; Don't follow symlinks to other directories.
  657. (unless (file-symlink-p full-file)
  658. (setq result
  659. (nconc result (directory-files-recursively
  660. full-file match include-directories))))
  661. (when (and include-directories
  662. (string-match match leaf))
  663. (setq result (nconc result (list full-file)))))
  664. (when (string-match match file)
  665. (push (expand-file-name file dir) files)))))
  666. (nconc result (nreverse files))))
  667. (defun load-file (file)
  668. "Load the Lisp file named FILE."
  669. ;; This is a case where .elc makes a lot of sense.
  670. (interactive (list (let ((completion-ignored-extensions
  671. (remove ".elc" completion-ignored-extensions)))
  672. (read-file-name "Load file: " nil nil 'lambda))))
  673. (load (expand-file-name file) nil nil t))
  674. (defun locate-file (filename path &optional suffixes predicate)
  675. "Search for FILENAME through PATH.
  676. If found, return the absolute file name of FILENAME; otherwise
  677. return nil.
  678. PATH should be a list of directories to look in, like the lists in
  679. `exec-path' or `load-path'.
  680. If SUFFIXES is non-nil, it should be a list of suffixes to append to
  681. file name when searching. If SUFFIXES is nil, it is equivalent to '(\"\").
  682. Use '(\"/\") to disable PATH search, but still try the suffixes in SUFFIXES.
  683. If non-nil, PREDICATE is used instead of `file-readable-p'.
  684. This function will normally skip directories, so if you want it to find
  685. directories, make sure the PREDICATE function returns `dir-ok' for them.
  686. PREDICATE can also be an integer to pass to the `access' system call,
  687. in which case file-name handlers are ignored. This usage is deprecated.
  688. For compatibility, PREDICATE can also be one of the symbols
  689. `executable', `readable', `writable', or `exists', or a list of
  690. one or more of those symbols."
  691. (if (and predicate (symbolp predicate) (not (functionp predicate)))
  692. (setq predicate (list predicate)))
  693. (when (and (consp predicate) (not (functionp predicate)))
  694. (setq predicate
  695. (logior (if (memq 'executable predicate) 1 0)
  696. (if (memq 'writable predicate) 2 0)
  697. (if (memq 'readable predicate) 4 0))))
  698. (locate-file-internal filename path suffixes predicate))
  699. (defun locate-file-completion-table (dirs suffixes string pred action)
  700. "Do completion for file names passed to `locate-file'."
  701. (cond
  702. ((file-name-absolute-p string)
  703. ;; FIXME: maybe we should use completion-file-name-table instead,
  704. ;; tho at least for `load', the arg is passed through
  705. ;; substitute-in-file-name for historical reasons.
  706. (read-file-name-internal string pred action))
  707. ((eq (car-safe action) 'boundaries)
  708. (let ((suffix (cdr action)))
  709. `(boundaries
  710. ,(length (file-name-directory string))
  711. ,@(let ((x (file-name-directory suffix)))
  712. (if x (1- (length x)) (length suffix))))))
  713. (t
  714. (let ((names '())
  715. ;; If we have files like "foo.el" and "foo.elc", we could load one of
  716. ;; them with "foo.el", "foo.elc", or "foo", where just "foo" is the
  717. ;; preferred way. So if we list all 3, that gives a lot of redundant
  718. ;; entries for the poor soul looking just for "foo". OTOH, sometimes
  719. ;; the user does want to pay attention to the extension. We try to
  720. ;; diffuse this tension by stripping the suffix, except when the
  721. ;; result is a single element (i.e. usually we only list "foo" unless
  722. ;; it's the only remaining element in the list, in which case we do
  723. ;; list "foo", "foo.elc" and "foo.el").
  724. (fullnames '())
  725. (suffix (concat (regexp-opt suffixes t) "\\'"))
  726. (string-dir (file-name-directory string))
  727. (string-file (file-name-nondirectory string)))
  728. (dolist (dir dirs)
  729. (unless dir
  730. (setq dir default-directory))
  731. (if string-dir (setq dir (expand-file-name string-dir dir)))
  732. (when (file-directory-p dir)
  733. (dolist (file (file-name-all-completions
  734. string-file dir))
  735. (if (not (string-match suffix file))
  736. (push file names)
  737. (push file fullnames)
  738. (push (substring file 0 (match-beginning 0)) names)))))
  739. ;; Switching from names to names+fullnames creates a non-monotonicity
  740. ;; which can cause problems with things like partial-completion.
  741. ;; To minimize the problem, filter out completion-regexp-list, so that
  742. ;; M-x load-library RET t/x.e TAB finds some files. Also remove elements
  743. ;; from `names' which only matched `string' when they still had
  744. ;; their suffix.
  745. (setq names (all-completions string names))
  746. ;; Remove duplicates of the first element, so that we can easily check
  747. ;; if `names' really only contains a single element.
  748. (when (cdr names) (setcdr names (delete (car names) (cdr names))))
  749. (unless (cdr names)
  750. ;; There's no more than one matching non-suffixed element, so expand
  751. ;; the list by adding the suffixed elements as well.
  752. (setq names (nconc names fullnames)))
  753. (completion-table-with-context
  754. string-dir names string-file pred action)))))
  755. (defun locate-file-completion (string path-and-suffixes action)
  756. "Do completion for file names passed to `locate-file'.
  757. PATH-AND-SUFFIXES is a pair of lists, (DIRECTORIES . SUFFIXES)."
  758. (declare (obsolete locate-file-completion-table "23.1"))
  759. (locate-file-completion-table (car path-and-suffixes)
  760. (cdr path-and-suffixes)
  761. string nil action))
  762. (defvar locate-dominating-stop-dir-regexp
  763. (purecopy "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'")
  764. "Regexp of directory names which stop the search in `locate-dominating-file'.
  765. Any directory whose name matches this regexp will be treated like
  766. a kind of root directory by `locate-dominating-file' which will stop its search
  767. when it bumps into it.
  768. The default regexp prevents fruitless and time-consuming attempts to find
  769. special files in directories in which filenames are interpreted as hostnames,
  770. or mount points potentially requiring authentication as a different user.")
  771. ;; (defun locate-dominating-files (file regexp)
  772. ;; "Look up the directory hierarchy from FILE for a file matching REGEXP.
  773. ;; Stop at the first parent where a matching file is found and return the list
  774. ;; of files that that match in this directory."
  775. ;; (catch 'found
  776. ;; ;; `user' is not initialized yet because `file' may not exist, so we may
  777. ;; ;; have to walk up part of the hierarchy before we find the "initial UID".
  778. ;; (let ((user nil)
  779. ;; ;; Abbreviate, so as to stop when we cross ~/.
  780. ;; (dir (abbreviate-file-name (file-name-as-directory file)))
  781. ;; files)
  782. ;; (while (and dir
  783. ;; ;; As a heuristic, we stop looking up the hierarchy of
  784. ;; ;; directories as soon as we find a directory belonging to
  785. ;; ;; another user. This should save us from looking in
  786. ;; ;; things like /net and /afs. This assumes that all the
  787. ;; ;; files inside a project belong to the same user.
  788. ;; (let ((prev-user user))
  789. ;; (setq user (nth 2 (file-attributes dir)))
  790. ;; (or (null prev-user) (equal user prev-user))))
  791. ;; (if (setq files (condition-case nil
  792. ;; (directory-files dir 'full regexp 'nosort)
  793. ;; (error nil)))
  794. ;; (throw 'found files)
  795. ;; (if (equal dir
  796. ;; (setq dir (file-name-directory
  797. ;; (directory-file-name dir))))
  798. ;; (setq dir nil))))
  799. ;; nil)))
  800. (defun locate-dominating-file (file name)
  801. "Look up the directory hierarchy from FILE for a directory containing NAME.
  802. Stop at the first parent directory containing a file NAME,
  803. and return the directory. Return nil if not found.
  804. Instead of a string, NAME can also be a predicate taking one argument
  805. \(a directory) and returning a non-nil value if that directory is the one for
  806. which we're looking."
  807. ;; We used to use the above locate-dominating-files code, but the
  808. ;; directory-files call is very costly, so we're much better off doing
  809. ;; multiple calls using the code in here.
  810. ;;
  811. ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
  812. ;; `name' in /home or in /.
  813. (setq file (abbreviate-file-name (expand-file-name file)))
  814. (let ((root nil)
  815. ;; `user' is not initialized outside the loop because
  816. ;; `file' may not exist, so we may have to walk up part of the
  817. ;; hierarchy before we find the "initial UID". Note: currently unused
  818. ;; (user nil)
  819. try)
  820. (while (not (or root
  821. (null file)
  822. ;; FIXME: Disabled this heuristic because it is sometimes
  823. ;; inappropriate.
  824. ;; As a heuristic, we stop looking up the hierarchy of
  825. ;; directories as soon as we find a directory belonging
  826. ;; to another user. This should save us from looking in
  827. ;; things like /net and /afs. This assumes that all the
  828. ;; files inside a project belong to the same user.
  829. ;; (let ((prev-user user))
  830. ;; (setq user (nth 2 (file-attributes file)))
  831. ;; (and prev-user (not (equal user prev-user))))
  832. (string-match locate-dominating-stop-dir-regexp file)))
  833. (setq try (if (stringp name)
  834. (file-exists-p (expand-file-name name file))
  835. (funcall name file)))
  836. (cond (try (setq root file))
  837. ((equal file (setq file (file-name-directory
  838. (directory-file-name file))))
  839. (setq file nil))))
  840. (if root (file-name-as-directory root))))
  841. (defcustom user-emacs-directory-warning t
  842. "Non-nil means warn if cannot access `user-emacs-directory'.
  843. Set this to nil at your own risk..."
  844. :type 'boolean
  845. :group 'initialization
  846. :version "24.4")
  847. (defun locate-user-emacs-file (new-name &optional old-name)
  848. "Return an absolute per-user Emacs-specific file name.
  849. If NEW-NAME exists in `user-emacs-directory', return it.
  850. Else if OLD-NAME is non-nil and ~/OLD-NAME exists, return ~/OLD-NAME.
  851. Else return NEW-NAME in `user-emacs-directory', creating the
  852. directory if it does not exist."
  853. (convert-standard-filename
  854. (let* ((home (concat "~" (or init-file-user "")))
  855. (at-home (and old-name (expand-file-name old-name home)))
  856. (bestname (abbreviate-file-name
  857. (expand-file-name new-name user-emacs-directory))))
  858. (if (and at-home (not (file-readable-p bestname))
  859. (file-readable-p at-home))
  860. at-home
  861. ;; Make sure `user-emacs-directory' exists,
  862. ;; unless we're in batch mode or dumping Emacs.
  863. (or noninteractive
  864. purify-flag
  865. (let (errtype)
  866. (if (file-directory-p user-emacs-directory)
  867. (or (file-accessible-directory-p user-emacs-directory)
  868. (setq errtype "access"))
  869. (with-file-modes ?\700
  870. (condition-case nil
  871. (make-directory user-emacs-directory)
  872. (error (setq errtype "create")))))
  873. (when (and errtype
  874. user-emacs-directory-warning
  875. (not (get 'user-emacs-directory-warning 'this-session)))
  876. ;; Only warn once per Emacs session.
  877. (put 'user-emacs-directory-warning 'this-session t)
  878. (display-warning 'initialization
  879. (format "\
  880. Unable to %s `user-emacs-directory' (%s).
  881. Any data that would normally be written there may be lost!
  882. If you never want to see this message again,
  883. customize the variable `user-emacs-directory-warning'."
  884. errtype user-emacs-directory)))))
  885. bestname))))
  886. (defun executable-find (command)
  887. "Search for COMMAND in `exec-path' and return the absolute file name.
  888. Return nil if COMMAND is not found anywhere in `exec-path'."
  889. ;; Use 1 rather than file-executable-p to better match the behavior of
  890. ;; call-process.
  891. (locate-file command exec-path exec-suffixes 1))
  892. (defun load-library (library)
  893. "Load the Emacs Lisp library named LIBRARY.
  894. This is an interface to the function `load'. LIBRARY is searched
  895. for in `load-path', both with and without `load-suffixes' (as
  896. well as `load-file-rep-suffixes').
  897. See Info node `(emacs)Lisp Libraries' for more details.
  898. See `load-file' for a different interface to `load'."
  899. (interactive
  900. (list (completing-read "Load library: "
  901. (apply-partially 'locate-file-completion-table
  902. load-path
  903. (get-load-suffixes)))))
  904. (load library))
  905. (defun file-remote-p (file &optional identification connected)
  906. "Test whether FILE specifies a location on a remote system.
  907. A file is considered remote if accessing it is likely to
  908. be slower or less reliable than accessing local files.
  909. `file-remote-p' never opens a new remote connection. It can
  910. only reuse a connection that is already open.
  911. Return nil or a string identifying the remote connection
  912. \(ideally a prefix of FILE). Return nil if FILE is a relative
  913. file name.
  914. When IDENTIFICATION is nil, the returned string is a complete
  915. remote identifier: with components method, user, and host. The
  916. components are those present in FILE, with defaults filled in for
  917. any that are missing.
  918. IDENTIFICATION can specify which part of the identification to
  919. return. IDENTIFICATION can be the symbol `method', `user',
  920. `host', or `localname'. Any other value is handled like nil and
  921. means to return the complete identification. The string returned
  922. for IDENTIFICATION `localname' can differ depending on whether
  923. there is an existing connection.
  924. If CONNECTED is non-nil, return an identification only if FILE is
  925. located on a remote system and a connection is established to
  926. that remote system.
  927. Tip: You can use this expansion of remote identifier components
  928. to derive a new remote file name from an existing one. For
  929. example, if FILE is \"/sudo::/path/to/file\" then
  930. (concat (file-remote-p FILE) \"/bin/sh\")
  931. returns a remote file name for file \"/bin/sh\" that has the
  932. same remote identifier as FILE but expanded; a name such as
  933. \"/sudo:root@myhost:/bin/sh\"."
  934. (let ((handler (find-file-name-handler file 'file-remote-p)))
  935. (if handler
  936. (funcall handler 'file-remote-p file identification connected)
  937. nil)))
  938. ;; Probably this entire variable should be obsolete now, in favor of
  939. ;; something Tramp-related (?). It is not used in many places.
  940. ;; It's not clear what the best file for this to be in is, but given
  941. ;; it uses custom-initialize-delay, it is easier if it is preloaded
  942. ;; rather than autoloaded.
  943. (defcustom remote-shell-program
  944. ;; This used to try various hard-coded places for remsh, rsh, and
  945. ;; rcmd, trying to guess based on location whether "rsh" was
  946. ;; "restricted shell" or "remote shell", but I don't see the point
  947. ;; in this day and age. Almost everyone will use ssh, and have
  948. ;; whatever command they want to use in PATH.
  949. (purecopy
  950. (let ((list '("ssh" "remsh" "rcmd" "rsh")))
  951. (while (and list
  952. (not (executable-find (car list)))
  953. (setq list (cdr list))))
  954. (or (car list) "ssh")))
  955. "Program to use to execute commands on a remote host (e.g. ssh or rsh)."
  956. :version "24.3" ; ssh rather than rsh, etc
  957. :initialize 'custom-initialize-delay
  958. :group 'environment
  959. :type 'file)
  960. (defcustom remote-file-name-inhibit-cache 10
  961. "Whether to use the remote file-name cache for read access.
  962. When nil, never expire cached values (caution)
  963. When t, never use the cache (safe, but may be slow)
  964. A number means use cached values for that amount of seconds since caching.
  965. The attributes of remote files are cached for better performance.
  966. If they are changed outside of Emacs's control, the cached values
  967. become invalid, and must be reread. If you are sure that nothing
  968. other than Emacs changes the files, you can set this variable to nil.
  969. If a remote file is checked regularly, it might be a good idea to
  970. let-bind this variable to a value less than the interval between
  971. consecutive checks. For example:
  972. (defun display-time-file-nonempty-p (file)
  973. (let ((remote-file-name-inhibit-cache (- display-time-interval 5)))
  974. (and (file-exists-p file)
  975. (< 0 (nth 7 (file-attributes (file-chase-links file)))))))"
  976. :group 'files
  977. :version "24.1"
  978. :type `(choice
  979. (const :tag "Do not inhibit file name cache" nil)
  980. (const :tag "Do not use file name cache" t)
  981. (integer :tag "Do not use file name cache"
  982. :format "Do not use file name cache older then %v seconds"
  983. :value 10)))
  984. (defun file-local-copy (file)
  985. "Copy the file FILE into a temporary file on this machine.
  986. Returns the name of the local copy, or nil, if FILE is directly
  987. accessible."
  988. ;; This formerly had an optional BUFFER argument that wasn't used by
  989. ;; anything.
  990. (let ((handler (find-file-name-handler file 'file-local-copy)))
  991. (if handler
  992. (funcall handler 'file-local-copy file)
  993. nil)))
  994. (defun file-truename (filename &optional counter prev-dirs)
  995. "Return the truename of FILENAME.
  996. If FILENAME is not absolute, first expands it against `default-directory'.
  997. The truename of a file name is found by chasing symbolic links
  998. both at the level of the file and at the level of the directories
  999. containing it, until no links are left at any level.
  1000. \(fn FILENAME)" ;; Don't document the optional arguments.
  1001. ;; COUNTER and PREV-DIRS are only used in recursive calls.
  1002. ;; COUNTER can be a cons cell whose car is the count of how many
  1003. ;; more links to chase before getting an error.
  1004. ;; PREV-DIRS can be a cons cell whose car is an alist
  1005. ;; of truenames we've just recently computed.
  1006. (cond ((or (string= filename "") (string= filename "~"))
  1007. (setq filename (expand-file-name filename))
  1008. (if (string= filename "")
  1009. (setq filename "/")))
  1010. ((and (string= (substring filename 0 1) "~")
  1011. (string-match "~[^/]*/?" filename))
  1012. (let ((first-part
  1013. (substring filename 0 (match-end 0)))
  1014. (rest (substring filename (match-end 0))))
  1015. (setq filename (concat (expand-file-name first-part) rest)))))
  1016. (or counter (setq counter (list 100)))
  1017. (let (done
  1018. ;; For speed, remove the ange-ftp completion handler from the list.
  1019. ;; We know it's not needed here.
  1020. ;; For even more speed, do this only on the outermost call.
  1021. (file-name-handler-alist
  1022. (if prev-dirs file-name-handler-alist
  1023. (let ((tem (copy-sequence file-name-handler-alist)))
  1024. (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
  1025. (or prev-dirs (setq prev-dirs (list nil)))
  1026. ;; andrewi@harlequin.co.uk - on Windows, there is an issue with
  1027. ;; case differences being ignored by the OS, and short "8.3 DOS"
  1028. ;; name aliases existing for all files. (The short names are not
  1029. ;; reported by directory-files, but can be used to refer to files.)
  1030. ;; It seems appropriate for file-truename to resolve these issues in
  1031. ;; the most natural way, which on Windows is to call the function
  1032. ;; `w32-long-file-name' - this returns the exact name of a file as
  1033. ;; it is stored on disk (expanding short name aliases with the full
  1034. ;; name in the process).
  1035. (if (eq system-type 'windows-nt)
  1036. (unless (string-match "[[*?]" filename)
  1037. ;; If filename exists, use its long name. If it doesn't
  1038. ;; exist, the recursion below on the directory of filename
  1039. ;; will drill down until we find a directory that exists,
  1040. ;; and use the long name of that, with the extra
  1041. ;; non-existent path components concatenated.
  1042. (let ((longname (w32-long-file-name filename)))
  1043. (if longname
  1044. (setq filename longname)))))
  1045. ;; If this file directly leads to a link, process that iteratively
  1046. ;; so that we don't use lots of stack.
  1047. (while (not done)
  1048. (setcar counter (1- (car counter)))
  1049. (if (< (car counter) 0)
  1050. (error "Apparent cycle of symbolic links for %s" filename))
  1051. (let ((handler (find-file-name-handler filename 'file-truename)))
  1052. ;; For file name that has a special handler, call handler.
  1053. ;; This is so that ange-ftp can save time by doing a no-op.
  1054. (if handler
  1055. (setq filename (funcall handler 'file-truename filename)
  1056. done t)
  1057. (let ((dir (or (file-name-directory filename) default-directory))
  1058. target dirfile)
  1059. ;; Get the truename of the directory.
  1060. (setq dirfile (directory-file-name dir))
  1061. ;; If these are equal, we have the (or a) root directory.
  1062. (or (string= dir dirfile)
  1063. (and (memq system-type '(windows-nt ms-dos cygwin nacl))
  1064. (eq (compare-strings dir 0 nil dirfile 0 nil t) t))
  1065. ;; If this is the same dir we last got the truename for,
  1066. ;; save time--don't recalculate.
  1067. (if (assoc dir (car prev-dirs))
  1068. (setq dir (cdr (assoc dir (car prev-dirs))))
  1069. (let ((old dir)
  1070. (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
  1071. (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
  1072. (setq dir new))))
  1073. (if (equal ".." (file-name-nondirectory filename))
  1074. (setq filename
  1075. (directory-file-name (file-name-directory (directory-file-name dir)))
  1076. done t)
  1077. (if (equal "." (file-name-nondirectory filename))
  1078. (setq filename (directory-file-name dir)
  1079. done t)
  1080. ;; Put it back on the file name.
  1081. (setq filename (concat dir (file-name-nondirectory filename)))
  1082. ;; Is the file name the name of a link?
  1083. (setq target (file-symlink-p filename))
  1084. (if target
  1085. ;; Yes => chase that link, then start all over
  1086. ;; since the link may point to a directory name that uses links.
  1087. ;; We can't safely use expand-file-name here
  1088. ;; since target might look like foo/../bar where foo
  1089. ;; is itself a link. Instead, we handle . and .. above.
  1090. (setq filename
  1091. (if (file-name-absolute-p target)
  1092. target
  1093. (concat dir target))
  1094. done nil)
  1095. ;; No, we are done!
  1096. (setq done t))))))))
  1097. filename))
  1098. (defun file-chase-links (filename &optional limit)
  1099. "Chase links in FILENAME until a name that is not a link.
  1100. Unlike `file-truename', this does not check whether a parent
  1101. directory name is a symbolic link.
  1102. If the optional argument LIMIT is a number,
  1103. it means chase no more than that many links and then stop."
  1104. (let (tem (newname filename)
  1105. (count 0))
  1106. (while (and (or (null limit) (< count limit))
  1107. (setq tem (file-symlink-p newname)))
  1108. (save-match-data
  1109. (if (and (null limit) (= count 100))
  1110. (error "Apparent cycle of symbolic links for %s" filename))
  1111. ;; In the context of a link, `//' doesn't mean what Emacs thinks.
  1112. (while (string-match "//+" tem)
  1113. (setq tem (replace-match "/" nil nil tem)))
  1114. ;; Handle `..' by hand, since it needs to work in the
  1115. ;; target of any directory symlink.
  1116. ;; This code is not quite complete; it does not handle
  1117. ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
  1118. (while (string-match "\\`\\.\\./" tem)
  1119. (setq tem (substring tem 3))
  1120. (setq newname (expand-file-name newname))
  1121. ;; Chase links in the default dir of the symlink.
  1122. (setq newname
  1123. (file-chase-links
  1124. (directory-file-name (file-name-directory newname))))
  1125. ;; Now find the parent of that dir.
  1126. (setq newname (file-name-directory newname)))
  1127. (setq newname (expand-file-name tem (file-name-directory newname)))
  1128. (setq count (1+ count))))
  1129. newname))
  1130. ;; A handy function to display file sizes in human-readable form.
  1131. ;; See http://en.wikipedia.org/wiki/Kibibyte for the reference.
  1132. (defun file-size-human-readable (file-size &optional flavor)
  1133. "Produce a string showing FILE-SIZE in human-readable form.
  1134. Optional second argument FLAVOR controls the units and the display format:
  1135. If FLAVOR is nil or omitted, each kilobyte is 1024 bytes and the produced
  1136. suffixes are \"k\", \"M\", \"G\", \"T\", etc.
  1137. If FLAVOR is `si', each kilobyte is 1000 bytes and the produced suffixes
  1138. are \"k\", \"M\", \"G\", \"T\", etc.
  1139. If FLAVOR is `iec', each kilobyte is 1024 bytes and the produced suffixes
  1140. are \"KiB\", \"MiB\", \"GiB\", \"TiB\", etc."
  1141. (let ((power (if (or (null flavor) (eq flavor 'iec))
  1142. 1024.0
  1143. 1000.0))
  1144. (post-fixes
  1145. ;; none, kilo, mega, giga, tera, peta, exa, zetta, yotta
  1146. (list "" "k" "M" "G" "T" "P" "E" "Z" "Y")))
  1147. (while (and (>= file-size power) (cdr post-fixes))
  1148. (setq file-size (/ file-size power)
  1149. post-fixes (cdr post-fixes)))
  1150. (format (if (> (mod file-size 1.0) 0.05)
  1151. "%.1f%s%s"
  1152. "%.0f%s%s")
  1153. file-size
  1154. (if (and (eq flavor 'iec) (string= (car post-fixes) "k"))
  1155. "K"
  1156. (car post-fixes))
  1157. (if (eq flavor 'iec) "iB" ""))))
  1158. (defun make-temp-file (prefix &optional dir-flag suffix)
  1159. "Create a temporary file.
  1160. The returned file name (created by appending some random characters at the end
  1161. of PREFIX, and expanding against `temporary-file-directory' if necessary),
  1162. is guaranteed to point to a newly created empty file.
  1163. You can then use `write-region' to write new data into the file.
  1164. If DIR-FLAG is non-nil, create a new empty directory instead of a file.
  1165. If SUFFIX is non-nil, add that at the end of the file name."
  1166. ;; Create temp files with strict access rights. It's easy to
  1167. ;; loosen them later, whereas it's impossible to close the
  1168. ;; time-window of loose permissions otherwise.
  1169. (with-file-modes ?\700
  1170. (let (file)
  1171. (while (condition-case ()
  1172. (progn
  1173. (setq file
  1174. (make-temp-name
  1175. (if (zerop (length prefix))
  1176. (file-name-as-directory
  1177. temporary-file-directory)
  1178. (expand-file-name prefix
  1179. temporary-file-directory))))
  1180. (if suffix
  1181. (setq file (concat file suffix)))
  1182. (if dir-flag
  1183. (make-directory file)
  1184. (write-region "" nil file nil 'silent nil 'excl))
  1185. nil)
  1186. (file-already-exists t))
  1187. ;; the file was somehow created by someone else between
  1188. ;; `make-temp-name' and `write-region', let's try again.
  1189. nil)
  1190. file)))
  1191. (defun recode-file-name (file coding new-coding &optional ok-if-already-exists)
  1192. "Change the encoding of FILE's name from CODING to NEW-CODING.
  1193. The value is a new name of FILE.
  1194. Signals a `file-already-exists' error if a file of the new name
  1195. already exists unless optional fourth argument OK-IF-ALREADY-EXISTS
  1196. is non-nil. A number as fourth arg means request confirmation if
  1197. the new name already exists. This is what happens in interactive
  1198. use with M-x."
  1199. (interactive
  1200. (let ((default-coding (or file-name-coding-system
  1201. default-file-name-coding-system))
  1202. (filename (read-file-name "Recode filename: " nil nil t))
  1203. from-coding to-coding)
  1204. (if (and default-coding
  1205. ;; We provide the default coding only when it seems that
  1206. ;; the filename is correctly decoded by the default
  1207. ;; coding.
  1208. (let ((charsets (find-charset-string filename)))
  1209. (and (not (memq 'eight-bit-control charsets))
  1210. (not (memq 'eight-bit-graphic charsets)))))
  1211. (setq from-coding (read-coding-system
  1212. (format "Recode filename %s from (default %s): "
  1213. filename default-coding)
  1214. default-coding))
  1215. (setq from-coding (read-coding-system
  1216. (format "Recode filename %s from: " filename))))
  1217. ;; We provide the default coding only when a user is going to
  1218. ;; change the encoding not from the default coding.
  1219. (if (eq from-coding default-coding)
  1220. (setq to-coding (read-coding-system
  1221. (format "Recode filename %s from %s to: "
  1222. filename from-coding)))
  1223. (setq to-coding (read-coding-system
  1224. (format "Recode filename %s from %s to (default %s): "
  1225. filename from-coding default-coding)
  1226. default-coding)))
  1227. (list filename from-coding to-coding)))
  1228. (let* ((default-coding (or file-name-coding-system
  1229. default-file-name-coding-system))
  1230. ;; FILE should have been decoded by DEFAULT-CODING.
  1231. (encoded (encode-coding-string file default-coding))
  1232. (newname (decode-coding-string encoded coding))
  1233. (new-encoded (encode-coding-string newname new-coding))
  1234. ;; Suppress further encoding.
  1235. (file-name-coding-system nil)
  1236. (default-file-name-coding-system nil)
  1237. (locale-coding-system nil))
  1238. (rename-file encoded new-encoded ok-if-already-exists)
  1239. newname))
  1240. (defcustom confirm-nonexistent-file-or-buffer 'after-completion
  1241. "Whether confirmation is requested before visiting a new file or buffer.
  1242. If nil, confirmation is not requested.
  1243. If the value is `after-completion', confirmation is only
  1244. requested if the user called `minibuffer-complete' right before
  1245. `minibuffer-complete-and-exit'.
  1246. Any other non-nil value means to request confirmation.
  1247. This affects commands like `switch-to-buffer' and `find-file'."
  1248. :group 'find-file
  1249. :version "23.1"
  1250. :type '(choice (const :tag "After completion" after-completion)
  1251. (const :tag "Never" nil)
  1252. (other :tag "Always" t)))
  1253. (defun confirm-nonexistent-file-or-buffer ()
  1254. "Whether to request confirmation before visiting a new file or buffer.
  1255. The variable `confirm-nonexistent-file-or-buffer' determines the
  1256. return value, which may be passed as the REQUIRE-MATCH arg to
  1257. `read-buffer' or `find-file-read-args'."
  1258. (cond ((eq confirm-nonexistent-file-or-buffer 'after-completion)
  1259. 'confirm-after-completion)
  1260. (confirm-nonexistent-file-or-buffer
  1261. 'confirm)
  1262. (t nil)))
  1263. (defmacro minibuffer-with-setup-hook (fun &rest body)
  1264. "Temporarily add FUN to `minibuffer-setup-hook' while executing BODY.
  1265. FUN can also be (:append FUN1), in which case FUN1 is appended to
  1266. `minibuffer-setup-hook'.
  1267. BODY should use the minibuffer at most once.
  1268. Recursive uses of the minibuffer are unaffected (FUN is not
  1269. called additional times).
  1270. This macro actually adds an auxiliary function that calls FUN,
  1271. rather than FUN itself, to `minibuffer-setup-hook'."
  1272. (declare (indent 1) (debug t))
  1273. (let ((hook (make-symbol "setup-hook"))
  1274. (funsym (make-symbol "fun"))
  1275. (append nil))
  1276. (when (eq (car-safe fun) :append)
  1277. (setq append '(t) fun (cadr fun)))
  1278. `(let ((,funsym ,fun)
  1279. ,hook)
  1280. (setq ,hook
  1281. (lambda ()
  1282. ;; Clear out this hook so it does not interfere
  1283. ;; with any recursive minibuffer usage.
  1284. (remove-hook 'minibuffer-setup-hook ,hook)
  1285. (funcall ,funsym)))
  1286. (unwind-protect
  1287. (progn
  1288. (add-hook 'minibuffer-setup-hook ,hook ,@append)
  1289. ,@body)
  1290. (remove-hook 'minibuffer-setup-hook ,hook)))))
  1291. (defun find-file-read-args (prompt mustmatch)
  1292. (list (read-file-name prompt nil default-directory mustmatch)
  1293. t))
  1294. (defun find-file (filename &optional wildcards)
  1295. "Edit file FILENAME.
  1296. Switch to a buffer visiting file FILENAME,
  1297. creating one if none already exists.
  1298. Interactively, the default if you just type RET is the current directory,
  1299. but the visited file name is available through the minibuffer history:
  1300. type M-n to pull it into the minibuffer.
  1301. You can visit files on remote machines by specifying something
  1302. like /ssh:SOME_REMOTE_MACHINE:FILE for the file name. You can
  1303. also visit local files as a different user by specifying
  1304. /sudo::FILE for the file name.
  1305. See the Info node `(tramp)File name Syntax' in the Tramp Info
  1306. manual, for more about this.
  1307. Interactively, or if WILDCARDS is non-nil in a call from Lisp,
  1308. expand wildcards (if any) and visit multiple files. You can
  1309. suppress wildcard expansion by setting `find-file-wildcards' to nil.
  1310. To visit a file without any kind of conversion and without
  1311. automatically choosing a major mode, use \\[find-file-literally]."
  1312. (interactive
  1313. (find-file-read-args "Find file: "
  1314. (confirm-nonexistent-file-or-buffer)))
  1315. (let ((value (find-file-noselect filename nil nil wildcards)))
  1316. (if (listp value)
  1317. (mapcar 'switch-to-buffer (nreverse value))
  1318. (switch-to-buffer value))))
  1319. (defun find-file-other-window (filename &optional wildcards)
  1320. "Edit file FILENAME, in another window.
  1321. Like \\[find-file] (which see), but creates a new window or reuses
  1322. an existing one. See the function `display-buffer'.
  1323. Interactively, the default if you just type RET is the current directory,
  1324. but the visited file name is available through the minibuffer history:
  1325. type M-n to pull it into the minibuffer.
  1326. Interactively, or if WILDCARDS is non-nil in a call from Lisp,
  1327. expand wildcards (if any) and visit multiple files."
  1328. (interactive
  1329. (find-file-read-args "Find file in other window: "
  1330. (confirm-nonexistent-file-or-buffer)))
  1331. (let ((value (find-file-noselect filename nil nil wildcards)))
  1332. (if (listp value)
  1333. (progn
  1334. (setq value (nreverse value))
  1335. (switch-to-buffer-other-window (car value))
  1336. (mapc 'switch-to-buffer (cdr value))
  1337. value)
  1338. (switch-to-buffer-other-window value))))
  1339. (defun find-file-other-frame (filename &optional wildcards)
  1340. "Edit file FILENAME, in another frame.
  1341. Like \\[find-file] (which see), but creates a new frame or reuses
  1342. an existing one. See the function `display-buffer'.
  1343. Interactively, the default if you just type RET is the current directory,
  1344. but the visited file name is available through the minibuffer history:
  1345. type M-n to pull it into the minibuffer.
  1346. Interactively, or if WILDCARDS is non-nil in a call from Lisp,
  1347. expand wildcards (if any) and visit multiple files."
  1348. (interactive
  1349. (find-file-read-args "Find file in other frame: "
  1350. (confirm-nonexistent-file-or-buffer)))
  1351. (let ((value (find-file-noselect filename nil nil wildcards)))
  1352. (if (listp value)
  1353. (progn
  1354. (setq value (nreverse value))
  1355. (switch-to-buffer-other-frame (car value))
  1356. (mapc 'switch-to-buffer (cdr value))
  1357. value)
  1358. (switch-to-buffer-other-frame value))))
  1359. (defun find-file-existing (filename)
  1360. "Edit the existing file FILENAME.
  1361. Like \\[find-file], but only allow a file that exists, and do not allow
  1362. file names with wildcards."
  1363. (interactive (nbutlast (find-file-read-args "Find existing file: " t)))
  1364. (if (and (not (called-interactively-p 'interactive))
  1365. (not (file-exists-p filename)))
  1366. (error "%s does not exist" filename)
  1367. (find-file filename)
  1368. (current-buffer)))
  1369. (defun find-file--read-only (fun filename wildcards)
  1370. (unless (or (and wildcards find-file-wildcards
  1371. (not (string-match "\\`/:" filename))
  1372. (string-match "[[*?]" filename))
  1373. (file-exists-p filename))
  1374. (error "%s does not exist" filename))
  1375. (let ((value (funcall fun filename wildcards)))
  1376. (mapc (lambda (b) (with-current-buffer b (read-only-mode 1)))
  1377. (if (listp value) value (list value)))
  1378. value))
  1379. (defun find-file-read-only (filename &optional wildcards)
  1380. "Edit file FILENAME but don't allow changes.
  1381. Like \\[find-file], but marks buffer as read-only.
  1382. Use \\[read-only-mode] to permit editing."
  1383. (interactive
  1384. (find-file-read-args "Find file read-only: "
  1385. (confirm-nonexistent-file-or-buffer)))
  1386. (find-file--read-only #'find-file filename wildcards))
  1387. (defun find-file-read-only-other-window (filename &optional wildcards)
  1388. "Edit file FILENAME in another window but don't allow changes.
  1389. Like \\[find-file-other-window], but marks buffer as read-only.
  1390. Use \\[read-only-mode] to permit editing."
  1391. (interactive
  1392. (find-file-read-args "Find file read-only other window: "
  1393. (confirm-nonexistent-file-or-buffer)))
  1394. (find-file--read-only #'find-file-other-window filename wildcards))
  1395. (defun find-file-read-only-other-frame (filename &optional wildcards)
  1396. "Edit file FILENAME in another frame but don't allow changes.
  1397. Like \\[find-file-other-frame], but marks buffer as read-only.
  1398. Use \\[read-only-mode] to permit editing."
  1399. (interactive
  1400. (find-file-read-args "Find file read-only other frame: "
  1401. (confirm-nonexistent-file-or-buffer)))
  1402. (find-file--read-only #'find-file-other-frame filename wildcards))
  1403. (defun find-alternate-file-other-window (filename &optional wildcards)
  1404. "Find file FILENAME as a replacement for the file in the next window.
  1405. This command does not select that window.
  1406. See \\[find-file] for the possible forms of the FILENAME argument.
  1407. Interactively, or if WILDCARDS is non-nil in a call from Lisp,
  1408. expand wildcards (if any) and replace the file with multiple files."
  1409. (interactive
  1410. (save-selected-window
  1411. (other-window 1)
  1412. (let ((file buffer-file-name)
  1413. (file-name nil)
  1414. (file-dir nil))
  1415. (and file
  1416. (setq file-name (file-name-nondirectory file)
  1417. file-dir (file-name-directory file)))
  1418. (list (read-file-name
  1419. "Find alternate file: " file-dir nil
  1420. (confirm-nonexistent-file-or-buffer) file-name)
  1421. t))))
  1422. (if (one-window-p)
  1423. (find-file-other-window filename wildcards)
  1424. (save-selected-window
  1425. (other-window 1)
  1426. (find-alternate-file filename wildcards))))
  1427. ;; Defined and used in buffer.c, but not as a DEFVAR_LISP.
  1428. (defvar kill-buffer-hook nil
  1429. "Hook run when a buffer is killed.
  1430. The buffer being killed is current while the hook is running.
  1431. See `kill-buffer'.
  1432. Note: Be careful with let-binding this hook considering it is
  1433. frequently used for cleanup.")
  1434. (defun find-alternate-file (filename &optional wildcards)
  1435. "Find file FILENAME, select its buffer, kill previous buffer.
  1436. If the current buffer now contains an empty file that you just visited
  1437. \(presumably by mistake), use this command to visit the file you really want.
  1438. See \\[find-file] for the possible forms of the FILENAME argument.
  1439. Interactively, or if WILDCARDS is non-nil in a call from Lisp,
  1440. expand wildcards (if any) and replace the file with multiple files.
  1441. If the current buffer is an indirect buffer, or the base buffer
  1442. for one or more indirect buffers, the other buffer(s) are not
  1443. killed."
  1444. (interactive
  1445. (let ((file buffer-file-name)
  1446. (file-name nil)
  1447. (file-dir nil))
  1448. (and file
  1449. (setq file-name (file-name-nondirectory file)
  1450. file-dir (file-name-directory file)))
  1451. (list (read-file-name
  1452. "Find alternate file: " file-dir nil
  1453. (confirm-nonexistent-file-or-buffer) file-name)
  1454. t)))
  1455. (unless (run-hook-with-args-until-failure 'kill-buffer-query-functions)
  1456. (user-error "Aborted"))
  1457. (and (buffer-modified-p) buffer-file-name
  1458. (not (yes-or-no-p
  1459. (format-message "Kill and replace buffer `%s' without saving it? "
  1460. (buffer-name))))
  1461. (user-error "Aborted"))
  1462. (let ((obuf (current-buffer))
  1463. (ofile buffer-file-name)
  1464. (onum buffer-file-number)
  1465. (odir dired-directory)
  1466. (otrue buffer-file-truename)
  1467. (oname (buffer-name)))
  1468. ;; Run `kill-buffer-hook' here. It needs to happen before
  1469. ;; variables like `buffer-file-name' etc are set to nil below,
  1470. ;; because some of the hooks that could be invoked
  1471. ;; (e.g., `save-place-to-alist') depend on those variables.
  1472. ;;
  1473. ;; Note that `kill-buffer-hook' is not what queries whether to
  1474. ;; save a modified buffer visiting a file. Rather, `kill-buffer'
  1475. ;; asks that itself. Thus, there's no need to temporarily do
  1476. ;; `(set-buffer-modified-p nil)' before running this hook.
  1477. (run-hooks 'kill-buffer-hook)
  1478. ;; Okay, now we can end-of-life the old buffer.
  1479. (if (get-buffer " **lose**")
  1480. (kill-buffer " **lose**"))
  1481. (rename-buffer " **lose**")
  1482. (unwind-protect
  1483. (progn
  1484. (unlock-buffer)
  1485. ;; This prevents us from finding the same buffer
  1486. ;; if we specified the same file again.
  1487. (setq buffer-file-name nil)
  1488. (setq buffer-file-number nil)
  1489. (setq buffer-file-truename nil)
  1490. ;; Likewise for dired buffers.
  1491. (setq dired-directory nil)
  1492. (find-file filename wildcards))
  1493. (when (eq obuf (current-buffer))
  1494. ;; This executes if find-file gets an error
  1495. ;; and does not really find anything.
  1496. ;; We put things back as they were.
  1497. ;; If find-file actually finds something, we kill obuf below.
  1498. (setq buffer-file-name ofile)
  1499. (setq buffer-file-number onum)
  1500. (setq buffer-file-truename otrue)
  1501. (setq dired-directory odir)
  1502. (lock-buffer)
  1503. (rename-buffer oname)))
  1504. (unless (eq (current-buffer) obuf)
  1505. (with-current-buffer obuf
  1506. ;; We already ran these; don't run them again.
  1507. (let (kill-buffer-query-functions kill-buffer-hook)
  1508. (kill-buffer obuf))))))
  1509. ;; FIXME we really need to fold the uniquify stuff in here by default,
  1510. ;; not using advice, and add it to the doc string.
  1511. (defun create-file-buffer (filename)
  1512. "Create a suitably named buffer for visiting FILENAME, and return it.
  1513. FILENAME (sans directory) is used unchanged if that name is free;
  1514. otherwise a string <2> or <3> or ... is appended to get an unused name.
  1515. Emacs treats buffers whose names begin with a space as internal buffers.
  1516. To avoid confusion when visiting a file whose name begins with a space,
  1517. this function prepends a \"|\" to the final result if necessary."
  1518. (let ((lastname (file-name-nondirectory filename)))
  1519. (if (string= lastname "")
  1520. (setq lastname filename))
  1521. (generate-new-buffer (if (string-match-p "\\` " lastname)
  1522. (concat "|" lastname)
  1523. lastname))))
  1524. (defun generate-new-buffer (name)
  1525. "Create and return a buffer with a name based on NAME.
  1526. Choose the buffer's name using `generate-new-buffer-name'."
  1527. (get-buffer-create (generate-new-buffer-name name)))
  1528. (defcustom automount-dir-prefix (purecopy "^/tmp_mnt/")
  1529. "Regexp to match the automounter prefix in a directory name."
  1530. :group 'files
  1531. :type 'regexp)
  1532. (make-obsolete-variable 'automount-dir-prefix 'directory-abbrev-alist "24.3")
  1533. (defvar abbreviated-home-dir nil
  1534. "The user's homedir abbreviated according to `directory-abbrev-alist'.")
  1535. (defun abbreviate-file-name (filename)
  1536. "Return a version of FILENAME shortened using `directory-abbrev-alist'.
  1537. This also substitutes \"~\" for the user's home directory (unless the
  1538. home directory is a root directory) and removes automounter prefixes
  1539. \(see the variable `automount-dir-prefix')."
  1540. ;; Get rid of the prefixes added by the automounter.
  1541. (save-match-data
  1542. (if (and automount-dir-prefix
  1543. (string-match automount-dir-prefix filename)
  1544. (file-exists-p (file-name-directory
  1545. (substring filename (1- (match-end 0))))))
  1546. (setq filename (substring filename (1- (match-end 0)))))
  1547. ;; Avoid treating /home/foo as /home/Foo during `~' substitution.
  1548. ;; To fix this right, we need a `file-name-case-sensitive-p'
  1549. ;; function, but we don't have that yet, so just guess.
  1550. (let ((case-fold-search
  1551. (memq system-type '(ms-dos windows-nt darwin cygwin))))
  1552. ;; If any elt of directory-abbrev-alist matches this name,
  1553. ;; abbreviate accordingly.
  1554. (dolist (dir-abbrev directory-abbrev-alist)
  1555. (if (string-match (car dir-abbrev) filename)
  1556. (setq filename
  1557. (concat (cdr dir-abbrev)
  1558. (substring filename (match-end 0))))))
  1559. ;; Compute and save the abbreviated homedir name.
  1560. ;; We defer computing this until the first time it's needed, to
  1561. ;; give time for directory-abbrev-alist to be set properly.
  1562. ;; We include a slash at the end, to avoid spurious matches
  1563. ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
  1564. (or abbreviated-home-dir
  1565. (setq abbreviated-home-dir
  1566. (let ((abbreviated-home-dir "$foo"))
  1567. (concat "\\`" (abbreviate-file-name (expand-file-name "~"))
  1568. "\\(/\\|\\'\\)"))))
  1569. ;; If FILENAME starts with the abbreviated homedir,
  1570. ;; make it start with `~' instead.
  1571. (if (and (string-match abbreviated-home-dir filename)
  1572. ;; If the home dir is just /, don't change it.
  1573. (not (and (= (match-end 0) 1)
  1574. (= (aref filename 0) ?/)))
  1575. ;; MS-DOS root directories can come with a drive letter;
  1576. ;; Novell Netware allows drive letters beyond `Z:'.
  1577. (not (and (memq system-type '(ms-dos windows-nt cygwin))
  1578. (save-match-data
  1579. (string-match "^[a-zA-`]:/$" filename)))))
  1580. (setq filename
  1581. (concat "~"
  1582. (match-string 1 filename)
  1583. (substring filename (match-end 0)))))
  1584. filename)))
  1585. (defun find-buffer-visiting (filename &optional predicate)
  1586. "Return the buffer visiting file FILENAME (a string).
  1587. This is like `get-file-buffer', except that it checks for any buffer
  1588. visiting the same file, possibly under a different name.
  1589. If PREDICATE is non-nil, only buffers satisfying it are eligible,
  1590. and others are ignored.
  1591. If there is no such live buffer, return nil."
  1592. (let ((predicate (or predicate #'identity))
  1593. (truename (abbreviate-file-name (file-truename filename))))
  1594. (or (let ((buf (get-file-buffer filename)))
  1595. (when (and buf (funcall predicate buf)) buf))
  1596. (let ((list (buffer-list)) found)
  1597. (while (and (not found) list)
  1598. (with-current-buffer (car list)
  1599. (if (and buffer-file-name
  1600. (string= buffer-file-truename truename)
  1601. (funcall predicate (current-buffer)))
  1602. (setq found (car list))))
  1603. (setq list (cdr list)))
  1604. found)
  1605. (let* ((attributes (file-attributes truename))
  1606. (number (nthcdr 10 attributes))
  1607. (list (buffer-list)) found)
  1608. (and buffer-file-numbers-unique
  1609. (car-safe number) ;Make sure the inode is not just nil.
  1610. (while (and (not found) list)
  1611. (with-current-buffer (car list)
  1612. (if (and buffer-file-name
  1613. (equal buffer-file-number number)
  1614. ;; Verify this buffer's file number
  1615. ;; still belongs to its file.
  1616. (file-exists-p buffer-file-name)
  1617. (equal (file-attributes buffer-file-truename)
  1618. attributes)
  1619. (funcall predicate (current-buffer)))
  1620. (setq found (car list))))
  1621. (setq list (cdr list))))
  1622. found))))
  1623. (defcustom find-file-wildcards t
  1624. "Non-nil means file-visiting commands should handle wildcards.
  1625. For example, if you specify `*.c', that would visit all the files
  1626. whose names match the pattern."
  1627. :group 'files
  1628. :version "20.4"
  1629. :type 'boolean)
  1630. (defcustom find-file-suppress-same-file-warnings nil
  1631. "Non-nil means suppress warning messages for symlinked files.
  1632. When nil, Emacs prints a warning when visiting a file that is already
  1633. visited, but with a different name. Setting this option to t
  1634. suppresses this warning."
  1635. :group 'files
  1636. :version "21.1"
  1637. :type 'boolean)
  1638. (defcustom large-file-warning-threshold 10000000
  1639. "Maximum size of file above which a confirmation is requested.
  1640. When nil, never request confirmation."
  1641. :group 'files
  1642. :group 'find-file
  1643. :version "22.1"
  1644. :type '(choice integer (const :tag "Never request confirmation" nil)))
  1645. (defcustom out-of-memory-warning-percentage nil
  1646. "Warn if file size exceeds this percentage of available free memory.
  1647. When nil, never issue warning. Beware: This probably doesn't do what you
  1648. think it does, because \"free\" is pretty hard to define in practice."
  1649. :group 'files
  1650. :group 'find-file
  1651. :version "25.1"
  1652. :type '(choice integer (const :tag "Never issue warning" nil)))
  1653. (defun abort-if-file-too-large (size op-type filename)
  1654. "If file SIZE larger than `large-file-warning-threshold', allow user to abort.
  1655. OP-TYPE specifies the file operation being performed (for message to user)."
  1656. (when (and large-file-warning-threshold size
  1657. (> size large-file-warning-threshold)
  1658. (not (y-or-n-p (format "File %s is large (%s), really %s? "
  1659. (file-name-nondirectory filename)
  1660. (file-size-human-readable size) op-type))))
  1661. (user-error "Aborted")))
  1662. (defun warn-maybe-out-of-memory (size)
  1663. "Warn if an attempt to open file of SIZE bytes may run out of memory."
  1664. (when (and (numberp size) (not (zerop size))
  1665. (integerp out-of-memory-warning-percentage))
  1666. (let ((meminfo (memory-info)))
  1667. (when (consp meminfo)
  1668. (let ((total-free-memory (float (+ (nth 1 meminfo) (nth 3 meminfo)))))
  1669. (when (> (/ size 1024)
  1670. (/ (* total-free-memory out-of-memory-warning-percentage)
  1671. 100.0))
  1672. (warn
  1673. "You are trying to open a file whose size (%s)
  1674. exceeds the %S%% of currently available free memory (%s).
  1675. If that fails, try to open it with `find-file-literally'
  1676. \(but note that some characters might be displayed incorrectly)."
  1677. (file-size-human-readable size)
  1678. out-of-memory-warning-percentage
  1679. (file-size-human-readable (* total-free-memory 1024)))))))))
  1680. (defun files--message (format &rest args)
  1681. "Like `message', except sometimes don't print to minibuffer.
  1682. If the variable `save-silently' is non-nil, the message is not
  1683. displayed on the minibuffer."
  1684. (apply #'message format args)
  1685. (when save-silently (message nil)))
  1686. (defun find-file-noselect (filename &optional nowarn rawfile wildcards)
  1687. "Read file FILENAME into a buffer and return the buffer.
  1688. If a buffer exists visiting FILENAME, return that one, but
  1689. verify that the file has not changed since visited or saved.
  1690. The buffer is not selected, just returned to the caller.
  1691. Optional second arg NOWARN non-nil means suppress any warning messages.
  1692. Optional third arg RAWFILE non-nil means the file is read literally.
  1693. Optional fourth arg WILDCARDS non-nil means do wildcard processing
  1694. and visit all the matching files. When wildcards are actually
  1695. used and expanded, return a list of buffers that are visiting
  1696. the various files."
  1697. (setq filename
  1698. (abbreviate-file-name
  1699. (expand-file-name filename)))
  1700. (if (file-directory-p filename)
  1701. (or (and find-file-run-dired
  1702. (run-hook-with-args-until-success
  1703. 'find-directory-functions
  1704. (if find-file-visit-truename
  1705. (abbreviate-file-name (file-truename filename))
  1706. filename)))
  1707. (error "%s is a directory" filename))
  1708. (if (and wildcards
  1709. find-file-wildcards
  1710. (not (string-match "\\`/:" filename))
  1711. (string-match "[[*?]" filename))
  1712. (let ((files (condition-case nil
  1713. (file-expand-wildcards filename t)
  1714. (error (list filename))))
  1715. (find-file-wildcards nil))
  1716. (if (null files)
  1717. (find-file-noselect filename)
  1718. (mapcar #'find-file-noselect files)))
  1719. (let* ((buf (get-file-buffer filename))
  1720. (truename (abbreviate-file-name (file-truename filename)))
  1721. (attributes (file-attributes truename))
  1722. (number (nthcdr 10 attributes))
  1723. ;; Find any buffer for a file which has same truename.
  1724. (other (and (not buf) (find-buffer-visiting filename))))
  1725. ;; Let user know if there is a buffer with the same truename.
  1726. (if other
  1727. (progn
  1728. (or nowarn
  1729. find-file-suppress-same-file-warnings
  1730. (string-equal filename (buffer-file-name other))
  1731. (files--message "%s and %s are the same file"
  1732. filename (buffer-file-name other)))
  1733. ;; Optionally also find that buffer.
  1734. (if (or find-file-existing-other-name find-file-visit-truename)
  1735. (setq buf other))))
  1736. ;; Check to see if the file looks uncommonly large.
  1737. (when (not (or buf nowarn))
  1738. (abort-if-file-too-large (nth 7 attributes) "open" filename)
  1739. (warn-maybe-out-of-memory (nth 7 attributes)))
  1740. (if buf
  1741. ;; We are using an existing buffer.
  1742. (let (nonexistent)
  1743. (or nowarn
  1744. (verify-visited-file-modtime buf)
  1745. (cond ((not (file-exists-p filename))
  1746. (setq nonexistent t)
  1747. (message "File %s no longer exists!" filename))
  1748. ;; Certain files should be reverted automatically
  1749. ;; if they have changed on disk and not in the buffer.
  1750. ((and (not (buffer-modified-p buf))
  1751. (let ((tail revert-without-query)
  1752. (found nil))
  1753. (while tail
  1754. (if (string-match (car tail) filename)
  1755. (setq found t))
  1756. (setq tail (cdr tail)))
  1757. found))
  1758. (with-current-buffer buf
  1759. (message "Reverting file %s..." filename)
  1760. (revert-buffer t t)
  1761. (message "Reverting file %s...done" filename)))
  1762. ((yes-or-no-p
  1763. (if (string= (file-name-nondirectory filename)
  1764. (buffer-name buf))
  1765. (format
  1766. (if (buffer-modified-p buf)
  1767. "File %s changed on disk. Discard your edits? "
  1768. "File %s changed on disk. Reread from disk? ")
  1769. (file-name-nondirectory filename))
  1770. (format
  1771. (if (buffer-modified-p buf)
  1772. "File %s changed on disk. Discard your edits in %s? "
  1773. "File %s changed on disk. Reread from disk into %s? ")
  1774. (file-name-nondirectory filename)
  1775. (buffer-name buf))))
  1776. (with-current-buffer buf
  1777. (revert-buffer t t)))))
  1778. (with-current-buffer buf
  1779. ;; Check if a formerly read-only file has become
  1780. ;; writable and vice versa, but if the buffer agrees
  1781. ;; with the new state of the file, that is ok too.
  1782. (let ((read-only (not (file-writable-p buffer-file-name))))
  1783. (unless (or nonexistent
  1784. (eq read-only buffer-file-read-only)
  1785. (eq read-only buffer-read-only))
  1786. (when (or nowarn
  1787. (let* ((new-status
  1788. (if read-only "read-only" "writable"))
  1789. (question
  1790. (format "File %s is %s on disk. Make buffer %s, too? "
  1791. buffer-file-name
  1792. new-status new-status)))
  1793. (y-or-n-p question)))
  1794. (setq buffer-read-only read-only)))
  1795. (setq buffer-file-read-only read-only))
  1796. (unless (or (eq (null rawfile) (null find-file-literally))
  1797. nonexistent
  1798. ;; It is confusing to ask whether to visit
  1799. ;; non-literally if they have the file in
  1800. ;; hexl-mode or image-mode.
  1801. (memq major-mode '(hexl-mode image-mode)))
  1802. (if (buffer-modified-p)
  1803. (if (y-or-n-p
  1804. (format
  1805. (if rawfile
  1806. "The file %s is already visited normally,
  1807. and you have edited the buffer. Now you have asked to visit it literally,
  1808. meaning no coding system handling, format conversion, or local variables.
  1809. Emacs can only visit a file in one way at a time.
  1810. Do you want to save the file, and visit it literally instead? "
  1811. "The file %s is already visited literally,
  1812. meaning no coding system handling, format conversion, or local variables.
  1813. You have edited the buffer. Now you have asked to visit the file normally,
  1814. but Emacs can only visit a file in one way at a time.
  1815. Do you want to save the file, and visit it normally instead? ")
  1816. (file-name-nondirectory filename)))
  1817. (progn
  1818. (save-buffer)
  1819. (find-file-noselect-1 buf filename nowarn
  1820. rawfile truename number))
  1821. (if (y-or-n-p
  1822. (format
  1823. (if rawfile
  1824. "\
  1825. Do you want to discard your changes, and visit the file literally now? "
  1826. "\
  1827. Do you want to discard your changes, and visit the file normally now? ")))
  1828. (find-file-noselect-1 buf filename nowarn
  1829. rawfile truename number)
  1830. (error (if rawfile "File already visited non-literally"
  1831. "File already visited literally"))))
  1832. (if (y-or-n-p
  1833. (format
  1834. (if rawfile
  1835. "The file %s is already visited normally.
  1836. You have asked to visit it literally,
  1837. meaning no coding system decoding, format conversion, or local variables.
  1838. But Emacs can only visit a file in one way at a time.
  1839. Do you want to revisit the file literally now? "
  1840. "The file %s is already visited literally,
  1841. meaning no coding system decoding, format conversion, or local variables.
  1842. You have asked to visit it normally,
  1843. but Emacs can only visit a file in one way at a time.
  1844. Do you want to revisit the file normally now? ")
  1845. (file-name-nondirectory filename)))
  1846. (find-file-noselect-1 buf filename nowarn
  1847. rawfile truename number)
  1848. (error (if rawfile "File already visited non-literally"
  1849. "File already visited literally"))))))
  1850. ;; Return the buffer we are using.
  1851. buf)
  1852. ;; Create a new buffer.
  1853. (setq buf (create-file-buffer filename))
  1854. ;; find-file-noselect-1 may use a different buffer.
  1855. (find-file-noselect-1 buf filename nowarn
  1856. rawfile truename number))))))
  1857. (defun find-file-noselect-1 (buf filename nowarn rawfile truename number)
  1858. (let (error)
  1859. (with-current-buffer buf
  1860. (kill-local-variable 'find-file-literally)
  1861. ;; Needed in case we are re-visiting the file with a different
  1862. ;; text representation.
  1863. (kill-local-variable 'buffer-file-coding-system)
  1864. (kill-local-variable 'cursor-type)
  1865. (let ((inhibit-read-only t))
  1866. (erase-buffer))
  1867. (and (default-value 'enable-multibyte-characters)
  1868. (not rawfile)
  1869. (set-buffer-multibyte t))
  1870. (if rawfile
  1871. (condition-case ()
  1872. (let ((inhibit-read-only t))
  1873. (insert-file-contents-literally filename t))
  1874. (file-error
  1875. (when (and (file-exists-p filename)
  1876. (not (file-readable-p filename)))
  1877. (kill-buffer buf)
  1878. (signal 'file-error (list "File is not readable"
  1879. filename)))
  1880. ;; Unconditionally set error
  1881. (setq error t)))
  1882. (condition-case ()
  1883. (let ((inhibit-read-only t))
  1884. (insert-file-contents filename t))
  1885. (file-error
  1886. (when (and (file-exists-p filename)
  1887. (not (file-readable-p filename)))
  1888. (kill-buffer buf)
  1889. (signal 'file-error (list "File is not readable"
  1890. filename)))
  1891. ;; Run find-file-not-found-functions until one returns non-nil.
  1892. (or (run-hook-with-args-until-success 'find-file-not-found-functions)
  1893. ;; If they fail too, set error.
  1894. (setq error t)))))
  1895. ;; Record the file's truename, and maybe use that as visited name.
  1896. (if (equal filename buffer-file-name)
  1897. (setq buffer-file-truename truename)
  1898. (setq buffer-file-truename
  1899. (abbreviate-file-name (file-truename buffer-file-name))))
  1900. (setq buffer-file-number number)
  1901. (if find-file-visit-truename
  1902. (setq buffer-file-name (expand-file-name buffer-file-truename)))
  1903. ;; Set buffer's default directory to that of the file.
  1904. (setq default-directory (file-name-directory buffer-file-name))
  1905. ;; Turn off backup files for certain file names. Since
  1906. ;; this is a permanent local, the major mode won't eliminate it.
  1907. (and backup-enable-predicate
  1908. (not (funcall backup-enable-predicate buffer-file-name))
  1909. (progn
  1910. (make-local-variable 'backup-inhibited)
  1911. (setq backup-inhibited t)))
  1912. (if rawfile
  1913. (progn
  1914. (set-buffer-multibyte nil)
  1915. (setq buffer-file-coding-system 'no-conversion)
  1916. (set-buffer-major-mode buf)
  1917. (setq-local find-file-literally t))
  1918. (after-find-file error (not nowarn)))
  1919. (current-buffer))))
  1920. (defun insert-file-contents-literally (filename &optional visit beg end replace)
  1921. "Like `insert-file-contents', but only reads in the file literally.
  1922. A buffer may be modified in several ways after reading into the buffer,
  1923. due to Emacs features such as format decoding, character code
  1924. conversion, `find-file-hook', automatic uncompression, etc.
  1925. This function ensures that none of these modifications will take place."
  1926. (let ((format-alist nil)
  1927. (after-insert-file-functions nil)
  1928. (coding-system-for-read 'no-conversion)
  1929. (coding-system-for-write 'no-conversion)
  1930. (inhibit-file-name-handlers
  1931. ;; FIXME: Yuck!! We should turn insert-file-contents-literally
  1932. ;; into a file operation instead!
  1933. (append '(jka-compr-handler image-file-handler epa-file-handler)
  1934. inhibit-file-name-handlers))
  1935. (inhibit-file-name-operation 'insert-file-contents))
  1936. (insert-file-contents filename visit beg end replace)))
  1937. (defun insert-file-1 (filename insert-func)
  1938. (if (file-directory-p filename)
  1939. (signal 'file-error (list "Opening input file" "Is a directory"
  1940. filename)))
  1941. ;; Check whether the file is uncommonly large
  1942. (abort-if-file-too-large (nth 7 (file-attributes filename)) "insert" filename)
  1943. (let* ((buffer (find-buffer-visiting (abbreviate-file-name (file-truename filename))
  1944. #'buffer-modified-p))
  1945. (tem (funcall insert-func filename)))
  1946. (push-mark (+ (point) (car (cdr tem))))
  1947. (when buffer
  1948. (message "File %s already visited and modified in buffer %s"
  1949. filename (buffer-name buffer)))))
  1950. (defun insert-file-literally (filename)
  1951. "Insert contents of file FILENAME into buffer after point with no conversion.
  1952. This function is meant for the user to run interactively.
  1953. Don't call it from programs! Use `insert-file-contents-literally' instead.
  1954. \(Its calling sequence is different; see its documentation)."
  1955. (declare (interactive-only insert-file-contents-literally))
  1956. (interactive "*fInsert file literally: ")
  1957. (insert-file-1 filename #'insert-file-contents-literally))
  1958. (defvar find-file-literally nil
  1959. "Non-nil if this buffer was made by `find-file-literally' or equivalent.
  1960. This has the `permanent-local' property, which takes effect if you
  1961. make the variable buffer-local.")
  1962. (put 'find-file-literally 'permanent-local t)
  1963. (defun find-file-literally (filename)
  1964. "Visit file FILENAME with no conversion of any kind.
  1965. Format conversion and character code conversion are both disabled,
  1966. and multibyte characters are disabled in the resulting buffer.
  1967. The major mode used is Fundamental mode regardless of the file name,
  1968. and local variable specifications in the file are ignored.
  1969. Automatic uncompression and adding a newline at the end of the
  1970. file due to `require-final-newline' is also disabled.
  1971. You cannot absolutely rely on this function to result in
  1972. visiting the file literally. If Emacs already has a buffer
  1973. which is visiting the file, you get the existing buffer,
  1974. regardless of whether it was created literally or not.
  1975. In a Lisp program, if you want to be sure of accessing a file's
  1976. contents literally, you should create a temporary buffer and then read
  1977. the file contents into it using `insert-file-contents-literally'."
  1978. (interactive
  1979. (list (read-file-name
  1980. "Find file literally: " nil default-directory
  1981. (confirm-nonexistent-file-or-buffer))))
  1982. (switch-to-buffer (find-file-noselect filename nil t)))
  1983. (defun after-find-file (&optional error warn noauto
  1984. _after-find-file-from-revert-buffer
  1985. nomodes)
  1986. "Called after finding a file and by the default revert function.
  1987. Sets buffer mode, parses local variables.
  1988. Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
  1989. error in reading the file. WARN non-nil means warn if there
  1990. exists an auto-save file more recent than the visited file.
  1991. NOAUTO means don't mess with auto-save mode.
  1992. Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER is ignored
  1993. \(see `revert-buffer-in-progress-p' for similar functionality).
  1994. Fifth arg NOMODES non-nil means don't alter the file's modes.
  1995. Finishes by calling the functions in `find-file-hook'
  1996. unless NOMODES is non-nil."
  1997. (setq buffer-read-only (not (file-writable-p buffer-file-name)))
  1998. (if noninteractive
  1999. nil
  2000. (let* (not-serious
  2001. (msg
  2002. (cond
  2003. ((not warn) nil)
  2004. ((and error (file-attributes buffer-file-name))
  2005. (setq buffer-read-only t)
  2006. (if (and (file-symlink-p buffer-file-name)
  2007. (not (file-exists-p
  2008. (file-chase-links buffer-file-name))))
  2009. "Symbolic link that points to nonexistent file"
  2010. "File exists, but cannot be read"))
  2011. ((not buffer-read-only)
  2012. (if (and warn
  2013. ;; No need to warn if buffer is auto-saved
  2014. ;; under the name of the visited file.
  2015. (not (and buffer-file-name
  2016. auto-save-visited-file-name))
  2017. (file-newer-than-file-p (or buffer-auto-save-file-name
  2018. (make-auto-save-file-name))
  2019. buffer-file-name))
  2020. (format "%s has auto save data; consider M-x recover-this-file"
  2021. (file-name-nondirectory buffer-file-name))
  2022. (setq not-serious t)
  2023. (if error "(New file)" nil)))
  2024. ((not error)
  2025. (setq not-serious t)
  2026. "Note: file is write protected")
  2027. ((file-attributes (directory-file-name default-directory))
  2028. "File not found and directory write-protected")
  2029. ((file-exists-p (file-name-directory buffer-file-name))
  2030. (setq buffer-read-only nil))
  2031. (t
  2032. (setq buffer-read-only nil)
  2033. "Use M-x make-directory RET RET to create the directory and its parents"))))
  2034. (when msg
  2035. (message "%s" msg)
  2036. (or not-serious (sit-for 1 t))))
  2037. (when (and auto-save-default (not noauto))
  2038. (auto-save-mode 1)))
  2039. ;; Make people do a little extra work (C-x C-q)
  2040. ;; before altering a backup file.
  2041. (when (backup-file-name-p buffer-file-name)
  2042. (setq buffer-read-only t))
  2043. ;; When a file is marked read-only,
  2044. ;; make the buffer read-only even if root is looking at it.
  2045. (when (and (file-modes (buffer-file-name))
  2046. (zerop (logand (file-modes (buffer-file-name)) #o222)))
  2047. (setq buffer-read-only t))
  2048. (unless nomodes
  2049. (when (and view-read-only view-mode)
  2050. (view-mode -1))
  2051. (normal-mode t)
  2052. ;; If requested, add a newline at the end of the file.
  2053. (and (memq require-final-newline '(visit visit-save))
  2054. (> (point-max) (point-min))
  2055. (/= (char-after (1- (point-max))) ?\n)
  2056. (not (and (eq selective-display t)
  2057. (= (char-after (1- (point-max))) ?\r)))
  2058. (not buffer-read-only)
  2059. (save-excursion
  2060. (goto-char (point-max))
  2061. (ignore-errors (insert "\n"))))
  2062. (when (and buffer-read-only
  2063. view-read-only
  2064. (not (eq (get major-mode 'mode-class) 'special)))
  2065. (view-mode-enter))
  2066. (run-hooks 'find-file-hook)))
  2067. (define-obsolete-function-alias 'report-errors 'with-demoted-errors "25.1")
  2068. (defun normal-mode (&optional find-file)
  2069. "Choose the major mode for this buffer automatically.
  2070. Also sets up any specified local variables of the file.
  2071. Uses the visited file name, the -*- line, and the local variables spec.
  2072. This function is called automatically from `find-file'. In that case,
  2073. we may set up the file-specified mode and local variables,
  2074. depending on the value of `enable-local-variables'.
  2075. In addition, if `local-enable-local-variables' is nil, we do
  2076. not set local variables (though we do notice a mode specified with -*-.)
  2077. `enable-local-variables' is ignored if you run `normal-mode' interactively,
  2078. or from Lisp without specifying the optional argument FIND-FILE;
  2079. in that case, this function acts as if `enable-local-variables' were t."
  2080. (interactive)
  2081. (fundamental-mode)
  2082. (let ((enable-local-variables (or (not find-file) enable-local-variables)))
  2083. ;; FIXME this is less efficient than it could be, since both
  2084. ;; s-a-m and h-l-v may parse the same regions, looking for "mode:".
  2085. (with-demoted-errors "File mode specification error: %s"
  2086. (set-auto-mode))
  2087. (with-demoted-errors "File local-variables error: %s"
  2088. (hack-local-variables)))
  2089. ;; Turn font lock off and on, to make sure it takes account of
  2090. ;; whatever file local variables are relevant to it.
  2091. (when (and font-lock-mode
  2092. ;; Font-lock-mode (now in font-core.el) can be ON when
  2093. ;; font-lock.el still hasn't been loaded.
  2094. (boundp 'font-lock-keywords)
  2095. (eq (car font-lock-keywords) t))
  2096. (setq font-lock-keywords (cadr font-lock-keywords))
  2097. (font-lock-mode 1)))
  2098. (defcustom auto-mode-case-fold t
  2099. "Non-nil means to try second pass through `auto-mode-alist'.
  2100. This means that if the first case-sensitive search through the alist fails
  2101. to find a matching major mode, a second case-insensitive search is made.
  2102. On systems with case-insensitive file names, this variable is ignored,
  2103. since only a single case-insensitive search through the alist is made."
  2104. :group 'files
  2105. :version "22.1"
  2106. :type 'boolean)
  2107. (defvar auto-mode-alist
  2108. ;; Note: The entries for the modes defined in cc-mode.el (c-mode,
  2109. ;; c++-mode, java-mode and more) are added through autoload
  2110. ;; directives in that file. That way is discouraged since it
  2111. ;; spreads out the definition of the initial value.
  2112. (mapcar
  2113. (lambda (elt)
  2114. (cons (purecopy (car elt)) (cdr elt)))
  2115. `(;; do this first, so that .html.pl is Polish html, not Perl
  2116. ("\\.[sx]?html?\\(\\.[a-zA-Z_]+\\)?\\'" . html-mode)
  2117. ("\\.svgz?\\'" . image-mode)
  2118. ("\\.svgz?\\'" . xml-mode)
  2119. ("\\.x[bp]m\\'" . image-mode)
  2120. ("\\.x[bp]m\\'" . c-mode)
  2121. ("\\.p[bpgn]m\\'" . image-mode)
  2122. ("\\.tiff?\\'" . image-mode)
  2123. ("\\.gif\\'" . image-mode)
  2124. ("\\.png\\'" . image-mode)
  2125. ("\\.jpe?g\\'" . image-mode)
  2126. ("\\.te?xt\\'" . text-mode)
  2127. ("\\.[tT]e[xX]\\'" . tex-mode)
  2128. ("\\.ins\\'" . tex-mode) ;Installation files for TeX packages.
  2129. ("\\.ltx\\'" . latex-mode)
  2130. ("\\.dtx\\'" . doctex-mode)
  2131. ("\\.org\\'" . org-mode)
  2132. ("\\.el\\'" . emacs-lisp-mode)
  2133. ("Project\\.ede\\'" . emacs-lisp-mode)
  2134. ("\\.\\(scm\\|stk\\|ss\\|sch\\)\\'" . scheme-mode)
  2135. ("\\.l\\'" . lisp-mode)
  2136. ("\\.li?sp\\'" . lisp-mode)
  2137. ("\\.[fF]\\'" . fortran-mode)
  2138. ("\\.for\\'" . fortran-mode)
  2139. ("\\.p\\'" . pascal-mode)
  2140. ("\\.pas\\'" . pascal-mode)
  2141. ("\\.\\(dpr\\|DPR\\)\\'" . delphi-mode)
  2142. ("\\.ad[abs]\\'" . ada-mode)
  2143. ("\\.ad[bs].dg\\'" . ada-mode)
  2144. ("\\.\\([pP]\\([Llm]\\|erl\\|od\\)\\|al\\)\\'" . perl-mode)
  2145. ("Imakefile\\'" . makefile-imake-mode)
  2146. ("Makeppfile\\(?:\\.mk\\)?\\'" . makefile-makepp-mode) ; Put this before .mk
  2147. ("\\.makepp\\'" . makefile-makepp-mode)
  2148. ,@(if (memq system-type '(berkeley-unix darwin))
  2149. '(("\\.mk\\'" . makefile-bsdmake-mode)
  2150. ("\\.make\\'" . makefile-bsdmake-mode)
  2151. ("GNUmakefile\\'" . makefile-gmake-mode)
  2152. ("[Mm]akefile\\'" . makefile-bsdmake-mode))
  2153. '(("\\.mk\\'" . makefile-gmake-mode) ; Might be any make, give Gnu the host advantage
  2154. ("\\.make\\'" . makefile-gmake-mode)
  2155. ("[Mm]akefile\\'" . makefile-gmake-mode)))
  2156. ("\\.am\\'" . makefile-automake-mode)
  2157. ;; Less common extensions come here
  2158. ;; so more common ones above are found faster.
  2159. ("\\.texinfo\\'" . texinfo-mode)
  2160. ("\\.te?xi\\'" . texinfo-mode)
  2161. ("\\.[sS]\\'" . asm-mode)
  2162. ("\\.asm\\'" . asm-mode)
  2163. ("\\.css\\'" . css-mode)
  2164. ("\\.mixal\\'" . mixal-mode)
  2165. ("\\.gcov\\'" . compilation-mode)
  2166. ;; Besides .gdbinit, gdb documents other names to be usable for init
  2167. ;; files, cross-debuggers can use something like
  2168. ;; .PROCESSORNAME-gdbinit so that the host and target gdbinit files
  2169. ;; don't interfere with each other.
  2170. ("/\\.[a-z0-9-]*gdbinit" . gdb-script-mode)
  2171. ;; GDB 7.5 introduced OBJFILE-gdb.gdb script files; e.g. a file
  2172. ;; named 'emacs-gdb.gdb', if it exists, will be automatically
  2173. ;; loaded when GDB reads an objfile called 'emacs'.
  2174. ("-gdb\\.gdb" . gdb-script-mode)
  2175. ("[cC]hange\\.?[lL]og?\\'" . change-log-mode)
  2176. ("[cC]hange[lL]og[-.][0-9]+\\'" . change-log-mode)
  2177. ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
  2178. ("\\.scm\\.[0-9]*\\'" . scheme-mode)
  2179. ("\\.[ckz]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
  2180. ("\\.bash\\'" . sh-mode)
  2181. ("\\(/\\|\\`\\)\\.\\(bash_\\(profile\\|history\\|log\\(in\\|out\\)\\)\\|z?log\\(in\\|out\\)\\)\\'" . sh-mode)
  2182. ("\\(/\\|\\`\\)\\.\\(shrc\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
  2183. ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
  2184. ("\\.m?spec\\'" . sh-mode)
  2185. ("\\.m[mes]\\'" . nroff-mode)
  2186. ("\\.man\\'" . nroff-mode)
  2187. ("\\.sty\\'" . latex-mode)
  2188. ("\\.cl[so]\\'" . latex-mode) ;LaTeX 2e class option
  2189. ("\\.bbl\\'" . latex-mode)
  2190. ("\\.bib\\'" . bibtex-mode)
  2191. ("\\.bst\\'" . bibtex-style-mode)
  2192. ("\\.sql\\'" . sql-mode)
  2193. ("\\.m[4c]\\'" . m4-mode)
  2194. ("\\.mf\\'" . metafont-mode)
  2195. ("\\.mp\\'" . metapost-mode)
  2196. ("\\.vhdl?\\'" . vhdl-mode)
  2197. ("\\.article\\'" . text-mode)
  2198. ("\\.letter\\'" . text-mode)
  2199. ("\\.i?tcl\\'" . tcl-mode)
  2200. ("\\.exp\\'" . tcl-mode)
  2201. ("\\.itk\\'" . tcl-mode)
  2202. ("\\.icn\\'" . icon-mode)
  2203. ("\\.sim\\'" . simula-mode)
  2204. ("\\.mss\\'" . scribe-mode)
  2205. ;; The Fortran standard does not say anything about file extensions.
  2206. ;; .f90 was widely used for F90, now we seem to be trapped into
  2207. ;; using a different extension for each language revision.
  2208. ;; Anyway, the following extensions are supported by gfortran.
  2209. ("\\.f9[05]\\'" . f90-mode)
  2210. ("\\.f0[38]\\'" . f90-mode)
  2211. ("\\.indent\\.pro\\'" . fundamental-mode) ; to avoid idlwave-mode
  2212. ("\\.\\(pro\\|PRO\\)\\'" . idlwave-mode)
  2213. ("\\.srt\\'" . srecode-template-mode)
  2214. ("\\.prolog\\'" . prolog-mode)
  2215. ("\\.tar\\'" . tar-mode)
  2216. ;; The list of archive file extensions should be in sync with
  2217. ;; `auto-coding-alist' with `no-conversion' coding system.
  2218. ("\\.\\(\
  2219. arc\\|zip\\|lzh\\|lha\\|zoo\\|[jew]ar\\|xpi\\|rar\\|7z\\|\
  2220. ARC\\|ZIP\\|LZH\\|LHA\\|ZOO\\|[JEW]AR\\|XPI\\|RAR\\|7Z\\)\\'" . archive-mode)
  2221. ("\\.oxt\\'" . archive-mode) ;(Open|Libre)Office extensions.
  2222. ("\\.\\(deb\\|[oi]pk\\)\\'" . archive-mode) ; Debian/Opkg packages.
  2223. ;; Mailer puts message to be edited in
  2224. ;; /tmp/Re.... or Message
  2225. ("\\`/tmp/Re" . text-mode)
  2226. ("/Message[0-9]*\\'" . text-mode)
  2227. ;; some news reader is reported to use this
  2228. ("\\`/tmp/fol/" . text-mode)
  2229. ("\\.oak\\'" . scheme-mode)
  2230. ("\\.sgml?\\'" . sgml-mode)
  2231. ("\\.x[ms]l\\'" . xml-mode)
  2232. ("\\.dbk\\'" . xml-mode)
  2233. ("\\.dtd\\'" . sgml-mode)
  2234. ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
  2235. ("\\.jsm?\\'" . javascript-mode)
  2236. ("\\.json\\'" . javascript-mode)
  2237. ("\\.[ds]?vh?\\'" . verilog-mode)
  2238. ("\\.by\\'" . bovine-grammar-mode)
  2239. ("\\.wy\\'" . wisent-grammar-mode)
  2240. ;; .emacs or .gnus or .viper following a directory delimiter in
  2241. ;; Unix or MS-DOS syntax.
  2242. ("[:/\\]\\..*\\(emacs\\|gnus\\|viper\\)\\'" . emacs-lisp-mode)
  2243. ("\\`\\..*emacs\\'" . emacs-lisp-mode)
  2244. ;; _emacs following a directory delimiter in MS-DOS syntax
  2245. ("[:/]_emacs\\'" . emacs-lisp-mode)
  2246. ("/crontab\\.X*[0-9]+\\'" . shell-script-mode)
  2247. ("\\.ml\\'" . lisp-mode)
  2248. ;; Linux-2.6.9 uses some different suffix for linker scripts:
  2249. ;; "ld", "lds", "lds.S", "lds.in", "ld.script", and "ld.script.balo".
  2250. ;; eCos uses "ld" and "ldi". Netbsd uses "ldscript.*".
  2251. ("\\.ld[si]?\\'" . ld-script-mode)
  2252. ("ld\\.?script\\'" . ld-script-mode)
  2253. ;; .xs is also used for ld scripts, but seems to be more commonly
  2254. ;; associated with Perl .xs files (C with Perl bindings). (Bug#7071)
  2255. ("\\.xs\\'" . c-mode)
  2256. ;; Explained in binutils ld/genscripts.sh. Eg:
  2257. ;; A .x script file is the default script.
  2258. ;; A .xr script is for linking without relocation (-r flag). Etc.
  2259. ("\\.x[abdsru]?[cnw]?\\'" . ld-script-mode)
  2260. ("\\.zone\\'" . dns-mode)
  2261. ("\\.soa\\'" . dns-mode)
  2262. ;; Common Lisp ASDF package system.
  2263. ("\\.asd\\'" . lisp-mode)
  2264. ("\\.\\(asn\\|mib\\|smi\\)\\'" . snmp-mode)
  2265. ("\\.\\(as\\|mi\\|sm\\)2\\'" . snmpv2-mode)
  2266. ("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode)
  2267. ("\\.\\(dif\\|pat\\)\\'" . diff-mode) ; for MS-DOS
  2268. ("\\.[eE]?[pP][sS]\\'" . ps-mode)
  2269. ("\\.\\(?:PDF\\|DVI\\|OD[FGPST]\\|DOCX?\\|XLSX?\\|PPTX?\\|pdf\\|djvu\\|dvi\\|od[fgpst]\\|docx?\\|xlsx?\\|pptx?\\)\\'" . doc-view-mode-maybe)
  2270. ("configure\\.\\(ac\\|in\\)\\'" . autoconf-mode)
  2271. ("\\.s\\(v\\|iv\\|ieve\\)\\'" . sieve-mode)
  2272. ("BROWSE\\'" . ebrowse-tree-mode)
  2273. ("\\.ebrowse\\'" . ebrowse-tree-mode)
  2274. ("#\\*mail\\*" . mail-mode)
  2275. ("\\.g\\'" . antlr-mode)
  2276. ("\\.mod\\'" . m2-mode)
  2277. ("\\.ses\\'" . ses-mode)
  2278. ("\\.docbook\\'" . sgml-mode)
  2279. ("\\.com\\'" . dcl-mode)
  2280. ("/config\\.\\(?:bat\\|log\\)\\'" . fundamental-mode)
  2281. ;; Windows candidates may be opened case sensitively on Unix
  2282. ("\\.\\(?:[iI][nN][iI]\\|[lL][sS][tT]\\|[rR][eE][gG]\\|[sS][yY][sS]\\)\\'" . conf-mode)
  2283. ("\\.\\(?:desktop\\|la\\)\\'" . conf-unix-mode)
  2284. ("\\.ppd\\'" . conf-ppd-mode)
  2285. ("java.+\\.conf\\'" . conf-javaprop-mode)
  2286. ("\\.properties\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-javaprop-mode)
  2287. ("\\`/etc/\\(?:DIR_COLORS\\|ethers\\|.?fstab\\|.*hosts\\|lesskey\\|login\\.?de\\(?:fs\\|vperm\\)\\|magic\\|mtab\\|pam\\.d/.*\\|permissions\\(?:\\.d/.+\\)?\\|protocols\\|rpc\\|services\\)\\'" . conf-space-mode)
  2288. ("\\`/etc/\\(?:acpid?/.+\\|aliases\\(?:\\.d/.+\\)?\\|default/.+\\|group-?\\|hosts\\..+\\|inittab\\|ksysguarddrc\\|opera6rc\\|passwd-?\\|shadow-?\\|sysconfig/.+\\)\\'" . conf-mode)
  2289. ;; ChangeLog.old etc. Other change-log-mode entries are above;
  2290. ;; this has lower priority to avoid matching changelog.sgml etc.
  2291. ("[cC]hange[lL]og[-.][-0-9a-z]+\\'" . change-log-mode)
  2292. ;; either user's dot-files or under /etc or some such
  2293. ("/\\.?\\(?:gitconfig\\|gnokiirc\\|hgrc\\|kde.*rc\\|mime\\.types\\|wgetrc\\)\\'" . conf-mode)
  2294. ;; alas not all ~/.*rc files are like this
  2295. ("/\\.\\(?:enigma\\|gltron\\|gtk\\|hxplayer\\|net\\|neverball\\|qt/.+\\|realplayer\\|scummvm\\|sversion\\|sylpheed/.+\\|xmp\\)rc\\'" . conf-mode)
  2296. ("/\\.\\(?:gdbtkinit\\|grip\\|orbital/.+txt\\|rhosts\\|tuxracer/options\\)\\'" . conf-mode)
  2297. ("/\\.?X\\(?:default\\|resource\\|re\\)s\\>" . conf-xdefaults-mode)
  2298. ("/X11.+app-defaults/\\|\\.ad\\'" . conf-xdefaults-mode)
  2299. ("/X11.+locale/.+/Compose\\'" . conf-colon-mode)
  2300. ;; this contains everything twice, with space and with colon :-(
  2301. ("/X11.+locale/compose\\.dir\\'" . conf-javaprop-mode)
  2302. ;; Get rid of any trailing .n.m and try again.
  2303. ;; This is for files saved by cvs-merge that look like .#<file>.<rev>
  2304. ;; or .#<file>.<rev>-<rev> or VC's <file>.~<rev>~.
  2305. ;; Using mode nil rather than `ignore' would let the search continue
  2306. ;; through this list (with the shortened name) rather than start over.
  2307. ("\\.~?[0-9]+\\.[0-9][-.0-9]*~?\\'" nil t)
  2308. ("\\.\\(?:orig\\|in\\|[bB][aA][kK]\\)\\'" nil t)
  2309. ;; This should come after "in" stripping (e.g. config.h.in).
  2310. ;; *.cf, *.cfg, *.conf, *.config[.local|.de_DE.UTF8|...], */config
  2311. ("[/.]c\\(?:on\\)?f\\(?:i?g\\)?\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-mode-maybe)
  2312. ;; The following should come after the ChangeLog pattern
  2313. ;; for the sake of ChangeLog.1, etc.
  2314. ;; and after the .scm.[0-9] and CVS' <file>.<rev> patterns too.
  2315. ("\\.[1-9]\\'" . nroff-mode)))
  2316. "Alist of filename patterns vs corresponding major mode functions.
  2317. Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
  2318. \(NON-NIL stands for anything that is not nil; the value does not matter.)
  2319. Visiting a file whose name matches REGEXP specifies FUNCTION as the
  2320. mode function to use. FUNCTION will be called, unless it is nil.
  2321. If the element has the form (REGEXP FUNCTION NON-NIL), then after
  2322. calling FUNCTION (if it's not nil), we delete the suffix that matched
  2323. REGEXP and search the list again for another match.
  2324. The extensions whose FUNCTION is `archive-mode' should also
  2325. appear in `auto-coding-alist' with `no-conversion' coding system.
  2326. See also `interpreter-mode-alist', which detects executable script modes
  2327. based on the interpreters they specify to run,
  2328. and `magic-mode-alist', which determines modes based on file contents.")
  2329. (put 'auto-mode-alist 'risky-local-variable t)
  2330. (defun conf-mode-maybe ()
  2331. "Select Conf mode or XML mode according to start of file."
  2332. (if (save-excursion
  2333. (save-restriction
  2334. (widen)
  2335. (goto-char (point-min))
  2336. (looking-at "<\\?xml \\|<!-- \\|<!DOCTYPE ")))
  2337. (xml-mode)
  2338. (conf-mode)))
  2339. (defvar interpreter-mode-alist
  2340. ;; Note: The entries for the modes defined in cc-mode.el (awk-mode
  2341. ;; and pike-mode) are added through autoload directives in that
  2342. ;; file. That way is discouraged since it spreads out the
  2343. ;; definition of the initial value.
  2344. (mapcar
  2345. (lambda (l)
  2346. (cons (purecopy (car l)) (cdr l)))
  2347. '(("\\(mini\\)?perl5?" . perl-mode)
  2348. ("wishx?" . tcl-mode)
  2349. ("tcl\\(sh\\)?" . tcl-mode)
  2350. ("expect" . tcl-mode)
  2351. ("octave" . octave-mode)
  2352. ("scm" . scheme-mode)
  2353. ("[acjkwz]sh" . sh-mode)
  2354. ("r?bash2?" . sh-mode)
  2355. ("dash" . sh-mode)
  2356. ("mksh" . sh-mode)
  2357. ("\\(dt\\|pd\\|w\\)ksh" . sh-mode)
  2358. ("es" . sh-mode)
  2359. ("i?tcsh" . sh-mode)
  2360. ("oash" . sh-mode)
  2361. ("rc" . sh-mode)
  2362. ("rpm" . sh-mode)
  2363. ("sh5?" . sh-mode)
  2364. ("tail" . text-mode)
  2365. ("more" . text-mode)
  2366. ("less" . text-mode)
  2367. ("pg" . text-mode)
  2368. ("make" . makefile-gmake-mode) ; Debian uses this
  2369. ("guile" . scheme-mode)
  2370. ("clisp" . lisp-mode)
  2371. ("emacs" . emacs-lisp-mode)))
  2372. "Alist mapping interpreter names to major modes.
  2373. This is used for files whose first lines match `auto-mode-interpreter-regexp'.
  2374. Each element looks like (REGEXP . MODE).
  2375. If REGEXP matches the entire name (minus any directory part) of
  2376. the interpreter specified in the first line of a script, enable
  2377. major mode MODE.
  2378. See also `auto-mode-alist'.")
  2379. (define-obsolete-variable-alias 'inhibit-first-line-modes-regexps
  2380. 'inhibit-file-local-variables-regexps "24.1")
  2381. ;; TODO really this should be a list of modes (eg tar-mode), not regexps,
  2382. ;; because we are duplicating info from auto-mode-alist.
  2383. ;; TODO many elements of this list are also in auto-coding-alist.
  2384. (defvar inhibit-local-variables-regexps
  2385. (mapcar 'purecopy '("\\.tar\\'" "\\.t[bg]z\\'"
  2386. "\\.arc\\'" "\\.zip\\'" "\\.lzh\\'" "\\.lha\\'"
  2387. "\\.zoo\\'" "\\.[jew]ar\\'" "\\.xpi\\'" "\\.rar\\'"
  2388. "\\.7z\\'"
  2389. "\\.sx[dmicw]\\'" "\\.odt\\'"
  2390. "\\.diff\\'" "\\.patch\\'"
  2391. "\\.tiff?\\'" "\\.gif\\'" "\\.png\\'" "\\.jpe?g\\'"))
  2392. "List of regexps matching file names in which to ignore local variables.
  2393. This includes `-*-' lines as well as trailing \"Local Variables\" sections.
  2394. Files matching this list are typically binary file formats.
  2395. They may happen to contain sequences that look like local variable
  2396. specifications, but are not really, or they may be containers for
  2397. member files with their own local variable sections, which are
  2398. not appropriate for the containing file.
  2399. The function `inhibit-local-variables-p' uses this.")
  2400. (define-obsolete-variable-alias 'inhibit-first-line-modes-suffixes
  2401. 'inhibit-local-variables-suffixes "24.1")
  2402. (defvar inhibit-local-variables-suffixes nil
  2403. "List of regexps matching suffixes to remove from file names.
  2404. The function `inhibit-local-variables-p' uses this: when checking
  2405. a file name, it first discards from the end of the name anything that
  2406. matches one of these regexps.")
  2407. ;; Can't think of any situation in which you'd want this to be nil...
  2408. (defvar inhibit-local-variables-ignore-case t
  2409. "Non-nil means `inhibit-local-variables-p' ignores case.")
  2410. (defun inhibit-local-variables-p ()
  2411. "Return non-nil if file local variables should be ignored.
  2412. This checks the file (or buffer) name against `inhibit-local-variables-regexps'
  2413. and `inhibit-local-variables-suffixes'. If
  2414. `inhibit-local-variables-ignore-case' is non-nil, this ignores case."
  2415. (let ((temp inhibit-local-variables-regexps)
  2416. (name (if buffer-file-name
  2417. (file-name-sans-versions buffer-file-name)
  2418. (buffer-name)))
  2419. (case-fold-search inhibit-local-variables-ignore-case))
  2420. (while (let ((sufs inhibit-local-variables-suffixes))
  2421. (while (and sufs (not (string-match (car sufs) name)))
  2422. (setq sufs (cdr sufs)))
  2423. sufs)
  2424. (setq name (substring name 0 (match-beginning 0))))
  2425. (while (and temp
  2426. (not (string-match (car temp) name)))
  2427. (setq temp (cdr temp)))
  2428. temp))
  2429. (defvar auto-mode-interpreter-regexp
  2430. (purecopy "#![ \t]?\\([^ \t\n]*\
  2431. /bin/env[ \t]\\)?\\([^ \t\n]+\\)")
  2432. "Regexp matching interpreters, for file mode determination.
  2433. This regular expression is matched against the first line of a file
  2434. to determine the file's mode in `set-auto-mode'. If it matches, the file
  2435. is assumed to be interpreted by the interpreter matched by the second group
  2436. of the regular expression. The mode is then determined as the mode
  2437. associated with that interpreter in `interpreter-mode-alist'.")
  2438. (defvar magic-mode-alist nil
  2439. "Alist of buffer beginnings vs. corresponding major mode functions.
  2440. Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
  2441. After visiting a file, if REGEXP matches the text at the beginning of the
  2442. buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
  2443. call FUNCTION rather than allowing `auto-mode-alist' to decide the buffer's
  2444. major mode.
  2445. If FUNCTION is nil, then it is not called. (That is a way of saying
  2446. \"allow `auto-mode-alist' to decide for these files.\")")
  2447. (put 'magic-mode-alist 'risky-local-variable t)
  2448. (defvar magic-fallback-mode-alist
  2449. (purecopy
  2450. `((image-type-auto-detected-p . image-mode)
  2451. ("\\(PK00\\)?[P]K\003\004" . archive-mode) ; zip
  2452. ;; The < comes before the groups (but the first) to reduce backtracking.
  2453. ;; TODO: UTF-16 <?xml may be preceded by a BOM 0xff 0xfe or 0xfe 0xff.
  2454. ;; We use [ \t\r\n] instead of `\\s ' to make regex overflow less likely.
  2455. (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
  2456. (comment-re (concat "\\(?:!--" incomment-re "*-->[ \t\r\n]*<\\)")))
  2457. (concat "\\(?:<\\?xml[ \t\r\n]+[^>]*>\\)?[ \t\r\n]*<"
  2458. comment-re "*"
  2459. "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re "*\\)?"
  2460. "[Hh][Tt][Mm][Ll]"))
  2461. . html-mode)
  2462. ("<!DOCTYPE[ \t\r\n]+[Hh][Tt][Mm][Ll]" . html-mode)
  2463. ;; These two must come after html, because they are more general:
  2464. ("<\\?xml " . xml-mode)
  2465. (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
  2466. (comment-re (concat "\\(?:!--" incomment-re "*-->[ \t\r\n]*<\\)")))
  2467. (concat "[ \t\r\n]*<" comment-re "*!DOCTYPE "))
  2468. . sgml-mode)
  2469. ("%!PS" . ps-mode)
  2470. ("# xmcd " . conf-unix-mode)))
  2471. "Like `magic-mode-alist' but has lower priority than `auto-mode-alist'.
  2472. Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
  2473. After visiting a file, if REGEXP matches the text at the beginning of the
  2474. buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
  2475. call FUNCTION, provided that `magic-mode-alist' and `auto-mode-alist'
  2476. have not specified a mode for this file.
  2477. If FUNCTION is nil, then it is not called.")
  2478. (put 'magic-fallback-mode-alist 'risky-local-variable t)
  2479. (defvar magic-mode-regexp-match-limit 4000
  2480. "Upper limit on `magic-mode-alist' regexp matches.
  2481. Also applies to `magic-fallback-mode-alist'.")
  2482. (defun set-auto-mode (&optional keep-mode-if-same)
  2483. "Select major mode appropriate for current buffer.
  2484. To find the right major mode, this function checks for a -*- mode tag
  2485. checks for a `mode:' entry in the Local Variables section of the file,
  2486. checks if it uses an interpreter listed in `interpreter-mode-alist',
  2487. matches the buffer beginning against `magic-mode-alist',
  2488. compares the filename against the entries in `auto-mode-alist',
  2489. then matches the buffer beginning against `magic-fallback-mode-alist'.
  2490. If `enable-local-variables' is nil, or if the file name matches
  2491. `inhibit-local-variables-regexps', this function does not check
  2492. for any mode: tag anywhere in the file. If `local-enable-local-variables'
  2493. is nil, then the only mode: tag that can be relevant is a -*- one.
  2494. If the optional argument KEEP-MODE-IF-SAME is non-nil, then we
  2495. set the major mode only if that would change it. In other words
  2496. we don't actually set it to the same mode the buffer already has."
  2497. ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
  2498. (let ((try-locals (not (inhibit-local-variables-p)))
  2499. end done mode modes)
  2500. ;; Once we drop the deprecated feature where mode: is also allowed to
  2501. ;; specify minor-modes (ie, there can be more than one "mode:"), we can
  2502. ;; remove this section and just let (hack-local-variables t) handle it.
  2503. ;; Find a -*- mode tag.
  2504. (save-excursion
  2505. (goto-char (point-min))
  2506. (skip-chars-forward " \t\n")
  2507. ;; Note by design local-enable-local-variables does not matter here.
  2508. (and enable-local-variables
  2509. try-locals
  2510. (setq end (set-auto-mode-1))
  2511. (if (save-excursion (search-forward ":" end t))
  2512. ;; Find all specifications for the `mode:' variable
  2513. ;; and execute them left to right.
  2514. (while (let ((case-fold-search t))
  2515. (or (and (looking-at "mode:")
  2516. (goto-char (match-end 0)))
  2517. (re-search-forward "[ \t;]mode:" end t)))
  2518. (skip-chars-forward " \t")
  2519. (let ((beg (point)))
  2520. (if (search-forward ";" end t)
  2521. (forward-char -1)
  2522. (goto-char end))
  2523. (skip-chars-backward " \t")
  2524. (push (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
  2525. modes)))
  2526. ;; Simple -*-MODE-*- case.
  2527. (push (intern (concat (downcase (buffer-substring (point) end))
  2528. "-mode"))
  2529. modes))))
  2530. ;; If we found modes to use, invoke them now, outside the save-excursion.
  2531. (if modes
  2532. (catch 'nop
  2533. (dolist (mode (nreverse modes))
  2534. (if (not (functionp mode))
  2535. (message "Ignoring unknown mode `%s'" mode)
  2536. (setq done t)
  2537. (or (set-auto-mode-0 mode keep-mode-if-same)
  2538. ;; continuing would call minor modes again, toggling them off
  2539. (throw 'nop nil))))))
  2540. ;; hack-local-variables checks local-enable-local-variables etc, but
  2541. ;; we might as well be explicit here for the sake of clarity.
  2542. (and (not done)
  2543. enable-local-variables
  2544. local-enable-local-variables
  2545. try-locals
  2546. (setq mode (hack-local-variables t))
  2547. (not (memq mode modes)) ; already tried and failed
  2548. (if (not (functionp mode))
  2549. (message "Ignoring unknown mode `%s'" mode)
  2550. (setq done t)
  2551. (set-auto-mode-0 mode keep-mode-if-same)))
  2552. ;; If we didn't, look for an interpreter specified in the first line.
  2553. ;; As a special case, allow for things like "#!/bin/env perl", which
  2554. ;; finds the interpreter anywhere in $PATH.
  2555. (and (not done)
  2556. (setq mode (save-excursion
  2557. (goto-char (point-min))
  2558. (if (looking-at auto-mode-interpreter-regexp)
  2559. (match-string 2))))
  2560. ;; Map interpreter name to a mode, signaling we're done at the
  2561. ;; same time.
  2562. (setq done (assoc-default
  2563. (file-name-nondirectory mode)
  2564. (mapcar (lambda (e)
  2565. (cons
  2566. (format "\\`%s\\'" (car e))
  2567. (cdr e)))
  2568. interpreter-mode-alist)
  2569. #'string-match-p))
  2570. ;; If we found an interpreter mode to use, invoke it now.
  2571. (set-auto-mode-0 done keep-mode-if-same))
  2572. ;; Next try matching the buffer beginning against magic-mode-alist.
  2573. (unless done
  2574. (if (setq done (save-excursion
  2575. (goto-char (point-min))
  2576. (save-restriction
  2577. (narrow-to-region (point-min)
  2578. (min (point-max)
  2579. (+ (point-min) magic-mode-regexp-match-limit)))
  2580. (assoc-default nil magic-mode-alist
  2581. (lambda (re _dummy)
  2582. (if (functionp re)
  2583. (funcall re)
  2584. (looking-at re)))))))
  2585. (set-auto-mode-0 done keep-mode-if-same)))
  2586. ;; Next compare the filename against the entries in auto-mode-alist.
  2587. (unless done
  2588. (if buffer-file-name
  2589. (let ((name buffer-file-name)
  2590. (remote-id (file-remote-p buffer-file-name)))
  2591. ;; Remove backup-suffixes from file name.
  2592. (setq name (file-name-sans-versions name))
  2593. ;; Remove remote file name identification.
  2594. (when (and (stringp remote-id)
  2595. (string-match (regexp-quote remote-id) name))
  2596. (setq name (substring name (match-end 0))))
  2597. (while name
  2598. ;; Find first matching alist entry.
  2599. (setq mode
  2600. (if (memq system-type '(windows-nt cygwin))
  2601. ;; System is case-insensitive.
  2602. (let ((case-fold-search t))
  2603. (assoc-default name auto-mode-alist
  2604. 'string-match))
  2605. ;; System is case-sensitive.
  2606. (or
  2607. ;; First match case-sensitively.
  2608. (let ((case-fold-search nil))
  2609. (assoc-default name auto-mode-alist
  2610. 'string-match))
  2611. ;; Fallback to case-insensitive match.
  2612. (and auto-mode-case-fold
  2613. (let ((case-fold-search t))
  2614. (assoc-default name auto-mode-alist
  2615. 'string-match))))))
  2616. (if (and mode
  2617. (consp mode)
  2618. (cadr mode))
  2619. (setq mode (car mode)
  2620. name (substring name 0 (match-beginning 0)))
  2621. (setq name nil))
  2622. (when mode
  2623. (set-auto-mode-0 mode keep-mode-if-same)
  2624. (setq done t))))))
  2625. ;; Next try matching the buffer beginning against magic-fallback-mode-alist.
  2626. (unless done
  2627. (if (setq done (save-excursion
  2628. (goto-char (point-min))
  2629. (save-restriction
  2630. (narrow-to-region (point-min)
  2631. (min (point-max)
  2632. (+ (point-min) magic-mode-regexp-match-limit)))
  2633. (assoc-default nil magic-fallback-mode-alist
  2634. (lambda (re _dummy)
  2635. (if (functionp re)
  2636. (funcall re)
  2637. (looking-at re)))))))
  2638. (set-auto-mode-0 done keep-mode-if-same)))
  2639. (unless done
  2640. (set-buffer-major-mode (current-buffer)))))
  2641. ;; When `keep-mode-if-same' is set, we are working on behalf of
  2642. ;; set-visited-file-name. In that case, if the major mode specified is the
  2643. ;; same one we already have, don't actually reset it. We don't want to lose
  2644. ;; minor modes such as Font Lock.
  2645. (defun set-auto-mode-0 (mode &optional keep-mode-if-same)
  2646. "Apply MODE and return it.
  2647. If optional arg KEEP-MODE-IF-SAME is non-nil, MODE is chased of
  2648. any aliases and compared to current major mode. If they are the
  2649. same, do nothing and return nil."
  2650. (unless (and keep-mode-if-same
  2651. (eq (indirect-function mode)
  2652. (indirect-function major-mode)))
  2653. (when mode
  2654. (funcall mode)
  2655. mode)))
  2656. (defvar file-auto-mode-skip "^\\(#!\\|'\\\\\"\\)"
  2657. "Regexp of lines to skip when looking for file-local settings.
  2658. If the first line matches this regular expression, then the -*-...-*- file-
  2659. local settings will be consulted on the second line instead of the first.")
  2660. (defun set-auto-mode-1 ()
  2661. "Find the -*- spec in the buffer.
  2662. Call with point at the place to start searching from.
  2663. If one is found, set point to the beginning and return the position
  2664. of the end. Otherwise, return nil; may change point.
  2665. The variable `inhibit-local-variables-regexps' can cause a -*- spec to
  2666. be ignored; but `enable-local-variables' and `local-enable-local-variables'
  2667. have no effect."
  2668. (let (beg end)
  2669. (and
  2670. ;; Don't look for -*- if this file name matches any
  2671. ;; of the regexps in inhibit-local-variables-regexps.
  2672. (not (inhibit-local-variables-p))
  2673. (search-forward "-*-" (line-end-position
  2674. ;; If the file begins with "#!" (exec
  2675. ;; interpreter magic), look for mode frobs
  2676. ;; in the first two lines. You cannot
  2677. ;; necessarily put them in the first line
  2678. ;; of such a file without screwing up the
  2679. ;; interpreter invocation. The same holds
  2680. ;; for '\" in man pages (preprocessor
  2681. ;; magic for the `man' program).
  2682. (and (looking-at file-auto-mode-skip) 2)) t)
  2683. (progn
  2684. (skip-chars-forward " \t")
  2685. (setq beg (point))
  2686. (search-forward "-*-" (line-end-position) t))
  2687. (progn
  2688. (forward-char -3)
  2689. (skip-chars-backward " \t")
  2690. (setq end (point))
  2691. (goto-char beg)
  2692. end))))
  2693. ;;; Handling file local variables
  2694. (defvar ignored-local-variables
  2695. '(ignored-local-variables safe-local-variable-values
  2696. file-local-variables-alist dir-local-variables-alist)
  2697. "Variables to be ignored in a file's local variable spec.")
  2698. (put 'ignored-local-variables 'risky-local-variable t)
  2699. (defvar hack-local-variables-hook nil
  2700. "Normal hook run after processing a file's local variables specs.
  2701. Major modes can use this to examine user-specified local variables
  2702. in order to initialize other data structure based on them.")
  2703. (defcustom safe-local-variable-values nil
  2704. "List variable-value pairs that are considered safe.
  2705. Each element is a cons cell (VAR . VAL), where VAR is a variable
  2706. symbol and VAL is a value that is considered safe."
  2707. :risky t
  2708. :group 'find-file
  2709. :type 'alist)
  2710. (defcustom safe-local-eval-forms
  2711. ;; This should be here at least as long as Emacs supports write-file-hooks.
  2712. '((add-hook 'write-file-hooks 'time-stamp)
  2713. (add-hook 'write-file-functions 'time-stamp)
  2714. (add-hook 'before-save-hook 'time-stamp nil t)
  2715. (add-hook 'before-save-hook 'delete-trailing-whitespace nil t))
  2716. "Expressions that are considered safe in an `eval:' local variable.
  2717. Add expressions to this list if you want Emacs to evaluate them, when
  2718. they appear in an `eval' local variable specification, without first
  2719. asking you for confirmation."
  2720. :risky t
  2721. :group 'find-file
  2722. :version "24.1" ; added write-file-hooks
  2723. :type '(repeat sexp))
  2724. ;; Risky local variables:
  2725. (mapc (lambda (var) (put var 'risky-local-variable t))
  2726. '(after-load-alist
  2727. buffer-auto-save-file-name
  2728. buffer-file-name
  2729. buffer-file-truename
  2730. buffer-undo-list
  2731. debugger
  2732. default-text-properties
  2733. eval
  2734. exec-directory
  2735. exec-path
  2736. file-name-handler-alist
  2737. frame-title-format
  2738. global-mode-string
  2739. header-line-format
  2740. icon-title-format
  2741. inhibit-quit
  2742. load-path
  2743. max-lisp-eval-depth
  2744. max-specpdl-size
  2745. minor-mode-map-alist
  2746. minor-mode-overriding-map-alist
  2747. mode-line-format
  2748. mode-name
  2749. overriding-local-map
  2750. overriding-terminal-local-map
  2751. process-environment
  2752. standard-input
  2753. standard-output
  2754. unread-command-events))
  2755. ;; Safe local variables:
  2756. ;;
  2757. ;; For variables defined by major modes, the safety declarations can go into
  2758. ;; the major mode's file, since that will be loaded before file variables are
  2759. ;; processed.
  2760. ;;
  2761. ;; For variables defined by minor modes, put the safety declarations in the
  2762. ;; file defining the minor mode after the defcustom/defvar using an autoload
  2763. ;; cookie, e.g.:
  2764. ;;
  2765. ;; ;;;###autoload(put 'variable 'safe-local-variable 'stringp)
  2766. ;;
  2767. ;; Otherwise, when Emacs visits a file specifying that local variable, the
  2768. ;; minor mode file may not be loaded yet.
  2769. ;;
  2770. ;; For variables defined in the C source code the declaration should go here:
  2771. (dolist (pair
  2772. '((buffer-read-only . booleanp) ;; C source code
  2773. (default-directory . stringp) ;; C source code
  2774. (fill-column . integerp) ;; C source code
  2775. (indent-tabs-mode . booleanp) ;; C source code
  2776. (left-margin . integerp) ;; C source code
  2777. (no-update-autoloads . booleanp)
  2778. (lexical-binding . booleanp) ;; C source code
  2779. (tab-width . integerp) ;; C source code
  2780. (truncate-lines . booleanp) ;; C source code
  2781. (word-wrap . booleanp) ;; C source code
  2782. (bidi-display-reordering . booleanp))) ;; C source code
  2783. (put (car pair) 'safe-local-variable (cdr pair)))
  2784. (put 'bidi-paragraph-direction 'safe-local-variable
  2785. (lambda (v) (memq v '(nil right-to-left left-to-right))))
  2786. (put 'c-set-style 'safe-local-eval-function t)
  2787. (defvar file-local-variables-alist nil
  2788. "Alist of file-local variable settings in the current buffer.
  2789. Each element in this list has the form (VAR . VALUE), where VAR
  2790. is a file-local variable (a symbol) and VALUE is the value
  2791. specified. The actual value in the buffer may differ from VALUE,
  2792. if it is changed by the major or minor modes, or by the user.")
  2793. (make-variable-buffer-local 'file-local-variables-alist)
  2794. (put 'file-local-variables-alist 'permanent-local t)
  2795. (defvar dir-local-variables-alist nil
  2796. "Alist of directory-local variable settings in the current buffer.
  2797. Each element in this list has the form (VAR . VALUE), where VAR
  2798. is a directory-local variable (a symbol) and VALUE is the value
  2799. specified in .dir-locals.el. The actual value in the buffer
  2800. may differ from VALUE, if it is changed by the major or minor modes,
  2801. or by the user.")
  2802. (make-variable-buffer-local 'dir-local-variables-alist)
  2803. (defvar before-hack-local-variables-hook nil
  2804. "Normal hook run before setting file-local variables.
  2805. It is called after checking for unsafe/risky variables and
  2806. setting `file-local-variables-alist', and before applying the
  2807. variables stored in `file-local-variables-alist'. A hook
  2808. function is allowed to change the contents of this alist.
  2809. This hook is called only if there is at least one file-local
  2810. variable to set.")
  2811. (defun hack-local-variables-confirm (all-vars unsafe-vars risky-vars dir-name)
  2812. "Get confirmation before setting up local variable values.
  2813. ALL-VARS is the list of all variables to be set up.
  2814. UNSAFE-VARS is the list of those that aren't marked as safe or risky.
  2815. RISKY-VARS is the list of those that are marked as risky.
  2816. If these settings come from directory-local variables, then
  2817. DIR-NAME is the name of the associated directory. Otherwise it is nil."
  2818. (unless noninteractive
  2819. (let ((name (cond (dir-name)
  2820. (buffer-file-name
  2821. (file-name-nondirectory buffer-file-name))
  2822. ((concat "buffer " (buffer-name)))))
  2823. (offer-save (and (eq enable-local-variables t)
  2824. unsafe-vars))
  2825. (buf (get-buffer-create "*Local Variables*")))
  2826. ;; Set up the contents of the *Local Variables* buffer.
  2827. (with-current-buffer buf
  2828. (erase-buffer)
  2829. (cond
  2830. (unsafe-vars
  2831. (insert "The local variables list in " name
  2832. "\ncontains values that may not be safe (*)"
  2833. (if risky-vars
  2834. ", and variables that are risky (**)."
  2835. ".")))
  2836. (risky-vars
  2837. (insert "The local variables list in " name
  2838. "\ncontains variables that are risky (**)."))
  2839. (t
  2840. (insert "A local variables list is specified in " name ".")))
  2841. (insert "\n\nDo you want to apply it? You can type
  2842. y -- to apply the local variables list.
  2843. n -- to ignore the local variables list.")
  2844. (if offer-save
  2845. (insert "
  2846. ! -- to apply the local variables list, and permanently mark these
  2847. values (*) as safe (in the future, they will be set automatically.)\n\n")
  2848. (insert "\n\n"))
  2849. (dolist (elt all-vars)
  2850. (cond ((member elt unsafe-vars)
  2851. (insert " * "))
  2852. ((member elt risky-vars)
  2853. (insert " ** "))
  2854. (t
  2855. (insert " ")))
  2856. (princ (car elt) buf)
  2857. (insert " : ")
  2858. ;; Make strings with embedded whitespace easier to read.
  2859. (let ((print-escape-newlines t))
  2860. (prin1 (cdr elt) buf))
  2861. (insert "\n"))
  2862. (set (make-local-variable 'cursor-type) nil)
  2863. (set-buffer-modified-p nil)
  2864. (goto-char (point-min)))
  2865. ;; Display the buffer and read a choice.
  2866. (save-window-excursion
  2867. (pop-to-buffer buf)
  2868. (let* ((exit-chars '(?y ?n ?\s ?\C-g ?\C-v))
  2869. (prompt (format "Please type %s%s: "
  2870. (if offer-save "y, n, or !" "y or n")
  2871. (if (< (line-number-at-pos (point-max))
  2872. (window-body-height))
  2873. ""
  2874. (push ?\C-v exit-chars)
  2875. ", or C-v to scroll")))
  2876. char)
  2877. (if offer-save (push ?! exit-chars))
  2878. (while (null char)
  2879. (setq char (read-char-choice prompt exit-chars t))
  2880. (when (eq char ?\C-v)
  2881. (condition-case nil
  2882. (scroll-up)
  2883. (error (goto-char (point-min))
  2884. (recenter 1)))
  2885. (setq char nil)))
  2886. (when (and offer-save (= char ?!) unsafe-vars)
  2887. (customize-push-and-save 'safe-local-variable-values unsafe-vars))
  2888. (prog1 (memq char '(?! ?\s ?y))
  2889. (quit-window t)))))))
  2890. (defconst hack-local-variable-regexp
  2891. "[ \t]*\\([^][;\"'?()\\ \t\n]+\\)[ \t]*:[ \t]*")
  2892. (defun hack-local-variables-prop-line (&optional mode-only)
  2893. "Return local variables specified in the -*- line.
  2894. Returns an alist of elements (VAR . VAL), where VAR is a variable
  2895. and VAL is the specified value. Ignores any specification for
  2896. `mode:' and `coding:' (which should have already been handled
  2897. by `set-auto-mode' and `set-auto-coding', respectively).
  2898. Return nil if the -*- line is malformed.
  2899. If MODE-ONLY is non-nil, just returns the symbol specifying the
  2900. mode, if there is one, otherwise nil."
  2901. (catch 'malformed-line
  2902. (save-excursion
  2903. (goto-char (point-min))
  2904. (let ((end (set-auto-mode-1))
  2905. result)
  2906. (cond ((not end)
  2907. nil)
  2908. ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
  2909. ;; Simple form: "-*- MODENAME -*-".
  2910. (if mode-only
  2911. (intern (concat (match-string 1) "-mode"))))
  2912. (t
  2913. ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
  2914. ;; (last ";" is optional).
  2915. ;; If MODE-ONLY, just check for `mode'.
  2916. ;; Otherwise, parse the -*- line into the RESULT alist.
  2917. (while (not (or (and mode-only result)
  2918. (>= (point) end)))
  2919. (unless (looking-at hack-local-variable-regexp)
  2920. (message "Malformed mode-line: %S"
  2921. (buffer-substring-no-properties (point) end))
  2922. (throw 'malformed-line nil))
  2923. (goto-char (match-end 0))
  2924. ;; There used to be a downcase here,
  2925. ;; but the manual didn't say so,
  2926. ;; and people want to set var names that aren't all lc.
  2927. (let* ((key (intern (match-string 1)))
  2928. (val (save-restriction
  2929. (narrow-to-region (point) end)
  2930. (let ((read-circle nil))
  2931. (read (current-buffer)))))
  2932. ;; It is traditional to ignore
  2933. ;; case when checking for `mode' in set-auto-mode,
  2934. ;; so we must do that here as well.
  2935. ;; That is inconsistent, but we're stuck with it.
  2936. ;; The same can be said for `coding' in set-auto-coding.
  2937. (keyname (downcase (symbol-name key))))
  2938. (if mode-only
  2939. (and (equal keyname "mode")
  2940. (setq result
  2941. (intern (concat (downcase (symbol-name val))
  2942. "-mode"))))
  2943. (or (equal keyname "coding")
  2944. (condition-case nil
  2945. (push (cons (cond ((eq key 'eval) 'eval)
  2946. ;; Downcase "Mode:".
  2947. ((equal keyname "mode") 'mode)
  2948. (t (indirect-variable key)))
  2949. val) result)
  2950. (error nil))))
  2951. (skip-chars-forward " \t;")))
  2952. result))))))
  2953. (defun hack-local-variables-filter (variables dir-name)
  2954. "Filter local variable settings, querying the user if necessary.
  2955. VARIABLES is the alist of variable-value settings. This alist is
  2956. filtered based on the values of `ignored-local-variables',
  2957. `enable-local-eval', `enable-local-variables', and (if necessary)
  2958. user interaction. The results are added to
  2959. `file-local-variables-alist', without applying them.
  2960. If these settings come from directory-local variables, then
  2961. DIR-NAME is the name of the associated directory. Otherwise it is nil."
  2962. ;; Find those variables that we may want to save to
  2963. ;; `safe-local-variable-values'.
  2964. (let (all-vars risky-vars unsafe-vars)
  2965. (dolist (elt variables)
  2966. (let ((var (car elt))
  2967. (val (cdr elt)))
  2968. (cond ((memq var ignored-local-variables)
  2969. ;; Ignore any variable in `ignored-local-variables'.
  2970. nil)
  2971. ;; Obey `enable-local-eval'.
  2972. ((eq var 'eval)
  2973. (when enable-local-eval
  2974. (let ((safe (or (hack-one-local-variable-eval-safep val)
  2975. ;; In case previously marked safe (bug#5636).
  2976. (safe-local-variable-p var val))))
  2977. ;; If not safe and e-l-v = :safe, ignore totally.
  2978. (when (or safe (not (eq enable-local-variables :safe)))
  2979. (push elt all-vars)
  2980. (or (eq enable-local-eval t)
  2981. safe
  2982. (push elt unsafe-vars))))))
  2983. ;; Ignore duplicates (except `mode') in the present list.
  2984. ((and (assq var all-vars) (not (eq var 'mode))) nil)
  2985. ;; Accept known-safe variables.
  2986. ((or (memq var '(mode unibyte coding))
  2987. (safe-local-variable-p var val))
  2988. (push elt all-vars))
  2989. ;; The variable is either risky or unsafe:
  2990. ((not (eq enable-local-variables :safe))
  2991. (push elt all-vars)
  2992. (if (risky-local-variable-p var val)
  2993. (push elt risky-vars)
  2994. (push elt unsafe-vars))))))
  2995. (and all-vars
  2996. ;; Query, unless all vars are safe or user wants no querying.
  2997. (or (and (eq enable-local-variables t)
  2998. (null unsafe-vars)
  2999. (null risky-vars))
  3000. (memq enable-local-variables '(:all :safe))
  3001. (hack-local-variables-confirm all-vars unsafe-vars
  3002. risky-vars dir-name))
  3003. (dolist (elt all-vars)
  3004. (unless (memq (car elt) '(eval mode))
  3005. (unless dir-name
  3006. (setq dir-local-variables-alist
  3007. (assq-delete-all (car elt) dir-local-variables-alist)))
  3008. (setq file-local-variables-alist
  3009. (assq-delete-all (car elt) file-local-variables-alist)))
  3010. (push elt file-local-variables-alist)))))
  3011. ;; TODO? Warn once per file rather than once per session?
  3012. (defvar hack-local-variables--warned-lexical nil)
  3013. (defun hack-local-variables (&optional mode-only)
  3014. "Parse and put into effect this buffer's local variables spec.
  3015. Uses `hack-local-variables-apply' to apply the variables.
  3016. If MODE-ONLY is non-nil, all we do is check whether a \"mode:\"
  3017. is specified, and return the corresponding mode symbol, or nil.
  3018. In this case, we try to ignore minor-modes, and only return a
  3019. major-mode.
  3020. If `enable-local-variables' or `local-enable-local-variables' is nil,
  3021. this function does nothing. If `inhibit-local-variables-regexps'
  3022. applies to the file in question, the file is not scanned for
  3023. local variables, but directory-local variables may still be applied."
  3024. ;; We don't let inhibit-local-variables-p influence the value of
  3025. ;; enable-local-variables, because then it would affect dir-local
  3026. ;; variables. We don't want to search eg tar files for file local
  3027. ;; variable sections, but there is no reason dir-locals cannot apply
  3028. ;; to them. The real meaning of inhibit-local-variables-p is "do
  3029. ;; not scan this file for local variables".
  3030. (let ((enable-local-variables
  3031. (and local-enable-local-variables enable-local-variables))
  3032. result)
  3033. (unless mode-only
  3034. (setq file-local-variables-alist nil)
  3035. (with-demoted-errors "Directory-local variables error: %s"
  3036. ;; Note this is a no-op if enable-local-variables is nil.
  3037. (hack-dir-local-variables)))
  3038. ;; This entire function is basically a no-op if enable-local-variables
  3039. ;; is nil. All it does is set file-local-variables-alist to nil.
  3040. (when enable-local-variables
  3041. ;; This part used to ignore enable-local-variables when mode-only
  3042. ;; was non-nil. That was inappropriate, eg consider the
  3043. ;; (artificial) example of:
  3044. ;; (setq local-enable-local-variables nil)
  3045. ;; Open a file foo.txt that contains "mode: sh".
  3046. ;; It correctly opens in text-mode.
  3047. ;; M-x set-visited-file name foo.c, and it incorrectly stays in text-mode.
  3048. (unless (or (inhibit-local-variables-p)
  3049. ;; If MODE-ONLY is non-nil, and the prop line specifies a
  3050. ;; mode, then we're done, and have no need to scan further.
  3051. (and (setq result (hack-local-variables-prop-line mode-only))
  3052. mode-only))
  3053. ;; Look for "Local variables:" line in last page.
  3054. (save-excursion
  3055. (goto-char (point-max))
  3056. (search-backward "\n\^L" (max (- (point-max) 3000) (point-min))
  3057. 'move)
  3058. (when (let ((case-fold-search t))
  3059. (search-forward "Local Variables:" nil t))
  3060. (skip-chars-forward " \t")
  3061. ;; suffix is what comes after "local variables:" in its line.
  3062. ;; prefix is what comes before "local variables:" in its line.
  3063. (let ((suffix
  3064. (concat
  3065. (regexp-quote (buffer-substring (point)
  3066. (line-end-position)))
  3067. "$"))
  3068. (prefix
  3069. (concat "^" (regexp-quote
  3070. (buffer-substring (line-beginning-position)
  3071. (match-beginning 0))))))
  3072. (forward-line 1)
  3073. (let ((startpos (point))
  3074. endpos
  3075. (thisbuf (current-buffer)))
  3076. (save-excursion
  3077. (unless (let ((case-fold-search t))
  3078. (re-search-forward
  3079. (concat prefix "[ \t]*End:[ \t]*" suffix)
  3080. nil t))
  3081. ;; This used to be an error, but really all it means is
  3082. ;; that this may simply not be a local-variables section,
  3083. ;; so just ignore it.
  3084. (message "Local variables list is not properly terminated"))
  3085. (beginning-of-line)
  3086. (setq endpos (point)))
  3087. (with-temp-buffer
  3088. (insert-buffer-substring thisbuf startpos endpos)
  3089. (goto-char (point-min))
  3090. (subst-char-in-region (point) (point-max) ?\^m ?\n)
  3091. (while (not (eobp))
  3092. ;; Discard the prefix.
  3093. (if (looking-at prefix)
  3094. (delete-region (point) (match-end 0))
  3095. (error "Local variables entry is missing the prefix"))
  3096. (end-of-line)
  3097. ;; Discard the suffix.
  3098. (if (looking-back suffix (line-beginning-position))
  3099. (delete-region (match-beginning 0) (point))
  3100. (error "Local variables entry is missing the suffix"))
  3101. (forward-line 1))
  3102. (goto-char (point-min))
  3103. (while (not (or (eobp)
  3104. (and mode-only result)))
  3105. ;; Find the variable name;
  3106. (unless (looking-at hack-local-variable-regexp)
  3107. (error "Malformed local variable line: %S"
  3108. (buffer-substring-no-properties
  3109. (point) (line-end-position))))
  3110. (goto-char (match-end 1))
  3111. (let* ((str (match-string 1))
  3112. (var (intern str))
  3113. val val2)
  3114. (and (equal (downcase (symbol-name var)) "mode")
  3115. (setq var 'mode))
  3116. ;; Read the variable value.
  3117. (skip-chars-forward "^:")
  3118. (forward-char 1)
  3119. (let ((read-circle nil))
  3120. (setq val (read (current-buffer))))
  3121. (if mode-only
  3122. (and (eq var 'mode)
  3123. ;; Specifying minor-modes via mode: is
  3124. ;; deprecated, but try to reject them anyway.
  3125. (not (string-match
  3126. "-minor\\'"
  3127. (setq val2 (downcase (symbol-name val)))))
  3128. (setq result (intern (concat val2 "-mode"))))
  3129. (cond ((eq var 'coding))
  3130. ((eq var 'lexical-binding)
  3131. (unless hack-local-variables--warned-lexical
  3132. (setq hack-local-variables--warned-lexical t)
  3133. (display-warning
  3134. :warning
  3135. (format-message
  3136. "%s: `lexical-binding' at end of file unreliable"
  3137. (file-name-nondirectory
  3138. (or buffer-file-name ""))))))
  3139. (t
  3140. (ignore-errors
  3141. (push (cons (if (eq var 'eval)
  3142. 'eval
  3143. (indirect-variable var))
  3144. val) result))))))
  3145. (forward-line 1))))))))
  3146. ;; Now we've read all the local variables.
  3147. ;; If MODE-ONLY is non-nil, return whether the mode was specified.
  3148. (if mode-only result
  3149. ;; Otherwise, set the variables.
  3150. (hack-local-variables-filter result nil)
  3151. (hack-local-variables-apply)))))
  3152. (defun hack-local-variables-apply ()
  3153. "Apply the elements of `file-local-variables-alist'.
  3154. If there are any elements, runs `before-hack-local-variables-hook',
  3155. then calls `hack-one-local-variable' to apply the alist elements one by one.
  3156. Finishes by running `hack-local-variables-hook', regardless of whether
  3157. the alist is empty or not.
  3158. Note that this function ignores a `mode' entry if it specifies the same
  3159. major mode as the buffer already has."
  3160. (when file-local-variables-alist
  3161. ;; Any 'evals must run in the Right sequence.
  3162. (setq file-local-variables-alist
  3163. (nreverse file-local-variables-alist))
  3164. (run-hooks 'before-hack-local-variables-hook)
  3165. (dolist (elt file-local-variables-alist)
  3166. (hack-one-local-variable (car elt) (cdr elt))))
  3167. (run-hooks 'hack-local-variables-hook))
  3168. (defun safe-local-variable-p (sym val)
  3169. "Non-nil if SYM is safe as a file-local variable with value VAL.
  3170. It is safe if any of these conditions are met:
  3171. * There is a matching entry (SYM . VAL) in the
  3172. `safe-local-variable-values' user option.
  3173. * The `safe-local-variable' property of SYM is a function that
  3174. evaluates to a non-nil value with VAL as an argument."
  3175. (or (member (cons sym val) safe-local-variable-values)
  3176. (let ((safep (get sym 'safe-local-variable)))
  3177. (and (functionp safep)
  3178. ;; If the function signals an error, that means it
  3179. ;; can't assure us that the value is safe.
  3180. (with-demoted-errors (funcall safep val))))))
  3181. (defun risky-local-variable-p (sym &optional _ignored)
  3182. "Non-nil if SYM could be dangerous as a file-local variable.
  3183. It is dangerous if either of these conditions are met:
  3184. * Its `risky-local-variable' property is non-nil.
  3185. * Its name ends with \"hook(s)\", \"function(s)\", \"form(s)\", \"map\",
  3186. \"program\", \"command(s)\", \"predicate(s)\", \"frame-alist\",
  3187. \"mode-alist\", \"font-lock-(syntactic-)keyword*\",
  3188. \"map-alist\", or \"bindat-spec\"."
  3189. ;; If this is an alias, check the base name.
  3190. (condition-case nil
  3191. (setq sym (indirect-variable sym))
  3192. (error nil))
  3193. (or (get sym 'risky-local-variable)
  3194. (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|\
  3195. -commands?$\\|-predicates?$\\|font-lock-keywords$\\|font-lock-keywords\
  3196. -[0-9]+$\\|font-lock-syntactic-keywords$\\|-frame-alist$\\|-mode-alist$\\|\
  3197. -map$\\|-map-alist$\\|-bindat-spec$" (symbol-name sym))))
  3198. (defun hack-one-local-variable-quotep (exp)
  3199. (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
  3200. (defun hack-one-local-variable-constantp (exp)
  3201. (or (and (not (symbolp exp)) (not (consp exp)))
  3202. (memq exp '(t nil))
  3203. (keywordp exp)
  3204. (hack-one-local-variable-quotep exp)))
  3205. (defun hack-one-local-variable-eval-safep (exp)
  3206. "Return t if it is safe to eval EXP when it is found in a file."
  3207. (or (not (consp exp))
  3208. ;; Detect certain `put' expressions.
  3209. (and (eq (car exp) 'put)
  3210. (hack-one-local-variable-quotep (nth 1 exp))
  3211. (hack-one-local-variable-quotep (nth 2 exp))
  3212. (let ((prop (nth 1 (nth 2 exp)))
  3213. (val (nth 3 exp)))
  3214. (cond ((memq prop '(lisp-indent-hook
  3215. lisp-indent-function
  3216. scheme-indent-function))
  3217. ;; Only allow safe values (not functions).
  3218. (or (numberp val)
  3219. (and (hack-one-local-variable-quotep val)
  3220. (eq (nth 1 val) 'defun))))
  3221. ((eq prop 'edebug-form-spec)
  3222. ;; Only allow indirect form specs.
  3223. ;; During bootstrapping, edebug-basic-spec might not be
  3224. ;; defined yet.
  3225. (and (fboundp 'edebug-basic-spec)
  3226. (hack-one-local-variable-quotep val)
  3227. (edebug-basic-spec (nth 1 val)))))))
  3228. ;; Allow expressions that the user requested.
  3229. (member exp safe-local-eval-forms)
  3230. ;; Certain functions can be allowed with safe arguments
  3231. ;; or can specify verification functions to try.
  3232. (and (symbolp (car exp))
  3233. ;; Allow (minor)-modes calls with no arguments.
  3234. ;; This obsoletes the use of "mode:" for such things. (Bug#8613)
  3235. (or (and (member (cdr exp) '(nil (1) (0) (-1)))
  3236. (string-match "-mode\\'" (symbol-name (car exp))))
  3237. (let ((prop (get (car exp) 'safe-local-eval-function)))
  3238. (cond ((eq prop t)
  3239. (let ((ok t))
  3240. (dolist (arg (cdr exp))
  3241. (unless (hack-one-local-variable-constantp arg)
  3242. (setq ok nil)))
  3243. ok))
  3244. ((functionp prop)
  3245. (funcall prop exp))
  3246. ((listp prop)
  3247. (let ((ok nil))
  3248. (dolist (function prop)
  3249. (if (funcall function exp)
  3250. (setq ok t)))
  3251. ok))))))))
  3252. (defun hack-one-local-variable--obsolete (var)
  3253. (let ((o (get var 'byte-obsolete-variable)))
  3254. (when o
  3255. (let ((instead (nth 0 o))
  3256. (since (nth 2 o)))
  3257. (message "%s is obsolete%s; %s"
  3258. var (if since (format " (since %s)" since))
  3259. (if (stringp instead)
  3260. (substitute-command-keys instead)
  3261. (format-message "use `%s' instead" instead)))))))
  3262. (defun hack-one-local-variable (var val)
  3263. "Set local variable VAR with value VAL.
  3264. If VAR is `mode', call `VAL-mode' as a function unless it's
  3265. already the major mode."
  3266. (pcase var
  3267. (`mode
  3268. (let ((mode (intern (concat (downcase (symbol-name val))
  3269. "-mode"))))
  3270. (unless (eq (indirect-function mode)
  3271. (indirect-function major-mode))
  3272. (funcall mode))))
  3273. (`eval
  3274. (pcase val
  3275. (`(add-hook ',hook . ,_) (hack-one-local-variable--obsolete hook)))
  3276. (save-excursion (eval val)))
  3277. (_
  3278. (hack-one-local-variable--obsolete var)
  3279. ;; Make sure the string has no text properties.
  3280. ;; Some text properties can get evaluated in various ways,
  3281. ;; so it is risky to put them on with a local variable list.
  3282. (if (stringp val)
  3283. (set-text-properties 0 (length val) nil val))
  3284. (set (make-local-variable var) val))))
  3285. ;;; Handling directory-local variables, aka project settings.
  3286. (defvar dir-locals-class-alist '()
  3287. "Alist mapping directory-local variable classes (symbols) to variable lists.")
  3288. (defvar dir-locals-directory-cache '()
  3289. "List of cached directory roots for directory-local variable classes.
  3290. Each element in this list has the form (DIR CLASS MTIME).
  3291. DIR is the name of the directory.
  3292. CLASS is the name of a variable class (a symbol).
  3293. MTIME is the recorded modification time of the directory-local
  3294. variables file associated with this entry. This time is a list
  3295. of integers (the same format as `file-attributes'), and is
  3296. used to test whether the cache entry is still valid.
  3297. Alternatively, MTIME can be nil, which means the entry is always
  3298. considered valid.")
  3299. (defsubst dir-locals-get-class-variables (class)
  3300. "Return the variable list for CLASS."
  3301. (cdr (assq class dir-locals-class-alist)))
  3302. (defun dir-locals-collect-mode-variables (mode-variables variables)
  3303. "Collect directory-local variables from MODE-VARIABLES.
  3304. VARIABLES is the initial list of variables.
  3305. Returns the new list."
  3306. (dolist (pair mode-variables variables)
  3307. (let* ((variable (car pair))
  3308. (value (cdr pair))
  3309. (slot (assq variable variables)))
  3310. ;; If variables are specified more than once, only use the last. (Why?)
  3311. ;; The pseudo-variables mode and eval are different (bug#3430).
  3312. (if (and slot (not (memq variable '(mode eval))))
  3313. (setcdr slot value)
  3314. ;; Need a new cons in case we setcdr later.
  3315. (push (cons variable value) variables)))))
  3316. (defun dir-locals-collect-variables (class-variables root variables)
  3317. "Collect entries from CLASS-VARIABLES into VARIABLES.
  3318. ROOT is the root directory of the project.
  3319. Return the new variables list."
  3320. (let* ((file-name (or (buffer-file-name)
  3321. ;; Handle non-file buffers, too.
  3322. (expand-file-name default-directory)))
  3323. (sub-file-name (if file-name
  3324. ;; FIXME: Why not use file-relative-name?
  3325. (substring file-name (length root)))))
  3326. (condition-case err
  3327. (dolist (entry class-variables variables)
  3328. (let ((key (car entry)))
  3329. (cond
  3330. ((stringp key)
  3331. ;; Don't include this in the previous condition, because we
  3332. ;; want to filter all strings before the next condition.
  3333. (when (and sub-file-name
  3334. (>= (length sub-file-name) (length key))
  3335. (string-prefix-p key sub-file-name))
  3336. (setq variables (dir-locals-collect-variables
  3337. (cdr entry) root variables))))
  3338. ((or (not key)
  3339. (derived-mode-p key))
  3340. (let* ((alist (cdr entry))
  3341. (subdirs (assq 'subdirs alist)))
  3342. (if (or (not subdirs)
  3343. (progn
  3344. (setq alist (delq subdirs alist))
  3345. (cdr-safe subdirs))
  3346. ;; TODO someone might want to extend this to allow
  3347. ;; integer values for subdir, where N means
  3348. ;; variables apply to this directory and N levels
  3349. ;; below it (0 == nil).
  3350. (equal root default-directory))
  3351. (setq variables (dir-locals-collect-mode-variables
  3352. alist variables))))))))
  3353. (error
  3354. ;; The file's content might be invalid (e.g. have a merge conflict), but
  3355. ;; that shouldn't prevent the user from opening the file.
  3356. (message "%s error: %s" dir-locals-file (error-message-string err))
  3357. nil))))
  3358. (defun dir-locals-set-directory-class (directory class &optional mtime)
  3359. "Declare that the DIRECTORY root is an instance of CLASS.
  3360. DIRECTORY is the name of a directory, a string.
  3361. CLASS is the name of a project class, a symbol.
  3362. MTIME is either the modification time of the directory-local
  3363. variables file that defined this class, or nil.
  3364. When a file beneath DIRECTORY is visited, the mode-specific
  3365. variables from CLASS are applied to the buffer. The variables
  3366. for a class are defined using `dir-locals-set-class-variables'."
  3367. (setq directory (file-name-as-directory (expand-file-name directory)))
  3368. (unless (assq class dir-locals-class-alist)
  3369. (error "No such class `%s'" (symbol-name class)))
  3370. (push (list directory class mtime) dir-locals-directory-cache))
  3371. (defun dir-locals-set-class-variables (class variables)
  3372. "Map the type CLASS to a list of variable settings.
  3373. CLASS is the project class, a symbol. VARIABLES is a list
  3374. that declares directory-local variables for the class.
  3375. An element in VARIABLES is either of the form:
  3376. (MAJOR-MODE . ALIST)
  3377. or
  3378. (DIRECTORY . LIST)
  3379. In the first form, MAJOR-MODE is a symbol, and ALIST is an alist
  3380. whose elements are of the form (VARIABLE . VALUE).
  3381. In the second form, DIRECTORY is a directory name (a string), and
  3382. LIST is a list of the form accepted by the function.
  3383. When a file is visited, the file's class is found. A directory
  3384. may be assigned a class using `dir-locals-set-directory-class'.
  3385. Then variables are set in the file's buffer according to the
  3386. VARIABLES list of the class. The list is processed in order.
  3387. * If the element is of the form (MAJOR-MODE . ALIST), and the
  3388. buffer's major mode is derived from MAJOR-MODE (as determined
  3389. by `derived-mode-p'), then all the variables in ALIST are
  3390. applied. A MAJOR-MODE of nil may be used to match any buffer.
  3391. `make-local-variable' is called for each variable before it is
  3392. set.
  3393. * If the element is of the form (DIRECTORY . LIST), and DIRECTORY
  3394. is an initial substring of the file's directory, then LIST is
  3395. applied by recursively following these rules."
  3396. (setf (alist-get class dir-locals-class-alist) variables))
  3397. (defconst dir-locals-file ".dir-locals*.el"
  3398. "Pattern for files that contain directory-local variables.
  3399. It has to be constant to enforce uniform values across different
  3400. environments and users.
  3401. Multiple dir-locals files in the same directory are loaded in
  3402. `string<' order.
  3403. See Info node `(elisp)Directory Local Variables' for details.")
  3404. (defun dir-locals--all-files (file-or-dir)
  3405. "Return a list of all readable dir-locals files matching FILE-OR-DIR.
  3406. If FILE-OR-DIR is a file pattern, expand wildcards in it and
  3407. return a sorted list of the results. If it is a directory name,
  3408. return a sorted list of all files matching `dir-locals-file' in
  3409. this directory.
  3410. The returned list is sorted by `string<' order."
  3411. (require 'seq)
  3412. (let ((default-directory (if (file-directory-p file-or-dir)
  3413. file-or-dir
  3414. default-directory)))
  3415. (seq-filter (lambda (f) (and (file-readable-p f)
  3416. (file-regular-p f)))
  3417. (file-expand-wildcards
  3418. (cond ((not (file-directory-p file-or-dir)) file-or-dir)
  3419. ((eq system-type 'ms-dos) (dosified-file-name dir-locals-file))
  3420. (t dir-locals-file))
  3421. 'full))))
  3422. (defun dir-locals-find-file (file)
  3423. "Find the directory-local variables for FILE.
  3424. This searches upward in the directory tree from FILE.
  3425. It stops at the first directory that has been registered in
  3426. `dir-locals-directory-cache' or contains a `dir-locals-file'.
  3427. If it finds an entry in the cache, it checks that it is valid.
  3428. A cache entry with no modification time element (normally, one that
  3429. has been assigned directly using `dir-locals-set-directory-class', not
  3430. set from a file) is always valid.
  3431. A cache entry based on a `dir-locals-file' is valid if the modification
  3432. time stored in the cache matches the current file modification time.
  3433. If not, the cache entry is cleared so that the file will be re-read.
  3434. This function returns either nil (no directory local variables found),
  3435. or the matching entry from `dir-locals-directory-cache' (a list),
  3436. or the full path to the `dir-locals-file' (a string) in the case
  3437. of no valid cache entry. If `dir-locals-file' contains
  3438. wildcards, then the return value is not a proper filename, it is
  3439. an absolute version of `dir-locals-file' which is guaranteed to
  3440. expand to at least one file."
  3441. (setq file (expand-file-name file))
  3442. (let* ((locals-dir (locate-dominating-file (file-name-directory file)
  3443. #'dir-locals--all-files))
  3444. locals-file dir-elt)
  3445. ;; `locate-dominating-file' may have abbreviated the name.
  3446. (when locals-dir
  3447. (setq locals-dir (expand-file-name locals-dir))
  3448. (setq locals-file (expand-file-name (if (eq system-type 'ms-dos)
  3449. (dosified-file-name dir-locals-file)
  3450. dir-locals-file)
  3451. locals-dir)))
  3452. ;; Find the best cached value in `dir-locals-directory-cache'.
  3453. (dolist (elt dir-locals-directory-cache)
  3454. (when (and (string-prefix-p (car elt) file
  3455. (memq system-type
  3456. '(windows-nt cygwin ms-dos)))
  3457. (> (length (car elt)) (length (car dir-elt))))
  3458. (setq dir-elt elt)))
  3459. (if (and dir-elt
  3460. (or (null locals-dir)
  3461. (<= (length locals-dir)
  3462. (length (car dir-elt)))))
  3463. ;; Found a potential cache entry. Check validity.
  3464. ;; A cache entry with no MTIME is assumed to always be valid
  3465. ;; (ie, set directly, not from a dir-locals file).
  3466. ;; Note, we don't bother to check that there is a matching class
  3467. ;; element in dir-locals-class-alist, since that's done by
  3468. ;; dir-locals-set-directory-class.
  3469. (if (or (null (nth 2 dir-elt))
  3470. (let ((cached-files (dir-locals--all-files (car dir-elt))))
  3471. ;; The entry MTIME should match the most recent
  3472. ;; MTIME among matching files.
  3473. (and cached-files
  3474. (= (time-to-seconds (nth 2 dir-elt))
  3475. (apply #'max (mapcar (lambda (f) (time-to-seconds (nth 5 (file-attributes f))))
  3476. cached-files))))))
  3477. ;; This cache entry is OK.
  3478. dir-elt
  3479. ;; This cache entry is invalid; clear it.
  3480. (setq dir-locals-directory-cache
  3481. (delq dir-elt dir-locals-directory-cache))
  3482. ;; Return the first existing dir-locals file. Might be the same
  3483. ;; as dir-elt's, might not (eg latter might have been deleted).
  3484. locals-file)
  3485. ;; No cache entry.
  3486. locals-file)))
  3487. (defun dir-locals-read-from-file (file)
  3488. "Load a variables FILE and register a new class and instance.
  3489. FILE is the absolute name of the file holding the variables to
  3490. apply. It may contain wildcards.
  3491. The new class name is the same as the directory in which FILE
  3492. is found. Returns the new class name."
  3493. (require 'map)
  3494. (let* ((dir-name (file-name-directory file))
  3495. (class-name (intern dir-name))
  3496. (files (dir-locals--all-files file))
  3497. (read-circle nil)
  3498. (success nil)
  3499. (variables))
  3500. (with-demoted-errors "Error reading dir-locals: %S"
  3501. (dolist (file files)
  3502. (with-temp-buffer
  3503. (insert-file-contents file)
  3504. (condition-case-unless-debug nil
  3505. (setq variables
  3506. (map-merge-with 'list (lambda (a b) (map-merge 'list a b))
  3507. variables
  3508. (read (current-buffer))))
  3509. (end-of-file nil))))
  3510. (setq success t))
  3511. (dir-locals-set-class-variables class-name variables)
  3512. (dir-locals-set-directory-class
  3513. dir-name class-name
  3514. (seconds-to-time
  3515. (if success
  3516. (apply #'max (mapcar (lambda (file)
  3517. (time-to-seconds (nth 5 (file-attributes file))))
  3518. files))
  3519. ;; If there was a problem, use the values we could get but
  3520. ;; don't let the cache prevent future reads.
  3521. 0)))
  3522. class-name))
  3523. (defcustom enable-remote-dir-locals nil
  3524. "Non-nil means dir-local variables will be applied to remote files."
  3525. :version "24.3"
  3526. :type 'boolean
  3527. :group 'find-file)
  3528. (defvar hack-dir-local-variables--warned-coding nil)
  3529. (defun hack-dir-local-variables ()
  3530. "Read per-directory local variables for the current buffer.
  3531. Store the directory-local variables in `dir-local-variables-alist'
  3532. and `file-local-variables-alist', without applying them.
  3533. This does nothing if either `enable-local-variables' or
  3534. `enable-dir-local-variables' are nil."
  3535. (when (and enable-local-variables
  3536. enable-dir-local-variables
  3537. (or enable-remote-dir-locals
  3538. (not (file-remote-p (or (buffer-file-name)
  3539. default-directory)))))
  3540. ;; Find the variables file.
  3541. (let ((file-pattern-or-cache (dir-locals-find-file
  3542. (or (buffer-file-name) default-directory)))
  3543. (class nil)
  3544. (dir-name nil))
  3545. (cond
  3546. ((stringp file-pattern-or-cache)
  3547. (setq dir-name (file-name-directory file-pattern-or-cache)
  3548. class (dir-locals-read-from-file file-pattern-or-cache)))
  3549. ((consp file-pattern-or-cache)
  3550. (setq dir-name (nth 0 file-pattern-or-cache))
  3551. (setq class (nth 1 file-pattern-or-cache))))
  3552. (when class
  3553. (let ((variables
  3554. (dir-locals-collect-variables
  3555. (dir-locals-get-class-variables class) dir-name nil)))
  3556. (when variables
  3557. (dolist (elt variables)
  3558. (if (eq (car elt) 'coding)
  3559. (unless hack-dir-local-variables--warned-coding
  3560. (setq hack-dir-local-variables--warned-coding t)
  3561. (display-warning :warning
  3562. "Coding cannot be specified by dir-locals"))
  3563. (unless (memq (car elt) '(eval mode))
  3564. (setq dir-local-variables-alist
  3565. (assq-delete-all (car elt) dir-local-variables-alist)))
  3566. (push elt dir-local-variables-alist)))
  3567. (hack-local-variables-filter variables dir-name)))))))
  3568. (defun hack-dir-local-variables-non-file-buffer ()
  3569. "Apply directory-local variables to a non-file buffer.
  3570. For non-file buffers, such as Dired buffers, directory-local
  3571. variables are looked for in `default-directory' and its parent
  3572. directories."
  3573. (hack-dir-local-variables)
  3574. (hack-local-variables-apply))
  3575. (defcustom change-major-mode-with-file-name t
  3576. "Non-nil means \\[write-file] should set the major mode from the file name.
  3577. However, the mode will not be changed if
  3578. \(1) a local variables list or the `-*-' line specifies a major mode, or
  3579. \(2) the current major mode is a \"special\" mode,
  3580. not suitable for ordinary files, or
  3581. \(3) the new file name does not particularly specify any mode."
  3582. :type 'boolean
  3583. :group 'editing-basics)
  3584. (defun set-visited-file-name (filename &optional no-query along-with-file)
  3585. "Change name of file visited in current buffer to FILENAME.
  3586. This also renames the buffer to correspond to the new file.
  3587. The next time the buffer is saved it will go in the newly specified file.
  3588. FILENAME nil or an empty string means mark buffer as not visiting any file.
  3589. Remember to delete the initial contents of the minibuffer
  3590. if you wish to pass an empty string as the argument.
  3591. The optional second argument NO-QUERY, if non-nil, inhibits asking for
  3592. confirmation in the case where another buffer is already visiting FILENAME.
  3593. The optional third argument ALONG-WITH-FILE, if non-nil, means that
  3594. the old visited file has been renamed to the new name FILENAME."
  3595. (interactive "FSet visited file name: ")
  3596. (if (buffer-base-buffer)
  3597. (error "An indirect buffer cannot visit a file"))
  3598. (let (truename old-try-locals)
  3599. (if filename
  3600. (setq filename
  3601. (if (string-equal filename "")
  3602. nil
  3603. (expand-file-name filename))))
  3604. (if filename
  3605. (progn
  3606. (setq truename (file-truename filename))
  3607. (if find-file-visit-truename
  3608. (setq filename truename))))
  3609. (if filename
  3610. (let ((new-name (file-name-nondirectory filename)))
  3611. (if (string= new-name "")
  3612. (error "Empty file name"))))
  3613. (let ((buffer (and filename (find-buffer-visiting filename))))
  3614. (and buffer (not (eq buffer (current-buffer)))
  3615. (not no-query)
  3616. (not (y-or-n-p (format "A buffer is visiting %s; proceed? "
  3617. filename)))
  3618. (user-error "Aborted")))
  3619. (or (equal filename buffer-file-name)
  3620. (progn
  3621. (and filename (lock-buffer filename))
  3622. (unlock-buffer)))
  3623. (setq old-try-locals (not (inhibit-local-variables-p))
  3624. buffer-file-name filename)
  3625. (if filename ; make buffer name reflect filename.
  3626. (let ((new-name (file-name-nondirectory buffer-file-name)))
  3627. (setq default-directory (file-name-directory buffer-file-name))
  3628. ;; If new-name == old-name, renaming would add a spurious <2>
  3629. ;; and it's considered as a feature in rename-buffer.
  3630. (or (string= new-name (buffer-name))
  3631. (rename-buffer new-name t))))
  3632. (setq buffer-backed-up nil)
  3633. (or along-with-file
  3634. (clear-visited-file-modtime))
  3635. ;; Abbreviate the file names of the buffer.
  3636. (if truename
  3637. (progn
  3638. (setq buffer-file-truename (abbreviate-file-name truename))
  3639. (if find-file-visit-truename
  3640. (setq buffer-file-name truename))))
  3641. (setq buffer-file-number
  3642. (if filename
  3643. (nthcdr 10 (file-attributes buffer-file-name))
  3644. nil))
  3645. ;; write-file-functions is normally used for things like ftp-find-file
  3646. ;; that visit things that are not local files as if they were files.
  3647. ;; Changing to visit an ordinary local file instead should flush the hook.
  3648. (kill-local-variable 'write-file-functions)
  3649. (kill-local-variable 'local-write-file-hooks)
  3650. (kill-local-variable 'revert-buffer-function)
  3651. (kill-local-variable 'backup-inhibited)
  3652. ;; If buffer was read-only because of version control,
  3653. ;; that reason is gone now, so make it writable.
  3654. (if vc-mode
  3655. (setq buffer-read-only nil))
  3656. (kill-local-variable 'vc-mode)
  3657. ;; Turn off backup files for certain file names.
  3658. ;; Since this is a permanent local, the major mode won't eliminate it.
  3659. (and buffer-file-name
  3660. backup-enable-predicate
  3661. (not (funcall backup-enable-predicate buffer-file-name))
  3662. (progn
  3663. (make-local-variable 'backup-inhibited)
  3664. (setq backup-inhibited t)))
  3665. (let ((oauto buffer-auto-save-file-name))
  3666. (cond ((null filename)
  3667. (setq buffer-auto-save-file-name nil))
  3668. ((not buffer-auto-save-file-name)
  3669. ;; If auto-save was not already on, turn it on if appropriate.
  3670. (and buffer-file-name auto-save-default (auto-save-mode t)))
  3671. (t
  3672. ;; If auto save is on, start using a new name. We
  3673. ;; deliberately don't rename or delete the old auto save
  3674. ;; for the old visited file name. This is because
  3675. ;; perhaps the user wants to save the new state and then
  3676. ;; compare with the previous state from the auto save
  3677. ;; file.
  3678. (setq buffer-auto-save-file-name (make-auto-save-file-name))))
  3679. ;; Rename the old auto save file if any.
  3680. (and oauto buffer-auto-save-file-name
  3681. (file-exists-p oauto)
  3682. (rename-file oauto buffer-auto-save-file-name t)))
  3683. (and buffer-file-name
  3684. (not along-with-file)
  3685. (set-buffer-modified-p t))
  3686. ;; Update the major mode, if the file name determines it.
  3687. (condition-case nil
  3688. ;; Don't change the mode if it is special.
  3689. (or (not change-major-mode-with-file-name)
  3690. (get major-mode 'mode-class)
  3691. ;; Don't change the mode if the local variable list specifies it.
  3692. ;; The file name can influence whether the local variables apply.
  3693. (and old-try-locals
  3694. ;; h-l-v also checks it, but might as well be explicit.
  3695. (not (inhibit-local-variables-p))
  3696. (hack-local-variables t))
  3697. ;; TODO consider making normal-mode handle this case.
  3698. (let ((old major-mode))
  3699. (set-auto-mode t)
  3700. (or (eq old major-mode)
  3701. (hack-local-variables))))
  3702. (error nil))))
  3703. (defun write-file (filename &optional confirm)
  3704. "Write current buffer into file FILENAME.
  3705. This makes the buffer visit that file, and marks it as not modified.
  3706. If you specify just a directory name as FILENAME, that means to use
  3707. the default file name but in that directory. You can also yank
  3708. the default file name into the minibuffer to edit it, using \\<minibuffer-local-map>\\[next-history-element].
  3709. If the buffer is not already visiting a file, the default file name
  3710. for the output file is the buffer name.
  3711. If optional second arg CONFIRM is non-nil, this function
  3712. asks for confirmation before overwriting an existing file.
  3713. Interactively, confirmation is required unless you supply a prefix argument."
  3714. ;; (interactive "FWrite file: ")
  3715. (interactive
  3716. (list (if buffer-file-name
  3717. (read-file-name "Write file: "
  3718. nil nil nil nil)
  3719. (read-file-name "Write file: " default-directory
  3720. (expand-file-name
  3721. (file-name-nondirectory (buffer-name))
  3722. default-directory)
  3723. nil nil))
  3724. (not current-prefix-arg)))
  3725. (or (null filename) (string-equal filename "")
  3726. (progn
  3727. ;; If arg is just a directory,
  3728. ;; use the default file name, but in that directory.
  3729. (if (file-directory-p filename)
  3730. (setq filename (concat (file-name-as-directory filename)
  3731. (file-name-nondirectory
  3732. (or buffer-file-name (buffer-name))))))
  3733. (and confirm
  3734. (file-exists-p filename)
  3735. ;; NS does its own confirm dialog.
  3736. (not (and (eq (framep-on-display) 'ns)
  3737. (listp last-nonmenu-event)
  3738. use-dialog-box))
  3739. (or (y-or-n-p (format-message
  3740. "File `%s' exists; overwrite? " filename))
  3741. (user-error "Canceled")))
  3742. (set-visited-file-name filename (not confirm))))
  3743. (set-buffer-modified-p t)
  3744. ;; Make buffer writable if file is writable.
  3745. (and buffer-file-name
  3746. (file-writable-p buffer-file-name)
  3747. (setq buffer-read-only nil))
  3748. (save-buffer)
  3749. ;; It's likely that the VC status at the new location is different from
  3750. ;; the one at the old location.
  3751. (vc-refresh-state))
  3752. (defun file-extended-attributes (filename)
  3753. "Return an alist of extended attributes of file FILENAME.
  3754. Extended attributes are platform-specific metadata about the file,
  3755. such as SELinux context, list of ACL entries, etc."
  3756. `((acl . ,(file-acl filename))
  3757. (selinux-context . ,(file-selinux-context filename))))
  3758. (defun set-file-extended-attributes (filename attributes)
  3759. "Set extended attributes of file FILENAME to ATTRIBUTES.
  3760. ATTRIBUTES must be an alist of file attributes as returned by
  3761. `file-extended-attributes'.
  3762. Value is t if the function succeeds in setting the attributes."
  3763. (let (result rv)
  3764. (dolist (elt attributes)
  3765. (let ((attr (car elt))
  3766. (val (cdr elt)))
  3767. (cond ((eq attr 'acl)
  3768. (setq rv (set-file-acl filename val)))
  3769. ((eq attr 'selinux-context)
  3770. (setq rv (set-file-selinux-context filename val))))
  3771. (setq result (or result rv))))
  3772. result))
  3773. (defun backup-buffer ()
  3774. "Make a backup of the disk file visited by the current buffer, if appropriate.
  3775. This is normally done before saving the buffer the first time.
  3776. A backup may be done by renaming or by copying; see documentation of
  3777. variable `make-backup-files'. If it's done by renaming, then the file is
  3778. no longer accessible under its old name.
  3779. The value is non-nil after a backup was made by renaming.
  3780. It has the form (MODES EXTENDED-ATTRIBUTES BACKUPNAME).
  3781. MODES is the result of `file-modes' on the original
  3782. file; this means that the caller, after saving the buffer, should change
  3783. the modes of the new file to agree with the old modes.
  3784. EXTENDED-ATTRIBUTES is the result of `file-extended-attributes'
  3785. on the original file; this means that the caller, after saving
  3786. the buffer, should change the extended attributes of the new file
  3787. to agree with the old attributes.
  3788. BACKUPNAME is the backup file name, which is the old file renamed."
  3789. (when (and make-backup-files (not backup-inhibited) (not buffer-backed-up))
  3790. (let ((attributes (file-attributes buffer-file-name)))
  3791. (when (and attributes (memq (aref (elt attributes 8) 0) '(?- ?l)))
  3792. ;; If specified name is a symbolic link, chase it to the target.
  3793. ;; This makes backups in the directory where the real file is.
  3794. (let* ((real-file-name (file-chase-links buffer-file-name))
  3795. (backup-info (find-backup-file-name real-file-name)))
  3796. (when backup-info
  3797. (let* ((backupname (car backup-info))
  3798. (targets (cdr backup-info))
  3799. (old-versions
  3800. ;; If have old versions to maybe delete,
  3801. ;; ask the user to confirm now, before doing anything.
  3802. ;; But don't actually delete til later.
  3803. (and targets
  3804. (booleanp delete-old-versions)
  3805. (or delete-old-versions
  3806. (y-or-n-p
  3807. (format "Delete excess backup versions of %s? "
  3808. real-file-name)))
  3809. targets))
  3810. (modes (file-modes buffer-file-name))
  3811. (extended-attributes
  3812. (file-extended-attributes buffer-file-name))
  3813. (copy-when-priv-mismatch
  3814. backup-by-copying-when-privileged-mismatch)
  3815. (make-copy
  3816. (or file-precious-flag backup-by-copying
  3817. ;; Don't rename a suid or sgid file.
  3818. (and modes (< 0 (logand modes #o6000)))
  3819. (not (file-writable-p
  3820. (file-name-directory real-file-name)))
  3821. (and backup-by-copying-when-linked
  3822. (< 1 (file-nlinks real-file-name)))
  3823. (and (or backup-by-copying-when-mismatch
  3824. (and (integerp copy-when-priv-mismatch)
  3825. (let ((attr (file-attributes
  3826. real-file-name
  3827. 'integer)))
  3828. (<= (nth 2 attr)
  3829. copy-when-priv-mismatch))))
  3830. (not (file-ownership-preserved-p real-file-name
  3831. t)))))
  3832. setmodes)
  3833. (condition-case ()
  3834. (progn
  3835. ;; Actually make the backup file.
  3836. (if make-copy
  3837. (backup-buffer-copy real-file-name backupname
  3838. modes extended-attributes)
  3839. ;; rename-file should delete old backup.
  3840. (rename-file real-file-name backupname t)
  3841. (setq setmodes (list modes extended-attributes
  3842. backupname)))
  3843. (setq buffer-backed-up t)
  3844. ;; Now delete the old versions, if desired.
  3845. (dolist (old-version old-versions)
  3846. (delete-file old-version)))
  3847. (file-error nil))
  3848. ;; If trouble writing the backup, write it in .emacs.d/%backup%.
  3849. (when (not buffer-backed-up)
  3850. (setq backupname (locate-user-emacs-file "%backup%~"))
  3851. (message "Cannot write backup file; backing up in %s"
  3852. backupname)
  3853. (sleep-for 1)
  3854. (backup-buffer-copy real-file-name backupname
  3855. modes extended-attributes)
  3856. (setq buffer-backed-up t))
  3857. setmodes)))))))
  3858. (defun backup-buffer-copy (from-name to-name modes extended-attributes)
  3859. ;; Create temp files with strict access rights. It's easy to
  3860. ;; loosen them later, whereas it's impossible to close the
  3861. ;; time-window of loose permissions otherwise.
  3862. (with-file-modes ?\700
  3863. (when (condition-case nil
  3864. ;; Try to overwrite old backup first.
  3865. (copy-file from-name to-name t t t)
  3866. (error t))
  3867. (while (condition-case nil
  3868. (progn
  3869. (when (file-exists-p to-name)
  3870. (delete-file to-name))
  3871. (copy-file from-name to-name nil t t)
  3872. nil)
  3873. (file-already-exists t))
  3874. ;; The file was somehow created by someone else between
  3875. ;; `delete-file' and `copy-file', so let's try again.
  3876. ;; rms says "I think there is also a possible race
  3877. ;; condition for making backup files" (emacs-devel 20070821).
  3878. nil)))
  3879. ;; If set-file-extended-attributes fails, fall back on set-file-modes.
  3880. (unless (and extended-attributes
  3881. (with-demoted-errors
  3882. (set-file-extended-attributes to-name extended-attributes)))
  3883. (and modes
  3884. (set-file-modes to-name (logand modes #o1777)))))
  3885. (defvar file-name-version-regexp
  3886. "\\(?:~\\|\\.~[-[:alnum:]:#@^._]+\\(?:~[[:digit:]]+\\)?~\\)"
  3887. ;; The last ~[[:digit]]+ matches relative versions in git,
  3888. ;; e.g. `foo.js.~HEAD~1~'.
  3889. "Regular expression matching the backup/version part of a file name.
  3890. Used by `file-name-sans-versions'.")
  3891. (defun file-name-sans-versions (name &optional keep-backup-version)
  3892. "Return file NAME sans backup versions or strings.
  3893. This is a separate procedure so your site-init or startup file can
  3894. redefine it.
  3895. If the optional argument KEEP-BACKUP-VERSION is non-nil,
  3896. we do not remove backup version numbers, only true file version numbers.
  3897. See also `file-name-version-regexp'."
  3898. (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
  3899. (if handler
  3900. (funcall handler 'file-name-sans-versions name keep-backup-version)
  3901. (substring name 0
  3902. (unless keep-backup-version
  3903. (string-match (concat file-name-version-regexp "\\'")
  3904. name))))))
  3905. (defun file-ownership-preserved-p (file &optional group)
  3906. "Return t if deleting FILE and rewriting it would preserve the owner.
  3907. Return nil if FILE does not exist, or if deleting and recreating it
  3908. might not preserve the owner. If GROUP is non-nil, check whether
  3909. the group would be preserved too."
  3910. (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
  3911. (if handler
  3912. (funcall handler 'file-ownership-preserved-p file group)
  3913. (let ((attributes (file-attributes file 'integer)))
  3914. ;; Return t if the file doesn't exist, since it's true that no
  3915. ;; information would be lost by an (attempted) delete and create.
  3916. (or (null attributes)
  3917. (and (or (= (nth 2 attributes) (user-uid))
  3918. ;; Files created on Windows by Administrator (RID=500)
  3919. ;; have the Administrators group (RID=544) recorded as
  3920. ;; their owner. Rewriting them will still preserve the
  3921. ;; owner.
  3922. (and (eq system-type 'windows-nt)
  3923. (= (user-uid) 500) (= (nth 2 attributes) 544)))
  3924. (or (not group)
  3925. ;; On BSD-derived systems files always inherit the parent
  3926. ;; directory's group, so skip the group-gid test.
  3927. (memq system-type '(berkeley-unix darwin gnu/kfreebsd))
  3928. (= (nth 3 attributes) (group-gid)))
  3929. (let* ((parent (or (file-name-directory file) "."))
  3930. (parent-attributes (file-attributes parent 'integer)))
  3931. (and parent-attributes
  3932. ;; On some systems, a file created in a setuid directory
  3933. ;; inherits that directory's owner.
  3934. (or
  3935. (= (nth 2 parent-attributes) (user-uid))
  3936. (string-match "^...[^sS]" (nth 8 parent-attributes)))
  3937. ;; On many systems, a file created in a setgid directory
  3938. ;; inherits that directory's group. On some systems
  3939. ;; this happens even if the setgid bit is not set.
  3940. (or (not group)
  3941. (= (nth 3 parent-attributes)
  3942. (nth 3 attributes)))))))))))
  3943. (defun file-name-sans-extension (filename)
  3944. "Return FILENAME sans final \"extension\".
  3945. The extension, in a file name, is the part that follows the last `.',
  3946. except that a leading `.', if any, doesn't count."
  3947. (save-match-data
  3948. (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
  3949. directory)
  3950. (if (and (string-match "\\.[^.]*\\'" file)
  3951. (not (eq 0 (match-beginning 0))))
  3952. (if (setq directory (file-name-directory filename))
  3953. ;; Don't use expand-file-name here; if DIRECTORY is relative,
  3954. ;; we don't want to expand it.
  3955. (concat directory (substring file 0 (match-beginning 0)))
  3956. (substring file 0 (match-beginning 0)))
  3957. filename))))
  3958. (defun file-name-extension (filename &optional period)
  3959. "Return FILENAME's final \"extension\".
  3960. The extension, in a file name, is the part that follows the last `.',
  3961. excluding version numbers and backup suffixes,
  3962. except that a leading `.', if any, doesn't count.
  3963. Return nil for extensionless file names such as `foo'.
  3964. Return the empty string for file names such as `foo.'.
  3965. If PERIOD is non-nil, then the returned value includes the period
  3966. that delimits the extension, and if FILENAME has no extension,
  3967. the value is \"\"."
  3968. (save-match-data
  3969. (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
  3970. (if (and (string-match "\\.[^.]*\\'" file)
  3971. (not (eq 0 (match-beginning 0))))
  3972. (substring file (+ (match-beginning 0) (if period 0 1)))
  3973. (if period
  3974. "")))))
  3975. (defun file-name-base (&optional filename)
  3976. "Return the base name of the FILENAME: no directory, no extension.
  3977. FILENAME defaults to `buffer-file-name'."
  3978. (file-name-sans-extension
  3979. (file-name-nondirectory (or filename (buffer-file-name)))))
  3980. (defcustom make-backup-file-name-function
  3981. #'make-backup-file-name--default-function
  3982. "A function that `make-backup-file-name' uses to create backup file names.
  3983. The function receives a single argument, the original file name.
  3984. If you change this, you may need to change `backup-file-name-p' and
  3985. `file-name-sans-versions' too.
  3986. You could make this buffer-local to do something special for specific files.
  3987. For historical reasons, a value of nil means to use the default function.
  3988. This should not be relied upon.
  3989. See also `backup-directory-alist'."
  3990. :version "24.4" ; nil -> make-backup-file-name--default-function
  3991. :group 'backup
  3992. :type '(choice (const :tag "Deprecated way to get the default function" nil)
  3993. (function :tag "Function")))
  3994. (defcustom backup-directory-alist nil
  3995. "Alist of filename patterns and backup directory names.
  3996. Each element looks like (REGEXP . DIRECTORY). Backups of files with
  3997. names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
  3998. relative or absolute. If it is absolute, so that all matching files
  3999. are backed up into the same directory, the file names in this
  4000. directory will be the full name of the file backed up with all
  4001. directory separators changed to `!' to prevent clashes. This will not
  4002. work correctly if your filesystem truncates the resulting name.
  4003. For the common case of all backups going into one directory, the alist
  4004. should contain a single element pairing \".\" with the appropriate
  4005. directory name.
  4006. If this variable is nil, or it fails to match a filename, the backup
  4007. is made in the original file's directory.
  4008. On MS-DOS filesystems without long names this variable is always
  4009. ignored."
  4010. :group 'backup
  4011. :type '(repeat (cons (regexp :tag "Regexp matching filename")
  4012. (directory :tag "Backup directory name"))))
  4013. (defun normal-backup-enable-predicate (name)
  4014. "Default `backup-enable-predicate' function.
  4015. Checks for files in `temporary-file-directory',
  4016. `small-temporary-file-directory', and /tmp."
  4017. (let ((temporary-file-directory temporary-file-directory)
  4018. caseless)
  4019. ;; On MS-Windows, file-truename will convert short 8+3 aliases to
  4020. ;; their long file-name equivalents, so compare-strings does TRT.
  4021. (if (memq system-type '(ms-dos windows-nt))
  4022. (setq temporary-file-directory (file-truename temporary-file-directory)
  4023. name (file-truename name)
  4024. caseless t))
  4025. (not (or (let ((comp (compare-strings temporary-file-directory 0 nil
  4026. name 0 nil caseless)))
  4027. ;; Directory is under temporary-file-directory.
  4028. (and (not (eq comp t))
  4029. (< comp (- (length temporary-file-directory)))))
  4030. (let ((comp (compare-strings "/tmp" 0 nil
  4031. name 0 nil)))
  4032. ;; Directory is under /tmp.
  4033. (and (not (eq comp t))
  4034. (< comp (- (length "/tmp")))))
  4035. (if small-temporary-file-directory
  4036. (let ((comp (compare-strings small-temporary-file-directory
  4037. 0 nil
  4038. name 0 nil caseless)))
  4039. ;; Directory is under small-temporary-file-directory.
  4040. (and (not (eq comp t))
  4041. (< comp (- (length small-temporary-file-directory))))))))))
  4042. (defun make-backup-file-name (file)
  4043. "Create the non-numeric backup file name for FILE.
  4044. This calls the function that `make-backup-file-name-function' specifies,
  4045. with a single argument FILE."
  4046. (funcall (or make-backup-file-name-function
  4047. #'make-backup-file-name--default-function)
  4048. file))
  4049. (defun make-backup-file-name--default-function (file)
  4050. "Default function for `make-backup-file-name'.
  4051. Normally this just returns FILE's name with `~' appended.
  4052. It searches for a match for FILE in `backup-directory-alist'.
  4053. If the directory for the backup doesn't exist, it is created."
  4054. (if (and (eq system-type 'ms-dos)
  4055. (not (msdos-long-file-names)))
  4056. (let ((fn (file-name-nondirectory file)))
  4057. (concat (file-name-directory file)
  4058. (or (and (string-match "\\`[^.]+\\'" fn)
  4059. (concat (match-string 0 fn) ".~"))
  4060. (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
  4061. (concat (match-string 0 fn) "~")))))
  4062. (concat (make-backup-file-name-1 file) "~")))
  4063. (defun make-backup-file-name-1 (file)
  4064. "Subroutine of `make-backup-file-name--default-function'.
  4065. The function `find-backup-file-name' also uses this."
  4066. (let ((alist backup-directory-alist)
  4067. elt backup-directory abs-backup-directory)
  4068. (while alist
  4069. (setq elt (pop alist))
  4070. (if (string-match (car elt) file)
  4071. (setq backup-directory (cdr elt)
  4072. alist nil)))
  4073. ;; If backup-directory is relative, it should be relative to the
  4074. ;; file's directory. By expanding explicitly here, we avoid
  4075. ;; depending on default-directory.
  4076. (if backup-directory
  4077. (setq abs-backup-directory
  4078. (expand-file-name backup-directory
  4079. (file-name-directory file))))
  4080. (if (and abs-backup-directory (not (file-exists-p abs-backup-directory)))
  4081. (condition-case nil
  4082. (make-directory abs-backup-directory 'parents)
  4083. (file-error (setq backup-directory nil
  4084. abs-backup-directory nil))))
  4085. (if (null backup-directory)
  4086. file
  4087. (if (file-name-absolute-p backup-directory)
  4088. (progn
  4089. (when (memq system-type '(windows-nt ms-dos cygwin))
  4090. ;; Normalize DOSish file names: downcase the drive
  4091. ;; letter, if any, and replace the leading "x:" with
  4092. ;; "/drive_x".
  4093. (or (file-name-absolute-p file)
  4094. (setq file (expand-file-name file))) ; make defaults explicit
  4095. ;; Replace any invalid file-name characters (for the
  4096. ;; case of backing up remote files).
  4097. (setq file (expand-file-name (convert-standard-filename file)))
  4098. (if (eq (aref file 1) ?:)
  4099. (setq file (concat "/"
  4100. "drive_"
  4101. (char-to-string (downcase (aref file 0)))
  4102. (if (eq (aref file 2) ?/)
  4103. ""
  4104. "/")
  4105. (substring file 2)))))
  4106. ;; Make the name unique by substituting directory
  4107. ;; separators. It may not really be worth bothering about
  4108. ;; doubling `!'s in the original name...
  4109. (expand-file-name
  4110. (subst-char-in-string
  4111. ?/ ?!
  4112. (replace-regexp-in-string "!" "!!" file))
  4113. backup-directory))
  4114. (expand-file-name (file-name-nondirectory file)
  4115. (file-name-as-directory abs-backup-directory))))))
  4116. (defun backup-file-name-p (file)
  4117. "Return non-nil if FILE is a backup file name (numeric or not).
  4118. This is a separate function so you can redefine it for customization.
  4119. You may need to redefine `file-name-sans-versions' as well."
  4120. (string-match "~\\'" file))
  4121. (defvar backup-extract-version-start)
  4122. ;; This is used in various files.
  4123. ;; The usage of backup-extract-version-start is not very clean,
  4124. ;; but I can't see a good alternative, so as of now I am leaving it alone.
  4125. (defun backup-extract-version (fn)
  4126. "Given the name of a numeric backup file, FN, return the backup number.
  4127. Uses the free variable `backup-extract-version-start', whose value should be
  4128. the index in the name where the version number begins."
  4129. (if (and (string-match "[0-9]+~/?$" fn backup-extract-version-start)
  4130. (= (match-beginning 0) backup-extract-version-start))
  4131. (string-to-number (substring fn backup-extract-version-start -1))
  4132. 0))
  4133. (defun find-backup-file-name (fn)
  4134. "Find a file name for a backup file FN, and suggestions for deletions.
  4135. Value is a list whose car is the name for the backup file
  4136. and whose cdr is a list of old versions to consider deleting now.
  4137. If the value is nil, don't make a backup.
  4138. Uses `backup-directory-alist' in the same way as
  4139. `make-backup-file-name--default-function' does."
  4140. (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
  4141. ;; Run a handler for this function so that ange-ftp can refuse to do it.
  4142. (if handler
  4143. (funcall handler 'find-backup-file-name fn)
  4144. (if (or (eq version-control 'never)
  4145. ;; We don't support numbered backups on plain MS-DOS
  4146. ;; when long file names are unavailable.
  4147. (and (eq system-type 'ms-dos)
  4148. (not (msdos-long-file-names))))
  4149. (list (make-backup-file-name fn))
  4150. (let* ((basic-name (make-backup-file-name-1 fn))
  4151. (base-versions (concat (file-name-nondirectory basic-name)
  4152. ".~"))
  4153. (backup-extract-version-start (length base-versions))
  4154. (high-water-mark 0)
  4155. (number-to-delete 0)
  4156. possibilities deserve-versions-p versions)
  4157. (condition-case ()
  4158. (setq possibilities (file-name-all-completions
  4159. base-versions
  4160. (file-name-directory basic-name))
  4161. versions (sort (mapcar #'backup-extract-version
  4162. possibilities)
  4163. #'<)
  4164. high-water-mark (apply 'max 0 versions)
  4165. deserve-versions-p (or version-control
  4166. (> high-water-mark 0))
  4167. number-to-delete (- (length versions)
  4168. kept-old-versions
  4169. kept-new-versions
  4170. -1))
  4171. (file-error (setq possibilities nil)))
  4172. (if (not deserve-versions-p)
  4173. (list (make-backup-file-name fn))
  4174. (cons (format "%s.~%d~" basic-name (1+ high-water-mark))
  4175. (if (and (> number-to-delete 0)
  4176. ;; Delete nothing if there is overflow
  4177. ;; in the number of versions to keep.
  4178. (>= (+ kept-new-versions kept-old-versions -1) 0))
  4179. (mapcar (lambda (n)
  4180. (format "%s.~%d~" basic-name n))
  4181. (let ((v (nthcdr kept-old-versions versions)))
  4182. (rplacd (nthcdr (1- number-to-delete) v) ())
  4183. v))))))))))
  4184. (defun file-nlinks (filename)
  4185. "Return number of names file FILENAME has."
  4186. (car (cdr (file-attributes filename))))
  4187. ;; (defun file-relative-name (filename &optional directory)
  4188. ;; "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
  4189. ;; This function returns a relative file name which is equivalent to FILENAME
  4190. ;; when used with that default directory as the default.
  4191. ;; If this is impossible (which can happen on MSDOS and Windows
  4192. ;; when the file name and directory use different drive names)
  4193. ;; then it returns FILENAME."
  4194. ;; (save-match-data
  4195. ;; (let ((fname (expand-file-name filename)))
  4196. ;; (setq directory (file-name-as-directory
  4197. ;; (expand-file-name (or directory default-directory))))
  4198. ;; ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
  4199. ;; ;; drive names, they can't be relative, so return the absolute name.
  4200. ;; (if (and (or (eq system-type 'ms-dos)
  4201. ;; (eq system-type 'cygwin)
  4202. ;; (eq system-type 'windows-nt))
  4203. ;; (not (string-equal (substring fname 0 2)
  4204. ;; (substring directory 0 2))))
  4205. ;; filename
  4206. ;; (let ((ancestor ".")
  4207. ;; (fname-dir (file-name-as-directory fname)))
  4208. ;; (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
  4209. ;; (not (string-match (concat "^" (regexp-quote directory)) fname)))
  4210. ;; (setq directory (file-name-directory (substring directory 0 -1))
  4211. ;; ancestor (if (equal ancestor ".")
  4212. ;; ".."
  4213. ;; (concat "../" ancestor))))
  4214. ;; ;; Now ancestor is empty, or .., or ../.., etc.
  4215. ;; (if (string-match (concat "^" (regexp-quote directory)) fname)
  4216. ;; ;; We matched within FNAME's directory part.
  4217. ;; ;; Add the rest of FNAME onto ANCESTOR.
  4218. ;; (let ((rest (substring fname (match-end 0))))
  4219. ;; (if (and (equal ancestor ".")
  4220. ;; (not (equal rest "")))
  4221. ;; ;; But don't bother with ANCESTOR if it would give us `./'.
  4222. ;; rest
  4223. ;; (concat (file-name-as-directory ancestor) rest)))
  4224. ;; ;; We matched FNAME's directory equivalent.
  4225. ;; ancestor))))))
  4226. (defun file-relative-name (filename &optional directory)
  4227. "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
  4228. This function returns a relative file name which is equivalent to FILENAME
  4229. when used with that default directory as the default.
  4230. If FILENAME is a relative file name, it will be interpreted as existing in
  4231. `default-directory'.
  4232. If FILENAME and DIRECTORY lie on different machines or on different drives
  4233. on a DOS/Windows machine, it returns FILENAME in expanded form."
  4234. (save-match-data
  4235. (setq directory
  4236. (file-name-as-directory (expand-file-name (or directory
  4237. default-directory))))
  4238. (setq filename (expand-file-name filename))
  4239. (let ((fremote (file-remote-p filename))
  4240. (dremote (file-remote-p directory))
  4241. (fold-case (or (memq system-type '(ms-dos cygwin windows-nt))
  4242. read-file-name-completion-ignore-case)))
  4243. (if ;; Conditions for separate trees
  4244. (or
  4245. ;; Test for different filesystems on DOS/Windows
  4246. (and
  4247. ;; Should `cygwin' really be included here? --stef
  4248. (memq system-type '(ms-dos cygwin windows-nt))
  4249. (or
  4250. ;; Test for different drive letters
  4251. (not (eq t (compare-strings filename 0 2 directory 0 2 fold-case)))
  4252. ;; Test for UNCs on different servers
  4253. (not (eq t (compare-strings
  4254. (progn
  4255. (if (string-match "\\`//\\([^:/]+\\)/" filename)
  4256. (match-string 1 filename)
  4257. ;; Windows file names cannot have ? in
  4258. ;; them, so use that to detect when
  4259. ;; neither FILENAME nor DIRECTORY is a
  4260. ;; UNC.
  4261. "?"))
  4262. 0 nil
  4263. (progn
  4264. (if (string-match "\\`//\\([^:/]+\\)/" directory)
  4265. (match-string 1 directory)
  4266. "?"))
  4267. 0 nil t)))))
  4268. ;; Test for different remote file system identification
  4269. (not (equal fremote dremote)))
  4270. filename
  4271. (let ((ancestor ".")
  4272. (filename-dir (file-name-as-directory filename)))
  4273. (while (not
  4274. (or (string-prefix-p directory filename-dir fold-case)
  4275. (string-prefix-p directory filename fold-case)))
  4276. (setq directory (file-name-directory (substring directory 0 -1))
  4277. ancestor (if (equal ancestor ".")
  4278. ".."
  4279. (concat "../" ancestor))))
  4280. ;; Now ancestor is empty, or .., or ../.., etc.
  4281. (if (string-prefix-p directory filename fold-case)
  4282. ;; We matched within FILENAME's directory part.
  4283. ;; Add the rest of FILENAME onto ANCESTOR.
  4284. (let ((rest (substring filename (length directory))))
  4285. (if (and (equal ancestor ".") (not (equal rest "")))
  4286. ;; But don't bother with ANCESTOR if it would give us `./'.
  4287. rest
  4288. (concat (file-name-as-directory ancestor) rest)))
  4289. ;; We matched FILENAME's directory equivalent.
  4290. ancestor))))))
  4291. (defun save-buffer (&optional arg)
  4292. "Save current buffer in visited file if modified.
  4293. Variations are described below.
  4294. By default, makes the previous version into a backup file
  4295. if previously requested or if this is the first save.
  4296. Prefixed with one \\[universal-argument], marks this version
  4297. to become a backup when the next save is done.
  4298. Prefixed with two \\[universal-argument]'s,
  4299. unconditionally makes the previous version into a backup file.
  4300. Prefixed with three \\[universal-argument]'s, marks this version
  4301. to become a backup when the next save is done,
  4302. and unconditionally makes the previous version into a backup file.
  4303. With a numeric prefix argument of 0, never make the previous version
  4304. into a backup file.
  4305. If a file's name is FOO, the names of its numbered backup versions are
  4306. FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
  4307. Numeric backups (rather than FOO~) will be made if value of
  4308. `version-control' is not the atom `never' and either there are already
  4309. numeric versions of the file being backed up, or `version-control' is
  4310. non-nil.
  4311. We don't want excessive versions piling up, so there are variables
  4312. `kept-old-versions', which tells Emacs how many oldest versions to keep,
  4313. and `kept-new-versions', which tells how many newest versions to keep.
  4314. Defaults are 2 old versions and 2 new.
  4315. `dired-kept-versions' controls dired's clean-directory (.) command.
  4316. If `delete-old-versions' is nil, system will query user
  4317. before trimming versions. Otherwise it does it silently.
  4318. If `vc-make-backup-files' is nil, which is the default,
  4319. no backup files are made for files managed by version control.
  4320. (This is because the version control system itself records previous versions.)
  4321. See the subroutine `basic-save-buffer' for more information."
  4322. (interactive "p")
  4323. (let ((modp (buffer-modified-p))
  4324. (make-backup-files (or (and make-backup-files (not (eq arg 0)))
  4325. (memq arg '(16 64)))))
  4326. (and modp (memq arg '(16 64)) (setq buffer-backed-up nil))
  4327. ;; We used to display the message below only for files > 50KB, but
  4328. ;; then Rmail-mbox never displays it due to buffer swapping. If
  4329. ;; the test is ever re-introduced, be sure to handle saving of
  4330. ;; Rmail files.
  4331. (if (and modp
  4332. (buffer-file-name)
  4333. (not noninteractive)
  4334. (not save-silently))
  4335. (message "Saving file %s..." (buffer-file-name)))
  4336. (basic-save-buffer (called-interactively-p 'any))
  4337. (and modp (memq arg '(4 64)) (setq buffer-backed-up nil))))
  4338. (defun delete-auto-save-file-if-necessary (&optional force)
  4339. "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
  4340. Normally delete only if the file was written by this Emacs since
  4341. the last real save, but optional arg FORCE non-nil means delete anyway."
  4342. (and buffer-auto-save-file-name delete-auto-save-files
  4343. (not (string= buffer-file-name buffer-auto-save-file-name))
  4344. (or force (recent-auto-save-p))
  4345. (progn
  4346. (condition-case ()
  4347. (delete-file buffer-auto-save-file-name)
  4348. (file-error nil))
  4349. (set-buffer-auto-saved))))
  4350. (defvar auto-save-hook nil
  4351. "Normal hook run just before auto-saving.")
  4352. (defcustom before-save-hook nil
  4353. "Normal hook that is run before a buffer is saved to its file."
  4354. :options '(copyright-update time-stamp)
  4355. :type 'hook
  4356. :group 'files)
  4357. (defcustom after-save-hook nil
  4358. "Normal hook that is run after a buffer is saved to its file."
  4359. :options '(executable-make-buffer-file-executable-if-script-p)
  4360. :type 'hook
  4361. :group 'files)
  4362. (defvar save-buffer-coding-system nil
  4363. "If non-nil, use this coding system for saving the buffer.
  4364. More precisely, use this coding system in place of the
  4365. value of `buffer-file-coding-system', when saving the buffer.
  4366. Calling `write-region' for any purpose other than saving the buffer
  4367. will still use `buffer-file-coding-system'; this variable has no effect
  4368. in such cases.")
  4369. (make-variable-buffer-local 'save-buffer-coding-system)
  4370. (put 'save-buffer-coding-system 'permanent-local t)
  4371. (defun basic-save-buffer (&optional called-interactively)
  4372. "Save the current buffer in its visited file, if it has been modified.
  4373. The hooks `write-contents-functions' and `write-file-functions' get a chance
  4374. to do the job of saving; if they do not, then the buffer is saved in
  4375. the visited file in the usual way.
  4376. Before and after saving the buffer, this function runs
  4377. `before-save-hook' and `after-save-hook', respectively."
  4378. (interactive '(called-interactively))
  4379. (save-current-buffer
  4380. ;; In an indirect buffer, save its base buffer instead.
  4381. (if (buffer-base-buffer)
  4382. (set-buffer (buffer-base-buffer)))
  4383. (if (or (buffer-modified-p)
  4384. ;; handle the case when no modification has been made but
  4385. ;; the file disappeared since visited
  4386. (and buffer-file-name
  4387. (not (file-exists-p buffer-file-name))))
  4388. (let ((recent-save (recent-auto-save-p))
  4389. setmodes)
  4390. ;; If buffer has no file name, ask user for one.
  4391. (or buffer-file-name
  4392. (let ((filename
  4393. (expand-file-name
  4394. (read-file-name "File to save in: "
  4395. nil (expand-file-name (buffer-name))))))
  4396. (if (file-exists-p filename)
  4397. (if (file-directory-p filename)
  4398. ;; Signal an error if the user specified the name of an
  4399. ;; existing directory.
  4400. (error "%s is a directory" filename)
  4401. (unless (y-or-n-p (format-message
  4402. "File `%s' exists; overwrite? "
  4403. filename))
  4404. (error "Canceled"))))
  4405. (set-visited-file-name filename)))
  4406. (or (verify-visited-file-modtime (current-buffer))
  4407. (not (file-exists-p buffer-file-name))
  4408. (yes-or-no-p
  4409. (format
  4410. "%s has changed since visited or saved. Save anyway? "
  4411. (file-name-nondirectory buffer-file-name)))
  4412. (user-error "Save not confirmed"))
  4413. (save-restriction
  4414. (widen)
  4415. (save-excursion
  4416. (and (> (point-max) (point-min))
  4417. (not find-file-literally)
  4418. (/= (char-after (1- (point-max))) ?\n)
  4419. (not (and (eq selective-display t)
  4420. (= (char-after (1- (point-max))) ?\r)))
  4421. (or (eq require-final-newline t)
  4422. (eq require-final-newline 'visit-save)
  4423. (and require-final-newline
  4424. (y-or-n-p
  4425. (format "Buffer %s does not end in newline. Add one? "
  4426. (buffer-name)))))
  4427. (save-excursion
  4428. (goto-char (point-max))
  4429. (insert ?\n))))
  4430. ;; Support VC version backups.
  4431. (vc-before-save)
  4432. ;; Don't let errors prevent saving the buffer.
  4433. (with-demoted-errors (run-hooks 'before-save-hook))
  4434. (or (run-hook-with-args-until-success 'write-contents-functions)
  4435. (run-hook-with-args-until-success 'local-write-file-hooks)
  4436. (run-hook-with-args-until-success 'write-file-functions)
  4437. ;; If a hook returned t, file is already "written".
  4438. ;; Otherwise, write it the usual way now.
  4439. (let ((dir (file-name-directory
  4440. (expand-file-name buffer-file-name))))
  4441. (unless (file-exists-p dir)
  4442. (if (y-or-n-p
  4443. (format-message
  4444. "Directory `%s' does not exist; create? " dir))
  4445. (make-directory dir t)
  4446. (error "Canceled")))
  4447. (setq setmodes (basic-save-buffer-1))))
  4448. ;; Now we have saved the current buffer. Let's make sure
  4449. ;; that buffer-file-coding-system is fixed to what
  4450. ;; actually used for saving by binding it locally.
  4451. (if save-buffer-coding-system
  4452. (setq save-buffer-coding-system last-coding-system-used)
  4453. (setq buffer-file-coding-system last-coding-system-used))
  4454. (setq buffer-file-number
  4455. (nthcdr 10 (file-attributes buffer-file-name)))
  4456. (if setmodes
  4457. (condition-case ()
  4458. (progn
  4459. (unless
  4460. (with-demoted-errors
  4461. (set-file-modes buffer-file-name (car setmodes)))
  4462. (set-file-extended-attributes buffer-file-name
  4463. (nth 1 setmodes))))
  4464. (error nil))))
  4465. ;; If the auto-save file was recent before this command,
  4466. ;; delete it now.
  4467. (delete-auto-save-file-if-necessary recent-save)
  4468. ;; Support VC `implicit' locking.
  4469. (vc-after-save)
  4470. (run-hooks 'after-save-hook))
  4471. (or noninteractive
  4472. (not called-interactively)
  4473. (files--message "(No changes need to be saved)")))))
  4474. ;; This does the "real job" of writing a buffer into its visited file
  4475. ;; and making a backup file. This is what is normally done
  4476. ;; but inhibited if one of write-file-functions returns non-nil.
  4477. ;; It returns a value (MODES EXTENDED-ATTRIBUTES BACKUPNAME), like
  4478. ;; backup-buffer.
  4479. (defun basic-save-buffer-1 ()
  4480. (prog1
  4481. (if save-buffer-coding-system
  4482. (let ((coding-system-for-write save-buffer-coding-system))
  4483. (basic-save-buffer-2))
  4484. (basic-save-buffer-2))
  4485. (if buffer-file-coding-system-explicit
  4486. (setcar buffer-file-coding-system-explicit last-coding-system-used))))
  4487. ;; This returns a value (MODES EXTENDED-ATTRIBUTES BACKUPNAME), like
  4488. ;; backup-buffer.
  4489. (defun basic-save-buffer-2 ()
  4490. (let (tempsetmodes setmodes)
  4491. (if (not (file-writable-p buffer-file-name))
  4492. (let ((dir (file-name-directory buffer-file-name)))
  4493. (if (not (file-directory-p dir))
  4494. (if (file-exists-p dir)
  4495. (error "%s is not a directory" dir)
  4496. (error "%s: no such directory" dir))
  4497. (if (not (file-exists-p buffer-file-name))
  4498. (error "Directory %s write-protected" dir)
  4499. (if (yes-or-no-p
  4500. (format
  4501. "File %s is write-protected; try to save anyway? "
  4502. (file-name-nondirectory
  4503. buffer-file-name)))
  4504. (setq tempsetmodes t)
  4505. (error "Attempt to save to a file which you aren't allowed to write"))))))
  4506. (or buffer-backed-up
  4507. (setq setmodes (backup-buffer)))
  4508. (let* ((dir (file-name-directory buffer-file-name))
  4509. (dir-writable (file-writable-p dir)))
  4510. (if (or (and file-precious-flag dir-writable)
  4511. (and break-hardlink-on-save
  4512. (file-exists-p buffer-file-name)
  4513. (> (file-nlinks buffer-file-name) 1)
  4514. (or dir-writable
  4515. (error (concat "Directory %s write-protected; "
  4516. "cannot break hardlink when saving")
  4517. dir))))
  4518. ;; Write temp name, then rename it.
  4519. ;; This requires write access to the containing dir,
  4520. ;; which is why we don't try it if we don't have that access.
  4521. (let ((realname buffer-file-name)
  4522. tempname succeed
  4523. (umask (default-file-modes))
  4524. (old-modtime (visited-file-modtime)))
  4525. ;; Create temp files with strict access rights. It's easy to
  4526. ;; loosen them later, whereas it's impossible to close the
  4527. ;; time-window of loose permissions otherwise.
  4528. (unwind-protect
  4529. (progn
  4530. (clear-visited-file-modtime)
  4531. (set-default-file-modes ?\700)
  4532. ;; Try various temporary names.
  4533. ;; This code follows the example of make-temp-file,
  4534. ;; but it calls write-region in the appropriate way
  4535. ;; for saving the buffer.
  4536. (while (condition-case ()
  4537. (progn
  4538. (setq tempname
  4539. (make-temp-name
  4540. (expand-file-name "tmp" dir)))
  4541. ;; Pass in nil&nil rather than point-min&max
  4542. ;; cause we're saving the whole buffer.
  4543. ;; write-region-annotate-functions may use it.
  4544. (write-region nil nil
  4545. tempname nil realname
  4546. buffer-file-truename 'excl)
  4547. (when save-silently (message nil))
  4548. nil)
  4549. (file-already-exists t))
  4550. ;; The file was somehow created by someone else between
  4551. ;; `make-temp-name' and `write-region', let's try again.
  4552. nil)
  4553. (setq succeed t))
  4554. ;; Reset the umask.
  4555. (set-default-file-modes umask)
  4556. ;; If we failed, restore the buffer's modtime.
  4557. (unless succeed
  4558. (set-visited-file-modtime old-modtime)))
  4559. ;; Since we have created an entirely new file,
  4560. ;; make sure it gets the right permission bits set.
  4561. (setq setmodes (or setmodes
  4562. (list (or (file-modes buffer-file-name)
  4563. (logand ?\666 umask))
  4564. (file-extended-attributes buffer-file-name)
  4565. buffer-file-name)))
  4566. ;; We succeeded in writing the temp file,
  4567. ;; so rename it.
  4568. (rename-file tempname buffer-file-name t))
  4569. ;; If file not writable, see if we can make it writable
  4570. ;; temporarily while we write it.
  4571. ;; But no need to do so if we have just backed it up
  4572. ;; (setmodes is set) because that says we're superseding.
  4573. (cond ((and tempsetmodes (not setmodes))
  4574. ;; Change the mode back, after writing.
  4575. (setq setmodes (list (file-modes buffer-file-name)
  4576. (file-extended-attributes buffer-file-name)
  4577. buffer-file-name))
  4578. ;; If set-file-extended-attributes fails, fall back on
  4579. ;; set-file-modes.
  4580. (unless
  4581. (with-demoted-errors
  4582. (set-file-extended-attributes buffer-file-name
  4583. (nth 1 setmodes)))
  4584. (set-file-modes buffer-file-name
  4585. (logior (car setmodes) 128))))))
  4586. (let (success)
  4587. (unwind-protect
  4588. (progn
  4589. ;; Pass in nil&nil rather than point-min&max to indicate
  4590. ;; we're saving the buffer rather than just a region.
  4591. ;; write-region-annotate-functions may make us of it.
  4592. (write-region nil nil
  4593. buffer-file-name nil t buffer-file-truename)
  4594. (when save-silently (message nil))
  4595. (setq success t))
  4596. ;; If we get an error writing the new file, and we made
  4597. ;; the backup by renaming, undo the backing-up.
  4598. (and setmodes (not success)
  4599. (progn
  4600. (rename-file (nth 2 setmodes) buffer-file-name t)
  4601. (setq buffer-backed-up nil))))))
  4602. setmodes))
  4603. (declare-function diff-no-select "diff"
  4604. (old new &optional switches no-async buf))
  4605. (defvar save-some-buffers-action-alist
  4606. `((?\C-r
  4607. ,(lambda (buf)
  4608. (if (not enable-recursive-minibuffers)
  4609. (progn (display-buffer buf)
  4610. (setq other-window-scroll-buffer buf))
  4611. (view-buffer buf (lambda (_) (exit-recursive-edit)))
  4612. (recursive-edit))
  4613. ;; Return nil to ask about BUF again.
  4614. nil)
  4615. ,(purecopy "view this buffer"))
  4616. (?d ,(lambda (buf)
  4617. (if (null (buffer-file-name buf))
  4618. (message "Not applicable: no file")
  4619. (require 'diff) ;for diff-no-select.
  4620. (let ((diffbuf (diff-no-select (buffer-file-name buf) buf
  4621. nil 'noasync)))
  4622. (if (not enable-recursive-minibuffers)
  4623. (progn (display-buffer diffbuf)
  4624. (setq other-window-scroll-buffer diffbuf))
  4625. (view-buffer diffbuf (lambda (_) (exit-recursive-edit)))
  4626. (recursive-edit))))
  4627. ;; Return nil to ask about BUF again.
  4628. nil)
  4629. ,(purecopy "view changes in this buffer")))
  4630. "ACTION-ALIST argument used in call to `map-y-or-n-p'.")
  4631. (put 'save-some-buffers-action-alist 'risky-local-variable t)
  4632. (defvar buffer-save-without-query nil
  4633. "Non-nil means `save-some-buffers' should save this buffer without asking.")
  4634. (make-variable-buffer-local 'buffer-save-without-query)
  4635. (defun save-some-buffers (&optional arg pred)
  4636. "Save some modified file-visiting buffers. Asks user about each one.
  4637. You can answer `y' to save, `n' not to save, `C-r' to look at the
  4638. buffer in question with `view-buffer' before deciding or `d' to
  4639. view the differences using `diff-buffer-with-file'.
  4640. This command first saves any buffers where `buffer-save-without-query' is
  4641. non-nil, without asking.
  4642. Optional argument (the prefix) non-nil means save all with no questions.
  4643. Optional second argument PRED determines which buffers are considered:
  4644. If PRED is nil, all the file-visiting buffers are considered.
  4645. If PRED is t, then certain non-file buffers will also be considered.
  4646. If PRED is a zero-argument function, it indicates for each buffer whether
  4647. to consider it or not when called with that buffer current.
  4648. See `save-some-buffers-action-alist' if you want to
  4649. change the additional actions you can take on files."
  4650. (interactive "P")
  4651. (save-window-excursion
  4652. (let* (queried autosaved-buffers
  4653. files-done abbrevs-done)
  4654. (dolist (buffer (buffer-list))
  4655. ;; First save any buffers that we're supposed to save unconditionally.
  4656. ;; That way the following code won't ask about them.
  4657. (with-current-buffer buffer
  4658. (when (and buffer-save-without-query (buffer-modified-p))
  4659. (push (buffer-name) autosaved-buffers)
  4660. (save-buffer))))
  4661. ;; Ask about those buffers that merit it,
  4662. ;; and record the number thus saved.
  4663. (setq files-done
  4664. (map-y-or-n-p
  4665. (lambda (buffer)
  4666. ;; Note that killing some buffers may kill others via
  4667. ;; hooks (e.g. Rmail and its viewing buffer).
  4668. (and (buffer-live-p buffer)
  4669. (buffer-modified-p buffer)
  4670. (not (buffer-base-buffer buffer))
  4671. (or
  4672. (buffer-file-name buffer)
  4673. (and pred
  4674. (progn
  4675. (set-buffer buffer)
  4676. (and buffer-offer-save (> (buffer-size) 0)))))
  4677. (or (not (functionp pred))
  4678. (with-current-buffer buffer (funcall pred)))
  4679. (if arg
  4680. t
  4681. (setq queried t)
  4682. (if (buffer-file-name buffer)
  4683. (format "Save file %s? "
  4684. (buffer-file-name buffer))
  4685. (format "Save buffer %s? "
  4686. (buffer-name buffer))))))
  4687. (lambda (buffer)
  4688. (with-current-buffer buffer
  4689. (save-buffer)))
  4690. (buffer-list)
  4691. '("buffer" "buffers" "save")
  4692. save-some-buffers-action-alist))
  4693. ;; Maybe to save abbrevs, and record whether
  4694. ;; we either saved them or asked to.
  4695. (and save-abbrevs abbrevs-changed
  4696. (progn
  4697. (if (or arg
  4698. (eq save-abbrevs 'silently)
  4699. (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name)))
  4700. (write-abbrev-file nil))
  4701. ;; Don't keep bothering user if he says no.
  4702. (setq abbrevs-changed nil)
  4703. (setq abbrevs-done t)))
  4704. (or queried (> files-done 0) abbrevs-done
  4705. (cond
  4706. ((null autosaved-buffers)
  4707. (when (called-interactively-p 'any)
  4708. (files--message "(No files need saving)")))
  4709. ((= (length autosaved-buffers) 1)
  4710. (files--message "(Saved %s)" (car autosaved-buffers)))
  4711. (t
  4712. (files--message "(Saved %d files: %s)"
  4713. (length autosaved-buffers)
  4714. (mapconcat 'identity autosaved-buffers ", "))))))))
  4715. (defun clear-visited-file-modtime ()
  4716. "Clear out records of last mod time of visited file.
  4717. Next attempt to save will certainly not complain of a discrepancy."
  4718. (set-visited-file-modtime 0))
  4719. (defun not-modified (&optional arg)
  4720. "Mark current buffer as unmodified, not needing to be saved.
  4721. With prefix ARG, mark buffer as modified, so \\[save-buffer] will save.
  4722. It is not a good idea to use this function in Lisp programs, because it
  4723. prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
  4724. (declare (interactive-only set-buffer-modified-p))
  4725. (interactive "P")
  4726. (files--message (if arg "Modification-flag set"
  4727. "Modification-flag cleared"))
  4728. (set-buffer-modified-p arg))
  4729. (defun toggle-read-only (&optional arg interactive)
  4730. "Change whether this buffer is read-only."
  4731. (declare (obsolete read-only-mode "24.3"))
  4732. (interactive (list current-prefix-arg t))
  4733. (if interactive
  4734. (call-interactively 'read-only-mode)
  4735. (read-only-mode (or arg 'toggle))))
  4736. (defun insert-file (filename)
  4737. "Insert contents of file FILENAME into buffer after point.
  4738. Set mark after the inserted text.
  4739. This function is meant for the user to run interactively.
  4740. Don't call it from programs! Use `insert-file-contents' instead.
  4741. \(Its calling sequence is different; see its documentation)."
  4742. (declare (interactive-only insert-file-contents))
  4743. (interactive "*fInsert file: ")
  4744. (insert-file-1 filename #'insert-file-contents))
  4745. (defun append-to-file (start end filename)
  4746. "Append the contents of the region to the end of file FILENAME.
  4747. When called from a function, expects three arguments,
  4748. START, END and FILENAME. START and END are normally buffer positions
  4749. specifying the part of the buffer to write.
  4750. If START is nil, that means to use the entire buffer contents.
  4751. If START is a string, then output that string to the file
  4752. instead of any buffer contents; END is ignored.
  4753. This does character code conversion and applies annotations
  4754. like `write-region' does."
  4755. (interactive "r\nFAppend to file: ")
  4756. (prog1 (write-region start end filename t)
  4757. (when save-silently (message nil))))
  4758. (defun file-newest-backup (filename)
  4759. "Return most recent backup file for FILENAME or nil if no backups exist."
  4760. ;; `make-backup-file-name' will get us the right directory for
  4761. ;; ordinary or numeric backups. It might create a directory for
  4762. ;; backups as a side-effect, according to `backup-directory-alist'.
  4763. (let* ((filename (file-name-sans-versions
  4764. (make-backup-file-name (expand-file-name filename))))
  4765. (file (file-name-nondirectory filename))
  4766. (dir (file-name-directory filename))
  4767. (comp (file-name-all-completions file dir))
  4768. (newest nil)
  4769. tem)
  4770. (while comp
  4771. (setq tem (pop comp))
  4772. (cond ((and (backup-file-name-p tem)
  4773. (string= (file-name-sans-versions tem) file))
  4774. (setq tem (concat dir tem))
  4775. (if (or (null newest)
  4776. (file-newer-than-file-p tem newest))
  4777. (setq newest tem)))))
  4778. newest))
  4779. (defun rename-uniquely ()
  4780. "Rename current buffer to a similar name not already taken.
  4781. This function is useful for creating multiple shell process buffers
  4782. or multiple mail buffers, etc.
  4783. Note that some commands, in particular those based on `compilation-mode'
  4784. \(`compile', `grep', etc.) will reuse the current buffer if it has the
  4785. appropriate mode even if it has been renamed. So as well as renaming
  4786. the buffer, you also need to switch buffers before running another
  4787. instance of such commands."
  4788. (interactive)
  4789. (save-match-data
  4790. (let ((base-name (buffer-name)))
  4791. (and (string-match "<[0-9]+>\\'" base-name)
  4792. (not (and buffer-file-name
  4793. (string= base-name
  4794. (file-name-nondirectory buffer-file-name))))
  4795. ;; If the existing buffer name has a <NNN>,
  4796. ;; which isn't part of the file name (if any),
  4797. ;; then get rid of that.
  4798. (setq base-name (substring base-name 0 (match-beginning 0))))
  4799. (rename-buffer (generate-new-buffer-name base-name))
  4800. (force-mode-line-update))))
  4801. (defun make-directory (dir &optional parents)
  4802. "Create the directory DIR and optionally any nonexistent parent dirs.
  4803. If DIR already exists as a directory, signal an error, unless
  4804. PARENTS is non-nil.
  4805. Interactively, the default choice of directory to create is the
  4806. current buffer's default directory. That is useful when you have
  4807. visited a file in a nonexistent directory.
  4808. Noninteractively, the second (optional) argument PARENTS, if
  4809. non-nil, says whether to create parent directories that don't
  4810. exist. Interactively, this happens by default.
  4811. If creating the directory or directories fail, an error will be
  4812. raised."
  4813. (interactive
  4814. (list (read-file-name "Make directory: " default-directory default-directory
  4815. nil nil)
  4816. t))
  4817. ;; If default-directory is a remote directory,
  4818. ;; make sure we find its make-directory handler.
  4819. (setq dir (expand-file-name dir))
  4820. (let ((handler (find-file-name-handler dir 'make-directory)))
  4821. (if handler
  4822. (funcall handler 'make-directory dir parents)
  4823. (if (not parents)
  4824. (make-directory-internal dir)
  4825. (let ((dir (directory-file-name (expand-file-name dir)))
  4826. create-list)
  4827. (while (and (not (file-exists-p dir))
  4828. ;; If directory is its own parent, then we can't
  4829. ;; keep looping forever
  4830. (not (equal dir
  4831. (directory-file-name
  4832. (file-name-directory dir)))))
  4833. (setq create-list (cons dir create-list)
  4834. dir (directory-file-name (file-name-directory dir))))
  4835. (while create-list
  4836. (make-directory-internal (car create-list))
  4837. (setq create-list (cdr create-list))))))))
  4838. (defconst directory-files-no-dot-files-regexp
  4839. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"
  4840. "Regexp matching any file name except \".\" and \"..\".")
  4841. (defun delete-directory (directory &optional recursive trash)
  4842. "Delete the directory named DIRECTORY. Does not follow symlinks.
  4843. If RECURSIVE is non-nil, all files in DIRECTORY are deleted as well.
  4844. TRASH non-nil means to trash the directory instead, provided
  4845. `delete-by-moving-to-trash' is non-nil.
  4846. When called interactively, TRASH is t if no prefix argument is
  4847. given. With a prefix argument, TRASH is nil."
  4848. (interactive
  4849. (let* ((trashing (and delete-by-moving-to-trash
  4850. (null current-prefix-arg)))
  4851. (dir (expand-file-name
  4852. (read-directory-name
  4853. (if trashing
  4854. "Move directory to trash: "
  4855. "Delete directory: ")
  4856. default-directory default-directory nil nil))))
  4857. (list dir
  4858. (if (directory-files dir nil directory-files-no-dot-files-regexp)
  4859. (y-or-n-p
  4860. (format-message "Directory `%s' is not empty, really %s? "
  4861. dir (if trashing "trash" "delete")))
  4862. nil)
  4863. (null current-prefix-arg))))
  4864. ;; If default-directory is a remote directory, make sure we find its
  4865. ;; delete-directory handler.
  4866. (setq directory (directory-file-name (expand-file-name directory)))
  4867. (let ((handler (find-file-name-handler directory 'delete-directory)))
  4868. (cond
  4869. (handler
  4870. (funcall handler 'delete-directory directory recursive))
  4871. ((and delete-by-moving-to-trash trash)
  4872. ;; Only move non-empty dir to trash if recursive deletion was
  4873. ;; requested. This mimics the non-`delete-by-moving-to-trash'
  4874. ;; case, where the operation fails in delete-directory-internal.
  4875. ;; As `move-file-to-trash' trashes directories (empty or
  4876. ;; otherwise) as a unit, we do not need to recurse here.
  4877. (if (and (not recursive)
  4878. ;; Check if directory is empty apart from "." and "..".
  4879. (directory-files
  4880. directory 'full directory-files-no-dot-files-regexp))
  4881. (error "Directory is not empty, not moving to trash")
  4882. (move-file-to-trash directory)))
  4883. ;; Otherwise, call ourselves recursively if needed.
  4884. (t
  4885. (if (and recursive (not (file-symlink-p directory)))
  4886. (mapc (lambda (file)
  4887. ;; This test is equivalent to
  4888. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  4889. ;; but more efficient
  4890. (if (eq t (car (file-attributes file)))
  4891. (delete-directory file recursive nil)
  4892. (delete-file file nil)))
  4893. ;; We do not want to delete "." and "..".
  4894. (directory-files
  4895. directory 'full directory-files-no-dot-files-regexp)))
  4896. (delete-directory-internal directory)))))
  4897. (defun file-equal-p (file1 file2)
  4898. "Return non-nil if files FILE1 and FILE2 name the same file.
  4899. If FILE1 or FILE2 does not exist, the return value is unspecified."
  4900. (let ((handler (or (find-file-name-handler file1 'file-equal-p)
  4901. (find-file-name-handler file2 'file-equal-p))))
  4902. (if handler
  4903. (funcall handler 'file-equal-p file1 file2)
  4904. (let (f1-attr f2-attr)
  4905. (and (setq f1-attr (file-attributes (file-truename file1)))
  4906. (setq f2-attr (file-attributes (file-truename file2)))
  4907. (equal f1-attr f2-attr))))))
  4908. (defun file-in-directory-p (file dir)
  4909. "Return non-nil if FILE is in DIR or a subdirectory of DIR.
  4910. A directory is considered to be \"in\" itself.
  4911. Return nil if DIR is not an existing directory."
  4912. (let ((handler (or (find-file-name-handler file 'file-in-directory-p)
  4913. (find-file-name-handler dir 'file-in-directory-p))))
  4914. (if handler
  4915. (funcall handler 'file-in-directory-p file dir)
  4916. (when (file-directory-p dir) ; DIR must exist.
  4917. (setq file (file-truename file)
  4918. dir (file-truename dir))
  4919. (let ((ls1 (split-string file "/" t))
  4920. (ls2 (split-string dir "/" t))
  4921. (root
  4922. (cond
  4923. ;; A UNC on Windows systems, or a "super-root" on Apollo.
  4924. ((string-match "\\`//" file) "//")
  4925. ((string-match "\\`/" file) "/")
  4926. (t "")))
  4927. (mismatch nil))
  4928. (while (and ls1 ls2 (not mismatch))
  4929. (if (string-equal (car ls1) (car ls2))
  4930. (setq root (concat root (car ls1) "/"))
  4931. (setq mismatch t))
  4932. (setq ls1 (cdr ls1)
  4933. ls2 (cdr ls2)))
  4934. (unless mismatch
  4935. (file-equal-p root dir)))))))
  4936. (defun copy-directory (directory newname &optional keep-time parents copy-contents)
  4937. "Copy DIRECTORY to NEWNAME. Both args must be strings.
  4938. This function always sets the file modes of the output files to match
  4939. the corresponding input file.
  4940. The third arg KEEP-TIME non-nil means give the output files the same
  4941. last-modified time as the old ones. (This works on only some systems.)
  4942. A prefix arg makes KEEP-TIME non-nil.
  4943. Noninteractively, the last argument PARENTS says whether to
  4944. create parent directories if they don't exist. Interactively,
  4945. this happens by default.
  4946. If NEWNAME names an existing directory, copy DIRECTORY as a
  4947. subdirectory there. However, if called from Lisp with a non-nil
  4948. optional argument COPY-CONTENTS, copy the contents of DIRECTORY
  4949. directly into NEWNAME instead."
  4950. (interactive
  4951. (let ((dir (read-directory-name
  4952. "Copy directory: " default-directory default-directory t nil)))
  4953. (list dir
  4954. (read-directory-name
  4955. (format "Copy directory %s to: " dir)
  4956. default-directory default-directory nil nil)
  4957. current-prefix-arg t nil)))
  4958. (when (file-in-directory-p newname directory)
  4959. (error "Cannot copy `%s' into its subdirectory `%s'"
  4960. directory newname))
  4961. ;; If default-directory is a remote directory, make sure we find its
  4962. ;; copy-directory handler.
  4963. (let ((handler (or (find-file-name-handler directory 'copy-directory)
  4964. (find-file-name-handler newname 'copy-directory))))
  4965. (if handler
  4966. (funcall handler 'copy-directory directory
  4967. newname keep-time parents copy-contents)
  4968. ;; Compute target name.
  4969. (setq directory (directory-file-name (expand-file-name directory))
  4970. newname (directory-file-name (expand-file-name newname)))
  4971. (cond ((not (file-directory-p newname))
  4972. ;; If NEWNAME is not an existing directory, create it;
  4973. ;; that is where we will copy the files of DIRECTORY.
  4974. (make-directory newname parents))
  4975. ;; If NEWNAME is an existing directory and COPY-CONTENTS
  4976. ;; is nil, copy into NEWNAME/[DIRECTORY-BASENAME].
  4977. ((not copy-contents)
  4978. (setq newname (expand-file-name
  4979. (file-name-nondirectory
  4980. (directory-file-name directory))
  4981. newname))
  4982. (and (file-exists-p newname)
  4983. (not (file-directory-p newname))
  4984. (error "Cannot overwrite non-directory %s with a directory"
  4985. newname))
  4986. (make-directory newname t)))
  4987. ;; Copy recursively.
  4988. (dolist (file
  4989. ;; We do not want to copy "." and "..".
  4990. (directory-files directory 'full
  4991. directory-files-no-dot-files-regexp))
  4992. (let ((target (expand-file-name (file-name-nondirectory file) newname))
  4993. (filetype (car (file-attributes file))))
  4994. (cond
  4995. ((eq filetype t) ; Directory but not a symlink.
  4996. (copy-directory file newname keep-time parents))
  4997. ((stringp filetype) ; Symbolic link
  4998. (make-symbolic-link filetype target t))
  4999. ((copy-file file target t keep-time)))))
  5000. ;; Set directory attributes.
  5001. (let ((modes (file-modes directory))
  5002. (times (and keep-time (nth 5 (file-attributes directory)))))
  5003. (if modes (set-file-modes newname modes))
  5004. (if times (set-file-times newname times))))))
  5005. ;; At time of writing, only info uses this.
  5006. (defun prune-directory-list (dirs &optional keep reject)
  5007. "Return a copy of DIRS with all non-existent directories removed.
  5008. The optional argument KEEP is a list of directories to retain even if
  5009. they don't exist, and REJECT is a list of directories to remove from
  5010. DIRS, even if they exist; REJECT takes precedence over KEEP.
  5011. Note that membership in REJECT and KEEP is checked using simple string
  5012. comparison."
  5013. (apply #'nconc
  5014. (mapcar (lambda (dir)
  5015. (and (not (member dir reject))
  5016. (or (member dir keep) (file-directory-p dir))
  5017. (list dir)))
  5018. dirs)))
  5019. (put 'revert-buffer-function 'permanent-local t)
  5020. (defvar revert-buffer-function #'revert-buffer--default
  5021. "Function to use to revert this buffer.
  5022. The function receives two arguments IGNORE-AUTO and NOCONFIRM,
  5023. which are the arguments that `revert-buffer' received.
  5024. It also has access to the `preserve-modes' argument of `revert-buffer'
  5025. via the `revert-buffer-preserve-modes' dynamic variable.
  5026. For historical reasons, a value of nil means to use the default function.
  5027. This should not be relied upon.")
  5028. (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
  5029. (defvar revert-buffer-insert-file-contents-function
  5030. #'revert-buffer-insert-file-contents--default-function
  5031. "Function to use to insert contents when reverting this buffer.
  5032. The function receives two arguments: the first the nominal file name to use;
  5033. the second is t if reading the auto-save file.
  5034. The function is responsible for updating (or preserving) point.
  5035. For historical reasons, a value of nil means to use the default function.
  5036. This should not be relied upon.")
  5037. (defun buffer-stale--default-function (&optional _noconfirm)
  5038. "Default function to use for `buffer-stale-function'.
  5039. This function ignores its argument.
  5040. This returns non-nil if the current buffer is visiting a readable file
  5041. whose modification time does not match that of the buffer.
  5042. This function only handles buffers that are visiting files.
  5043. Non-file buffers need a custom function"
  5044. (and buffer-file-name
  5045. (file-readable-p buffer-file-name)
  5046. (not (buffer-modified-p (current-buffer)))
  5047. (not (verify-visited-file-modtime (current-buffer)))))
  5048. (defvar buffer-stale-function #'buffer-stale--default-function
  5049. "Function to check whether a buffer needs reverting.
  5050. This should be a function with one optional argument NOCONFIRM.
  5051. Auto Revert Mode passes t for NOCONFIRM. The function should return
  5052. non-nil if the buffer should be reverted. A return value of
  5053. `fast' means that the need for reverting was not checked, but
  5054. that reverting the buffer is fast. The buffer is current when
  5055. this function is called.
  5056. The idea behind the NOCONFIRM argument is that it should be
  5057. non-nil if the buffer is going to be reverted without asking the
  5058. user. In such situations, one has to be careful with potentially
  5059. time consuming operations.
  5060. For historical reasons, a value of nil means to use the default function.
  5061. This should not be relied upon.
  5062. For more information on how this variable is used by Auto Revert mode,
  5063. see Info node `(emacs)Supporting additional buffers'.")
  5064. (defvar before-revert-hook nil
  5065. "Normal hook for `revert-buffer' to run before reverting.
  5066. The function `revert-buffer--default' runs this.
  5067. A customized `revert-buffer-function' need not run this hook.")
  5068. (defvar after-revert-hook nil
  5069. "Normal hook for `revert-buffer' to run after reverting.
  5070. Note that the hook value that it runs is the value that was in effect
  5071. before reverting; that makes a difference if you have buffer-local
  5072. hook functions.
  5073. The function `revert-buffer--default' runs this.
  5074. A customized `revert-buffer-function' need not run this hook.")
  5075. (defvar revert-buffer-in-progress-p nil
  5076. "Non-nil if a `revert-buffer' operation is in progress, nil otherwise.")
  5077. (defvar revert-buffer-internal-hook)
  5078. ;; `revert-buffer-function' was defined long ago to be a function of only
  5079. ;; 2 arguments, so we have to use a dynbind variable to pass the
  5080. ;; `preserve-modes' argument of `revert-buffer'.
  5081. (defvar revert-buffer-preserve-modes)
  5082. (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
  5083. "Replace current buffer text with the text of the visited file on disk.
  5084. This undoes all changes since the file was visited or saved.
  5085. With a prefix argument, offer to revert from latest auto-save file, if
  5086. that is more recent than the visited file.
  5087. This command also implements an interface for special buffers
  5088. that contain text which doesn't come from a file, but reflects
  5089. some other data instead (e.g. Dired buffers, `buffer-list'
  5090. buffers). This is done via the variable `revert-buffer-function'.
  5091. In these cases, it should reconstruct the buffer contents from the
  5092. appropriate data.
  5093. When called from Lisp, the first argument is IGNORE-AUTO; only offer
  5094. to revert from the auto-save file when this is nil. Note that the
  5095. sense of this argument is the reverse of the prefix argument, for the
  5096. sake of backward compatibility. IGNORE-AUTO is optional, defaulting
  5097. to nil.
  5098. Optional second argument NOCONFIRM means don't ask for confirmation
  5099. at all. (The variable `revert-without-query' offers another way to
  5100. revert buffers without querying for confirmation.)
  5101. Optional third argument PRESERVE-MODES non-nil means don't alter
  5102. the files modes. Normally we reinitialize them using `normal-mode'.
  5103. This function binds `revert-buffer-in-progress-p' non-nil while it operates.
  5104. This function calls the function that `revert-buffer-function' specifies
  5105. to do the work, with arguments IGNORE-AUTO and NOCONFIRM.
  5106. The default function runs the hooks `before-revert-hook' and
  5107. `after-revert-hook'."
  5108. ;; I admit it's odd to reverse the sense of the prefix argument, but
  5109. ;; there is a lot of code out there which assumes that the first
  5110. ;; argument should be t to avoid consulting the auto-save file, and
  5111. ;; there's no straightforward way to encourage authors to notice a
  5112. ;; reversal of the argument sense. So I'm just changing the user
  5113. ;; interface, but leaving the programmatic interface the same.
  5114. (interactive (list (not current-prefix-arg)))
  5115. (let ((revert-buffer-in-progress-p t)
  5116. (revert-buffer-preserve-modes preserve-modes))
  5117. (funcall (or revert-buffer-function #'revert-buffer--default)
  5118. ignore-auto noconfirm)))
  5119. (defun revert-buffer--default (ignore-auto noconfirm)
  5120. "Default function for `revert-buffer'.
  5121. The arguments IGNORE-AUTO and NOCONFIRM are as described for `revert-buffer'.
  5122. Runs the hooks `before-revert-hook' and `after-revert-hook' at the
  5123. start and end.
  5124. Calls `revert-buffer-insert-file-contents-function' to reread the
  5125. contents of the visited file, with two arguments: the first is the file
  5126. name, the second is non-nil if reading an auto-save file.
  5127. This function only handles buffers that are visiting files.
  5128. Non-file buffers need a custom function."
  5129. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  5130. (current-buffer))
  5131. (let* ((auto-save-p (and (not ignore-auto)
  5132. (recent-auto-save-p)
  5133. buffer-auto-save-file-name
  5134. (file-readable-p buffer-auto-save-file-name)
  5135. (y-or-n-p
  5136. "Buffer has been auto-saved recently. Revert from auto-save file? ")))
  5137. (file-name (if auto-save-p
  5138. buffer-auto-save-file-name
  5139. buffer-file-name)))
  5140. (cond ((null file-name)
  5141. (error "Buffer does not seem to be associated with any file"))
  5142. ((or noconfirm
  5143. (and (not (buffer-modified-p))
  5144. (catch 'found
  5145. (dolist (regexp revert-without-query)
  5146. (when (string-match regexp file-name)
  5147. (throw 'found t)))))
  5148. (yes-or-no-p (format "Revert buffer from file %s? "
  5149. file-name)))
  5150. (run-hooks 'before-revert-hook)
  5151. ;; If file was backed up but has changed since,
  5152. ;; we should make another backup.
  5153. (and (not auto-save-p)
  5154. (not (verify-visited-file-modtime (current-buffer)))
  5155. (setq buffer-backed-up nil))
  5156. ;; Effectively copy the after-revert-hook status,
  5157. ;; since after-find-file will clobber it.
  5158. (let ((global-hook (default-value 'after-revert-hook))
  5159. (local-hook (when (local-variable-p 'after-revert-hook)
  5160. after-revert-hook))
  5161. (inhibit-read-only t))
  5162. ;; FIXME: Throw away undo-log when preserve-modes is nil?
  5163. (funcall
  5164. (or revert-buffer-insert-file-contents-function
  5165. #'revert-buffer-insert-file-contents--default-function)
  5166. file-name auto-save-p)
  5167. ;; Recompute the truename in case changes in symlinks
  5168. ;; have changed the truename.
  5169. (setq buffer-file-truename
  5170. (abbreviate-file-name (file-truename buffer-file-name)))
  5171. (after-find-file nil nil t nil revert-buffer-preserve-modes)
  5172. ;; Run after-revert-hook as it was before we reverted.
  5173. (setq-default revert-buffer-internal-hook global-hook)
  5174. (if local-hook
  5175. (set (make-local-variable 'revert-buffer-internal-hook)
  5176. local-hook)
  5177. (kill-local-variable 'revert-buffer-internal-hook))
  5178. (run-hooks 'revert-buffer-internal-hook))
  5179. t)))))
  5180. (defun revert-buffer-insert-file-contents--default-function (file-name auto-save-p)
  5181. "Default function for `revert-buffer-insert-file-contents-function'.
  5182. The function `revert-buffer--default' calls this.
  5183. FILE-NAME is the name of the file. AUTO-SAVE-P is non-nil if this is
  5184. an auto-save file."
  5185. (cond
  5186. ((not (file-exists-p file-name))
  5187. (error (if buffer-file-number
  5188. "File %s no longer exists!"
  5189. "Cannot revert nonexistent file %s")
  5190. file-name))
  5191. ((not (file-readable-p file-name))
  5192. (error (if buffer-file-number
  5193. "File %s no longer readable!"
  5194. "Cannot revert unreadable file %s")
  5195. file-name))
  5196. (t
  5197. ;; Bind buffer-file-name to nil
  5198. ;; so that we don't try to lock the file.
  5199. (let ((buffer-file-name nil))
  5200. (or auto-save-p
  5201. (unlock-buffer)))
  5202. (widen)
  5203. (let ((coding-system-for-read
  5204. ;; Auto-saved file should be read by Emacs's
  5205. ;; internal coding.
  5206. (if auto-save-p 'auto-save-coding
  5207. (or coding-system-for-read
  5208. (and
  5209. buffer-file-coding-system-explicit
  5210. (car buffer-file-coding-system-explicit))))))
  5211. (if (and (not enable-multibyte-characters)
  5212. coding-system-for-read
  5213. (not (memq (coding-system-base
  5214. coding-system-for-read)
  5215. '(no-conversion raw-text))))
  5216. ;; As a coding system suitable for multibyte
  5217. ;; buffer is specified, make the current
  5218. ;; buffer multibyte.
  5219. (set-buffer-multibyte t))
  5220. ;; This force after-insert-file-set-coding
  5221. ;; (called from insert-file-contents) to set
  5222. ;; buffer-file-coding-system to a proper value.
  5223. (kill-local-variable 'buffer-file-coding-system)
  5224. ;; Note that this preserves point in an intelligent way.
  5225. (if revert-buffer-preserve-modes
  5226. (let ((buffer-file-format buffer-file-format))
  5227. (insert-file-contents file-name (not auto-save-p)
  5228. nil nil t))
  5229. (insert-file-contents file-name (not auto-save-p)
  5230. nil nil t))))))
  5231. (defun recover-this-file ()
  5232. "Recover the visited file--get contents from its last auto-save file."
  5233. (interactive)
  5234. (recover-file buffer-file-name))
  5235. (defun recover-file (file)
  5236. "Visit file FILE, but get contents from its last auto-save file."
  5237. ;; Actually putting the file name in the minibuffer should be used
  5238. ;; only rarely.
  5239. ;; Not just because users often use the default.
  5240. (interactive "FRecover file: ")
  5241. (setq file (expand-file-name file))
  5242. (if (auto-save-file-name-p (file-name-nondirectory file))
  5243. (error "%s is an auto-save file" (abbreviate-file-name file)))
  5244. (let ((file-name (let ((buffer-file-name file))
  5245. (make-auto-save-file-name))))
  5246. (cond ((if (file-exists-p file)
  5247. (not (file-newer-than-file-p file-name file))
  5248. (not (file-exists-p file-name)))
  5249. (error "Auto-save file %s not current"
  5250. (abbreviate-file-name file-name)))
  5251. ((with-temp-buffer-window
  5252. "*Directory*" nil
  5253. #'(lambda (window _value)
  5254. (with-selected-window window
  5255. (unwind-protect
  5256. (yes-or-no-p (format "Recover auto save file %s? " file-name))
  5257. (when (window-live-p window)
  5258. (quit-restore-window window 'kill)))))
  5259. (with-current-buffer standard-output
  5260. (let ((switches dired-listing-switches))
  5261. (if (file-symlink-p file)
  5262. (setq switches (concat switches " -L")))
  5263. ;; Use insert-directory-safely, not insert-directory,
  5264. ;; because these files might not exist. In particular,
  5265. ;; FILE might not exist if the auto-save file was for
  5266. ;; a buffer that didn't visit a file, such as "*mail*".
  5267. ;; The code in v20.x called `ls' directly, so we need
  5268. ;; to emulate what `ls' did in that case.
  5269. (insert-directory-safely file switches)
  5270. (insert-directory-safely file-name switches))))
  5271. (switch-to-buffer (find-file-noselect file t))
  5272. (let ((inhibit-read-only t)
  5273. ;; Keep the current buffer-file-coding-system.
  5274. (coding-system buffer-file-coding-system)
  5275. ;; Auto-saved file should be read with special coding.
  5276. (coding-system-for-read 'auto-save-coding))
  5277. (erase-buffer)
  5278. (insert-file-contents file-name nil)
  5279. (set-buffer-file-coding-system coding-system))
  5280. (after-find-file nil nil t))
  5281. (t (user-error "Recover-file canceled")))))
  5282. (defun recover-session ()
  5283. "Recover auto save files from a previous Emacs session.
  5284. This command first displays a Dired buffer showing you the
  5285. previous sessions that you could recover from.
  5286. To choose one, move point to the proper line and then type C-c C-c.
  5287. Then you'll be asked about a number of files to recover."
  5288. (interactive)
  5289. (if (null auto-save-list-file-prefix)
  5290. (error "You set `auto-save-list-file-prefix' to disable making session files"))
  5291. (let ((dir (file-name-directory auto-save-list-file-prefix))
  5292. (nd (file-name-nondirectory auto-save-list-file-prefix)))
  5293. (unless (file-directory-p dir)
  5294. (make-directory dir t))
  5295. (unless (directory-files dir nil
  5296. (if (string= "" nd)
  5297. directory-files-no-dot-files-regexp
  5298. (concat "\\`" (regexp-quote nd)))
  5299. t)
  5300. (error "No previous sessions to recover")))
  5301. (let ((ls-lisp-support-shell-wildcards t))
  5302. (dired (concat auto-save-list-file-prefix "*")
  5303. (concat dired-listing-switches " -t")))
  5304. (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
  5305. (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish)
  5306. (save-excursion
  5307. (goto-char (point-min))
  5308. (or (looking-at " Move to the session you want to recover,")
  5309. (let ((inhibit-read-only t))
  5310. ;; Each line starts with a space
  5311. ;; so that Font Lock mode won't highlight the first character.
  5312. (insert " To recover a session, move to it and type C-c C-c.\n"
  5313. (substitute-command-keys
  5314. " To delete a session file, type \
  5315. \\[dired-flag-file-deletion] on its line to flag
  5316. the file for deletion, then \\[dired-do-flagged-delete] to \
  5317. delete flagged files.\n\n"))))))
  5318. (defun recover-session-finish ()
  5319. "Choose one saved session to recover auto-save files from.
  5320. This command is used in the special Dired buffer created by
  5321. \\[recover-session]."
  5322. (interactive)
  5323. ;; Get the name of the session file to recover from.
  5324. (let ((file (dired-get-filename))
  5325. files
  5326. (buffer (get-buffer-create " *recover*")))
  5327. (dired-unmark 1)
  5328. (dired-do-flagged-delete t)
  5329. (unwind-protect
  5330. (with-current-buffer buffer
  5331. ;; Read in the auto-save-list file.
  5332. (erase-buffer)
  5333. (insert-file-contents file)
  5334. ;; Loop thru the text of that file
  5335. ;; and get out the names of the files to recover.
  5336. (while (not (eobp))
  5337. (let (thisfile autofile)
  5338. (if (eolp)
  5339. ;; This is a pair of lines for a non-file-visiting buffer.
  5340. ;; Get the auto-save file name and manufacture
  5341. ;; a "visited file name" from that.
  5342. (progn
  5343. (forward-line 1)
  5344. ;; If there is no auto-save file name, the
  5345. ;; auto-save-list file is probably corrupted.
  5346. (unless (eolp)
  5347. (setq autofile
  5348. (buffer-substring-no-properties
  5349. (point)
  5350. (line-end-position)))
  5351. (setq thisfile
  5352. (expand-file-name
  5353. (substring
  5354. (file-name-nondirectory autofile)
  5355. 1 -1)
  5356. (file-name-directory autofile))))
  5357. (forward-line 1))
  5358. ;; This pair of lines is a file-visiting
  5359. ;; buffer. Use the visited file name.
  5360. (progn
  5361. (setq thisfile
  5362. (buffer-substring-no-properties
  5363. (point) (progn (end-of-line) (point))))
  5364. (forward-line 1)
  5365. (setq autofile
  5366. (buffer-substring-no-properties
  5367. (point) (progn (end-of-line) (point))))
  5368. (forward-line 1)))
  5369. ;; Ignore a file if its auto-save file does not exist now.
  5370. (if (and autofile (file-exists-p autofile))
  5371. (setq files (cons thisfile files)))))
  5372. (setq files (nreverse files))
  5373. ;; The file contains a pair of line for each auto-saved buffer.
  5374. ;; The first line of the pair contains the visited file name
  5375. ;; or is empty if the buffer was not visiting a file.
  5376. ;; The second line is the auto-save file name.
  5377. (if files
  5378. (map-y-or-n-p "Recover %s? "
  5379. (lambda (file)
  5380. (condition-case nil
  5381. (save-excursion (recover-file file))
  5382. (error
  5383. "Failed to recover `%s'" file)))
  5384. files
  5385. '("file" "files" "recover"))
  5386. (message "No files can be recovered from this session now")))
  5387. (kill-buffer buffer))))
  5388. (defun kill-buffer-ask (buffer)
  5389. "Kill BUFFER if confirmed."
  5390. (when (yes-or-no-p (format "Buffer %s %s. Kill? "
  5391. (buffer-name buffer)
  5392. (if (buffer-modified-p buffer)
  5393. "HAS BEEN EDITED" "is unmodified")))
  5394. (kill-buffer buffer)))
  5395. (defun kill-some-buffers (&optional list)
  5396. "Kill some buffers. Asks the user whether to kill each one of them.
  5397. Non-interactively, if optional argument LIST is non-nil, it
  5398. specifies the list of buffers to kill, asking for approval for each one."
  5399. (interactive)
  5400. (if (null list)
  5401. (setq list (buffer-list)))
  5402. (while list
  5403. (let* ((buffer (car list))
  5404. (name (buffer-name buffer)))
  5405. (and name ; Can be nil for an indirect buffer
  5406. ; if we killed the base buffer.
  5407. (not (string-equal name ""))
  5408. (/= (aref name 0) ?\s)
  5409. (kill-buffer-ask buffer)))
  5410. (setq list (cdr list))))
  5411. (defun kill-matching-buffers (regexp &optional internal-too)
  5412. "Kill buffers whose name matches the specified REGEXP.
  5413. The optional second argument indicates whether to kill internal buffers too."
  5414. (interactive "sKill buffers matching this regular expression: \nP")
  5415. (dolist (buffer (buffer-list))
  5416. (let ((name (buffer-name buffer)))
  5417. (when (and name (not (string-equal name ""))
  5418. (or internal-too (/= (aref name 0) ?\s))
  5419. (string-match regexp name))
  5420. (kill-buffer-ask buffer)))))
  5421. (defun rename-auto-save-file ()
  5422. "Adjust current buffer's auto save file name for current conditions.
  5423. Also rename any existing auto save file, if it was made in this session."
  5424. (let ((osave buffer-auto-save-file-name))
  5425. (setq buffer-auto-save-file-name
  5426. (make-auto-save-file-name))
  5427. (if (and osave buffer-auto-save-file-name
  5428. (not (string= buffer-auto-save-file-name buffer-file-name))
  5429. (not (string= buffer-auto-save-file-name osave))
  5430. (file-exists-p osave)
  5431. (recent-auto-save-p))
  5432. (rename-file osave buffer-auto-save-file-name t))))
  5433. (defun make-auto-save-file-name ()
  5434. "Return file name to use for auto-saves of current buffer.
  5435. Does not consider `auto-save-visited-file-name' as that variable is checked
  5436. before calling this function. You can redefine this for customization.
  5437. See also `auto-save-file-name-p'."
  5438. (if buffer-file-name
  5439. (let ((handler (find-file-name-handler buffer-file-name
  5440. 'make-auto-save-file-name)))
  5441. (if handler
  5442. (funcall handler 'make-auto-save-file-name)
  5443. (let ((list auto-save-file-name-transforms)
  5444. (filename buffer-file-name)
  5445. result uniq)
  5446. ;; Apply user-specified translations
  5447. ;; to the file name.
  5448. (while (and list (not result))
  5449. (if (string-match (car (car list)) filename)
  5450. (setq result (replace-match (cadr (car list)) t nil
  5451. filename)
  5452. uniq (car (cddr (car list)))))
  5453. (setq list (cdr list)))
  5454. (if result
  5455. (if uniq
  5456. (setq filename (concat
  5457. (file-name-directory result)
  5458. (subst-char-in-string
  5459. ?/ ?!
  5460. (replace-regexp-in-string "!" "!!"
  5461. filename))))
  5462. (setq filename result)))
  5463. (setq result
  5464. (if (and (eq system-type 'ms-dos)
  5465. (not (msdos-long-file-names)))
  5466. ;; We truncate the file name to DOS 8+3 limits
  5467. ;; before doing anything else, because the regexp
  5468. ;; passed to string-match below cannot handle
  5469. ;; extensions longer than 3 characters, multiple
  5470. ;; dots, and other atrocities.
  5471. (let ((fn (dos-8+3-filename
  5472. (file-name-nondirectory buffer-file-name))))
  5473. (string-match
  5474. "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'"
  5475. fn)
  5476. (concat (file-name-directory buffer-file-name)
  5477. "#" (match-string 1 fn)
  5478. "." (match-string 3 fn) "#"))
  5479. (concat (file-name-directory filename)
  5480. "#"
  5481. (file-name-nondirectory filename)
  5482. "#")))
  5483. ;; Make sure auto-save file names don't contain characters
  5484. ;; invalid for the underlying filesystem.
  5485. (if (and (memq system-type '(ms-dos windows-nt cygwin))
  5486. ;; Don't modify remote (ange-ftp) filenames
  5487. (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" result)))
  5488. (convert-standard-filename result)
  5489. result))))
  5490. ;; Deal with buffers that don't have any associated files. (Mail
  5491. ;; mode tends to create a good number of these.)
  5492. (let ((buffer-name (buffer-name))
  5493. (limit 0)
  5494. file-name)
  5495. ;; Restrict the characters used in the file name to those which
  5496. ;; are known to be safe on all filesystems, url-encoding the
  5497. ;; rest.
  5498. ;; We do this on all platforms, because even if we are not
  5499. ;; running on DOS/Windows, the current directory may be on a
  5500. ;; mounted VFAT filesystem, such as a USB memory stick.
  5501. (while (string-match "[^A-Za-z0-9-_.~#+]" buffer-name limit)
  5502. (let* ((character (aref buffer-name (match-beginning 0)))
  5503. (replacement
  5504. ;; For multibyte characters, this will produce more than
  5505. ;; 2 hex digits, so is not true URL encoding.
  5506. (format "%%%02X" character)))
  5507. (setq buffer-name (replace-match replacement t t buffer-name))
  5508. (setq limit (1+ (match-end 0)))))
  5509. ;; Generate the file name.
  5510. (setq file-name
  5511. (make-temp-file
  5512. (let ((fname
  5513. (expand-file-name
  5514. (format "#%s#" buffer-name)
  5515. ;; Try a few alternative directories, to get one we can
  5516. ;; write it.
  5517. (cond
  5518. ((file-writable-p default-directory) default-directory)
  5519. ((file-writable-p "/var/tmp/") "/var/tmp/")
  5520. ("~/")))))
  5521. (if (and (memq system-type '(ms-dos windows-nt cygwin))
  5522. ;; Don't modify remote (ange-ftp) filenames
  5523. (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" fname)))
  5524. ;; The call to convert-standard-filename is in case
  5525. ;; buffer-name includes characters not allowed by the
  5526. ;; DOS/Windows filesystems. make-temp-file writes to the
  5527. ;; file it creates, so we must fix the file name _before_
  5528. ;; make-temp-file is called.
  5529. (convert-standard-filename fname)
  5530. fname))
  5531. nil "#"))
  5532. ;; make-temp-file creates the file,
  5533. ;; but we don't want it to exist until we do an auto-save.
  5534. (condition-case ()
  5535. (delete-file file-name)
  5536. (file-error nil))
  5537. file-name)))
  5538. (defun auto-save-file-name-p (filename)
  5539. "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
  5540. FILENAME should lack slashes. You can redefine this for customization."
  5541. (string-match "\\`#.*#\\'" filename))
  5542. (defun wildcard-to-regexp (wildcard)
  5543. "Given a shell file name pattern WILDCARD, return an equivalent regexp.
  5544. The generated regexp will match a filename only if the filename
  5545. matches that wildcard according to shell rules. Only wildcards known
  5546. by `sh' are supported."
  5547. (let* ((i (string-match "[[.*+\\^$?]" wildcard))
  5548. ;; Copy the initial run of non-special characters.
  5549. (result (substring wildcard 0 i))
  5550. (len (length wildcard)))
  5551. ;; If no special characters, we're almost done.
  5552. (if i
  5553. (while (< i len)
  5554. (let ((ch (aref wildcard i))
  5555. j)
  5556. (setq
  5557. result
  5558. (concat result
  5559. (cond
  5560. ((and (eq ch ?\[)
  5561. (< (1+ i) len)
  5562. (eq (aref wildcard (1+ i)) ?\]))
  5563. "\\[")
  5564. ((eq ch ?\[) ; [...] maps to regexp char class
  5565. (progn
  5566. (setq i (1+ i))
  5567. (concat
  5568. (cond
  5569. ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
  5570. (progn
  5571. (setq i (1+ i))
  5572. (if (eq (aref wildcard i) ?\])
  5573. (progn
  5574. (setq i (1+ i))
  5575. "[^]")
  5576. "[^")))
  5577. ((eq (aref wildcard i) ?^)
  5578. ;; Found "[^". Insert a `\0' character
  5579. ;; (which cannot happen in a filename)
  5580. ;; into the character class, so that `^'
  5581. ;; is not the first character after `[',
  5582. ;; and thus non-special in a regexp.
  5583. (progn
  5584. (setq i (1+ i))
  5585. "[\000^"))
  5586. ((eq (aref wildcard i) ?\])
  5587. ;; I don't think `]' can appear in a
  5588. ;; character class in a wildcard, but
  5589. ;; let's be general here.
  5590. (progn
  5591. (setq i (1+ i))
  5592. "[]"))
  5593. (t "["))
  5594. (prog1 ; copy everything upto next `]'.
  5595. (substring wildcard
  5596. i
  5597. (setq j (string-match
  5598. "]" wildcard i)))
  5599. (setq i (if j (1- j) (1- len)))))))
  5600. ((eq ch ?.) "\\.")
  5601. ((eq ch ?*) "[^\000]*")
  5602. ((eq ch ?+) "\\+")
  5603. ((eq ch ?^) "\\^")
  5604. ((eq ch ?$) "\\$")
  5605. ((eq ch ?\\) "\\\\") ; probably cannot happen...
  5606. ((eq ch ??) "[^\000]")
  5607. (t (char-to-string ch)))))
  5608. (setq i (1+ i)))))
  5609. ;; Shell wildcards should match the entire filename,
  5610. ;; not its part. Make the regexp say so.
  5611. (concat "\\`" result "\\'")))
  5612. (defcustom list-directory-brief-switches
  5613. (purecopy "-CF")
  5614. "Switches for `list-directory' to pass to `ls' for brief listing."
  5615. :type 'string
  5616. :group 'dired)
  5617. (defcustom list-directory-verbose-switches
  5618. (purecopy "-l")
  5619. "Switches for `list-directory' to pass to `ls' for verbose listing."
  5620. :type 'string
  5621. :group 'dired)
  5622. (defun file-expand-wildcards (pattern &optional full)
  5623. "Expand wildcard pattern PATTERN.
  5624. This returns a list of file names which match the pattern.
  5625. Files are sorted in `string<' order.
  5626. If PATTERN is written as an absolute file name,
  5627. the values are absolute also.
  5628. If PATTERN is written as a relative file name, it is interpreted
  5629. relative to the current default directory, `default-directory'.
  5630. The file names returned are normally also relative to the current
  5631. default directory. However, if FULL is non-nil, they are absolute."
  5632. (save-match-data
  5633. (let* ((nondir (file-name-nondirectory pattern))
  5634. (dirpart (file-name-directory pattern))
  5635. ;; A list of all dirs that DIRPART specifies.
  5636. ;; This can be more than one dir
  5637. ;; if DIRPART contains wildcards.
  5638. (dirs (if (and dirpart
  5639. (string-match "[[*?]"
  5640. (or (file-remote-p dirpart 'localname)
  5641. dirpart)))
  5642. (mapcar 'file-name-as-directory
  5643. (file-expand-wildcards (directory-file-name dirpart)))
  5644. (list dirpart)))
  5645. contents)
  5646. (dolist (dir dirs)
  5647. (when (or (null dir) ; Possible if DIRPART is not wild.
  5648. (file-accessible-directory-p dir))
  5649. (let ((this-dir-contents
  5650. ;; Filter out "." and ".."
  5651. (delq nil
  5652. (mapcar #'(lambda (name)
  5653. (unless (string-match "\\`\\.\\.?\\'"
  5654. (file-name-nondirectory name))
  5655. name))
  5656. (directory-files (or dir ".") full
  5657. (wildcard-to-regexp nondir))))))
  5658. (setq contents
  5659. (nconc
  5660. (if (and dir (not full))
  5661. (mapcar #'(lambda (name) (concat dir name))
  5662. this-dir-contents)
  5663. this-dir-contents)
  5664. contents)))))
  5665. contents)))
  5666. ;; Let Tramp know that `file-expand-wildcards' does not need an advice.
  5667. (provide 'files '(remote-wildcards))
  5668. (defun list-directory (dirname &optional verbose)
  5669. "Display a list of files in or matching DIRNAME, a la `ls'.
  5670. DIRNAME is globbed by the shell if necessary.
  5671. Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
  5672. Actions controlled by variables `list-directory-brief-switches'
  5673. and `list-directory-verbose-switches'."
  5674. (interactive (let ((pfx current-prefix-arg))
  5675. (list (read-directory-name (if pfx "List directory (verbose): "
  5676. "List directory (brief): ")
  5677. nil default-directory nil)
  5678. pfx)))
  5679. (let ((switches (if verbose list-directory-verbose-switches
  5680. list-directory-brief-switches))
  5681. buffer)
  5682. (or dirname (setq dirname default-directory))
  5683. (setq dirname (expand-file-name dirname))
  5684. (with-output-to-temp-buffer "*Directory*"
  5685. (setq buffer standard-output)
  5686. (buffer-disable-undo standard-output)
  5687. (princ "Directory ")
  5688. (princ dirname)
  5689. (terpri)
  5690. (with-current-buffer "*Directory*"
  5691. (let ((wildcard (not (file-directory-p dirname))))
  5692. (insert-directory dirname switches wildcard (not wildcard)))))
  5693. ;; Finishing with-output-to-temp-buffer seems to clobber default-directory.
  5694. (with-current-buffer buffer
  5695. (setq default-directory
  5696. (if (file-directory-p dirname)
  5697. (file-name-as-directory dirname)
  5698. (file-name-directory dirname))))))
  5699. (defun shell-quote-wildcard-pattern (pattern)
  5700. "Quote characters special to the shell in PATTERN, leave wildcards alone.
  5701. PATTERN is assumed to represent a file-name wildcard suitable for the
  5702. underlying filesystem. For Unix and GNU/Linux, each character from the
  5703. set [ \\t\\n;<>&|()`'\"#$] is quoted with a backslash; for DOS/Windows, all
  5704. the parts of the pattern which don't include wildcard characters are
  5705. quoted with double quotes.
  5706. This function leaves alone existing quote characters (\\ on Unix and \"
  5707. on Windows), so PATTERN can use them to quote wildcard characters that
  5708. need to be passed verbatim to shell commands."
  5709. (save-match-data
  5710. (cond
  5711. ((memq system-type '(ms-dos windows-nt cygwin))
  5712. ;; DOS/Windows don't allow `"' in file names. So if the
  5713. ;; argument has quotes, we can safely assume it is already
  5714. ;; quoted by the caller.
  5715. (if (or (string-match "[\"]" pattern)
  5716. ;; We quote [&()#$`'] in case their shell is a port of a
  5717. ;; Unixy shell. We quote [,=+] because stock DOS and
  5718. ;; Windows shells require that in some cases, such as
  5719. ;; passing arguments to batch files that use positional
  5720. ;; arguments like %1.
  5721. (not (string-match "[ \t;&()#$`',=+]" pattern)))
  5722. pattern
  5723. (let ((result "\"")
  5724. (beg 0)
  5725. end)
  5726. (while (string-match "[*?]+" pattern beg)
  5727. (setq end (match-beginning 0)
  5728. result (concat result (substring pattern beg end)
  5729. "\""
  5730. (substring pattern end (match-end 0))
  5731. "\"")
  5732. beg (match-end 0)))
  5733. (concat result (substring pattern beg) "\""))))
  5734. (t
  5735. (let ((beg 0))
  5736. (while (string-match "[ \t\n;<>&|()`'\"#$]" pattern beg)
  5737. (setq pattern
  5738. (concat (substring pattern 0 (match-beginning 0))
  5739. "\\"
  5740. (substring pattern (match-beginning 0)))
  5741. beg (1+ (match-end 0)))))
  5742. pattern))))
  5743. (defvar insert-directory-program (purecopy "ls")
  5744. "Absolute or relative name of the `ls' program used by `insert-directory'.")
  5745. (defcustom directory-free-space-program (purecopy "df")
  5746. "Program to get the amount of free space on a file system.
  5747. We assume the output has the format of `df'.
  5748. The value of this variable must be just a command name or file name;
  5749. if you want to specify options, use `directory-free-space-args'.
  5750. A value of nil disables this feature.
  5751. If the function `file-system-info' is defined, it is always used in
  5752. preference to the program given by this variable."
  5753. :type '(choice (string :tag "Program") (const :tag "None" nil))
  5754. :group 'dired)
  5755. (defcustom directory-free-space-args
  5756. (purecopy (if (eq system-type 'darwin) "-k" "-Pk"))
  5757. "Options to use when running `directory-free-space-program'."
  5758. :type 'string
  5759. :group 'dired)
  5760. (defun get-free-disk-space (dir)
  5761. "Return the amount of free space on directory DIR's file system.
  5762. The return value is a string describing the amount of free
  5763. space (normally, the number of free 1KB blocks).
  5764. This function calls `file-system-info' if it is available, or
  5765. invokes the program specified by `directory-free-space-program'
  5766. and `directory-free-space-args'. If the system call or program
  5767. is unsuccessful, or if DIR is a remote directory, this function
  5768. returns nil."
  5769. (unless (file-remote-p dir)
  5770. ;; Try to find the number of free blocks. Non-Posix systems don't
  5771. ;; always have df, but might have an equivalent system call.
  5772. (if (fboundp 'file-system-info)
  5773. (let ((fsinfo (file-system-info dir)))
  5774. (if fsinfo
  5775. (format "%.0f" (/ (nth 2 fsinfo) 1024))))
  5776. (setq dir (expand-file-name dir))
  5777. (save-match-data
  5778. (with-temp-buffer
  5779. (when (and directory-free-space-program
  5780. ;; Avoid failure if the default directory does
  5781. ;; not exist (Bug#2631, Bug#3911).
  5782. (let ((default-directory
  5783. (locate-dominating-file dir 'file-directory-p)))
  5784. (eq (process-file directory-free-space-program
  5785. nil t nil
  5786. directory-free-space-args
  5787. (file-relative-name dir))
  5788. 0)))
  5789. ;; Assume that the "available" column is before the
  5790. ;; "capacity" column. Find the "%" and scan backward.
  5791. (goto-char (point-min))
  5792. (forward-line 1)
  5793. (when (re-search-forward
  5794. "[[:space:]]+[^[:space:]]+%[^%]*$"
  5795. (line-end-position) t)
  5796. (goto-char (match-beginning 0))
  5797. (let ((endpt (point)))
  5798. (skip-chars-backward "^[:space:]")
  5799. (buffer-substring-no-properties (point) endpt)))))))))
  5800. ;; The following expression replaces `dired-move-to-filename-regexp'.
  5801. (defvar directory-listing-before-filename-regexp
  5802. (let* ((l "\\([A-Za-z]\\|[^\0-\177]\\)")
  5803. (l-or-quote "\\([A-Za-z']\\|[^\0-\177]\\)")
  5804. ;; In some locales, month abbreviations are as short as 2 letters,
  5805. ;; and they can be followed by ".".
  5806. ;; In Breton, a month name can include a quote character.
  5807. (month (concat l-or-quote l-or-quote "+\\.?"))
  5808. (s " ")
  5809. (yyyy "[0-9][0-9][0-9][0-9]")
  5810. (dd "[ 0-3][0-9]")
  5811. (HH:MM "[ 0-2][0-9][:.][0-5][0-9]")
  5812. (seconds "[0-6][0-9]\\([.,][0-9]+\\)?")
  5813. (zone "[-+][0-2][0-9][0-5][0-9]")
  5814. (iso-mm-dd "[01][0-9]-[0-3][0-9]")
  5815. (iso-time (concat HH:MM "\\(:" seconds "\\( ?" zone "\\)?\\)?"))
  5816. (iso (concat "\\(\\(" yyyy "-\\)?" iso-mm-dd "[ T]" iso-time
  5817. "\\|" yyyy "-" iso-mm-dd "\\)"))
  5818. (western (concat "\\(" month s "+" dd "\\|" dd "\\.?" s month "\\)"
  5819. s "+"
  5820. "\\(" HH:MM "\\|" yyyy "\\)"))
  5821. (western-comma (concat month s "+" dd "," s "+" yyyy))
  5822. ;; Japanese MS-Windows ls-lisp has one-digit months, and
  5823. ;; omits the Kanji characters after month and day-of-month.
  5824. ;; On Mac OS X 10.3, the date format in East Asian locales is
  5825. ;; day-of-month digits followed by month digits.
  5826. (mm "[ 0-1]?[0-9]")
  5827. (east-asian
  5828. (concat "\\(" mm l "?" s dd l "?" s "+"
  5829. "\\|" dd s mm s "+" "\\)"
  5830. "\\(" HH:MM "\\|" yyyy l "?" "\\)")))
  5831. ;; The "[0-9]" below requires the previous column to end in a digit.
  5832. ;; This avoids recognizing `1 may 1997' as a date in the line:
  5833. ;; -r--r--r-- 1 may 1997 1168 Oct 19 16:49 README
  5834. ;; The "[BkKMGTPEZY]?" below supports "ls -alh" output.
  5835. ;; For non-iso date formats, we add the ".*" in order to find
  5836. ;; the last possible match. This avoids recognizing
  5837. ;; `jservice 10 1024' as a date in the line:
  5838. ;; drwxr-xr-x 3 jservice 10 1024 Jul 2 1997 esg-host
  5839. ;; vc dired listings provide the state or blanks between file
  5840. ;; permissions and date. The state is always surrounded by
  5841. ;; parentheses:
  5842. ;; -rw-r--r-- (modified) 2005-10-22 21:25 files.el
  5843. ;; This is not supported yet.
  5844. (purecopy (concat "\\([0-9][BkKMGTPEZY]? " iso
  5845. "\\|.*[0-9][BkKMGTPEZY]? "
  5846. "\\(" western "\\|" western-comma "\\|" east-asian "\\)"
  5847. "\\) +")))
  5848. "Regular expression to match up to the file name in a directory listing.
  5849. The default value is designed to recognize dates and times
  5850. regardless of the language.")
  5851. (defvar insert-directory-ls-version 'unknown)
  5852. ;; insert-directory
  5853. ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
  5854. ;; FULL-DIRECTORY-P is nil.
  5855. ;; The single line of output must display FILE's name as it was
  5856. ;; given, namely, an absolute path name.
  5857. ;; - must insert exactly one line for each file if WILDCARD or
  5858. ;; FULL-DIRECTORY-P is t, plus one optional "total" line
  5859. ;; before the file lines, plus optional text after the file lines.
  5860. ;; Lines are delimited by "\n", so filenames containing "\n" are not
  5861. ;; allowed.
  5862. ;; File lines should display the basename.
  5863. ;; - must be consistent with
  5864. ;; - functions dired-move-to-filename, (these two define what a file line is)
  5865. ;; dired-move-to-end-of-filename,
  5866. ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
  5867. ;; dired-insert-headerline
  5868. ;; dired-after-subdir-garbage (defines what a "total" line is)
  5869. ;; - variable dired-subdir-regexp
  5870. ;; - may be passed "--dired" as the first argument in SWITCHES.
  5871. ;; Filename handlers might have to remove this switch if their
  5872. ;; "ls" command does not support it.
  5873. (defun insert-directory (file switches &optional wildcard full-directory-p)
  5874. "Insert directory listing for FILE, formatted according to SWITCHES.
  5875. Leaves point after the inserted text.
  5876. SWITCHES may be a string of options, or a list of strings
  5877. representing individual options.
  5878. Optional third arg WILDCARD means treat FILE as shell wildcard.
  5879. Optional fourth arg FULL-DIRECTORY-P means file is a directory and
  5880. switches do not contain `d', so that a full listing is expected.
  5881. This works by running a directory listing program
  5882. whose name is in the variable `insert-directory-program'.
  5883. If WILDCARD, it also runs the shell specified by `shell-file-name'.
  5884. When SWITCHES contains the long `--dired' option, this function
  5885. treats it specially, for the sake of dired. However, the
  5886. normally equivalent short `-D' option is just passed on to
  5887. `insert-directory-program', as any other option."
  5888. ;; We need the directory in order to find the right handler.
  5889. (let ((handler (find-file-name-handler (expand-file-name file)
  5890. 'insert-directory)))
  5891. (if handler
  5892. (funcall handler 'insert-directory file switches
  5893. wildcard full-directory-p)
  5894. (let (result (beg (point)))
  5895. ;; Read the actual directory using `insert-directory-program'.
  5896. ;; RESULT gets the status code.
  5897. (let* (;; We at first read by no-conversion, then after
  5898. ;; putting text property `dired-filename, decode one
  5899. ;; bunch by one to preserve that property.
  5900. (coding-system-for-read 'no-conversion)
  5901. ;; This is to control encoding the arguments in call-process.
  5902. (coding-system-for-write
  5903. (and enable-multibyte-characters
  5904. (or file-name-coding-system
  5905. default-file-name-coding-system))))
  5906. (setq result
  5907. (if wildcard
  5908. ;; Run ls in the directory part of the file pattern
  5909. ;; using the last component as argument.
  5910. (let ((default-directory
  5911. (if (file-name-absolute-p file)
  5912. (file-name-directory file)
  5913. (file-name-directory (expand-file-name file))))
  5914. (pattern (file-name-nondirectory file)))
  5915. ;; NB since switches is passed to the shell, be
  5916. ;; careful of malicious values, eg "-l;reboot".
  5917. ;; See eg dired-safe-switches-p.
  5918. (call-process
  5919. shell-file-name nil t nil
  5920. "-c"
  5921. (concat (if (memq system-type '(ms-dos windows-nt))
  5922. ""
  5923. "\\") ; Disregard Unix shell aliases!
  5924. insert-directory-program
  5925. " -d "
  5926. (if (stringp switches)
  5927. switches
  5928. (mapconcat 'identity switches " "))
  5929. " -- "
  5930. ;; Quote some characters that have
  5931. ;; special meanings in shells; but
  5932. ;; don't quote the wildcards--we want
  5933. ;; them to be special. We also
  5934. ;; currently don't quote the quoting
  5935. ;; characters in case people want to
  5936. ;; use them explicitly to quote
  5937. ;; wildcard characters.
  5938. (shell-quote-wildcard-pattern pattern))))
  5939. ;; SunOS 4.1.3, SVr4 and others need the "." to list the
  5940. ;; directory if FILE is a symbolic link.
  5941. (unless full-directory-p
  5942. (setq switches
  5943. (cond
  5944. ((stringp switches) (concat switches " -d"))
  5945. ((member "-d" switches) switches)
  5946. (t (append switches '("-d"))))))
  5947. (apply 'call-process
  5948. insert-directory-program nil t nil
  5949. (append
  5950. (if (listp switches) switches
  5951. (unless (equal switches "")
  5952. ;; Split the switches at any spaces so we can
  5953. ;; pass separate options as separate args.
  5954. (split-string switches)))
  5955. ;; Avoid lossage if FILE starts with `-'.
  5956. '("--")
  5957. (progn
  5958. (if (string-match "\\`~" file)
  5959. (setq file (expand-file-name file)))
  5960. (list
  5961. (if full-directory-p
  5962. (concat (file-name-as-directory file) ".")
  5963. file))))))))
  5964. ;; If we got "//DIRED//" in the output, it means we got a real
  5965. ;; directory listing, even if `ls' returned nonzero.
  5966. ;; So ignore any errors.
  5967. (when (if (stringp switches)
  5968. (string-match "--dired\\>" switches)
  5969. (member "--dired" switches))
  5970. (save-excursion
  5971. (forward-line -2)
  5972. (when (looking-at "//SUBDIRED//")
  5973. (forward-line -1))
  5974. (if (looking-at "//DIRED//")
  5975. (setq result 0))))
  5976. (when (and (not (eq 0 result))
  5977. (eq insert-directory-ls-version 'unknown))
  5978. ;; The first time ls returns an error,
  5979. ;; find the version numbers of ls,
  5980. ;; and set insert-directory-ls-version
  5981. ;; to > if it is more than 5.2.1, < if it is less, nil if it
  5982. ;; is equal or if the info cannot be obtained.
  5983. ;; (That can mean it isn't GNU ls.)
  5984. (let ((version-out
  5985. (with-temp-buffer
  5986. (call-process "ls" nil t nil "--version")
  5987. (buffer-string))))
  5988. (if (string-match "ls (.*utils) \\([0-9.]*\\)$" version-out)
  5989. (let* ((version (match-string 1 version-out))
  5990. (split (split-string version "[.]"))
  5991. (numbers (mapcar 'string-to-number split))
  5992. (min '(5 2 1))
  5993. comparison)
  5994. (while (and (not comparison) (or numbers min))
  5995. (cond ((null min)
  5996. (setq comparison '>))
  5997. ((null numbers)
  5998. (setq comparison '<))
  5999. ((> (car numbers) (car min))
  6000. (setq comparison '>))
  6001. ((< (car numbers) (car min))
  6002. (setq comparison '<))
  6003. (t
  6004. (setq numbers (cdr numbers)
  6005. min (cdr min)))))
  6006. (setq insert-directory-ls-version (or comparison '=)))
  6007. (setq insert-directory-ls-version nil))))
  6008. ;; For GNU ls versions 5.2.2 and up, ignore minor errors.
  6009. (when (and (eq 1 result) (eq insert-directory-ls-version '>))
  6010. (setq result 0))
  6011. ;; If `insert-directory-program' failed, signal an error.
  6012. (unless (eq 0 result)
  6013. ;; Delete the error message it may have output.
  6014. (delete-region beg (point))
  6015. ;; On non-Posix systems, we cannot open a directory, so
  6016. ;; don't even try, because that will always result in
  6017. ;; the ubiquitous "Access denied". Instead, show the
  6018. ;; command line so the user can try to guess what went wrong.
  6019. (if (and (file-directory-p file)
  6020. (memq system-type '(ms-dos windows-nt)))
  6021. (error
  6022. "Reading directory: \"%s %s -- %s\" exited with status %s"
  6023. insert-directory-program
  6024. (if (listp switches) (concat switches) switches)
  6025. file result)
  6026. ;; Unix. Access the file to get a suitable error.
  6027. (access-file file "Reading directory")
  6028. (error "Listing directory failed but `access-file' worked")))
  6029. (when (if (stringp switches)
  6030. (string-match "--dired\\>" switches)
  6031. (member "--dired" switches))
  6032. ;; The following overshoots by one line for an empty
  6033. ;; directory listed with "--dired", but without "-a"
  6034. ;; switch, where the ls output contains a
  6035. ;; "//DIRED-OPTIONS//" line, but no "//DIRED//" line.
  6036. ;; We take care of that case later.
  6037. (forward-line -2)
  6038. (when (looking-at "//SUBDIRED//")
  6039. (delete-region (point) (progn (forward-line 1) (point)))
  6040. (forward-line -1))
  6041. (if (looking-at "//DIRED//")
  6042. (let ((end (line-end-position))
  6043. (linebeg (point))
  6044. error-lines)
  6045. ;; Find all the lines that are error messages,
  6046. ;; and record the bounds of each one.
  6047. (goto-char beg)
  6048. (while (< (point) linebeg)
  6049. (or (eql (following-char) ?\s)
  6050. (push (list (point) (line-end-position)) error-lines))
  6051. (forward-line 1))
  6052. (setq error-lines (nreverse error-lines))
  6053. ;; Now read the numeric positions of file names.
  6054. (goto-char linebeg)
  6055. (forward-word 1)
  6056. (forward-char 3)
  6057. (while (< (point) end)
  6058. (let ((start (insert-directory-adj-pos
  6059. (+ beg (read (current-buffer)))
  6060. error-lines))
  6061. (end (insert-directory-adj-pos
  6062. (+ beg (read (current-buffer)))
  6063. error-lines)))
  6064. (if (memq (char-after end) '(?\n ?\s))
  6065. ;; End is followed by \n or by " -> ".
  6066. (put-text-property start end 'dired-filename t)
  6067. ;; It seems that we can't trust ls's output as to
  6068. ;; byte positions of filenames.
  6069. (put-text-property beg (point) 'dired-filename nil)
  6070. (end-of-line))))
  6071. (goto-char end)
  6072. (beginning-of-line)
  6073. (delete-region (point) (progn (forward-line 1) (point))))
  6074. ;; Take care of the case where the ls output contains a
  6075. ;; "//DIRED-OPTIONS//"-line, but no "//DIRED//"-line
  6076. ;; and we went one line too far back (see above).
  6077. (forward-line 1))
  6078. (if (looking-at "//DIRED-OPTIONS//")
  6079. (delete-region (point) (progn (forward-line 1) (point)))))
  6080. ;; Now decode what read if necessary.
  6081. (let ((coding (or coding-system-for-read
  6082. file-name-coding-system
  6083. default-file-name-coding-system
  6084. 'undecided))
  6085. coding-no-eol
  6086. val pos)
  6087. (when (and enable-multibyte-characters
  6088. (not (memq (coding-system-base coding)
  6089. '(raw-text no-conversion))))
  6090. ;; If no coding system is specified or detection is
  6091. ;; requested, detect the coding.
  6092. (if (eq (coding-system-base coding) 'undecided)
  6093. (setq coding (detect-coding-region beg (point) t)))
  6094. (if (not (eq (coding-system-base coding) 'undecided))
  6095. (save-restriction
  6096. (setq coding-no-eol
  6097. (coding-system-change-eol-conversion coding 'unix))
  6098. (narrow-to-region beg (point))
  6099. (goto-char (point-min))
  6100. (while (not (eobp))
  6101. (setq pos (point)
  6102. val (get-text-property (point) 'dired-filename))
  6103. (goto-char (next-single-property-change
  6104. (point) 'dired-filename nil (point-max)))
  6105. ;; Force no eol conversion on a file name, so
  6106. ;; that CR is preserved.
  6107. (decode-coding-region pos (point)
  6108. (if val coding-no-eol coding))
  6109. (if val
  6110. (put-text-property pos (point)
  6111. 'dired-filename t)))))))
  6112. (if full-directory-p
  6113. ;; Try to insert the amount of free space.
  6114. (save-excursion
  6115. (goto-char beg)
  6116. ;; First find the line to put it on.
  6117. (when (re-search-forward "^ *\\(total\\)" nil t)
  6118. (let ((available (get-free-disk-space ".")))
  6119. (when available
  6120. ;; Replace "total" with "used", to avoid confusion.
  6121. (replace-match "total used in directory" nil nil nil 1)
  6122. (end-of-line)
  6123. (insert " available " available))))))))))
  6124. (defun insert-directory-adj-pos (pos error-lines)
  6125. "Convert `ls --dired' file name position value POS to a buffer position.
  6126. File name position values returned in ls --dired output
  6127. count only stdout; they don't count the error messages sent to stderr.
  6128. So this function converts to them to real buffer positions.
  6129. ERROR-LINES is a list of buffer positions of error message lines,
  6130. of the form (START END)."
  6131. (while (and error-lines (< (caar error-lines) pos))
  6132. (setq pos (+ pos (- (nth 1 (car error-lines)) (nth 0 (car error-lines)))))
  6133. (pop error-lines))
  6134. pos)
  6135. (defun insert-directory-safely (file switches
  6136. &optional wildcard full-directory-p)
  6137. "Insert directory listing for FILE, formatted according to SWITCHES.
  6138. Like `insert-directory', but if FILE does not exist, it inserts a
  6139. message to that effect instead of signaling an error."
  6140. (if (file-exists-p file)
  6141. (insert-directory file switches wildcard full-directory-p)
  6142. ;; Simulate the message printed by `ls'.
  6143. (insert (format "%s: No such file or directory\n" file))))
  6144. (defvar kill-emacs-query-functions nil
  6145. "Functions to call with no arguments to query about killing Emacs.
  6146. If any of these functions returns nil, killing Emacs is canceled.
  6147. `save-buffers-kill-emacs' calls these functions, but `kill-emacs',
  6148. the low level primitive, does not. See also `kill-emacs-hook'.")
  6149. (defcustom confirm-kill-emacs nil
  6150. "How to ask for confirmation when leaving Emacs.
  6151. If nil, the default, don't ask at all. If the value is non-nil, it should
  6152. be a predicate function; for example `yes-or-no-p'."
  6153. :type '(choice (const :tag "Ask with yes-or-no-p" yes-or-no-p)
  6154. (const :tag "Ask with y-or-n-p" y-or-n-p)
  6155. (const :tag "Don't confirm" nil)
  6156. (function :tag "Predicate function"))
  6157. :group 'convenience
  6158. :version "21.1")
  6159. (defun save-buffers-kill-emacs (&optional arg)
  6160. "Offer to save each buffer, then kill this Emacs process.
  6161. With prefix ARG, silently save all file-visiting buffers without asking.
  6162. If there are active processes where `process-query-on-exit-flag'
  6163. returns non-nil, asks whether processes should be killed.
  6164. Runs the members of `kill-emacs-query-functions' in turn and stops
  6165. if any returns nil. If `confirm-kill-emacs' is non-nil, calls it."
  6166. (interactive "P")
  6167. (save-some-buffers arg t)
  6168. (let ((confirm confirm-kill-emacs))
  6169. (and
  6170. (or (not (memq t (mapcar (function
  6171. (lambda (buf) (and (buffer-file-name buf)
  6172. (buffer-modified-p buf))))
  6173. (buffer-list))))
  6174. (progn (setq confirm nil)
  6175. (yes-or-no-p "Modified buffers exist; exit anyway? ")))
  6176. (or (not (fboundp 'process-list))
  6177. ;; process-list is not defined on MSDOS.
  6178. (let ((processes (process-list))
  6179. active)
  6180. (while processes
  6181. (and (memq (process-status (car processes)) '(run stop open listen))
  6182. (process-query-on-exit-flag (car processes))
  6183. (setq active t))
  6184. (setq processes (cdr processes)))
  6185. (or (not active)
  6186. (with-current-buffer-window
  6187. (get-buffer-create "*Process List*") nil
  6188. #'(lambda (window _value)
  6189. (with-selected-window window
  6190. (unwind-protect
  6191. (progn
  6192. (setq confirm nil)
  6193. (yes-or-no-p "Active processes exist; kill them and exit anyway? "))
  6194. (when (window-live-p window)
  6195. (quit-restore-window window 'kill)))))
  6196. (list-processes t)))))
  6197. ;; Query the user for other things, perhaps.
  6198. (run-hook-with-args-until-failure 'kill-emacs-query-functions)
  6199. (or (null confirm)
  6200. (funcall confirm "Really exit Emacs? "))
  6201. (kill-emacs))))
  6202. (defun save-buffers-kill-terminal (&optional arg)
  6203. "Offer to save each buffer, then kill the current connection.
  6204. If the current frame has no client, kill Emacs itself.
  6205. With prefix ARG, silently save all file-visiting buffers, then kill.
  6206. If emacsclient was started with a list of filenames to edit, then
  6207. only these files will be asked to be saved."
  6208. (interactive "P")
  6209. (if (frame-parameter nil 'client)
  6210. (server-save-buffers-kill-terminal arg)
  6211. (save-buffers-kill-emacs arg)))
  6212. ;; We use /: as a prefix to "quote" a file name
  6213. ;; so that magic file name handlers will not apply to it.
  6214. (setq file-name-handler-alist
  6215. (cons (cons (purecopy "\\`/:") 'file-name-non-special)
  6216. file-name-handler-alist))
  6217. ;; We depend on being the last handler on the list,
  6218. ;; so that anything else which does need handling
  6219. ;; has been handled already.
  6220. ;; So it is safe for us to inhibit *all* magic file name handlers.
  6221. (defun file-name-non-special (operation &rest arguments)
  6222. (let ((file-name-handler-alist nil)
  6223. (default-directory
  6224. (if (eq operation 'insert-directory)
  6225. (directory-file-name
  6226. (expand-file-name
  6227. (unhandled-file-name-directory default-directory)))
  6228. default-directory))
  6229. ;; Get a list of the indices of the args which are file names.
  6230. (file-arg-indices
  6231. (cdr (or (assq operation
  6232. ;; The first six are special because they
  6233. ;; return a file name. We want to include the /:
  6234. ;; in the return value.
  6235. ;; So just avoid stripping it in the first place.
  6236. '((expand-file-name . nil)
  6237. (file-name-directory . nil)
  6238. (file-name-as-directory . nil)
  6239. (directory-file-name . nil)
  6240. (file-name-sans-versions . nil)
  6241. (find-backup-file-name . nil)
  6242. ;; `identity' means just return the first arg
  6243. ;; not stripped of its quoting.
  6244. (substitute-in-file-name identity)
  6245. ;; `add' means add "/:" to the result.
  6246. (file-truename add 0)
  6247. (insert-file-contents insert-file-contents 0)
  6248. ;; `unquote-then-quote' means set buffer-file-name
  6249. ;; temporarily to unquoted filename.
  6250. (verify-visited-file-modtime unquote-then-quote)
  6251. ;; List the arguments which are filenames.
  6252. (file-name-completion 1)
  6253. (file-name-all-completions 1)
  6254. (write-region 2 5)
  6255. (rename-file 0 1)
  6256. (copy-file 0 1)
  6257. (make-symbolic-link 0 1)
  6258. (add-name-to-file 0 1)))
  6259. ;; For all other operations, treat the first argument only
  6260. ;; as the file name.
  6261. '(nil 0))))
  6262. method
  6263. ;; Copy ARGUMENTS so we can replace elements in it.
  6264. (arguments (copy-sequence arguments)))
  6265. (if (symbolp (car file-arg-indices))
  6266. (setq method (pop file-arg-indices)))
  6267. ;; Strip off the /: from the file names that have it.
  6268. (save-match-data
  6269. (while (consp file-arg-indices)
  6270. (let ((pair (nthcdr (car file-arg-indices) arguments)))
  6271. (and (car pair)
  6272. (string-match "\\`/:" (car pair))
  6273. (setcar pair
  6274. (if (= (length (car pair)) 2)
  6275. "/"
  6276. (substring (car pair) 2)))))
  6277. (setq file-arg-indices (cdr file-arg-indices))))
  6278. (pcase method
  6279. (`identity (car arguments))
  6280. (`add (concat "/:" (apply operation arguments)))
  6281. (`insert-file-contents
  6282. (let ((visit (nth 1 arguments)))
  6283. (unwind-protect
  6284. (apply operation arguments)
  6285. (when (and visit buffer-file-name)
  6286. (setq buffer-file-name (concat "/:" buffer-file-name))))))
  6287. (`unquote-then-quote
  6288. (let ((buffer-file-name (substring buffer-file-name 2)))
  6289. (apply operation arguments)))
  6290. (_
  6291. (apply operation arguments)))))
  6292. ;; Symbolic modes and read-file-modes.
  6293. (defun file-modes-char-to-who (char)
  6294. "Convert CHAR to a numeric bit-mask for extracting mode bits.
  6295. CHAR is in [ugoa] and represents the category of users (Owner, Group,
  6296. Others, or All) for whom to produce the mask.
  6297. The bit-mask that is returned extracts from mode bits the access rights
  6298. for the specified category of users."
  6299. (cond ((= char ?u) #o4700)
  6300. ((= char ?g) #o2070)
  6301. ((= char ?o) #o1007)
  6302. ((= char ?a) #o7777)
  6303. (t (error "%c: bad `who' character" char))))
  6304. (defun file-modes-char-to-right (char &optional from)
  6305. "Convert CHAR to a numeric value of mode bits.
  6306. CHAR is in [rwxXstugo] and represents symbolic access permissions.
  6307. If CHAR is in [Xugo], the value is taken from FROM (or 0 if omitted)."
  6308. (or from (setq from 0))
  6309. (cond ((= char ?r) #o0444)
  6310. ((= char ?w) #o0222)
  6311. ((= char ?x) #o0111)
  6312. ((= char ?s) #o1000)
  6313. ((= char ?t) #o6000)
  6314. ;; Rights relative to the previous file modes.
  6315. ((= char ?X) (if (= (logand from #o111) 0) 0 #o0111))
  6316. ((= char ?u) (let ((uright (logand #o4700 from)))
  6317. (+ uright (/ uright #o10) (/ uright #o100))))
  6318. ((= char ?g) (let ((gright (logand #o2070 from)))
  6319. (+ gright (/ gright #o10) (* gright #o10))))
  6320. ((= char ?o) (let ((oright (logand #o1007 from)))
  6321. (+ oright (* oright #o10) (* oright #o100))))
  6322. (t (error "%c: bad right character" char))))
  6323. (defun file-modes-rights-to-number (rights who-mask &optional from)
  6324. "Convert a symbolic mode string specification to an equivalent number.
  6325. RIGHTS is the symbolic mode spec, it should match \"([+=-][rwxXstugo]*)+\".
  6326. WHO-MASK is the bit-mask specifying the category of users to which to
  6327. apply the access permissions. See `file-modes-char-to-who'.
  6328. FROM (or 0 if nil) gives the mode bits on which to base permissions if
  6329. RIGHTS request to add, remove, or set permissions based on existing ones,
  6330. as in \"og+rX-w\"."
  6331. (let* ((num-rights (or from 0))
  6332. (list-rights (string-to-list rights))
  6333. (op (pop list-rights)))
  6334. (while (memq op '(?+ ?- ?=))
  6335. (let ((num-right 0)
  6336. char-right)
  6337. (while (memq (setq char-right (pop list-rights))
  6338. '(?r ?w ?x ?X ?s ?t ?u ?g ?o))
  6339. (setq num-right
  6340. (logior num-right
  6341. (file-modes-char-to-right char-right num-rights))))
  6342. (setq num-right (logand who-mask num-right)
  6343. num-rights
  6344. (cond ((= op ?+) (logior num-rights num-right))
  6345. ((= op ?-) (logand num-rights (lognot num-right)))
  6346. (t (logior (logand num-rights (lognot who-mask)) num-right)))
  6347. op char-right)))
  6348. num-rights))
  6349. (defun file-modes-symbolic-to-number (modes &optional from)
  6350. "Convert symbolic file modes to numeric file modes.
  6351. MODES is the string to convert, it should match
  6352. \"[ugoa]*([+-=][rwxXstugo]*)+,...\".
  6353. See Info node `(coreutils)File permissions' for more information on this
  6354. notation.
  6355. FROM (or 0 if nil) gives the mode bits on which to base permissions if
  6356. MODES request to add, remove, or set permissions based on existing ones,
  6357. as in \"og+rX-w\"."
  6358. (save-match-data
  6359. (let ((case-fold-search nil)
  6360. (num-modes (or from 0)))
  6361. (while (/= (string-to-char modes) 0)
  6362. (if (string-match "^\\([ugoa]*\\)\\([+=-][rwxXstugo]*\\)+\\(,\\|\\)" modes)
  6363. (let ((num-who (apply 'logior 0
  6364. (mapcar 'file-modes-char-to-who
  6365. (match-string 1 modes)))))
  6366. (when (= num-who 0)
  6367. (setq num-who (default-file-modes)))
  6368. (setq num-modes
  6369. (file-modes-rights-to-number (substring modes (match-end 1))
  6370. num-who num-modes)
  6371. modes (substring modes (match-end 3))))
  6372. (error "Parse error in modes near `%s'" (substring modes 0))))
  6373. num-modes)))
  6374. (defun read-file-modes (&optional prompt orig-file)
  6375. "Read file modes in octal or symbolic notation and return its numeric value.
  6376. PROMPT is used as the prompt, default to `File modes (octal or symbolic): '.
  6377. ORIG-FILE is the name of a file on whose mode bits to base returned
  6378. permissions if what user types requests to add, remove, or set permissions
  6379. based on existing mode bits, as in \"og+rX-w\"."
  6380. (let* ((modes (or (if orig-file (file-modes orig-file) 0)
  6381. (error "File not found")))
  6382. (modestr (and (stringp orig-file)
  6383. (nth 8 (file-attributes orig-file))))
  6384. (default
  6385. (and (stringp modestr)
  6386. (string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr)
  6387. (replace-regexp-in-string
  6388. "-" ""
  6389. (format "u=%s,g=%s,o=%s"
  6390. (match-string 1 modestr)
  6391. (match-string 2 modestr)
  6392. (match-string 3 modestr)))))
  6393. (value (read-string (or prompt "File modes (octal or symbolic): ")
  6394. nil nil default)))
  6395. (save-match-data
  6396. (if (string-match "^[0-7]+" value)
  6397. (string-to-number value 8)
  6398. (file-modes-symbolic-to-number value modes)))))
  6399. (define-obsolete-variable-alias 'cache-long-line-scans
  6400. 'cache-long-scans "24.4")
  6401. ;; Trashcan handling.
  6402. (defcustom trash-directory nil
  6403. "Directory for `move-file-to-trash' to move files and directories to.
  6404. This directory is only used when the function `system-move-file-to-trash'
  6405. is not defined.
  6406. Relative paths are interpreted relative to `default-directory'.
  6407. If the value is nil, Emacs uses a freedesktop.org-style trashcan."
  6408. :type '(choice (const nil) directory)
  6409. :group 'auto-save
  6410. :version "23.2")
  6411. (defvar trash--hexify-table)
  6412. (declare-function system-move-file-to-trash "w32fns.c" (filename))
  6413. (defun move-file-to-trash (filename)
  6414. "Move the file (or directory) named FILENAME to the trash.
  6415. When `delete-by-moving-to-trash' is non-nil, this function is
  6416. called by `delete-file' and `delete-directory' instead of
  6417. deleting files outright.
  6418. If the function `system-move-file-to-trash' is defined, call it
  6419. with FILENAME as an argument.
  6420. Otherwise, if `trash-directory' is non-nil, move FILENAME to that
  6421. directory.
  6422. Otherwise, trash FILENAME using the freedesktop.org conventions,
  6423. like the GNOME, KDE and XFCE desktop environments. Emacs only
  6424. moves files to \"home trash\", ignoring per-volume trashcans."
  6425. (interactive "fMove file to trash: ")
  6426. (cond (trash-directory
  6427. ;; If `trash-directory' is non-nil, move the file there.
  6428. (let* ((trash-dir (expand-file-name trash-directory))
  6429. (fn (directory-file-name (expand-file-name filename)))
  6430. (new-fn (expand-file-name (file-name-nondirectory fn)
  6431. trash-dir)))
  6432. ;; We can't trash a parent directory of trash-directory.
  6433. (if (string-prefix-p fn trash-dir)
  6434. (error "Trash directory `%s' is a subdirectory of `%s'"
  6435. trash-dir filename))
  6436. (unless (file-directory-p trash-dir)
  6437. (make-directory trash-dir t))
  6438. ;; Ensure that the trashed file-name is unique.
  6439. (if (file-exists-p new-fn)
  6440. (let ((version-control t)
  6441. (backup-directory-alist nil))
  6442. (setq new-fn (car (find-backup-file-name new-fn)))))
  6443. (let (delete-by-moving-to-trash)
  6444. (rename-file fn new-fn))))
  6445. ;; If `system-move-file-to-trash' is defined, use it.
  6446. ((fboundp 'system-move-file-to-trash)
  6447. (system-move-file-to-trash filename))
  6448. ;; Otherwise, use the freedesktop.org method, as specified at
  6449. ;; http://freedesktop.org/wiki/Specifications/trash-spec
  6450. (t
  6451. (let* ((xdg-data-dir
  6452. (directory-file-name
  6453. (expand-file-name "Trash"
  6454. (or (getenv "XDG_DATA_HOME")
  6455. "~/.local/share"))))
  6456. (trash-files-dir (expand-file-name "files" xdg-data-dir))
  6457. (trash-info-dir (expand-file-name "info" xdg-data-dir))
  6458. (fn (directory-file-name (expand-file-name filename))))
  6459. ;; Check if we have permissions to delete.
  6460. (unless (file-writable-p (directory-file-name
  6461. (file-name-directory fn)))
  6462. (error "Cannot move %s to trash: Permission denied" filename))
  6463. ;; The trashed file cannot be the trash dir or its parent.
  6464. (if (string-prefix-p fn trash-files-dir)
  6465. (error "The trash directory %s is a subdirectory of %s"
  6466. trash-files-dir filename))
  6467. (if (string-prefix-p fn trash-info-dir)
  6468. (error "The trash directory %s is a subdirectory of %s"
  6469. trash-info-dir filename))
  6470. ;; Ensure that the trash directory exists; otherwise, create it.
  6471. (with-file-modes #o700
  6472. (unless (file-exists-p trash-files-dir)
  6473. (make-directory trash-files-dir t))
  6474. (unless (file-exists-p trash-info-dir)
  6475. (make-directory trash-info-dir t)))
  6476. ;; Try to move to trash with .trashinfo undo information
  6477. (save-excursion
  6478. (with-temp-buffer
  6479. (set-buffer-file-coding-system 'utf-8-unix)
  6480. (insert "[Trash Info]\nPath=")
  6481. ;; Perform url-encoding on FN. For compatibility with
  6482. ;; other programs (e.g. XFCE Thunar), allow literal "/"
  6483. ;; for path separators.
  6484. (unless (boundp 'trash--hexify-table)
  6485. (setq trash--hexify-table (make-vector 256 nil))
  6486. (let ((unreserved-chars
  6487. (list ?/ ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m
  6488. ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z ?A
  6489. ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O
  6490. ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z ?0 ?1 ?2
  6491. ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?- ?_ ?. ?! ?~ ?* ?'
  6492. ?\( ?\))))
  6493. (dotimes (byte 256)
  6494. (aset trash--hexify-table byte
  6495. (if (memq byte unreserved-chars)
  6496. (char-to-string byte)
  6497. (format "%%%02x" byte))))))
  6498. (mapc (lambda (byte)
  6499. (insert (aref trash--hexify-table byte)))
  6500. (if (multibyte-string-p fn)
  6501. (encode-coding-string fn 'utf-8)
  6502. fn))
  6503. (insert "\nDeletionDate="
  6504. (format-time-string "%Y-%m-%dT%T")
  6505. "\n")
  6506. ;; Attempt to make .trashinfo file, trying up to 5
  6507. ;; times. The .trashinfo file is opened with O_EXCL,
  6508. ;; as per trash-spec 0.7, even if that can be a problem
  6509. ;; on old NFS versions...
  6510. (let* ((tries 5)
  6511. (base-fn (expand-file-name
  6512. (file-name-nondirectory fn)
  6513. trash-files-dir))
  6514. (new-fn base-fn)
  6515. success info-fn)
  6516. (while (> tries 0)
  6517. (setq info-fn (expand-file-name
  6518. (concat (file-name-nondirectory new-fn)
  6519. ".trashinfo")
  6520. trash-info-dir))
  6521. (unless (condition-case nil
  6522. (progn
  6523. (write-region nil nil info-fn nil
  6524. 'quiet info-fn 'excl)
  6525. (setq tries 0 success t))
  6526. (file-already-exists nil))
  6527. (setq tries (1- tries))
  6528. ;; Uniquify new-fn. (Some file managers do not
  6529. ;; like Emacs-style backup file names---e.g. bug
  6530. ;; 170956 in Konqueror bug tracker.)
  6531. (setq new-fn (make-temp-name (concat base-fn "_")))))
  6532. (unless success
  6533. (error "Cannot move %s to trash: Lock failed" filename))
  6534. ;; Finally, try to move the file to the trashcan.
  6535. (let ((delete-by-moving-to-trash nil))
  6536. (rename-file fn new-fn)))))))))
  6537. (define-key ctl-x-map "\C-f" 'find-file)
  6538. (define-key ctl-x-map "\C-r" 'find-file-read-only)
  6539. (define-key ctl-x-map "\C-v" 'find-alternate-file)
  6540. (define-key ctl-x-map "\C-s" 'save-buffer)
  6541. (define-key ctl-x-map "s" 'save-some-buffers)
  6542. (define-key ctl-x-map "\C-w" 'write-file)
  6543. (define-key ctl-x-map "i" 'insert-file)
  6544. (define-key esc-map "~" 'not-modified)
  6545. (define-key ctl-x-map "\C-d" 'list-directory)
  6546. (define-key ctl-x-map "\C-c" 'save-buffers-kill-terminal)
  6547. (define-key ctl-x-map "\C-q" 'read-only-mode)
  6548. (define-key ctl-x-4-map "f" 'find-file-other-window)
  6549. (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
  6550. (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
  6551. (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
  6552. (define-key ctl-x-4-map "\C-o" 'display-buffer)
  6553. (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
  6554. (define-key ctl-x-5-map "f" 'find-file-other-frame)
  6555. (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
  6556. (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
  6557. (define-key ctl-x-5-map "\C-o" 'display-buffer-other-frame)
  6558. ;;; files.el ends here