files.el 305 KB

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