files.el 273 KB

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