files.el 302 KB

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