elisp-5 288 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549
  1. This is /home/cyd/emacs/doc/lispref/../../info/elisp, produced by
  2. makeinfo version 4.13 from /home/cyd/emacs/doc/lispref/elisp.texi.
  3. This is the `GNU Emacs Lisp Reference Manual' corresponding to Emacs
  4. version 24.2.
  5. Copyright (C) 1990-1996, 1998-2012 Free Software Foundation, Inc.
  6. Permission is granted to copy, distribute and/or modify this
  7. document under the terms of the GNU Free Documentation License,
  8. Version 1.3 or any later version published by the Free Software
  9. Foundation; with the Invariant Sections being "GNU General Public
  10. License," with the Front-Cover texts being "A GNU Manual," and
  11. with the Back-Cover Texts as in (a) below. A copy of the license
  12. is included in the section entitled "GNU Free Documentation
  13. License."
  14. (a) The FSF's Back-Cover Text is: "You have the freedom to copy and
  15. modify this GNU manual. Buying copies from the FSF supports it in
  16. developing GNU and promoting software freedom."
  17. INFO-DIR-SECTION GNU Emacs Lisp
  18. START-INFO-DIR-ENTRY
  19. * Elisp: (elisp). The Emacs Lisp Reference Manual.
  20. END-INFO-DIR-ENTRY
  21. 
  22. File: elisp, Node: Major Mode Conventions, Next: Auto Major Mode, Up: Major Modes
  23. 23.2.1 Major Mode Conventions
  24. -----------------------------
  25. The code for every major mode should follow various coding conventions,
  26. including conventions for local keymap and syntax table initialization,
  27. function and variable names, and hooks.
  28. If you use the `define-derived-mode' macro, it will take care of
  29. many of these conventions automatically. *Note Derived Modes::. Note
  30. also that Fundamental mode is an exception to many of these conventions,
  31. because it represents the default state of Emacs.
  32. The following list of conventions is only partial. Each major mode
  33. should aim for consistency in general with other Emacs major modes, as
  34. this makes Emacs as a whole more coherent. It is impossible to list
  35. here all the possible points where this issue might come up; if the
  36. Emacs developers point out an area where your major mode deviates from
  37. the usual conventions, please make it compatible.
  38. * Define a major mode command whose name ends in `-mode'. When
  39. called with no arguments, this command should switch to the new
  40. mode in the current buffer by setting up the keymap, syntax table,
  41. and buffer-local variables in an existing buffer. It should not
  42. change the buffer's contents.
  43. * Write a documentation string for this command that describes the
  44. special commands available in this mode. *Note Mode Help::.
  45. The documentation string may include the special documentation
  46. substrings, `\[COMMAND]', `\{KEYMAP}', and `\<KEYMAP>', which
  47. allow the help display to adapt automatically to the user's own
  48. key bindings. *Note Keys in Documentation::.
  49. * The major mode command should start by calling
  50. `kill-all-local-variables'. This runs the normal hook
  51. `change-major-mode-hook', then gets rid of the buffer-local
  52. variables of the major mode previously in effect. *Note Creating
  53. Buffer-Local::.
  54. * The major mode command should set the variable `major-mode' to the
  55. major mode command symbol. This is how `describe-mode' discovers
  56. which documentation to print.
  57. * The major mode command should set the variable `mode-name' to the
  58. "pretty" name of the mode, usually a string (but see *note Mode
  59. Line Data::, for other possible forms). The name of the mode
  60. appears in the mode line.
  61. * Since all global names are in the same name space, all the global
  62. variables, constants, and functions that are part of the mode
  63. should have names that start with the major mode name (or with an
  64. abbreviation of it if the name is long). *Note Coding
  65. Conventions::.
  66. * In a major mode for editing some kind of structured text, such as a
  67. programming language, indentation of text according to structure is
  68. probably useful. So the mode should set `indent-line-function' to
  69. a suitable function, and probably customize other variables for
  70. indentation. *Note Auto-Indentation::.
  71. * The major mode should usually have its own keymap, which is used
  72. as the local keymap in all buffers in that mode. The major mode
  73. command should call `use-local-map' to install this local map.
  74. *Note Active Keymaps::, for more information.
  75. This keymap should be stored permanently in a global variable named
  76. `MODENAME-mode-map'. Normally the library that defines the mode
  77. sets this variable.
  78. *Note Tips for Defining::, for advice about how to write the code
  79. to set up the mode's keymap variable.
  80. * The key sequences bound in a major mode keymap should usually
  81. start with `C-c', followed by a control character, a digit, or `{',
  82. `}', `<', `>', `:' or `;'. The other punctuation characters are
  83. reserved for minor modes, and ordinary letters are reserved for
  84. users.
  85. A major mode can also rebind the keys `M-n', `M-p' and `M-s'. The
  86. bindings for `M-n' and `M-p' should normally be some kind of
  87. "moving forward and backward", but this does not necessarily mean
  88. cursor motion.
  89. It is legitimate for a major mode to rebind a standard key
  90. sequence if it provides a command that does "the same job" in a
  91. way better suited to the text this mode is used for. For example,
  92. a major mode for editing a programming language might redefine
  93. `C-M-a' to "move to the beginning of a function" in a way that
  94. works better for that language.
  95. It is also legitimate for a major mode to rebind a standard key
  96. sequence whose standard meaning is rarely useful in that mode. For
  97. instance, minibuffer modes rebind `M-r', whose standard meaning is
  98. rarely of any use in the minibuffer. Major modes such as Dired or
  99. Rmail that do not allow self-insertion of text can reasonably
  100. redefine letters and other printing characters as special commands.
  101. * Major modes for editing text should not define <RET> to do
  102. anything other than insert a newline. However, it is ok for
  103. specialized modes for text that users don't directly edit, such as
  104. Dired and Info modes, to redefine <RET> to do something entirely
  105. different.
  106. * Major modes should not alter options that are primarily a matter
  107. of user preference, such as whether Auto-Fill mode is enabled.
  108. Leave this to each user to decide. However, a major mode should
  109. customize other variables so that Auto-Fill mode will work
  110. usefully _if_ the user decides to use it.
  111. * The mode may have its own syntax table or may share one with other
  112. related modes. If it has its own syntax table, it should store
  113. this in a variable named `MODENAME-mode-syntax-table'. *Note
  114. Syntax Tables::.
  115. * If the mode handles a language that has a syntax for comments, it
  116. should set the variables that define the comment syntax. *Note
  117. Options Controlling Comments: (emacs)Options for Comments.
  118. * The mode may have its own abbrev table or may share one with other
  119. related modes. If it has its own abbrev table, it should store
  120. this in a variable named `MODENAME-mode-abbrev-table'. If the
  121. major mode command defines any abbrevs itself, it should pass `t'
  122. for the SYSTEM-FLAG argument to `define-abbrev'. *Note Defining
  123. Abbrevs::.
  124. * The mode should specify how to do highlighting for Font Lock mode,
  125. by setting up a buffer-local value for the variable
  126. `font-lock-defaults' (*note Font Lock Mode::).
  127. * Each face that the mode defines should, if possible, inherit from
  128. an existing Emacs face. *Note Basic Faces::, and *note Faces for
  129. Font Lock::.
  130. * The mode should specify how Imenu should find the definitions or
  131. sections of a buffer, by setting up a buffer-local value for the
  132. variable `imenu-generic-expression', for the two variables
  133. `imenu-prev-index-position-function' and
  134. `imenu-extract-index-name-function', or for the variable
  135. `imenu-create-index-function' (*note Imenu::).
  136. * The mode can specify a local value for
  137. `eldoc-documentation-function' to tell ElDoc mode how to handle
  138. this mode.
  139. * The mode can specify how to complete various keywords by adding
  140. one or more buffer-local entries to the special hook
  141. `completion-at-point-functions'. *Note Completion in Buffers::.
  142. * To make a buffer-local binding for an Emacs customization
  143. variable, use `make-local-variable' in the major mode command, not
  144. `make-variable-buffer-local'. The latter function would make the
  145. variable local to every buffer in which it is subsequently set,
  146. which would affect buffers that do not use this mode. It is
  147. undesirable for a mode to have such global effects. *Note
  148. Buffer-Local Variables::.
  149. With rare exceptions, the only reasonable way to use
  150. `make-variable-buffer-local' in a Lisp package is for a variable
  151. which is used only within that package. Using it on a variable
  152. used by other packages would interfere with them.
  153. * Each major mode should have a normal "mode hook" named
  154. `MODENAME-mode-hook'. The very last thing the major mode command
  155. should do is to call `run-mode-hooks'. This runs the normal hook
  156. `change-major-mode-after-body-hook', the mode hook, and then the
  157. normal hook `after-change-major-mode-hook'. *Note Mode Hooks::.
  158. * The major mode command may start by calling some other major mode
  159. command (called the "parent mode") and then alter some of its
  160. settings. A mode that does this is called a "derived mode". The
  161. recommended way to define one is to use the `define-derived-mode'
  162. macro, but this is not required. Such a mode should call the
  163. parent mode command inside a `delay-mode-hooks' form. (Using
  164. `define-derived-mode' does this automatically.) *Note Derived
  165. Modes::, and *note Mode Hooks::.
  166. * If something special should be done if the user switches a buffer
  167. from this mode to any other major mode, this mode can set up a
  168. buffer-local value for `change-major-mode-hook' (*note Creating
  169. Buffer-Local::).
  170. * If this mode is appropriate only for specially-prepared text
  171. produced by the mode itself (rather than by the user typing at the
  172. keyboard or by an external file), then the major mode command
  173. symbol should have a property named `mode-class' with value
  174. `special', put on as follows:
  175. (put 'funny-mode 'mode-class 'special)
  176. This tells Emacs that new buffers created while the current buffer
  177. is in Funny mode should not be put in Funny mode, even though the
  178. default value of `major-mode' is `nil'. By default, the value of
  179. `nil' for `major-mode' means to use the current buffer's major
  180. mode when creating new buffers (*note Auto Major Mode::), but with
  181. such `special' modes, Fundamental mode is used instead. Modes
  182. such as Dired, Rmail, and Buffer List use this feature.
  183. The function `view-buffer' does not enable View mode in buffers
  184. whose mode-class is special, because such modes usually provide
  185. their own View-like bindings.
  186. The `define-derived-mode' macro automatically marks the derived
  187. mode as special if the parent mode is special. Special mode is a
  188. convenient parent for such modes to inherit from; *Note Basic
  189. Major Modes::.
  190. * If you want to make the new mode the default for files with certain
  191. recognizable names, add an element to `auto-mode-alist' to select
  192. the mode for those file names (*note Auto Major Mode::). If you
  193. define the mode command to autoload, you should add this element in
  194. the same file that calls `autoload'. If you use an autoload
  195. cookie for the mode command, you can also use an autoload cookie
  196. for the form that adds the element (*note autoload cookie::). If
  197. you do not autoload the mode command, it is sufficient to add the
  198. element in the file that contains the mode definition.
  199. * The top-level forms in the file defining the mode should be
  200. written so that they may be evaluated more than once without
  201. adverse consequences. For instance, use `defvar' or `defcustom'
  202. to set mode-related variables, so that they are not reinitialized
  203. if they already have a value (*note Defining Variables::).
  204. 
  205. File: elisp, Node: Auto Major Mode, Next: Mode Help, Prev: Major Mode Conventions, Up: Major Modes
  206. 23.2.2 How Emacs Chooses a Major Mode
  207. -------------------------------------
  208. When Emacs visits a file, it automatically selects a major mode for the
  209. buffer based on information in the file name or in the file itself. It
  210. also processes local variables specified in the file text.
  211. -- Command: normal-mode &optional find-file
  212. This function establishes the proper major mode and buffer-local
  213. variable bindings for the current buffer. First it calls
  214. `set-auto-mode' (see below), then it runs `hack-local-variables'
  215. to parse, and bind or evaluate as appropriate, the file's local
  216. variables (*note File Local Variables::).
  217. If the FIND-FILE argument to `normal-mode' is non-`nil',
  218. `normal-mode' assumes that the `find-file' function is calling it.
  219. In this case, it may process local variables in the `-*-' line or
  220. at the end of the file. The variable `enable-local-variables'
  221. controls whether to do so. *Note Local Variables in Files:
  222. (emacs)File Variables, for the syntax of the local variables
  223. section of a file.
  224. If you run `normal-mode' interactively, the argument FIND-FILE is
  225. normally `nil'. In this case, `normal-mode' unconditionally
  226. processes any file local variables.
  227. The function calls `set-auto-mode' to choose a major mode. If this
  228. does not specify a mode, the buffer stays in the major mode
  229. determined by the default value of `major-mode' (see below).
  230. `normal-mode' uses `condition-case' around the call to the major
  231. mode command, so errors are caught and reported as a `File mode
  232. specification error', followed by the original error message.
  233. -- Function: set-auto-mode &optional keep-mode-if-same
  234. This function selects the major mode that is appropriate for the
  235. current buffer. It bases its decision (in order of precedence) on
  236. the `-*-' line, on any `mode:' local variable near the end of a
  237. file, on the `#!' line (using `interpreter-mode-alist'), on the
  238. text at the beginning of the buffer (using `magic-mode-alist'),
  239. and finally on the visited file name (using `auto-mode-alist').
  240. *Note How Major Modes are Chosen: (emacs)Choosing Modes. If
  241. `enable-local-variables' is `nil', `set-auto-mode' does not check
  242. the `-*-' line, or near the end of the file, for any mode tag.
  243. There are some file types where it is not appropriate to scan the
  244. file contents for a mode specifier. For example, a tar archive
  245. may happen to contain, near the end of the file, a member file
  246. that has a local variables section specifying a mode for that
  247. particular file. This should not be applied to the containing tar
  248. file. Similarly, a tiff image file might just happen to contain a
  249. first line that seems to match the `-*-' pattern. For these
  250. reasons, both these file extensions are members of the list
  251. INHIBIT-LOCAL-VARIABLES-REGEXPS. Add patterns to this list to
  252. prevent Emacs searching them for local variables of any kind (not
  253. just mode specifiers).
  254. If KEEP-MODE-IF-SAME is non-`nil', this function does not call the
  255. mode command if the buffer is already in the proper major mode.
  256. For instance, `set-visited-file-name' sets this to `t' to avoid
  257. killing buffer local variables that the user may have set.
  258. -- Function: set-buffer-major-mode buffer
  259. This function sets the major mode of BUFFER to the default value of
  260. `major-mode'; if that is `nil', it uses the current buffer's major
  261. mode (if that is suitable). As an exception, if BUFFER's name is
  262. `*scratch*', it sets the mode to `initial-major-mode'.
  263. The low-level primitives for creating buffers do not use this
  264. function, but medium-level commands such as `switch-to-buffer' and
  265. `find-file-noselect' use it whenever they create buffers.
  266. -- User Option: initial-major-mode
  267. The value of this variable determines the major mode of the initial
  268. `*scratch*' buffer. The value should be a symbol that is a major
  269. mode command. The default value is `lisp-interaction-mode'.
  270. -- Variable: interpreter-mode-alist
  271. This variable specifies major modes to use for scripts that
  272. specify a command interpreter in a `#!' line. Its value is an
  273. alist with elements of the form `(INTERPRETER . MODE)'; for
  274. example, `("perl" . perl-mode)' is one element present by default.
  275. The element says to use mode MODE if the file specifies an
  276. interpreter which matches INTERPRETER.
  277. -- Variable: magic-mode-alist
  278. This variable's value is an alist with elements of the form
  279. `(REGEXP . FUNCTION)', where REGEXP is a regular expression and
  280. FUNCTION is a function or `nil'. After visiting a file,
  281. `set-auto-mode' calls FUNCTION if the text at the beginning of the
  282. buffer matches REGEXP and FUNCTION is non-`nil'; if FUNCTION is
  283. `nil', `auto-mode-alist' gets to decide the mode.
  284. -- Variable: magic-fallback-mode-alist
  285. This works like `magic-mode-alist', except that it is handled only
  286. if `auto-mode-alist' does not specify a mode for this file.
  287. -- Variable: auto-mode-alist
  288. This variable contains an association list of file name patterns
  289. (regular expressions) and corresponding major mode commands.
  290. Usually, the file name patterns test for suffixes, such as `.el'
  291. and `.c', but this need not be the case. An ordinary element of
  292. the alist looks like `(REGEXP . MODE-FUNCTION)'.
  293. For example,
  294. (("\\`/tmp/fol/" . text-mode)
  295. ("\\.texinfo\\'" . texinfo-mode)
  296. ("\\.texi\\'" . texinfo-mode)
  297. ("\\.el\\'" . emacs-lisp-mode)
  298. ("\\.c\\'" . c-mode)
  299. ("\\.h\\'" . c-mode)
  300. ...)
  301. When you visit a file whose expanded file name (*note File Name
  302. Expansion::), with version numbers and backup suffixes removed
  303. using `file-name-sans-versions' (*note File Name Components::),
  304. matches a REGEXP, `set-auto-mode' calls the corresponding
  305. MODE-FUNCTION. This feature enables Emacs to select the proper
  306. major mode for most files.
  307. If an element of `auto-mode-alist' has the form `(REGEXP FUNCTION
  308. t)', then after calling FUNCTION, Emacs searches `auto-mode-alist'
  309. again for a match against the portion of the file name that did
  310. not match before. This feature is useful for uncompression
  311. packages: an entry of the form `("\\.gz\\'" FUNCTION t)' can
  312. uncompress the file and then put the uncompressed file in the
  313. proper mode according to the name sans `.gz'.
  314. Here is an example of how to prepend several pattern pairs to
  315. `auto-mode-alist'. (You might use this sort of expression in your
  316. init file.)
  317. (setq auto-mode-alist
  318. (append
  319. ;; File name (within directory) starts with a dot.
  320. '(("/\\.[^/]*\\'" . fundamental-mode)
  321. ;; File name has no dot.
  322. ("/[^\\./]*\\'" . fundamental-mode)
  323. ;; File name ends in `.C'.
  324. ("\\.C\\'" . c++-mode))
  325. auto-mode-alist))
  326. 
  327. File: elisp, Node: Mode Help, Next: Derived Modes, Prev: Auto Major Mode, Up: Major Modes
  328. 23.2.3 Getting Help about a Major Mode
  329. --------------------------------------
  330. The `describe-mode' function provides information about major modes.
  331. It is normally bound to `C-h m'. It uses the value of the variable
  332. `major-mode' (*note Major Modes::), which is why every major mode
  333. command needs to set that variable.
  334. -- Command: describe-mode &optional buffer
  335. This command displays the documentation of the current buffer's
  336. major mode and minor modes. It uses the `documentation' function
  337. to retrieve the documentation strings of the major and minor mode
  338. commands (*note Accessing Documentation::).
  339. If called from Lisp with a non-nil BUFFER argument, this function
  340. displays the documentation for that buffer's major and minor
  341. modes, rather than those of the current buffer.
  342. 
  343. File: elisp, Node: Derived Modes, Next: Basic Major Modes, Prev: Mode Help, Up: Major Modes
  344. 23.2.4 Defining Derived Modes
  345. -----------------------------
  346. The recommended way to define a new major mode is to derive it from an
  347. existing one using `define-derived-mode'. If there is no closely
  348. related mode, you should inherit from either `text-mode',
  349. `special-mode', or `prog-mode'. *Note Basic Major Modes::. If none of
  350. these are suitable, you can inherit from `fundamental-mode' (*note
  351. Major Modes::).
  352. -- Macro: define-derived-mode variant parent name docstring
  353. keyword-args... body...
  354. This macro defines VARIANT as a major mode command, using NAME as
  355. the string form of the mode name. VARIANT and PARENT should be
  356. unquoted symbols.
  357. The new command VARIANT is defined to call the function PARENT,
  358. then override certain aspects of that parent mode:
  359. * The new mode has its own sparse keymap, named `VARIANT-map'.
  360. `define-derived-mode' makes the parent mode's keymap the
  361. parent of the new map, unless `VARIANT-map' is already set
  362. and already has a parent.
  363. * The new mode has its own syntax table, kept in the variable
  364. `VARIANT-syntax-table', unless you override this using the
  365. `:syntax-table' keyword (see below). `define-derived-mode'
  366. makes the parent mode's syntax-table the parent of
  367. `VARIANT-syntax-table', unless the latter is already set and
  368. already has a parent different from the standard syntax table.
  369. * The new mode has its own abbrev table, kept in the variable
  370. `VARIANT-abbrev-table', unless you override this using the
  371. `:abbrev-table' keyword (see below).
  372. * The new mode has its own mode hook, `VARIANT-hook'. It runs
  373. this hook, after running the hooks of its ancestor modes, with
  374. `run-mode-hooks', as the last thing it does. *Note Mode
  375. Hooks::.
  376. In addition, you can specify how to override other aspects of
  377. PARENT with BODY. The command VARIANT evaluates the forms in BODY
  378. after setting up all its usual overrides, just before running the
  379. mode hooks.
  380. If PARENT has a non-`nil' `mode-class' symbol property, then
  381. `define-derived-mode' sets the `mode-class' property of VARIANT to
  382. the same value. This ensures, for example, that if PARENT is a
  383. special mode, then VARIANT is also a special mode (*note Major
  384. Mode Conventions::).
  385. You can also specify `nil' for PARENT. This gives the new mode no
  386. parent. Then `define-derived-mode' behaves as described above,
  387. but, of course, omits all actions connected with PARENT.
  388. The argument DOCSTRING specifies the documentation string for the
  389. new mode. `define-derived-mode' adds some general information
  390. about the mode's hook, followed by the mode's keymap, at the end
  391. of this documentation string. If you omit DOCSTRING,
  392. `define-derived-mode' generates a documentation string.
  393. The KEYWORD-ARGS are pairs of keywords and values. The values are
  394. evaluated. The following keywords are currently supported:
  395. `:syntax-table'
  396. You can use this to explicitly specify a syntax table for the
  397. new mode. If you specify a `nil' value, the new mode uses
  398. the same syntax table as PARENT, or the standard syntax table
  399. if PARENT is `nil'. (Note that this does _not_ follow the
  400. convention used for non-keyword arguments that a `nil' value
  401. is equivalent with not specifying the argument.)
  402. `:abbrev-table'
  403. You can use this to explicitly specify an abbrev table for
  404. the new mode. If you specify a `nil' value, the new mode
  405. uses the same abbrev table as PARENT, or
  406. `fundamental-mode-abbrev-table' if PARENT is `nil'. (Again,
  407. a `nil' value is _not_ equivalent to not specifying this
  408. keyword.)
  409. `:group'
  410. If this is specified, the value should be the customization
  411. group for this mode. (Not all major modes have one.) Only
  412. the (still experimental and unadvertised) command
  413. `customize-mode' currently uses this. `define-derived-mode'
  414. does _not_ automatically define the specified customization
  415. group.
  416. Here is a hypothetical example:
  417. (define-derived-mode hypertext-mode
  418. text-mode "Hypertext"
  419. "Major mode for hypertext.
  420. \\{hypertext-mode-map}"
  421. (setq case-fold-search nil))
  422. (define-key hypertext-mode-map
  423. [down-mouse-3] 'do-hyper-link)
  424. Do not write an `interactive' spec in the definition;
  425. `define-derived-mode' does that automatically.
  426. -- Function: derived-mode-p &rest modes
  427. This function returns non-`nil' if the current major mode is
  428. derived from any of the major modes given by the symbols MODES.
  429. 
  430. File: elisp, Node: Basic Major Modes, Next: Mode Hooks, Prev: Derived Modes, Up: Major Modes
  431. 23.2.5 Basic Major Modes
  432. ------------------------
  433. Apart from Fundamental mode, there are three major modes that other
  434. major modes commonly derive from: Text mode, Prog mode, and Special
  435. mode. While Text mode is useful in its own right (e.g. for editing
  436. files ending in `.txt'), Prog mode and Special mode exist mainly to let
  437. other modes derive from them.
  438. As far as possible, new major modes should be derived, either
  439. directly or indirectly, from one of these three modes. One reason is
  440. that this allows users to customize a single mode hook (e.g.
  441. `prog-mode-hook') for an entire family of relevant modes (e.g. all
  442. programming language modes).
  443. -- Command: text-mode
  444. Text mode is a major mode for editing human languages. It defines
  445. the `"' and `\' characters as having punctuation syntax (*note
  446. Syntax Class Table::), and binds `M-<TAB>' to
  447. `ispell-complete-word' (*note Spelling: (emacs)Spelling.).
  448. An example of a major mode derived from Text mode is HTML mode.
  449. *Note SGML and HTML Modes: (emacs)HTML Mode.
  450. -- Command: prog-mode
  451. Prog mode is a basic major mode for buffers containing programming
  452. language source code. Most of the programming language major modes
  453. built into Emacs are derived from it.
  454. Prog mode binds `parse-sexp-ignore-comments' to `t' (*note Motion
  455. via Parsing::) and `bidi-paragraph-direction' to `left-to-right'
  456. (*note Bidirectional Display::).
  457. -- Command: special-mode
  458. Special mode is a basic major mode for buffers containing text
  459. that is produced specially by Emacs, rather than directly from a
  460. file. Major modes derived from Special mode are given a
  461. `mode-class' property of `special' (*note Major Mode
  462. Conventions::).
  463. Special mode sets the buffer to read-only. Its keymap defines
  464. several common bindings, including `q' for `quit-window', `z' for
  465. `kill-this-buffer', and `g' for `revert-buffer' (*note
  466. Reverting::).
  467. An example of a major mode derived from Special mode is Buffer Menu
  468. mode, which is used by the `*Buffer List*' buffer. *Note Listing
  469. Existing Buffers: (emacs)List Buffers.
  470. In addition, modes for buffers of tabulated data can inherit from
  471. Tabulated List mode, which is in turn derived from Special mode. *Note
  472. Tabulated List Mode::.
  473. 
  474. File: elisp, Node: Mode Hooks, Next: Tabulated List Mode, Prev: Basic Major Modes, Up: Major Modes
  475. 23.2.6 Mode Hooks
  476. -----------------
  477. Every major mode command should finish by running the mode-independent
  478. normal hook `change-major-mode-after-body-hook', its mode hook, and the
  479. normal hook `after-change-major-mode-hook'. It does this by calling
  480. `run-mode-hooks'. If the major mode is a derived mode, that is if it
  481. calls another major mode (the parent mode) in its body, it should do
  482. this inside `delay-mode-hooks' so that the parent won't run these hooks
  483. itself. Instead, the derived mode's call to `run-mode-hooks' runs the
  484. parent's mode hook too. *Note Major Mode Conventions::.
  485. Emacs versions before Emacs 22 did not have `delay-mode-hooks'.
  486. Versions before 24 did not have `change-major-mode-after-body-hook'.
  487. When user-implemented major modes do not use `run-mode-hooks' and have
  488. not been updated to use these newer features, they won't entirely
  489. follow these conventions: they may run the parent's mode hook too early,
  490. or fail to run `after-change-major-mode-hook'. If you encounter such a
  491. major mode, please correct it to follow these conventions.
  492. When you defined a major mode using `define-derived-mode', it
  493. automatically makes sure these conventions are followed. If you define
  494. a major mode "by hand", not using `define-derived-mode', use the
  495. following functions to handle these conventions automatically.
  496. -- Function: run-mode-hooks &rest hookvars
  497. Major modes should run their mode hook using this function. It is
  498. similar to `run-hooks' (*note Hooks::), but it also runs
  499. `change-major-mode-after-body-hook' and
  500. `after-change-major-mode-hook'.
  501. When this function is called during the execution of a
  502. `delay-mode-hooks' form, it does not run the hooks immediately.
  503. Instead, it arranges for the next call to `run-mode-hooks' to run
  504. them.
  505. -- Macro: delay-mode-hooks body...
  506. When one major mode command calls another, it should do so inside
  507. of `delay-mode-hooks'.
  508. This macro executes BODY, but tells all `run-mode-hooks' calls
  509. during the execution of BODY to delay running their hooks. The
  510. hooks will actually run during the next call to `run-mode-hooks'
  511. after the end of the `delay-mode-hooks' construct.
  512. -- Variable: change-major-mode-after-body-hook
  513. This is a normal hook run by `run-mode-hooks'. It is run before
  514. the mode hooks.
  515. -- Variable: after-change-major-mode-hook
  516. This is a normal hook run by `run-mode-hooks'. It is run at the
  517. very end of every properly-written major mode command.
  518. 
  519. File: elisp, Node: Tabulated List Mode, Next: Generic Modes, Prev: Mode Hooks, Up: Major Modes
  520. 23.2.7 Tabulated List mode
  521. --------------------------
  522. Tabulated List mode is a major mode for displaying tabulated data, i.e.
  523. data consisting of "entries", each entry occupying one row of text with
  524. its contents divided into columns. Tabulated List mode provides
  525. facilities for pretty-printing rows and columns, and sorting the rows
  526. according to the values in each column. It is derived from Special
  527. mode (*note Basic Major Modes::).
  528. Tabulated List mode is intended to be used as a parent mode by a more
  529. specialized major mode. Examples include Process Menu mode (*note
  530. Process Information::) and Package Menu mode (*note Package Menu:
  531. (emacs)Package Menu.).
  532. Such a derived mode should use `define-derived-mode' in the usual
  533. way, specifying `tabulated-list-mode' as the second argument (*note
  534. Derived Modes::). The body of the `define-derived-mode' form should
  535. specify the format of the tabulated data, by assigning values to the
  536. variables documented below; then, it should call the function
  537. `tabulated-list-init-header' to initialize the header line.
  538. The derived mode should also define a "listing command". This, not
  539. the mode command, is what the user calls (e.g. `M-x list-processes').
  540. The listing command should create or switch to a buffer, turn on the
  541. derived mode, specify the tabulated data, and finally call
  542. `tabulated-list-print' to populate the buffer.
  543. -- Variable: tabulated-list-format
  544. This buffer-local variable specifies the format of the Tabulated
  545. List data. Its value should be a vector. Each element of the
  546. vector represents a data column, and should be a list `(NAME WIDTH
  547. SORT)', where
  548. * NAME is the column's name (a string).
  549. * WIDTH is the width to reserve for the column (an integer).
  550. This is meaningless for the last column, which runs to the
  551. end of each line.
  552. * SORT specifies how to sort entries by the column. If `nil',
  553. the column cannot be used for sorting. If `t', the column is
  554. sorted by comparing string values. Otherwise, this should be
  555. a predicate function for `sort' (*note Rearrangement::), which
  556. accepts two arguments with the same form as the elements of
  557. `tabulated-list-entries' (see below).
  558. -- Variable: tabulated-list-entries
  559. This buffer-local variable specifies the entries displayed in the
  560. Tabulated List buffer. Its value should be either a list, or a
  561. function.
  562. If the value is a list, each list element corresponds to one
  563. entry, and should have the form `(ID CONTENTS)', where
  564. * ID is either `nil', or a Lisp object that identifies the
  565. entry. If the latter, the cursor stays on the "same" entry
  566. when re-sorting entries. Comparison is done with `equal'.
  567. * CONTENTS is a vector with the same number of elements as
  568. `tabulated-list-format'. Each vector element is either a
  569. string, which is inserted into the buffer as-is, or a list
  570. `(LABEL . PROPERTIES)', which means to insert a text button
  571. by calling `insert-text-button' with LABEL and PROPERTIES as
  572. arguments (*note Making Buttons::).
  573. There should be no newlines in any of these strings.
  574. Otherwise, the value should be a function which returns a list of
  575. the above form when called with no arguments.
  576. -- Variable: tabulated-list-revert-hook
  577. This normal hook is run prior to reverting a Tabulated List
  578. buffer. A derived mode can add a function to this hook to
  579. recompute `tabulated-list-entries'.
  580. -- Variable: tabulated-list-printer
  581. The value of this variable is the function called to insert an
  582. entry at point, including its terminating newline. The function
  583. should accept two arguments, ID and CONTENTS, having the same
  584. meanings as in `tabulated-list-entries'. The default value is a
  585. function which inserts an entry in a straightforward way; a mode
  586. which uses Tabulated List mode in a more complex way can specify
  587. another function.
  588. -- Variable: tabulated-list-sort-key
  589. The value of this variable specifies the current sort key for the
  590. Tabulated List buffer. If it is `nil', no sorting is done.
  591. Otherwise, it should have the form `(NAME . FLIP)', where NAME is
  592. a string matching one of the column names in
  593. `tabulated-list-format', and FLIP, if non-`nil', means to invert
  594. the sort order.
  595. -- Function: tabulated-list-init-header
  596. This function computes and sets `header-line-format' for the
  597. Tabulated List buffer (*note Header Lines::), and assigns a keymap
  598. to the header line to allow sort entries by clicking on column
  599. headers.
  600. Modes derived from Tabulated List mode should call this after
  601. setting the above variables (in particular, only after setting
  602. `tabulated-list-format').
  603. -- Function: tabulated-list-print &optional remember-pos
  604. This function populates the current buffer with entries. It
  605. should be called by the listing command. It erases the buffer,
  606. sorts the entries specified by `tabulated-list-entries' according
  607. to `tabulated-list-sort-key', then calls the function specified by
  608. `tabulated-list-printer' to insert each entry.
  609. If the optional argument REMEMBER-POS is non-`nil', this function
  610. looks for the ID element on the current line, if any, and tries to
  611. move to that entry after all the entries are (re)inserted.
  612. 
  613. File: elisp, Node: Generic Modes, Next: Example Major Modes, Prev: Tabulated List Mode, Up: Major Modes
  614. 23.2.8 Generic Modes
  615. --------------------
  616. "Generic modes" are simple major modes with basic support for comment
  617. syntax and Font Lock mode. To define a generic mode, use the macro
  618. `define-generic-mode'. See the file `generic-x.el' for some examples
  619. of the use of `define-generic-mode'.
  620. -- Macro: define-generic-mode mode comment-list keyword-list
  621. font-lock-list auto-mode-list function-list &optional
  622. docstring
  623. This macro defines a generic mode command named MODE (a symbol,
  624. not quoted). The optional argument DOCSTRING is the documentation
  625. for the mode command. If you do not supply it,
  626. `define-generic-mode' generates one by default.
  627. The argument COMMENT-LIST is a list in which each element is
  628. either a character, a string of one or two characters, or a cons
  629. cell. A character or a string is set up in the mode's syntax
  630. table as a "comment starter". If the entry is a cons cell, the
  631. CAR is set up as a "comment starter" and the CDR as a "comment
  632. ender". (Use `nil' for the latter if you want comments to end at
  633. the end of the line.) Note that the syntax table mechanism has
  634. limitations about what comment starters and enders are actually
  635. possible. *Note Syntax Tables::.
  636. The argument KEYWORD-LIST is a list of keywords to highlight with
  637. `font-lock-keyword-face'. Each keyword should be a string.
  638. Meanwhile, FONT-LOCK-LIST is a list of additional expressions to
  639. highlight. Each element of this list should have the same form as
  640. an element of `font-lock-keywords'. *Note Search-based
  641. Fontification::.
  642. The argument AUTO-MODE-LIST is a list of regular expressions to
  643. add to the variable `auto-mode-alist'. They are added by the
  644. execution of the `define-generic-mode' form, not by expanding the
  645. macro call.
  646. Finally, FUNCTION-LIST is a list of functions for the mode command
  647. to call for additional setup. It calls these functions just
  648. before it runs the mode hook variable `MODE-hook'.
  649. 
  650. File: elisp, Node: Example Major Modes, Prev: Generic Modes, Up: Major Modes
  651. 23.2.9 Major Mode Examples
  652. --------------------------
  653. Text mode is perhaps the simplest mode besides Fundamental mode. Here
  654. are excerpts from `text-mode.el' that illustrate many of the
  655. conventions listed above:
  656. ;; Create the syntax table for this mode.
  657. (defvar text-mode-syntax-table
  658. (let ((st (make-syntax-table)))
  659. (modify-syntax-entry ?\" ". " st)
  660. (modify-syntax-entry ?\\ ". " st)
  661. ;; Add `p' so M-c on `hello' leads to `Hello', not `hello'.
  662. (modify-syntax-entry ?' "w p" st)
  663. st)
  664. "Syntax table used while in `text-mode'.")
  665. ;; Create the keymap for this mode.
  666. (defvar text-mode-map
  667. (let ((map (make-sparse-keymap)))
  668. (define-key map "\e\t" 'ispell-complete-word)
  669. map)
  670. "Keymap for `text-mode'.
  671. Many other modes, such as `mail-mode', `outline-mode' and
  672. `indented-text-mode', inherit all the commands defined in this map.")
  673. Here is how the actual mode command is defined now:
  674. (define-derived-mode text-mode nil "Text"
  675. "Major mode for editing text written for humans to read.
  676. In this mode, paragraphs are delimited only by blank or white lines.
  677. You can thus get the full benefit of adaptive filling
  678. (see the variable `adaptive-fill-mode').
  679. \\{text-mode-map}
  680. Turning on Text mode runs the normal hook `text-mode-hook'."
  681. (set (make-local-variable 'text-mode-variant) t)
  682. (set (make-local-variable 'require-final-newline)
  683. mode-require-final-newline)
  684. (set (make-local-variable 'indent-line-function) 'indent-relative))
  685. (The last line is redundant nowadays, since `indent-relative' is the
  686. default value, and we'll delete it in a future version.)
  687. The three Lisp modes (Lisp mode, Emacs Lisp mode, and Lisp
  688. Interaction mode) have more features than Text mode and the code is
  689. correspondingly more complicated. Here are excerpts from
  690. `lisp-mode.el' that illustrate how these modes are written.
  691. Here is how the Lisp mode syntax and abbrev tables are defined:
  692. ;; Create mode-specific table variables.
  693. (defvar lisp-mode-abbrev-table nil)
  694. (define-abbrev-table 'lisp-mode-abbrev-table ())
  695. (defvar lisp-mode-syntax-table
  696. (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
  697. (modify-syntax-entry ?\[ "_ " table)
  698. (modify-syntax-entry ?\] "_ " table)
  699. (modify-syntax-entry ?# "' 14" table)
  700. (modify-syntax-entry ?| "\" 23bn" table)
  701. table)
  702. "Syntax table used in `lisp-mode'.")
  703. The three modes for Lisp share much of their code. For instance,
  704. each calls the following function to set various variables:
  705. (defun lisp-mode-variables (&optional syntax keywords-case-insensitive)
  706. (when syntax
  707. (set-syntax-table lisp-mode-syntax-table))
  708. (setq local-abbrev-table lisp-mode-abbrev-table)
  709. ...
  710. Amongst other things, this function sets up the `comment-start'
  711. variable to handle Lisp comments:
  712. (make-local-variable 'comment-start)
  713. (setq comment-start ";")
  714. ...
  715. Each of the different Lisp modes has a slightly different keymap.
  716. For example, Lisp mode binds `C-c C-z' to `run-lisp', but the other
  717. Lisp modes do not. However, all Lisp modes have some commands in
  718. common. The following code sets up the common commands:
  719. (defvar lisp-mode-shared-map
  720. (let ((map (make-sparse-keymap)))
  721. (define-key map "\e\C-q" 'indent-sexp)
  722. (define-key map "\177" 'backward-delete-char-untabify)
  723. map)
  724. "Keymap for commands shared by all sorts of Lisp modes.")
  725. And here is the code to set up the keymap for Lisp mode:
  726. (defvar lisp-mode-map
  727. (let ((map (make-sparse-keymap))
  728. (menu-map (make-sparse-keymap "Lisp")))
  729. (set-keymap-parent map lisp-mode-shared-map)
  730. (define-key map "\e\C-x" 'lisp-eval-defun)
  731. (define-key map "\C-c\C-z" 'run-lisp)
  732. ...
  733. map)
  734. "Keymap for ordinary Lisp mode.
  735. All commands in `lisp-mode-shared-map' are inherited by this map.")
  736. Finally, here is the major mode command for Lisp mode:
  737. (define-derived-mode lisp-mode prog-mode "Lisp"
  738. "Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
  739. Commands:
  740. Delete converts tabs to spaces as it moves back.
  741. Blank lines separate paragraphs. Semicolons start comments.
  742. \\{lisp-mode-map}
  743. Note that `run-lisp' may be used either to start an inferior Lisp job
  744. or to switch back to an existing one.
  745. Entry to this mode calls the value of `lisp-mode-hook'
  746. if that value is non-nil."
  747. (lisp-mode-variables nil t)
  748. (set (make-local-variable 'find-tag-default-function)
  749. 'lisp-find-tag-default)
  750. (set (make-local-variable 'comment-start-skip)
  751. "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(;+\\|#|\\) *")
  752. (setq imenu-case-fold-search t))
  753. 
  754. File: elisp, Node: Minor Modes, Next: Mode Line Format, Prev: Major Modes, Up: Modes
  755. 23.3 Minor Modes
  756. ================
  757. A "minor mode" provides optional features that users may enable or
  758. disable independently of the choice of major mode. Minor modes can be
  759. enabled individually or in combination.
  760. Most minor modes implement features that are independent of the major
  761. mode, and can thus be used with most major modes. For example, Auto
  762. Fill mode works with any major mode that permits text insertion. A few
  763. minor modes, however, are specific to a particular major mode. For
  764. example, Diff Auto Refine mode is a minor mode that is intended to be
  765. used only with Diff mode.
  766. Ideally, a minor mode should have its desired effect regardless of
  767. the other minor modes in effect. It should be possible to activate and
  768. deactivate minor modes in any order.
  769. -- Variable: minor-mode-list
  770. The value of this variable is a list of all minor mode commands.
  771. * Menu:
  772. * Minor Mode Conventions:: Tips for writing a minor mode.
  773. * Keymaps and Minor Modes:: How a minor mode can have its own keymap.
  774. * Defining Minor Modes:: A convenient facility for defining minor modes.
  775. 
  776. File: elisp, Node: Minor Mode Conventions, Next: Keymaps and Minor Modes, Up: Minor Modes
  777. 23.3.1 Conventions for Writing Minor Modes
  778. ------------------------------------------
  779. There are conventions for writing minor modes just as there are for
  780. major modes. These conventions are described below. The easiest way to
  781. follow them is to use the macro `define-minor-mode'. *Note Defining
  782. Minor Modes::.
  783. * Define a variable whose name ends in `-mode'. We call this the
  784. "mode variable". The minor mode command should set this variable.
  785. The value will be `nil' is the mode is disabled, and non-`nil' if
  786. the mode is enabled. The variable should be buffer-local if the
  787. minor mode is buffer-local.
  788. This variable is used in conjunction with the `minor-mode-alist' to
  789. display the minor mode name in the mode line. It also determines
  790. whether the minor mode keymap is active, via `minor-mode-map-alist'
  791. (*note Controlling Active Maps::). Individual commands or hooks
  792. can also check its value.
  793. * Define a command, called the "mode command", whose name is the same
  794. as the mode variable. Its job is to set the value of the mode
  795. variable, plus anything else that needs to be done to actually
  796. enable or disable the mode's features.
  797. The mode command should accept one optional argument. If called
  798. interactively with no prefix argument, it should toggle the mode
  799. (i.e. enable if it is disabled, and disable if it is enabled). If
  800. called interactively with a prefix argument, it should enable the
  801. mode if the argument is positive and disable it otherwise.
  802. If the mode command is called from Lisp (i.e. non-interactively),
  803. it should enable the mode if the argument is omitted or `nil'; it
  804. should toggle the mode if the argument is the symbol `toggle';
  805. otherwise it should treat the argument in the same way as for an
  806. interactive call with a numeric prefix argument, as described
  807. above.
  808. The following example shows how to implement this behavior (it is
  809. similar to the code generated by the `define-minor-mode' macro):
  810. (interactive (list (or current-prefix-arg 'toggle)))
  811. (let ((enable (if (eq arg 'toggle)
  812. (not foo-mode) ; this mode's mode variable
  813. (> (prefix-numeric-value arg) 0))))
  814. (if enable
  815. DO-ENABLE
  816. DO-DISABLE))
  817. The reason for this somewhat complex behavior is that it lets users
  818. easily toggle the minor mode interactively, and also lets the
  819. minor mode be easily enabled in a mode hook, like this:
  820. (add-hook 'text-mode-hook 'foo-mode)
  821. This behaves correctly whether or not `foo-mode' was already
  822. enabled, since the `foo-mode' mode command unconditionally enables
  823. the minor mode when it is called from Lisp with no argument.
  824. Disabling a minor mode in a mode hook is a little uglier:
  825. (add-hook 'text-mode-hook (lambda () (foo-mode -1)))
  826. However, this is not very commonly done.
  827. * Add an element to `minor-mode-alist' for each minor mode (*note
  828. Definition of minor-mode-alist::), if you want to indicate the
  829. minor mode in the mode line. This element should be a list of the
  830. following form:
  831. (MODE-VARIABLE STRING)
  832. Here MODE-VARIABLE is the variable that controls enabling of the
  833. minor mode, and STRING is a short string, starting with a space,
  834. to represent the mode in the mode line. These strings must be
  835. short so that there is room for several of them at once.
  836. When you add an element to `minor-mode-alist', use `assq' to check
  837. for an existing element, to avoid duplication. For example:
  838. (unless (assq 'leif-mode minor-mode-alist)
  839. (push '(leif-mode " Leif") minor-mode-alist))
  840. or like this, using `add-to-list' (*note List Variables::):
  841. (add-to-list 'minor-mode-alist '(leif-mode " Leif"))
  842. In addition, several major mode conventions apply to minor modes as
  843. well: those regarding the names of global symbols, the use of a hook at
  844. the end of the initialization function, and the use of keymaps and other
  845. tables.
  846. The minor mode should, if possible, support enabling and disabling
  847. via Custom (*note Customization::). To do this, the mode variable
  848. should be defined with `defcustom', usually with `:type 'boolean'. If
  849. just setting the variable is not sufficient to enable the mode, you
  850. should also specify a `:set' method which enables the mode by invoking
  851. the mode command. Note in the variable's documentation string that
  852. setting the variable other than via Custom may not take effect. Also,
  853. mark the definition with an autoload cookie (*note autoload cookie::),
  854. and specify a `:require' so that customizing the variable will load the
  855. library that defines the mode. For example:
  856. ;;;###autoload
  857. (defcustom msb-mode nil
  858. "Toggle msb-mode.
  859. Setting this variable directly does not take effect;
  860. use either \\[customize] or the function `msb-mode'."
  861. :set 'custom-set-minor-mode
  862. :initialize 'custom-initialize-default
  863. :version "20.4"
  864. :type 'boolean
  865. :group 'msb
  866. :require 'msb)
  867. 
  868. File: elisp, Node: Keymaps and Minor Modes, Next: Defining Minor Modes, Prev: Minor Mode Conventions, Up: Minor Modes
  869. 23.3.2 Keymaps and Minor Modes
  870. ------------------------------
  871. Each minor mode can have its own keymap, which is active when the mode
  872. is enabled. To set up a keymap for a minor mode, add an element to the
  873. alist `minor-mode-map-alist'. *Note Definition of
  874. minor-mode-map-alist::.
  875. One use of minor mode keymaps is to modify the behavior of certain
  876. self-inserting characters so that they do something else as well as
  877. self-insert. (Another way to customize `self-insert-command' is
  878. through `post-self-insert-hook'. Apart from this, the facilities for
  879. customizing `self-insert-command' are limited to special cases,
  880. designed for abbrevs and Auto Fill mode. Do not try substituting your
  881. own definition of `self-insert-command' for the standard one. The
  882. editor command loop handles this function specially.)
  883. The key sequences bound in a minor mode should consist of `C-c'
  884. followed by one of `.,/?`'"[]\|~!#$%^&*()-_+='. (The other punctuation
  885. characters are reserved for major modes.)
  886. 
  887. File: elisp, Node: Defining Minor Modes, Prev: Keymaps and Minor Modes, Up: Minor Modes
  888. 23.3.3 Defining Minor Modes
  889. ---------------------------
  890. The macro `define-minor-mode' offers a convenient way of implementing a
  891. mode in one self-contained definition.
  892. -- Macro: define-minor-mode mode doc [init-value [lighter [keymap]]]
  893. keyword-args... body...
  894. This macro defines a new minor mode whose name is MODE (a symbol).
  895. It defines a command named MODE to toggle the minor mode, with DOC
  896. as its documentation string.
  897. The toggle command takes one optional (prefix) argument. If
  898. called interactively with no argument it toggles the mode on or
  899. off. A positive prefix argument enables the mode, any other
  900. prefix argument disables it. From Lisp, an argument of `toggle'
  901. toggles the mode, whereas an omitted or `nil' argument enables the
  902. mode. This makes it easy to enable the minor mode in a major mode
  903. hook, for example. If DOC is nil, the macro supplies a default
  904. documentation string explaining the above.
  905. By default, it also defines a variable named MODE, which is set to
  906. `t' or `nil' by enabling or disabling the mode. The variable is
  907. initialized to INIT-VALUE. Except in unusual circumstances (see
  908. below), this value must be `nil'.
  909. The string LIGHTER says what to display in the mode line when the
  910. mode is enabled; if it is `nil', the mode is not displayed in the
  911. mode line.
  912. The optional argument KEYMAP specifies the keymap for the minor
  913. mode. If non-`nil', it should be a variable name (whose value is
  914. a keymap), a keymap, or an alist of the form
  915. (KEY-SEQUENCE . DEFINITION)
  916. where each KEY-SEQUENCE and DEFINITION are arguments suitable for
  917. passing to `define-key' (*note Changing Key Bindings::). If
  918. KEYMAP is a keymap or an alist, this also defines the variable
  919. `MODE-map'.
  920. The above three arguments INIT-VALUE, LIGHTER, and KEYMAP can be
  921. (partially) omitted when KEYWORD-ARGS are used. The KEYWORD-ARGS
  922. consist of keywords followed by corresponding values. A few
  923. keywords have special meanings:
  924. `:group GROUP'
  925. Custom group name to use in all generated `defcustom' forms.
  926. Defaults to MODE without the possible trailing `-mode'.
  927. *Warning:* don't use this default group name unless you have
  928. written a `defgroup' to define that group properly. *Note
  929. Group Definitions::.
  930. `:global GLOBAL'
  931. If non-`nil', this specifies that the minor mode should be
  932. global rather than buffer-local. It defaults to `nil'.
  933. One of the effects of making a minor mode global is that the
  934. MODE variable becomes a customization variable. Toggling it
  935. through the Customize interface turns the mode on and off,
  936. and its value can be saved for future Emacs sessions (*note
  937. Saving Customizations: (emacs)Saving Customizations. For the
  938. saved variable to work, you should ensure that the
  939. `define-minor-mode' form is evaluated each time Emacs starts;
  940. for packages that are not part of Emacs, the easiest way to
  941. do this is to specify a `:require' keyword.
  942. `:init-value INIT-VALUE'
  943. This is equivalent to specifying INIT-VALUE positionally.
  944. `:lighter LIGHTER'
  945. This is equivalent to specifying LIGHTER positionally.
  946. `:keymap KEYMAP'
  947. This is equivalent to specifying KEYMAP positionally.
  948. `:variable PLACE'
  949. This replaces the default variable MODE, used to store the
  950. state of the mode. If you specify this, the MODE variable is
  951. not defined, and any INIT-VALUE argument is unused. PLACE
  952. can be a different named variable (which you must define
  953. yourself), or anything that can be used with the `setf'
  954. function (*note Generalized Variables: (cl)Generalized
  955. Variables.). PLACE can also be a cons `(GET . SET)', where
  956. GET is an expression that returns the current state, and SET
  957. is a function of one argument (a state) that sets it.
  958. `:after-hook AFTER-HOOK'
  959. This defines a single Lisp form which is evaluated after the
  960. mode hooks have run. It should not be quoted.
  961. Any other keyword arguments are passed directly to the `defcustom'
  962. generated for the variable MODE.
  963. The command named MODE first performs the standard actions such as
  964. setting the variable named MODE and then executes the BODY forms,
  965. if any. It then runs the mode hook variable `MODE-hook' and
  966. finishes by evaluating any form in `:after-hook'.
  967. The initial value must be `nil' except in cases where (1) the mode
  968. is preloaded in Emacs, or (2) it is painless for loading to enable the
  969. mode even though the user did not request it. For instance, if the
  970. mode has no effect unless something else is enabled, and will always be
  971. loaded by that time, enabling it by default is harmless. But these are
  972. unusual circumstances. Normally, the initial value must be `nil'.
  973. The name `easy-mmode-define-minor-mode' is an alias for this macro.
  974. Here is an example of using `define-minor-mode':
  975. (define-minor-mode hungry-mode
  976. "Toggle Hungry mode.
  977. Interactively with no argument, this command toggles the mode.
  978. A positive prefix argument enables the mode, any other prefix
  979. argument disables it. From Lisp, argument omitted or nil enables
  980. the mode, `toggle' toggles the state.
  981. When Hungry mode is enabled, the control delete key
  982. gobbles all preceding whitespace except the last.
  983. See the command \\[hungry-electric-delete]."
  984. ;; The initial value.
  985. nil
  986. ;; The indicator for the mode line.
  987. " Hungry"
  988. ;; The minor mode bindings.
  989. '(([C-backspace] . hungry-electric-delete))
  990. :group 'hunger)
  991. This defines a minor mode named "Hungry mode", a command named
  992. `hungry-mode' to toggle it, a variable named `hungry-mode' which
  993. indicates whether the mode is enabled, and a variable named
  994. `hungry-mode-map' which holds the keymap that is active when the mode
  995. is enabled. It initializes the keymap with a key binding for
  996. `C-<DEL>'. It puts the variable `hungry-mode' into custom group
  997. `hunger'. There are no BODY forms--many minor modes don't need any.
  998. Here's an equivalent way to write it:
  999. (define-minor-mode hungry-mode
  1000. "Toggle Hungry mode.
  1001. ...rest of documentation as before..."
  1002. ;; The initial value.
  1003. :init-value nil
  1004. ;; The indicator for the mode line.
  1005. :lighter " Hungry"
  1006. ;; The minor mode bindings.
  1007. :keymap
  1008. '(([C-backspace] . hungry-electric-delete)
  1009. ([C-M-backspace]
  1010. . (lambda ()
  1011. (interactive)
  1012. (hungry-electric-delete t))))
  1013. :group 'hunger)
  1014. -- Macro: define-globalized-minor-mode global-mode mode turn-on
  1015. keyword-args...
  1016. This defines a global toggle named GLOBAL-MODE whose meaning is to
  1017. enable or disable the buffer-local minor mode MODE in all buffers.
  1018. To turn on the minor mode in a buffer, it uses the function
  1019. TURN-ON; to turn off the minor mode, it calls `mode' with -1 as
  1020. argument.
  1021. Globally enabling the mode also affects buffers subsequently
  1022. created by visiting files, and buffers that use a major mode other
  1023. than Fundamental mode; but it does not detect the creation of a
  1024. new buffer in Fundamental mode.
  1025. This defines the customization option GLOBAL-MODE (*note
  1026. Customization::), which can be toggled in the Customize interface
  1027. to turn the minor mode on and off. As with `define-minor-mode',
  1028. you should ensure that the `define-globalized-minor-mode' form is
  1029. evaluated each time Emacs starts, for example by providing a
  1030. `:require' keyword.
  1031. Use `:group GROUP' in KEYWORD-ARGS to specify the custom group for
  1032. the mode variable of the global minor mode.
  1033. Generally speaking, when you define a globalized minor mode, you
  1034. should also define a non-globalized version, so that people can
  1035. use (or disable) it in individual buffers. This also allows them
  1036. to disable a globally enabled minor mode in a specific major mode,
  1037. by using that mode's hook.
  1038. 
  1039. File: elisp, Node: Mode Line Format, Next: Imenu, Prev: Minor Modes, Up: Modes
  1040. 23.4 Mode Line Format
  1041. =====================
  1042. Each Emacs window (aside from minibuffer windows) typically has a mode
  1043. line at the bottom, which displays status information about the buffer
  1044. displayed in the window. The mode line contains information about the
  1045. buffer, such as its name, associated file, depth of recursive editing,
  1046. and major and minor modes. A window can also have a "header line",
  1047. which is much like the mode line but appears at the top of the window.
  1048. This section describes how to control the contents of the mode line
  1049. and header line. We include it in this chapter because much of the
  1050. information displayed in the mode line relates to the enabled major and
  1051. minor modes.
  1052. * Menu:
  1053. * Base: Mode Line Basics. Basic ideas of mode line control.
  1054. * Data: Mode Line Data. The data structure that controls the mode line.
  1055. * Top: Mode Line Top. The top level variable, mode-line-format.
  1056. * Mode Line Variables:: Variables used in that data structure.
  1057. * %-Constructs:: Putting information into a mode line.
  1058. * Properties in Mode:: Using text properties in the mode line.
  1059. * Header Lines:: Like a mode line, but at the top.
  1060. * Emulating Mode Line:: Formatting text as the mode line would.
  1061. 
  1062. File: elisp, Node: Mode Line Basics, Next: Mode Line Data, Up: Mode Line Format
  1063. 23.4.1 Mode Line Basics
  1064. -----------------------
  1065. The contents of each mode line are specified by the buffer-local
  1066. variable `mode-line-format' (*note Mode Line Top::). This variable
  1067. holds a "mode line construct": a template that controls what is
  1068. displayed on the buffer's mode line. The value of `header-line-format'
  1069. specifies the buffer's header line in the same way. All windows for
  1070. the same buffer use the same `mode-line-format' and
  1071. `header-line-format'.
  1072. For efficiency, Emacs does not continuously recompute each window's
  1073. mode line and header line. It does so when circumstances appear to call
  1074. for it--for instance, if you change the window configuration, switch
  1075. buffers, narrow or widen the buffer, scroll, or modify the buffer. If
  1076. you alter any of the variables referenced by `mode-line-format' or
  1077. `header-line-format' (*note Mode Line Variables::), or any other data
  1078. structures that affect how text is displayed (*note Display::), you
  1079. should use the function `force-mode-line-update' to update the display.
  1080. -- Function: force-mode-line-update &optional all
  1081. This function forces Emacs to update the current buffer's mode
  1082. line and header line, based on the latest values of all relevant
  1083. variables, during its next redisplay cycle. If the optional
  1084. argument ALL is non-`nil', it forces an update for all mode lines
  1085. and header lines.
  1086. This function also forces an update of the menu bar and frame
  1087. title.
  1088. The selected window's mode line is usually displayed in a different
  1089. color using the face `mode-line'. Other windows' mode lines appear in
  1090. the face `mode-line-inactive' instead. *Note Faces::.
  1091. 
  1092. File: elisp, Node: Mode Line Data, Next: Mode Line Top, Prev: Mode Line Basics, Up: Mode Line Format
  1093. 23.4.2 The Data Structure of the Mode Line
  1094. ------------------------------------------
  1095. The mode line contents are controlled by a data structure called a
  1096. "mode line construct", made up of lists, strings, symbols, and numbers
  1097. kept in buffer-local variables. Each data type has a specific meaning
  1098. for the mode line appearance, as described below. The same data
  1099. structure is used for constructing frame titles (*note Frame Titles::)
  1100. and header lines (*note Header Lines::).
  1101. A mode line construct may be as simple as a fixed string of text,
  1102. but it usually specifies how to combine fixed strings with variables'
  1103. values to construct the text. Many of these variables are themselves
  1104. defined to have mode line constructs as their values.
  1105. Here are the meanings of various data types as mode line constructs:
  1106. `STRING'
  1107. A string as a mode line construct appears verbatim except for
  1108. "`%'-constructs" in it. These stand for substitution of other
  1109. data; see *note %-Constructs::.
  1110. If parts of the string have `face' properties, they control
  1111. display of the text just as they would text in the buffer. Any
  1112. characters which have no `face' properties are displayed, by
  1113. default, in the face `mode-line' or `mode-line-inactive' (*note
  1114. Standard Faces: (emacs)Standard Faces.). The `help-echo' and
  1115. `local-map' properties in STRING have special meanings. *Note
  1116. Properties in Mode::.
  1117. `SYMBOL'
  1118. A symbol as a mode line construct stands for its value. The value
  1119. of SYMBOL is used as a mode line construct, in place of SYMBOL.
  1120. However, the symbols `t' and `nil' are ignored, as is any symbol
  1121. whose value is void.
  1122. There is one exception: if the value of SYMBOL is a string, it is
  1123. displayed verbatim: the `%'-constructs are not recognized.
  1124. Unless SYMBOL is marked as "risky" (i.e., it has a non-`nil'
  1125. `risky-local-variable' property), all text properties specified in
  1126. SYMBOL's value are ignored. This includes the text properties of
  1127. strings in SYMBOL's value, as well as all `:eval' and
  1128. `:propertize' forms in it. (The reason for this is security:
  1129. non-risky variables could be set automatically from file variables
  1130. without prompting the user.)
  1131. `(STRING REST...)'
  1132. `(LIST REST...)'
  1133. A list whose first element is a string or list means to process
  1134. all the elements recursively and concatenate the results. This is
  1135. the most common form of mode line construct.
  1136. `(:eval FORM)'
  1137. A list whose first element is the symbol `:eval' says to evaluate
  1138. FORM, and use the result as a string to display. Make sure this
  1139. evaluation cannot load any files, as doing so could cause infinite
  1140. recursion.
  1141. `(:propertize ELT PROPS...)'
  1142. A list whose first element is the symbol `:propertize' says to
  1143. process the mode line construct ELT recursively, then add the text
  1144. properties specified by PROPS to the result. The argument PROPS
  1145. should consist of zero or more pairs TEXT-PROPERTY VALUE.
  1146. `(SYMBOL THEN ELSE)'
  1147. A list whose first element is a symbol that is not a keyword
  1148. specifies a conditional. Its meaning depends on the value of
  1149. SYMBOL. If SYMBOL has a non-`nil' value, the second element,
  1150. THEN, is processed recursively as a mode line element. Otherwise,
  1151. the third element, ELSE, is processed recursively. You may omit
  1152. ELSE; then the mode line element displays nothing if the value of
  1153. SYMBOL is `nil' or void.
  1154. `(WIDTH REST...)'
  1155. A list whose first element is an integer specifies truncation or
  1156. padding of the results of REST. The remaining elements REST are
  1157. processed recursively as mode line constructs and concatenated
  1158. together. When WIDTH is positive, the result is space filled on
  1159. the right if its width is less than WIDTH. When WIDTH is
  1160. negative, the result is truncated on the right to -WIDTH columns
  1161. if its width exceeds -WIDTH.
  1162. For example, the usual way to show what percentage of a buffer is
  1163. above the top of the window is to use a list like this: `(-3
  1164. "%p")'.
  1165. 
  1166. File: elisp, Node: Mode Line Top, Next: Mode Line Variables, Prev: Mode Line Data, Up: Mode Line Format
  1167. 23.4.3 The Top Level of Mode Line Control
  1168. -----------------------------------------
  1169. The variable in overall control of the mode line is `mode-line-format'.
  1170. -- User Option: mode-line-format
  1171. The value of this variable is a mode line construct that controls
  1172. the contents of the mode-line. It is always buffer-local in all
  1173. buffers.
  1174. If you set this variable to `nil' in a buffer, that buffer does not
  1175. have a mode line. (A window that is just one line tall also does
  1176. not display a mode line.)
  1177. The default value of `mode-line-format' is designed to use the
  1178. values of other variables such as `mode-line-position' and
  1179. `mode-line-modes' (which in turn incorporates the values of the
  1180. variables `mode-name' and `minor-mode-alist'). Very few modes need to
  1181. alter `mode-line-format' itself. For most purposes, it is sufficient
  1182. to alter some of the variables that `mode-line-format' either directly
  1183. or indirectly refers to.
  1184. If you do alter `mode-line-format' itself, the new value should use
  1185. the same variables that appear in the default value (*note Mode Line
  1186. Variables::), rather than duplicating their contents or displaying the
  1187. information in another fashion. This way, customizations made by the
  1188. user or by Lisp programs (such as `display-time' and major modes) via
  1189. changes to those variables remain effective.
  1190. Here is a hypothetical example of a `mode-line-format' that might be
  1191. useful for Shell mode (in reality, Shell mode does not set
  1192. `mode-line-format'):
  1193. (setq mode-line-format
  1194. (list "-"
  1195. 'mode-line-mule-info
  1196. 'mode-line-modified
  1197. 'mode-line-frame-identification
  1198. "%b--"
  1199. ;; Note that this is evaluated while making the list.
  1200. ;; It makes a mode line construct which is just a string.
  1201. (getenv "HOST")
  1202. ":"
  1203. 'default-directory
  1204. " "
  1205. 'global-mode-string
  1206. " %[("
  1207. '(:eval (mode-line-mode-name))
  1208. 'mode-line-process
  1209. 'minor-mode-alist
  1210. "%n"
  1211. ")%]--"
  1212. '(which-func-mode ("" which-func-format "--"))
  1213. '(line-number-mode "L%l--")
  1214. '(column-number-mode "C%c--")
  1215. '(-3 "%p")))
  1216. (The variables `line-number-mode', `column-number-mode' and
  1217. `which-func-mode' enable particular minor modes; as usual, these
  1218. variable names are also the minor mode command names.)
  1219. 
  1220. File: elisp, Node: Mode Line Variables, Next: %-Constructs, Prev: Mode Line Top, Up: Mode Line Format
  1221. 23.4.4 Variables Used in the Mode Line
  1222. --------------------------------------
  1223. This section describes variables incorporated by the standard value of
  1224. `mode-line-format' into the text of the mode line. There is nothing
  1225. inherently special about these variables; any other variables could
  1226. have the same effects on the mode line if the value of
  1227. `mode-line-format' is changed to use them. However, various parts of
  1228. Emacs set these variables on the understanding that they will control
  1229. parts of the mode line; therefore, practically speaking, it is essential
  1230. for the mode line to use them.
  1231. -- Variable: mode-line-mule-info
  1232. This variable holds the value of the mode line construct that
  1233. displays information about the language environment, buffer coding
  1234. system, and current input method. *Note Non-ASCII Characters::.
  1235. -- Variable: mode-line-modified
  1236. This variable holds the value of the mode line construct that
  1237. displays whether the current buffer is modified. Its default
  1238. value displays `**' if the buffer is modified, `--' if the buffer
  1239. is not modified, `%%' if the buffer is read only, and `%*' if the
  1240. buffer is read only and modified.
  1241. Changing this variable does not force an update of the mode line.
  1242. -- Variable: mode-line-frame-identification
  1243. This variable identifies the current frame. Its default value
  1244. displays `" "' if you are using a window system which can show
  1245. multiple frames, or `"-%F "' on an ordinary terminal which shows
  1246. only one frame at a time.
  1247. -- Variable: mode-line-buffer-identification
  1248. This variable identifies the buffer being displayed in the window.
  1249. Its default value displays the buffer name, padded with spaces to
  1250. at least 12 columns.
  1251. -- User Option: mode-line-position
  1252. This variable indicates the position in the buffer. Its default
  1253. value displays the buffer percentage and, optionally, the buffer
  1254. size, the line number and the column number.
  1255. -- Variable: vc-mode
  1256. The variable `vc-mode', buffer-local in each buffer, records
  1257. whether the buffer's visited file is maintained with version
  1258. control, and, if so, which kind. Its value is a string that
  1259. appears in the mode line, or `nil' for no version control.
  1260. -- User Option: mode-line-modes
  1261. This variable displays the buffer's major and minor modes. Its
  1262. default value also displays the recursive editing level,
  1263. information on the process status, and whether narrowing is in
  1264. effect.
  1265. -- Variable: mode-line-remote
  1266. This variable is used to show whether `default-directory' for the
  1267. current buffer is remote.
  1268. -- Variable: mode-line-client
  1269. This variable is used to identify `emacsclient' frames.
  1270. The following three variables are used in `mode-line-modes':
  1271. -- Variable: mode-name
  1272. This buffer-local variable holds the "pretty" name of the current
  1273. buffer's major mode. Each major mode should set this variable so
  1274. that the mode name will appear in the mode line. The value does
  1275. not have to be a string, but can use any of the data types valid
  1276. in a mode-line construct (*note Mode Line Data::). To compute the
  1277. string that will identify the mode name in the mode line, use
  1278. `format-mode-line' (*note Emulating Mode Line::).
  1279. -- Variable: mode-line-process
  1280. This buffer-local variable contains the mode line information on
  1281. process status in modes used for communicating with subprocesses.
  1282. It is displayed immediately following the major mode name, with no
  1283. intervening space. For example, its value in the `*shell*' buffer
  1284. is `(":%s")', which allows the shell to display its status along
  1285. with the major mode as: `(Shell:run)'. Normally this variable is
  1286. `nil'.
  1287. -- Variable: minor-mode-alist
  1288. This variable holds an association list whose elements specify how
  1289. the mode line should indicate that a minor mode is active. Each
  1290. element of the `minor-mode-alist' should be a two-element list:
  1291. (MINOR-MODE-VARIABLE MODE-LINE-STRING)
  1292. More generally, MODE-LINE-STRING can be any mode line construct.
  1293. It appears in the mode line when the value of MINOR-MODE-VARIABLE
  1294. is non-`nil', and not otherwise. These strings should begin with
  1295. spaces so that they don't run together. Conventionally, the
  1296. MINOR-MODE-VARIABLE for a specific mode is set to a non-`nil'
  1297. value when that minor mode is activated.
  1298. `minor-mode-alist' itself is not buffer-local. Each variable
  1299. mentioned in the alist should be buffer-local if its minor mode
  1300. can be enabled separately in each buffer.
  1301. -- Variable: global-mode-string
  1302. This variable holds a mode line construct that, by default,
  1303. appears in the mode line just after the `which-func-mode' minor
  1304. mode if set, else after `mode-line-modes'. The command
  1305. `display-time' sets `global-mode-string' to refer to the variable
  1306. `display-time-string', which holds a string containing the time and
  1307. load information.
  1308. The `%M' construct substitutes the value of `global-mode-string',
  1309. but that is obsolete, since the variable is included in the mode
  1310. line from `mode-line-format'.
  1311. Here is a simplified version of the default value of
  1312. `mode-line-format'. The real default value also specifies addition of
  1313. text properties.
  1314. ("-"
  1315. mode-line-mule-info
  1316. mode-line-modified
  1317. mode-line-frame-identification
  1318. mode-line-buffer-identification
  1319. " "
  1320. mode-line-position
  1321. (vc-mode vc-mode)
  1322. " "
  1323. mode-line-modes
  1324. (which-func-mode ("" which-func-format "--"))
  1325. (global-mode-string ("--" global-mode-string))
  1326. "-%-")
  1327. 
  1328. File: elisp, Node: %-Constructs, Next: Properties in Mode, Prev: Mode Line Variables, Up: Mode Line Format
  1329. 23.4.5 `%'-Constructs in the Mode Line
  1330. --------------------------------------
  1331. Strings used as mode line constructs can use certain `%'-constructs to
  1332. substitute various kinds of data. Here is a list of the defined
  1333. `%'-constructs, and what they mean. In any construct except `%%', you
  1334. can add a decimal integer after the `%' to specify a minimum field
  1335. width. If the width is less, the field is padded with spaces to the
  1336. right.
  1337. `%b'
  1338. The current buffer name, obtained with the `buffer-name' function.
  1339. *Note Buffer Names::.
  1340. `%c'
  1341. The current column number of point.
  1342. `%e'
  1343. When Emacs is nearly out of memory for Lisp objects, a brief
  1344. message saying so. Otherwise, this is empty.
  1345. `%f'
  1346. The visited file name, obtained with the `buffer-file-name'
  1347. function. *Note Buffer File Name::.
  1348. `%F'
  1349. The title (only on a window system) or the name of the selected
  1350. frame. *Note Basic Parameters::.
  1351. `%i'
  1352. The size of the accessible part of the current buffer; basically
  1353. `(- (point-max) (point-min))'.
  1354. `%I'
  1355. Like `%i', but the size is printed in a more readable way by using
  1356. `k' for 10^3, `M' for 10^6, `G' for 10^9, etc., to abbreviate.
  1357. `%l'
  1358. The current line number of point, counting within the accessible
  1359. portion of the buffer.
  1360. `%n'
  1361. `Narrow' when narrowing is in effect; nothing otherwise (see
  1362. `narrow-to-region' in *note Narrowing::).
  1363. `%p'
  1364. The percentage of the buffer text above the *top* of window, or
  1365. `Top', `Bottom' or `All'. Note that the default mode line
  1366. construct truncates this to three characters.
  1367. `%P'
  1368. The percentage of the buffer text that is above the *bottom* of
  1369. the window (which includes the text visible in the window, as well
  1370. as the text above the top), plus `Top' if the top of the buffer is
  1371. visible on screen; or `Bottom' or `All'.
  1372. `%s'
  1373. The status of the subprocess belonging to the current buffer,
  1374. obtained with `process-status'. *Note Process Information::.
  1375. `%t'
  1376. Whether the visited file is a text file or a binary file. This is
  1377. a meaningful distinction only on certain operating systems (*note
  1378. MS-DOS File Types::).
  1379. `%z'
  1380. The mnemonics of keyboard, terminal, and buffer coding systems.
  1381. `%Z'
  1382. Like `%z', but including the end-of-line format.
  1383. `%*'
  1384. `%' if the buffer is read only (see `buffer-read-only');
  1385. `*' if the buffer is modified (see `buffer-modified-p');
  1386. `-' otherwise. *Note Buffer Modification::.
  1387. `%+'
  1388. `*' if the buffer is modified (see `buffer-modified-p');
  1389. `%' if the buffer is read only (see `buffer-read-only');
  1390. `-' otherwise. This differs from `%*' only for a modified
  1391. read-only buffer. *Note Buffer Modification::.
  1392. `%&'
  1393. `*' if the buffer is modified, and `-' otherwise.
  1394. `%['
  1395. An indication of the depth of recursive editing levels (not
  1396. counting minibuffer levels): one `[' for each editing level.
  1397. *Note Recursive Editing::.
  1398. `%]'
  1399. One `]' for each recursive editing level (not counting minibuffer
  1400. levels).
  1401. `%-'
  1402. Dashes sufficient to fill the remainder of the mode line.
  1403. `%%'
  1404. The character `%'--this is how to include a literal `%' in a
  1405. string in which `%'-constructs are allowed.
  1406. The following two `%'-constructs are still supported, but they are
  1407. obsolete, since you can get the same results with the variables
  1408. `mode-name' and `global-mode-string'.
  1409. `%m'
  1410. The value of `mode-name'.
  1411. `%M'
  1412. The value of `global-mode-string'.
  1413. 
  1414. File: elisp, Node: Properties in Mode, Next: Header Lines, Prev: %-Constructs, Up: Mode Line Format
  1415. 23.4.6 Properties in the Mode Line
  1416. ----------------------------------
  1417. Certain text properties are meaningful in the mode line. The `face'
  1418. property affects the appearance of text; the `help-echo' property
  1419. associates help strings with the text, and `local-map' can make the
  1420. text mouse-sensitive.
  1421. There are four ways to specify text properties for text in the mode
  1422. line:
  1423. 1. Put a string with a text property directly into the mode line data
  1424. structure.
  1425. 2. Put a text property on a mode line %-construct such as `%12b'; then
  1426. the expansion of the %-construct will have that same text property.
  1427. 3. Use a `(:propertize ELT PROPS...)' construct to give ELT a text
  1428. property specified by PROPS.
  1429. 4. Use a list containing `:eval FORM' in the mode line data
  1430. structure, and make FORM evaluate to a string that has a text
  1431. property.
  1432. You can use the `local-map' property to specify a keymap. This
  1433. keymap only takes real effect for mouse clicks; binding character keys
  1434. and function keys to it has no effect, since it is impossible to move
  1435. point into the mode line.
  1436. When the mode line refers to a variable which does not have a
  1437. non-`nil' `risky-local-variable' property, any text properties given or
  1438. specified within that variable's values are ignored. This is because
  1439. such properties could otherwise specify functions to be called, and
  1440. those functions could come from file local variables.
  1441. 
  1442. File: elisp, Node: Header Lines, Next: Emulating Mode Line, Prev: Properties in Mode, Up: Mode Line Format
  1443. 23.4.7 Window Header Lines
  1444. --------------------------
  1445. A window can have a "header line" at the top, just as it can have a
  1446. mode line at the bottom. The header line feature works just like the
  1447. mode line feature, except that it's controlled by `header-line-format':
  1448. -- Variable: header-line-format
  1449. This variable, local in every buffer, specifies how to display the
  1450. header line, for windows displaying the buffer. The format of the
  1451. value is the same as for `mode-line-format' (*note Mode Line
  1452. Data::). It is normally `nil', so that ordinary buffers have no
  1453. header line.
  1454. A window that is just one line tall never displays a header line. A
  1455. window that is two lines tall cannot display both a mode line and a
  1456. header line at once; if it has a mode line, then it does not display a
  1457. header line.
  1458. 
  1459. File: elisp, Node: Emulating Mode Line, Prev: Header Lines, Up: Mode Line Format
  1460. 23.4.8 Emulating Mode Line Formatting
  1461. -------------------------------------
  1462. You can use the function `format-mode-line' to compute the text that
  1463. would appear in a mode line or header line based on a certain mode line
  1464. construct.
  1465. -- Function: format-mode-line format &optional face window buffer
  1466. This function formats a line of text according to FORMAT as if it
  1467. were generating the mode line for WINDOW, but it also returns the
  1468. text as a string. The argument WINDOW defaults to the selected
  1469. window. If BUFFER is non-`nil', all the information used is taken
  1470. from BUFFER; by default, it comes from WINDOW's buffer.
  1471. The value string normally has text properties that correspond to
  1472. the faces, keymaps, etc., that the mode line would have. Any
  1473. character for which no `face' property is specified by FORMAT gets
  1474. a default value determined by FACE. If FACE is `t', that stands
  1475. for either `mode-line' if WINDOW is selected, otherwise
  1476. `mode-line-inactive'. If FACE is `nil' or omitted, that stands
  1477. for the default face. If FACE is an integer, the value returned
  1478. by this function will have no text properties.
  1479. You can also specify other valid faces as the value of FACE. If
  1480. specified, that face provides the `face' property for characters
  1481. whose face is not specified by FORMAT.
  1482. Note that using `mode-line', `mode-line-inactive', or
  1483. `header-line' as FACE will actually redisplay the mode line or the
  1484. header line, respectively, using the current definitions of the
  1485. corresponding face, in addition to returning the formatted string.
  1486. (Other faces do not cause redisplay.)
  1487. For example, `(format-mode-line header-line-format)' returns the
  1488. text that would appear in the selected window's header line (`""'
  1489. if it has no header line). `(format-mode-line header-line-format
  1490. 'header-line)' returns the same text, with each character carrying
  1491. the face that it will have in the header line itself, and also
  1492. redraws the header line.
  1493. 
  1494. File: elisp, Node: Imenu, Next: Font Lock Mode, Prev: Mode Line Format, Up: Modes
  1495. 23.5 Imenu
  1496. ==========
  1497. "Imenu" is a feature that lets users select a definition or section in
  1498. the buffer, from a menu which lists all of them, to go directly to that
  1499. location in the buffer. Imenu works by constructing a buffer index
  1500. which lists the names and buffer positions of the definitions, or other
  1501. named portions of the buffer; then the user can choose one of them and
  1502. move point to it. Major modes can add a menu bar item to use Imenu
  1503. using `imenu-add-to-menubar'.
  1504. -- Command: imenu-add-to-menubar name
  1505. This function defines a local menu bar item named NAME to run
  1506. Imenu.
  1507. The user-level commands for using Imenu are described in the Emacs
  1508. Manual (*note Imenu: (emacs)Imenu.). This section explains how to
  1509. customize Imenu's method of finding definitions or buffer portions for
  1510. a particular major mode.
  1511. The usual and simplest way is to set the variable
  1512. `imenu-generic-expression':
  1513. -- Variable: imenu-generic-expression
  1514. This variable, if non-`nil', is a list that specifies regular
  1515. expressions for finding definitions for Imenu. Simple elements of
  1516. `imenu-generic-expression' look like this:
  1517. (MENU-TITLE REGEXP INDEX)
  1518. Here, if MENU-TITLE is non-`nil', it says that the matches for
  1519. this element should go in a submenu of the buffer index;
  1520. MENU-TITLE itself specifies the name for the submenu. If
  1521. MENU-TITLE is `nil', the matches for this element go directly in
  1522. the top level of the buffer index.
  1523. The second item in the list, REGEXP, is a regular expression
  1524. (*note Regular Expressions::); anything in the buffer that it
  1525. matches is considered a definition, something to mention in the
  1526. buffer index. The third item, INDEX, is a non-negative integer
  1527. that indicates which subexpression in REGEXP matches the
  1528. definition's name.
  1529. An element can also look like this:
  1530. (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
  1531. Each match for this element creates an index item, and when the
  1532. index item is selected by the user, it calls FUNCTION with
  1533. arguments consisting of the item name, the buffer position, and
  1534. ARGUMENTS.
  1535. For Emacs Lisp mode, `imenu-generic-expression' could look like
  1536. this:
  1537. ((nil "^\\s-*(def\\(un\\|subst\\|macro\\|advice\\)\
  1538. \\s-+\\([-A-Za-z0-9+]+\\)" 2)
  1539. ("*Vars*" "^\\s-*(def\\(var\\|const\\)\
  1540. \\s-+\\([-A-Za-z0-9+]+\\)" 2)
  1541. ("*Types*"
  1542. "^\\s-*\
  1543. (def\\(type\\|struct\\|class\\|ine-condition\\)\
  1544. \\s-+\\([-A-Za-z0-9+]+\\)" 2))
  1545. Setting this variable makes it buffer-local in the current buffer.
  1546. -- Variable: imenu-case-fold-search
  1547. This variable controls whether matching against the regular
  1548. expressions in the value of `imenu-generic-expression' is
  1549. case-sensitive: `t', the default, means matching should ignore
  1550. case.
  1551. Setting this variable makes it buffer-local in the current buffer.
  1552. -- Variable: imenu-syntax-alist
  1553. This variable is an alist of syntax table modifiers to use while
  1554. processing `imenu-generic-expression', to override the syntax table
  1555. of the current buffer. Each element should have this form:
  1556. (CHARACTERS . SYNTAX-DESCRIPTION)
  1557. The CAR, CHARACTERS, can be either a character or a string. The
  1558. element says to give that character or characters the syntax
  1559. specified by SYNTAX-DESCRIPTION, which is passed to
  1560. `modify-syntax-entry' (*note Syntax Table Functions::).
  1561. This feature is typically used to give word syntax to characters
  1562. which normally have symbol syntax, and thus to simplify
  1563. `imenu-generic-expression' and speed up matching. For example,
  1564. Fortran mode uses it this way:
  1565. (setq imenu-syntax-alist '(("_$" . "w")))
  1566. The `imenu-generic-expression' regular expressions can then use
  1567. `\\sw+' instead of `\\(\\sw\\|\\s_\\)+'. Note that this technique
  1568. may be inconvenient when the mode needs to limit the initial
  1569. character of a name to a smaller set of characters than are
  1570. allowed in the rest of a name.
  1571. Setting this variable makes it buffer-local in the current buffer.
  1572. Another way to customize Imenu for a major mode is to set the
  1573. variables `imenu-prev-index-position-function' and
  1574. `imenu-extract-index-name-function':
  1575. -- Variable: imenu-prev-index-position-function
  1576. If this variable is non-`nil', its value should be a function that
  1577. finds the next "definition" to put in the buffer index, scanning
  1578. backward in the buffer from point. It should return `nil' if it
  1579. doesn't find another "definition" before point. Otherwise it
  1580. should leave point at the place it finds a "definition" and return
  1581. any non-`nil' value.
  1582. Setting this variable makes it buffer-local in the current buffer.
  1583. -- Variable: imenu-extract-index-name-function
  1584. If this variable is non-`nil', its value should be a function to
  1585. return the name for a definition, assuming point is in that
  1586. definition as the `imenu-prev-index-position-function' function
  1587. would leave it.
  1588. Setting this variable makes it buffer-local in the current buffer.
  1589. The last way to customize Imenu for a major mode is to set the
  1590. variable `imenu-create-index-function':
  1591. -- Variable: imenu-create-index-function
  1592. This variable specifies the function to use for creating a buffer
  1593. index. The function should take no arguments, and return an index
  1594. alist for the current buffer. It is called within
  1595. `save-excursion', so where it leaves point makes no difference.
  1596. The index alist can have three types of elements. Simple elements
  1597. look like this:
  1598. (INDEX-NAME . INDEX-POSITION)
  1599. Selecting a simple element has the effect of moving to position
  1600. INDEX-POSITION in the buffer. Special elements look like this:
  1601. (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
  1602. Selecting a special element performs:
  1603. (funcall FUNCTION
  1604. INDEX-NAME INDEX-POSITION ARGUMENTS...)
  1605. A nested sub-alist element looks like this:
  1606. (MENU-TITLE SUB-ALIST)
  1607. It creates the submenu MENU-TITLE specified by SUB-ALIST.
  1608. The default value of `imenu-create-index-function' is
  1609. `imenu-default-create-index-function'. This function calls the
  1610. value of `imenu-prev-index-position-function' and the value of
  1611. `imenu-extract-index-name-function' to produce the index alist.
  1612. However, if either of these two variables is `nil', the default
  1613. function uses `imenu-generic-expression' instead.
  1614. Setting this variable makes it buffer-local in the current buffer.
  1615. 
  1616. File: elisp, Node: Font Lock Mode, Next: Auto-Indentation, Prev: Imenu, Up: Modes
  1617. 23.6 Font Lock Mode
  1618. ===================
  1619. "Font Lock mode" is a buffer-local minor mode that automatically
  1620. attaches `face' properties to certain parts of the buffer based on
  1621. their syntactic role. How it parses the buffer depends on the major
  1622. mode; most major modes define syntactic criteria for which faces to use
  1623. in which contexts. This section explains how to customize Font Lock for
  1624. a particular major mode.
  1625. Font Lock mode finds text to highlight in two ways: through
  1626. syntactic parsing based on the syntax table, and through searching
  1627. (usually for regular expressions). Syntactic fontification happens
  1628. first; it finds comments and string constants and highlights them.
  1629. Search-based fontification happens second.
  1630. * Menu:
  1631. * Font Lock Basics:: Overview of customizing Font Lock.
  1632. * Search-based Fontification:: Fontification based on regexps.
  1633. * Customizing Keywords:: Customizing search-based fontification.
  1634. * Other Font Lock Variables:: Additional customization facilities.
  1635. * Levels of Font Lock:: Each mode can define alternative levels
  1636. so that the user can select more or less.
  1637. * Precalculated Fontification:: How Lisp programs that produce the buffer
  1638. contents can also specify how to fontify it.
  1639. * Faces for Font Lock:: Special faces specifically for Font Lock.
  1640. * Syntactic Font Lock:: Fontification based on syntax tables.
  1641. * Multiline Font Lock:: How to coerce Font Lock into properly
  1642. highlighting multiline constructs.
  1643. 
  1644. File: elisp, Node: Font Lock Basics, Next: Search-based Fontification, Up: Font Lock Mode
  1645. 23.6.1 Font Lock Basics
  1646. -----------------------
  1647. There are several variables that control how Font Lock mode highlights
  1648. text. But major modes should not set any of these variables directly.
  1649. Instead, they should set `font-lock-defaults' as a buffer-local
  1650. variable. The value assigned to this variable is used, if and when Font
  1651. Lock mode is enabled, to set all the other variables.
  1652. -- Variable: font-lock-defaults
  1653. This variable is set by major modes to specify how to fontify text
  1654. in that mode. It automatically becomes buffer-local when set. If
  1655. its value is `nil', Font Lock mode does no highlighting, and you
  1656. can use the `Faces' menu (under `Edit' and then `Text Properties'
  1657. in the menu bar) to assign faces explicitly to text in the buffer.
  1658. If non-`nil', the value should look like this:
  1659. (KEYWORDS [KEYWORDS-ONLY [CASE-FOLD
  1660. [SYNTAX-ALIST [SYNTAX-BEGIN OTHER-VARS...]]]])
  1661. The first element, KEYWORDS, indirectly specifies the value of
  1662. `font-lock-keywords' which directs search-based fontification. It
  1663. can be a symbol, a variable or a function whose value is the list
  1664. to use for `font-lock-keywords'. It can also be a list of several
  1665. such symbols, one for each possible level of fontification. The
  1666. first symbol specifies the `mode default' level of fontification,
  1667. the next symbol level 1 fontification, the next level 2, and so
  1668. on. The `mode default' level is normally the same as level 1. It
  1669. is used when `font-lock-maximum-decoration' has a `nil' value.
  1670. *Note Levels of Font Lock::.
  1671. The second element, KEYWORDS-ONLY, specifies the value of the
  1672. variable `font-lock-keywords-only'. If this is omitted or `nil',
  1673. syntactic fontification (of strings and comments) is also
  1674. performed. If this is non-`nil', syntactic fontification is not
  1675. performed. *Note Syntactic Font Lock::.
  1676. The third element, CASE-FOLD, specifies the value of
  1677. `font-lock-keywords-case-fold-search'. If it is non-`nil', Font
  1678. Lock mode ignores case during search-based fontification.
  1679. If the fourth element, SYNTAX-ALIST, is non-`nil', it should be a
  1680. list of cons cells of the form `(CHAR-OR-STRING . STRING)'. These
  1681. are used to set up a syntax table for syntactic fontification; the
  1682. resulting syntax table is stored in `font-lock-syntax-table'. If
  1683. SYNTAX-ALIST is omitted or `nil', syntactic fontification uses the
  1684. syntax table returned by the `syntax-table' function. *Note
  1685. Syntax Table Functions::.
  1686. The fifth element, SYNTAX-BEGIN, specifies the value of
  1687. `font-lock-beginning-of-syntax-function'. We recommend setting
  1688. this variable to `nil' and using `syntax-begin-function' instead.
  1689. All the remaining elements (if any) are collectively called
  1690. OTHER-VARS. Each of these elements should have the form
  1691. `(VARIABLE . VALUE)'--which means, make VARIABLE buffer-local and
  1692. then set it to VALUE. You can use these OTHER-VARS to set other
  1693. variables that affect fontification, aside from those you can
  1694. control with the first five elements. *Note Other Font Lock
  1695. Variables::.
  1696. If your mode fontifies text explicitly by adding `font-lock-face'
  1697. properties, it can specify `(nil t)' for `font-lock-defaults' to turn
  1698. off all automatic fontification. However, this is not required; it is
  1699. possible to fontify some things using `font-lock-face' properties and
  1700. set up automatic fontification for other parts of the text.
  1701. 
  1702. File: elisp, Node: Search-based Fontification, Next: Customizing Keywords, Prev: Font Lock Basics, Up: Font Lock Mode
  1703. 23.6.2 Search-based Fontification
  1704. ---------------------------------
  1705. The variable which directly controls search-based fontification is
  1706. `font-lock-keywords', which is typically specified via the KEYWORDS
  1707. element in `font-lock-defaults'.
  1708. -- Variable: font-lock-keywords
  1709. The value of this variable is a list of the keywords to highlight.
  1710. Lisp programs should not set this variable directly. Normally,
  1711. the value is automatically set by Font Lock mode, using the
  1712. KEYWORDS element in `font-lock-defaults'. The value can also be
  1713. altered using the functions `font-lock-add-keywords' and
  1714. `font-lock-remove-keywords' (*note Customizing Keywords::).
  1715. Each element of `font-lock-keywords' specifies how to find certain
  1716. cases of text, and how to highlight those cases. Font Lock mode
  1717. processes the elements of `font-lock-keywords' one by one, and for each
  1718. element, it finds and handles all matches. Ordinarily, once part of
  1719. the text has been fontified already, this cannot be overridden by a
  1720. subsequent match in the same text; but you can specify different
  1721. behavior using the OVERRIDE element of a SUBEXP-HIGHLIGHTER.
  1722. Each element of `font-lock-keywords' should have one of these forms:
  1723. `REGEXP'
  1724. Highlight all matches for REGEXP using `font-lock-keyword-face'.
  1725. For example,
  1726. ;; Highlight occurrences of the word `foo'
  1727. ;; using `font-lock-keyword-face'.
  1728. "\\<foo\\>"
  1729. Be careful when composing these regular expressions; a poorly
  1730. written pattern can dramatically slow things down! The function
  1731. `regexp-opt' (*note Regexp Functions::) is useful for calculating
  1732. optimal regular expressions to match several keywords.
  1733. `FUNCTION'
  1734. Find text by calling FUNCTION, and highlight the matches it finds
  1735. using `font-lock-keyword-face'.
  1736. When FUNCTION is called, it receives one argument, the limit of
  1737. the search; it should begin searching at point, and not search
  1738. beyond the limit. It should return non-`nil' if it succeeds, and
  1739. set the match data to describe the match that was found.
  1740. Returning `nil' indicates failure of the search.
  1741. Fontification will call FUNCTION repeatedly with the same limit,
  1742. and with point where the previous invocation left it, until
  1743. FUNCTION fails. On failure, FUNCTION need not reset point in any
  1744. particular way.
  1745. `(MATCHER . SUBEXP)'
  1746. In this kind of element, MATCHER is either a regular expression or
  1747. a function, as described above. The CDR, SUBEXP, specifies which
  1748. subexpression of MATCHER should be highlighted (instead of the
  1749. entire text that MATCHER matched).
  1750. ;; Highlight the `bar' in each occurrence of `fubar',
  1751. ;; using `font-lock-keyword-face'.
  1752. ("fu\\(bar\\)" . 1)
  1753. If you use `regexp-opt' to produce the regular expression MATCHER,
  1754. you can use `regexp-opt-depth' (*note Regexp Functions::) to
  1755. calculate the value for SUBEXP.
  1756. `(MATCHER . FACESPEC)'
  1757. In this kind of element, FACESPEC is an expression whose value
  1758. specifies the face to use for highlighting. In the simplest case,
  1759. FACESPEC is a Lisp variable (a symbol) whose value is a face name.
  1760. ;; Highlight occurrences of `fubar',
  1761. ;; using the face which is the value of `fubar-face'.
  1762. ("fubar" . fubar-face)
  1763. However, FACESPEC can also evaluate to a list of this form:
  1764. (face FACE PROP1 VAL1 PROP2 VAL2...)
  1765. to specify the face FACE and various additional text properties to
  1766. put on the text that matches. If you do this, be sure to add the
  1767. other text property names that you set in this way to the value of
  1768. `font-lock-extra-managed-props' so that the properties will also
  1769. be cleared out when they are no longer appropriate. Alternatively,
  1770. you can set the variable `font-lock-unfontify-region-function' to
  1771. a function that clears these properties. *Note Other Font Lock
  1772. Variables::.
  1773. `(MATCHER . SUBEXP-HIGHLIGHTER)'
  1774. In this kind of element, SUBEXP-HIGHLIGHTER is a list which
  1775. specifies how to highlight matches found by MATCHER. It has the
  1776. form:
  1777. (SUBEXP FACESPEC [OVERRIDE [LAXMATCH]])
  1778. The CAR, SUBEXP, is an integer specifying which subexpression of
  1779. the match to fontify (0 means the entire matching text). The
  1780. second subelement, FACESPEC, is an expression whose value
  1781. specifies the face, as described above.
  1782. The last two values in SUBEXP-HIGHLIGHTER, OVERRIDE and LAXMATCH,
  1783. are optional flags. If OVERRIDE is `t', this element can override
  1784. existing fontification made by previous elements of
  1785. `font-lock-keywords'. If it is `keep', then each character is
  1786. fontified if it has not been fontified already by some other
  1787. element. If it is `prepend', the face specified by FACESPEC is
  1788. added to the beginning of the `font-lock-face' property. If it is
  1789. `append', the face is added to the end of the `font-lock-face'
  1790. property.
  1791. If LAXMATCH is non-`nil', it means there should be no error if
  1792. there is no subexpression numbered SUBEXP in MATCHER. Obviously,
  1793. fontification of the subexpression numbered SUBEXP will not occur.
  1794. However, fontification of other subexpressions (and other regexps)
  1795. will continue. If LAXMATCH is `nil', and the specified
  1796. subexpression is missing, then an error is signaled which
  1797. terminates search-based fontification.
  1798. Here are some examples of elements of this kind, and what they do:
  1799. ;; Highlight occurrences of either `foo' or `bar', using
  1800. ;; `foo-bar-face', even if they have already been highlighted.
  1801. ;; `foo-bar-face' should be a variable whose value is a face.
  1802. ("foo\\|bar" 0 foo-bar-face t)
  1803. ;; Highlight the first subexpression within each occurrence
  1804. ;; that the function `fubar-match' finds,
  1805. ;; using the face which is the value of `fubar-face'.
  1806. (fubar-match 1 fubar-face)
  1807. `(MATCHER . ANCHORED-HIGHLIGHTER)'
  1808. In this kind of element, ANCHORED-HIGHLIGHTER specifies how to
  1809. highlight text that follows a match found by MATCHER. So a match
  1810. found by MATCHER acts as the anchor for further searches specified
  1811. by ANCHORED-HIGHLIGHTER. ANCHORED-HIGHLIGHTER is a list of the
  1812. following form:
  1813. (ANCHORED-MATCHER PRE-FORM POST-FORM
  1814. SUBEXP-HIGHLIGHTERS...)
  1815. Here, ANCHORED-MATCHER, like MATCHER, is either a regular
  1816. expression or a function. After a match of MATCHER is found,
  1817. point is at the end of the match. Now, Font Lock evaluates the
  1818. form PRE-FORM. Then it searches for matches of ANCHORED-MATCHER
  1819. and uses SUBEXP-HIGHLIGHTERS to highlight these. A
  1820. SUBEXP-HIGHLIGHTER is as described above. Finally, Font Lock
  1821. evaluates POST-FORM.
  1822. The forms PRE-FORM and POST-FORM can be used to initialize before,
  1823. and cleanup after, ANCHORED-MATCHER is used. Typically, PRE-FORM
  1824. is used to move point to some position relative to the match of
  1825. MATCHER, before starting with ANCHORED-MATCHER. POST-FORM might
  1826. be used to move back, before resuming with MATCHER.
  1827. After Font Lock evaluates PRE-FORM, it does not search for
  1828. ANCHORED-MATCHER beyond the end of the line. However, if PRE-FORM
  1829. returns a buffer position that is greater than the position of
  1830. point after PRE-FORM is evaluated, then the position returned by
  1831. PRE-FORM is used as the limit of the search instead. It is
  1832. generally a bad idea to return a position greater than the end of
  1833. the line; in other words, the ANCHORED-MATCHER search should not
  1834. span lines.
  1835. For example,
  1836. ;; Highlight occurrences of the word `item' following
  1837. ;; an occurrence of the word `anchor' (on the same line)
  1838. ;; in the value of `item-face'.
  1839. ("\\<anchor\\>" "\\<item\\>" nil nil (0 item-face))
  1840. Here, PRE-FORM and POST-FORM are `nil'. Therefore searching for
  1841. `item' starts at the end of the match of `anchor', and searching
  1842. for subsequent instances of `anchor' resumes from where searching
  1843. for `item' concluded.
  1844. `(MATCHER HIGHLIGHTERS...)'
  1845. This sort of element specifies several HIGHLIGHTER lists for a
  1846. single MATCHER. A HIGHLIGHTER list can be of the type
  1847. SUBEXP-HIGHLIGHTER or ANCHORED-HIGHLIGHTER as described above.
  1848. For example,
  1849. ;; Highlight occurrences of the word `anchor' in the value
  1850. ;; of `anchor-face', and subsequent occurrences of the word
  1851. ;; `item' (on the same line) in the value of `item-face'.
  1852. ("\\<anchor\\>" (0 anchor-face)
  1853. ("\\<item\\>" nil nil (0 item-face)))
  1854. `(eval . FORM)'
  1855. Here FORM is an expression to be evaluated the first time this
  1856. value of `font-lock-keywords' is used in a buffer. Its value
  1857. should have one of the forms described in this table.
  1858. *Warning:* Do not design an element of `font-lock-keywords' to match
  1859. text which spans lines; this does not work reliably. For details, see
  1860. *Note Multiline Font Lock::.
  1861. You can use CASE-FOLD in `font-lock-defaults' to specify the value
  1862. of `font-lock-keywords-case-fold-search' which says whether
  1863. search-based fontification should be case-insensitive.
  1864. -- Variable: font-lock-keywords-case-fold-search
  1865. Non-`nil' means that regular expression matching for the sake of
  1866. `font-lock-keywords' should be case-insensitive.
  1867. 
  1868. File: elisp, Node: Customizing Keywords, Next: Other Font Lock Variables, Prev: Search-based Fontification, Up: Font Lock Mode
  1869. 23.6.3 Customizing Search-Based Fontification
  1870. ---------------------------------------------
  1871. You can use `font-lock-add-keywords' to add additional search-based
  1872. fontification rules to a major mode, and `font-lock-remove-keywords' to
  1873. remove rules.
  1874. -- Function: font-lock-add-keywords mode keywords &optional how
  1875. This function adds highlighting KEYWORDS, for the current buffer
  1876. or for major mode MODE. The argument KEYWORDS should be a list
  1877. with the same format as the variable `font-lock-keywords'.
  1878. If MODE is a symbol which is a major mode command name, such as
  1879. `c-mode', the effect is that enabling Font Lock mode in MODE will
  1880. add KEYWORDS to `font-lock-keywords'. Calling with a non-`nil'
  1881. value of MODE is correct only in your `~/.emacs' file.
  1882. If MODE is `nil', this function adds KEYWORDS to
  1883. `font-lock-keywords' in the current buffer. This way of calling
  1884. `font-lock-add-keywords' is usually used in mode hook functions.
  1885. By default, KEYWORDS are added at the beginning of
  1886. `font-lock-keywords'. If the optional argument HOW is `set', they
  1887. are used to replace the value of `font-lock-keywords'. If HOW is
  1888. any other non-`nil' value, they are added at the end of
  1889. `font-lock-keywords'.
  1890. Some modes provide specialized support you can use in additional
  1891. highlighting patterns. See the variables
  1892. `c-font-lock-extra-types', `c++-font-lock-extra-types', and
  1893. `java-font-lock-extra-types', for example.
  1894. *Warning:* Major mode commands must not call
  1895. `font-lock-add-keywords' under any circumstances, either directly
  1896. or indirectly, except through their mode hooks. (Doing so would
  1897. lead to incorrect behavior for some minor modes.) They should set
  1898. up their rules for search-based fontification by setting
  1899. `font-lock-keywords'.
  1900. -- Function: font-lock-remove-keywords mode keywords
  1901. This function removes KEYWORDS from `font-lock-keywords' for the
  1902. current buffer or for major mode MODE. As in
  1903. `font-lock-add-keywords', MODE should be a major mode command name
  1904. or `nil'. All the caveats and requirements for
  1905. `font-lock-add-keywords' apply here too.
  1906. For example, the following code adds two fontification patterns for C
  1907. mode: one to fontify the word `FIXME', even in comments, and another to
  1908. fontify the words `and', `or' and `not' as keywords.
  1909. (font-lock-add-keywords 'c-mode
  1910. '(("\\<\\(FIXME\\):" 1 font-lock-warning-face prepend)
  1911. ("\\<\\(and\\|or\\|not\\)\\>" . font-lock-keyword-face)))
  1912. This example affects only C mode proper. To add the same patterns to C
  1913. mode _and_ all modes derived from it, do this instead:
  1914. (add-hook 'c-mode-hook
  1915. (lambda ()
  1916. (font-lock-add-keywords nil
  1917. '(("\\<\\(FIXME\\):" 1 font-lock-warning-face prepend)
  1918. ("\\<\\(and\\|or\\|not\\)\\>" .
  1919. font-lock-keyword-face)))))
  1920. 
  1921. File: elisp, Node: Other Font Lock Variables, Next: Levels of Font Lock, Prev: Customizing Keywords, Up: Font Lock Mode
  1922. 23.6.4 Other Font Lock Variables
  1923. --------------------------------
  1924. This section describes additional variables that a major mode can set
  1925. by means of OTHER-VARS in `font-lock-defaults' (*note Font Lock
  1926. Basics::).
  1927. -- Variable: font-lock-mark-block-function
  1928. If this variable is non-`nil', it should be a function that is
  1929. called with no arguments, to choose an enclosing range of text for
  1930. refontification for the command `M-o M-o'
  1931. (`font-lock-fontify-block').
  1932. The function should report its choice by placing the region around
  1933. it. A good choice is a range of text large enough to give proper
  1934. results, but not too large so that refontification becomes slow.
  1935. Typical values are `mark-defun' for programming modes or
  1936. `mark-paragraph' for textual modes.
  1937. -- Variable: font-lock-extra-managed-props
  1938. This variable specifies additional properties (other than
  1939. `font-lock-face') that are being managed by Font Lock mode. It is
  1940. used by `font-lock-default-unfontify-region', which normally only
  1941. manages the `font-lock-face' property. If you want Font Lock to
  1942. manage other properties as well, you must specify them in a
  1943. FACESPEC in `font-lock-keywords' as well as add them to this list.
  1944. *Note Search-based Fontification::.
  1945. -- Variable: font-lock-fontify-buffer-function
  1946. Function to use for fontifying the buffer. The default value is
  1947. `font-lock-default-fontify-buffer'.
  1948. -- Variable: font-lock-unfontify-buffer-function
  1949. Function to use for unfontifying the buffer. This is used when
  1950. turning off Font Lock mode. The default value is
  1951. `font-lock-default-unfontify-buffer'.
  1952. -- Variable: font-lock-fontify-region-function
  1953. Function to use for fontifying a region. It should take two
  1954. arguments, the beginning and end of the region, and an optional
  1955. third argument VERBOSE. If VERBOSE is non-`nil', the function
  1956. should print status messages. The default value is
  1957. `font-lock-default-fontify-region'.
  1958. -- Variable: font-lock-unfontify-region-function
  1959. Function to use for unfontifying a region. It should take two
  1960. arguments, the beginning and end of the region. The default value
  1961. is `font-lock-default-unfontify-region'.
  1962. -- Function: jit-lock-register function &optional contextual
  1963. This function tells Font Lock mode to run the Lisp function
  1964. FUNCTION any time it has to fontify or refontify part of the
  1965. current buffer. It calls FUNCTION before calling the default
  1966. fontification functions, and gives it two arguments, START and
  1967. END, which specify the region to be fontified or refontified.
  1968. The optional argument CONTEXTUAL, if non-`nil', forces Font Lock
  1969. mode to always refontify a syntactically relevant part of the
  1970. buffer, and not just the modified lines. This argument can
  1971. usually be omitted.
  1972. -- Function: jit-lock-unregister function
  1973. If FUNCTION was previously registered as a fontification function
  1974. using `jit-lock-register', this function unregisters it.
  1975. 
  1976. File: elisp, Node: Levels of Font Lock, Next: Precalculated Fontification, Prev: Other Font Lock Variables, Up: Font Lock Mode
  1977. 23.6.5 Levels of Font Lock
  1978. --------------------------
  1979. Some major modes offer three different levels of fontification. You
  1980. can define multiple levels by using a list of symbols for KEYWORDS in
  1981. `font-lock-defaults'. Each symbol specifies one level of
  1982. fontification; it is up to the user to choose one of these levels,
  1983. normally by setting `font-lock-maximum-decoration' (*note Font Lock:
  1984. (emacs)Font Lock.). The chosen level's symbol value is used to
  1985. initialize `font-lock-keywords'.
  1986. Here are the conventions for how to define the levels of
  1987. fontification:
  1988. * Level 1: highlight function declarations, file directives (such as
  1989. include or import directives), strings and comments. The idea is
  1990. speed, so only the most important and top-level components are
  1991. fontified.
  1992. * Level 2: in addition to level 1, highlight all language keywords,
  1993. including type names that act like keywords, as well as named
  1994. constant values. The idea is that all keywords (either syntactic
  1995. or semantic) should be fontified appropriately.
  1996. * Level 3: in addition to level 2, highlight the symbols being
  1997. defined in function and variable declarations, and all builtin
  1998. function names, wherever they appear.
  1999. 
  2000. File: elisp, Node: Precalculated Fontification, Next: Faces for Font Lock, Prev: Levels of Font Lock, Up: Font Lock Mode
  2001. 23.6.6 Precalculated Fontification
  2002. ----------------------------------
  2003. Some major modes such as `list-buffers' and `occur' construct the
  2004. buffer text programmatically. The easiest way for them to support Font
  2005. Lock mode is to specify the faces of text when they insert the text in
  2006. the buffer.
  2007. The way to do this is to specify the faces in the text with the
  2008. special text property `font-lock-face' (*note Special Properties::).
  2009. When Font Lock mode is enabled, this property controls the display,
  2010. just like the `face' property. When Font Lock mode is disabled,
  2011. `font-lock-face' has no effect on the display.
  2012. It is ok for a mode to use `font-lock-face' for some text and also
  2013. use the normal Font Lock machinery. But if the mode does not use the
  2014. normal Font Lock machinery, it should not set the variable
  2015. `font-lock-defaults'.
  2016. 
  2017. File: elisp, Node: Faces for Font Lock, Next: Syntactic Font Lock, Prev: Precalculated Fontification, Up: Font Lock Mode
  2018. 23.6.7 Faces for Font Lock
  2019. --------------------------
  2020. Font Lock mode can highlight using any face, but Emacs defines several
  2021. faces specifically for Font Lock to use to highlight text. These "Font
  2022. Lock faces" are listed below. They can also be used by major modes for
  2023. syntactic highlighting outside of Font Lock mode (*note Major Mode
  2024. Conventions::).
  2025. Each of these symbols is both a face name, and a variable whose
  2026. default value is the symbol itself. Thus, the default value of
  2027. `font-lock-comment-face' is `font-lock-comment-face'.
  2028. The faces are listed with descriptions of their typical usage, and in
  2029. order of greater to lesser "prominence". If a mode's syntactic
  2030. categories do not fit well with the usage descriptions, the faces can be
  2031. assigned using the ordering as a guide.
  2032. `font-lock-warning-face'
  2033. for a construct that is peculiar, or that greatly changes the
  2034. meaning of other text, like `;;;###autoload' in Emacs Lisp and
  2035. `#error' in C.
  2036. `font-lock-function-name-face'
  2037. for the name of a function being defined or declared.
  2038. `font-lock-variable-name-face'
  2039. for the name of a variable being defined or declared.
  2040. `font-lock-keyword-face'
  2041. for a keyword with special syntactic significance, like `for' and
  2042. `if' in C.
  2043. `font-lock-comment-face'
  2044. for comments.
  2045. `font-lock-comment-delimiter-face'
  2046. for comments delimiters, like `/*' and `*/' in C. On most
  2047. terminals, this inherits from `font-lock-comment-face'.
  2048. `font-lock-type-face'
  2049. for the names of user-defined data types.
  2050. `font-lock-constant-face'
  2051. for the names of constants, like `NULL' in C.
  2052. `font-lock-builtin-face'
  2053. for the names of built-in functions.
  2054. `font-lock-preprocessor-face'
  2055. for preprocessor commands. This inherits, by default, from
  2056. `font-lock-builtin-face'.
  2057. `font-lock-string-face'
  2058. for string constants.
  2059. `font-lock-doc-face'
  2060. for documentation strings in the code. This inherits, by default,
  2061. from `font-lock-string-face'.
  2062. `font-lock-negation-char-face'
  2063. for easily-overlooked negation characters.
  2064. 
  2065. File: elisp, Node: Syntactic Font Lock, Next: Multiline Font Lock, Prev: Faces for Font Lock, Up: Font Lock Mode
  2066. 23.6.8 Syntactic Font Lock
  2067. --------------------------
  2068. Syntactic fontification uses a syntax table (*note Syntax Tables::) to
  2069. find and highlight syntactically relevant text. If enabled, it runs
  2070. prior to search-based fontification. The variable
  2071. `font-lock-syntactic-face-function', documented below, determines which
  2072. syntactic constructs to highlight. There are several variables that
  2073. affect syntactic fontification; you should set them by means of
  2074. `font-lock-defaults' (*note Font Lock Basics::).
  2075. Whenever Font Lock mode performs syntactic fontification on a stretch
  2076. of text, it first calls the function specified by
  2077. `syntax-propertize-function'. Major modes can use this to apply
  2078. `syntax-table' text properties to override the buffer's syntax table in
  2079. special cases. *Note Syntax Properties::.
  2080. -- Variable: font-lock-keywords-only
  2081. If the value of this variable is non-`nil', Font Lock does not do
  2082. syntactic fontification, only search-based fontification based on
  2083. `font-lock-keywords'. It is normally set by Font Lock mode based
  2084. on the KEYWORDS-ONLY element in `font-lock-defaults'.
  2085. -- Variable: font-lock-syntax-table
  2086. This variable holds the syntax table to use for fontification of
  2087. comments and strings. It is normally set by Font Lock mode based
  2088. on the SYNTAX-ALIST element in `font-lock-defaults'. If this value
  2089. is `nil', syntactic fontification uses the buffer's syntax table
  2090. (the value returned by the function `syntax-table'; *note Syntax
  2091. Table Functions::).
  2092. -- Variable: font-lock-beginning-of-syntax-function
  2093. If this variable is non-`nil', it should be a function to move
  2094. point back to a position that is syntactically at "top level" and
  2095. outside of strings or comments. The value is normally set through
  2096. an OTHER-VARS element in `font-lock-defaults'. If it is `nil',
  2097. Font Lock uses `syntax-begin-function' to move back outside of any
  2098. comment, string, or sexp (*note Position Parse::).
  2099. This variable is semi-obsolete; we usually recommend setting
  2100. `syntax-begin-function' instead. One of its uses is to tune the
  2101. behavior of syntactic fontification, e.g. to ensure that different
  2102. kinds of strings or comments are highlighted differently.
  2103. The specified function is called with no arguments. It should
  2104. leave point at the beginning of any enclosing syntactic block.
  2105. Typical values are `beginning-of-line' (used when the start of the
  2106. line is known to be outside a syntactic block), or
  2107. `beginning-of-defun' for programming modes, or
  2108. `backward-paragraph' for textual modes.
  2109. -- Variable: font-lock-syntactic-face-function
  2110. If this variable is non-`nil', it should be a function to determine
  2111. which face to use for a given syntactic element (a string or a
  2112. comment). The value is normally set through an OTHER-VARS element
  2113. in `font-lock-defaults'.
  2114. The function is called with one argument, the parse state at point
  2115. returned by `parse-partial-sexp', and should return a face. The
  2116. default value returns `font-lock-comment-face' for comments and
  2117. `font-lock-string-face' for strings (*note Faces for Font Lock::).
  2118. 
  2119. File: elisp, Node: Multiline Font Lock, Prev: Syntactic Font Lock, Up: Font Lock Mode
  2120. 23.6.9 Multiline Font Lock Constructs
  2121. -------------------------------------
  2122. Normally, elements of `font-lock-keywords' should not match across
  2123. multiple lines; that doesn't work reliably, because Font Lock usually
  2124. scans just part of the buffer, and it can miss a multi-line construct
  2125. that crosses the line boundary where the scan starts. (The scan
  2126. normally starts at the beginning of a line.)
  2127. Making elements that match multiline constructs work properly has
  2128. two aspects: correct _identification_ and correct _rehighlighting_.
  2129. The first means that Font Lock finds all multiline constructs. The
  2130. second means that Font Lock will correctly rehighlight all the relevant
  2131. text when a multiline construct is changed--for example, if some of the
  2132. text that was previously part of a multiline construct ceases to be
  2133. part of it. The two aspects are closely related, and often getting one
  2134. of them to work will appear to make the other also work. However, for
  2135. reliable results you must attend explicitly to both aspects.
  2136. There are three ways to ensure correct identification of multiline
  2137. constructs:
  2138. * Add a function to `font-lock-extend-region-functions' that does
  2139. the _identification_ and extends the scan so that the scanned text
  2140. never starts or ends in the middle of a multiline construct.
  2141. * Use the `font-lock-fontify-region-function' hook similarly to
  2142. extend the scan so that the scanned text never starts or ends in
  2143. the middle of a multiline construct.
  2144. * Somehow identify the multiline construct right when it gets
  2145. inserted into the buffer (or at any point after that but before
  2146. font-lock tries to highlight it), and mark it with a
  2147. `font-lock-multiline' which will instruct font-lock not to start
  2148. or end the scan in the middle of the construct.
  2149. There are three ways to do rehighlighting of multiline constructs:
  2150. * Place a `font-lock-multiline' property on the construct. This
  2151. will rehighlight the whole construct if any part of it is changed.
  2152. In some cases you can do this automatically by setting the
  2153. `font-lock-multiline' variable, which see.
  2154. * Make sure `jit-lock-contextually' is set and rely on it doing its
  2155. job. This will only rehighlight the part of the construct that
  2156. follows the actual change, and will do it after a short delay.
  2157. This only works if the highlighting of the various parts of your
  2158. multiline construct never depends on text in subsequent lines.
  2159. Since `jit-lock-contextually' is activated by default, this can be
  2160. an attractive solution.
  2161. * Place a `jit-lock-defer-multiline' property on the construct.
  2162. This works only if `jit-lock-contextually' is used, and with the
  2163. same delay before rehighlighting, but like `font-lock-multiline',
  2164. it also handles the case where highlighting depends on subsequent
  2165. lines.
  2166. * Menu:
  2167. * Font Lock Multiline:: Marking multiline chunks with a text property.
  2168. * Region to Refontify:: Controlling which region gets refontified
  2169. after a buffer change.
  2170. 
  2171. File: elisp, Node: Font Lock Multiline, Next: Region to Refontify, Up: Multiline Font Lock
  2172. 23.6.9.1 Font Lock Multiline
  2173. ............................
  2174. One way to ensure reliable rehighlighting of multiline Font Lock
  2175. constructs is to put on them the text property `font-lock-multiline'.
  2176. It should be present and non-`nil' for text that is part of a multiline
  2177. construct.
  2178. When Font Lock is about to highlight a range of text, it first
  2179. extends the boundaries of the range as necessary so that they do not
  2180. fall within text marked with the `font-lock-multiline' property. Then
  2181. it removes any `font-lock-multiline' properties from the range, and
  2182. highlights it. The highlighting specification (mostly
  2183. `font-lock-keywords') must reinstall this property each time, whenever
  2184. it is appropriate.
  2185. *Warning:* don't use the `font-lock-multiline' property on large
  2186. ranges of text, because that will make rehighlighting slow.
  2187. -- Variable: font-lock-multiline
  2188. If the `font-lock-multiline' variable is set to `t', Font Lock
  2189. will try to add the `font-lock-multiline' property automatically
  2190. on multiline constructs. This is not a universal solution,
  2191. however, since it slows down Font Lock somewhat. It can miss some
  2192. multiline constructs, or make the property larger or smaller than
  2193. necessary.
  2194. For elements whose MATCHER is a function, the function should
  2195. ensure that submatch 0 covers the whole relevant multiline
  2196. construct, even if only a small subpart will be highlighted. It
  2197. is often just as easy to add the `font-lock-multiline' property by
  2198. hand.
  2199. The `font-lock-multiline' property is meant to ensure proper
  2200. refontification; it does not automatically identify new multiline
  2201. constructs. Identifying the requires that Font Lock mode operate on
  2202. large enough chunks at a time. This will happen by accident on many
  2203. cases, which may give the impression that multiline constructs magically
  2204. work. If you set the `font-lock-multiline' variable non-`nil', this
  2205. impression will be even stronger, since the highlighting of those
  2206. constructs which are found will be properly updated from then on. But
  2207. that does not work reliably.
  2208. To find multiline constructs reliably, you must either manually place
  2209. the `font-lock-multiline' property on the text before Font Lock mode
  2210. looks at it, or use `font-lock-fontify-region-function'.
  2211. 
  2212. File: elisp, Node: Region to Refontify, Prev: Font Lock Multiline, Up: Multiline Font Lock
  2213. 23.6.9.2 Region to Fontify after a Buffer Change
  2214. ................................................
  2215. When a buffer is changed, the region that Font Lock refontifies is by
  2216. default the smallest sequence of whole lines that spans the change.
  2217. While this works well most of the time, sometimes it doesn't--for
  2218. example, when a change alters the syntactic meaning of text on an
  2219. earlier line.
  2220. You can enlarge (or even reduce) the region to refontify by setting
  2221. the following variable:
  2222. -- Variable: font-lock-extend-after-change-region-function
  2223. This buffer-local variable is either `nil' or a function for Font
  2224. Lock mode to call to determine the region to scan and fontify.
  2225. The function is given three parameters, the standard BEG, END, and
  2226. OLD-LEN from `after-change-functions' (*note Change Hooks::). It
  2227. should return either a cons of the beginning and end buffer
  2228. positions (in that order) of the region to fontify, or `nil'
  2229. (which means choose the region in the standard way). This
  2230. function needs to preserve point, the match-data, and the current
  2231. restriction. The region it returns may start or end in the middle
  2232. of a line.
  2233. Since this function is called after every buffer change, it should
  2234. be reasonably fast.
  2235. 
  2236. File: elisp, Node: Auto-Indentation, Next: Desktop Save Mode, Prev: Font Lock Mode, Up: Modes
  2237. 23.7 Automatic Indentation of code
  2238. ==================================
  2239. For programming languages, an important feature of a major mode is to
  2240. provide automatic indentation. This is controlled in Emacs by
  2241. `indent-line-function' (*note Mode-Specific Indent::). Writing a good
  2242. indentation function can be difficult and to a large extent it is still
  2243. a black art.
  2244. Many major mode authors will start by writing a simple indentation
  2245. function that works for simple cases, for example by comparing with the
  2246. indentation of the previous text line. For most programming languages
  2247. that are not really line-based, this tends to scale very poorly:
  2248. improving such a function to let it handle more diverse situations tends
  2249. to become more and more difficult, resulting in the end with a large,
  2250. complex, unmaintainable indentation function which nobody dares to
  2251. touch.
  2252. A good indentation function will usually need to actually parse the
  2253. text, according to the syntax of the language. Luckily, it is not
  2254. necessary to parse the text in as much detail as would be needed for a
  2255. compiler, but on the other hand, the parser embedded in the indentation
  2256. code will want to be somewhat friendly to syntactically incorrect code.
  2257. Good maintainable indentation functions usually fall into two
  2258. categories: either parsing forward from some "safe" starting point
  2259. until the position of interest, or parsing backward from the position
  2260. of interest. Neither of the two is a clearly better choice than the
  2261. other: parsing backward is often more difficult than parsing forward
  2262. because programming languages are designed to be parsed forward, but
  2263. for the purpose of indentation it has the advantage of not needing to
  2264. guess a "safe" starting point, and it generally enjoys the property
  2265. that only a minimum of text will be analyzed to decide the indentation
  2266. of a line, so indentation will tend to be unaffected by syntax errors in
  2267. some earlier unrelated piece of code. Parsing forward on the other hand
  2268. is usually easier and has the advantage of making it possible to
  2269. reindent efficiently a whole region at a time, with a single parse.
  2270. Rather than write your own indentation function from scratch, it is
  2271. often preferable to try and reuse some existing ones or to rely on a
  2272. generic indentation engine. There are sadly few such engines. The
  2273. CC-mode indentation code (used with C, C++, Java, Awk and a few other
  2274. such modes) has been made more generic over the years, so if your
  2275. language seems somewhat similar to one of those languages, you might
  2276. try to use that engine. Another one is SMIE which takes an approach in
  2277. the spirit of Lisp sexps and adapts it to non-Lisp languages.
  2278. * Menu:
  2279. * SMIE:: A simple minded indentation engine.
  2280. 
  2281. File: elisp, Node: SMIE, Up: Auto-Indentation
  2282. 23.7.1 Simple Minded Indentation Engine
  2283. ---------------------------------------
  2284. SMIE is a package that provides a generic navigation and indentation
  2285. engine. Based on a very simple parser using an "operator precedence
  2286. grammar", it lets major modes extend the sexp-based navigation of Lisp
  2287. to non-Lisp languages as well as provide a simple to use but reliable
  2288. auto-indentation.
  2289. Operator precedence grammar is a very primitive technology for
  2290. parsing compared to some of the more common techniques used in
  2291. compilers. It has the following characteristics: its parsing power is
  2292. very limited, and it is largely unable to detect syntax errors, but it
  2293. has the advantage of being algorithmically efficient and able to parse
  2294. forward just as well as backward. In practice that means that SMIE can
  2295. use it for indentation based on backward parsing, that it can provide
  2296. both `forward-sexp' and `backward-sexp' functionality, and that it will
  2297. naturally work on syntactically incorrect code without any extra
  2298. effort. The downside is that it also means that most programming
  2299. languages cannot be parsed correctly using SMIE, at least not without
  2300. resorting to some special tricks (*note SMIE Tricks::).
  2301. * Menu:
  2302. * SMIE setup:: SMIE setup and features.
  2303. * Operator Precedence Grammars:: A very simple parsing technique.
  2304. * SMIE Grammar:: Defining the grammar of a language.
  2305. * SMIE Lexer:: Defining tokens.
  2306. * SMIE Tricks:: Working around the parser's limitations.
  2307. * SMIE Indentation:: Specifying indentation rules.
  2308. * SMIE Indentation Helpers:: Helper functions for indentation rules.
  2309. * SMIE Indentation Example:: Sample indentation rules.
  2310. 
  2311. File: elisp, Node: SMIE setup, Next: Operator Precedence Grammars, Up: SMIE
  2312. 23.7.1.1 SMIE Setup and Features
  2313. ................................
  2314. SMIE is meant to be a one-stop shop for structural navigation and
  2315. various other features which rely on the syntactic structure of code, in
  2316. particular automatic indentation. The main entry point is `smie-setup'
  2317. which is a function typically called while setting up a major mode.
  2318. -- Function: smie-setup grammar rules-function &rest keywords
  2319. Setup SMIE navigation and indentation. GRAMMAR is a grammar table
  2320. generated by `smie-prec2->grammar'. RULES-FUNCTION is a set of
  2321. indentation rules for use on `smie-rules-function'. KEYWORDS are
  2322. additional arguments, which can include the following keywords:
  2323. * `:forward-token' FUN: Specify the forward lexer to use.
  2324. * `:backward-token' FUN: Specify the backward lexer to use.
  2325. Calling this function is sufficient to make commands such as
  2326. `forward-sexp', `backward-sexp', and `transpose-sexps' be able to
  2327. properly handle structural elements other than just the paired
  2328. parentheses already handled by syntax tables. For example, if the
  2329. provided grammar is precise enough, `transpose-sexps' can correctly
  2330. transpose the two arguments of a `+' operator, taking into account the
  2331. precedence rules of the language.
  2332. Calling `smie-setup' is also sufficient to make TAB indentation work
  2333. in the expected way, extends `blink-matching-paren' to apply to
  2334. elements like `begin...end', and provides some commands that you can
  2335. bind in the major mode keymap.
  2336. -- Command: smie-close-block
  2337. This command closes the most recently opened (and not yet closed)
  2338. block.
  2339. -- Command: smie-down-list &optional arg
  2340. This command is like `down-list' but it also pays attention to
  2341. nesting of tokens other than parentheses, such as `begin...end'.
  2342. 
  2343. File: elisp, Node: Operator Precedence Grammars, Next: SMIE Grammar, Prev: SMIE setup, Up: SMIE
  2344. 23.7.1.2 Operator Precedence Grammars
  2345. .....................................
  2346. SMIE's precedence grammars simply give to each token a pair of
  2347. precedences: the left-precedence and the right-precedence. We say `T1
  2348. < T2' if the right-precedence of token `T1' is less than the
  2349. left-precedence of token `T2'. A good way to read this `<' is as a
  2350. kind of parenthesis: if we find `... T1 something T2 ...' then that
  2351. should be parsed as `... T1 (something T2 ...' rather than as `... T1
  2352. something) T2 ...'. The latter interpretation would be the case if we
  2353. had `T1 > T2'. If we have `T1 = T2', it means that token T2 follows
  2354. token T1 in the same syntactic construction, so typically we have
  2355. `"begin" = "end"'. Such pairs of precedences are sufficient to express
  2356. left-associativity or right-associativity of infix operators, nesting
  2357. of tokens like parentheses and many other cases.
  2358. -- Function: smie-prec2->grammar table
  2359. This function takes a _prec2_ grammar TABLE and returns an alist
  2360. suitable for use in `smie-setup'. The _prec2_ TABLE is itself
  2361. meant to be built by one of the functions below.
  2362. -- Function: smie-merge-prec2s &rest tables
  2363. This function takes several _prec2_ TABLES and merges them into a
  2364. new _prec2_ table.
  2365. -- Function: smie-precs->prec2 precs
  2366. This function builds a _prec2_ table from a table of precedences
  2367. PRECS. PRECS should be a list, sorted by precedence (for example
  2368. `"+"' will come before `"*"'), of elements of the form `(ASSOC OP
  2369. ...)', where each OP is a token that acts as an operator; ASSOC is
  2370. their associativity, which can be either `left', `right', `assoc',
  2371. or `nonassoc'. All operators in a given element share the same
  2372. precedence level and associativity.
  2373. -- Function: smie-bnf->prec2 bnf &rest resolvers
  2374. This function lets you specify the grammar using a BNF notation.
  2375. It accepts a BNF description of the grammar along with a set of
  2376. conflict resolution rules RESOLVERS, and returns a _prec2_ table.
  2377. BNF is a list of nonterminal definitions of the form `(NONTERM
  2378. RHS1 RHS2 ...)' where each RHS is a (non-empty) list of terminals
  2379. (aka tokens) or non-terminals.
  2380. Not all grammars are accepted:
  2381. * An RHS cannot be an empty list (an empty list is never needed,
  2382. since SMIE allows all non-terminals to match the empty string
  2383. anyway).
  2384. * An RHS cannot have 2 consecutive non-terminals: each pair of
  2385. non-terminals needs to be separated by a terminal (aka token).
  2386. This is a fundamental limitation of operator precedence
  2387. grammars.
  2388. Additionally, conflicts can occur:
  2389. * The returned _prec2_ table holds constraints between pairs of
  2390. tokens, and for any given pair only one constraint can be
  2391. present: T1 < T2, T1 = T2, or T1 > T2.
  2392. * A token can be an `opener' (something similar to an
  2393. open-paren), a `closer' (like a close-paren), or `neither' of
  2394. the two (e.g. an infix operator, or an inner token like
  2395. `"else"').
  2396. Precedence conflicts can be resolved via RESOLVERS, which is a
  2397. list of _precs_ tables (see `smie-precs->prec2'): for each
  2398. precedence conflict, if those `precs' tables specify a particular
  2399. constraint, then the conflict is resolved by using this constraint
  2400. instead, else a conflict is reported and one of the conflicting
  2401. constraints is picked arbitrarily and the others are simply
  2402. ignored.
  2403. 
  2404. File: elisp, Node: SMIE Grammar, Next: SMIE Lexer, Prev: Operator Precedence Grammars, Up: SMIE
  2405. 23.7.1.3 Defining the Grammar of a Language
  2406. ...........................................
  2407. The usual way to define the SMIE grammar of a language is by defining a
  2408. new global variable that holds the precedence table by giving a set of
  2409. BNF rules. For example, the grammar definition for a small Pascal-like
  2410. language could look like:
  2411. (require 'smie)
  2412. (defvar sample-smie-grammar
  2413. (smie-prec2->grammar
  2414. (smie-bnf->prec2
  2415. '((id)
  2416. (inst ("begin" insts "end")
  2417. ("if" exp "then" inst "else" inst)
  2418. (id ":=" exp)
  2419. (exp))
  2420. (insts (insts ";" insts) (inst))
  2421. (exp (exp "+" exp)
  2422. (exp "*" exp)
  2423. ("(" exps ")"))
  2424. (exps (exps "," exps) (exp)))
  2425. '((assoc ";"))
  2426. '((assoc ","))
  2427. '((assoc "+") (assoc "*")))))
  2428. A few things to note:
  2429. * The above grammar does not explicitly mention the syntax of
  2430. function calls: SMIE will automatically allow any sequence of
  2431. sexps, such as identifiers, balanced parentheses, or `begin ...
  2432. end' blocks to appear anywhere anyway.
  2433. * The grammar category `id' has no right hand side: this does not
  2434. mean that it can match only the empty string, since as mentioned
  2435. any sequence of sexps can appear anywhere anyway.
  2436. * Because non terminals cannot appear consecutively in the BNF
  2437. grammar, it is difficult to correctly handle tokens that act as
  2438. terminators, so the above grammar treats `";"' as a statement
  2439. _separator_ instead, which SMIE can handle very well.
  2440. * Separators used in sequences (such as `","' and `";"' above) are
  2441. best defined with BNF rules such as `(foo (foo "separator" foo)
  2442. ...)' which generate precedence conflicts which are then resolved
  2443. by giving them an explicit `(assoc "separator")'.
  2444. * The `("(" exps ")")' rule was not needed to pair up parens, since
  2445. SMIE will pair up any characters that are marked as having paren
  2446. syntax in the syntax table. What this rule does instead (together
  2447. with the definition of `exps') is to make it clear that `","'
  2448. should not appear outside of parentheses.
  2449. * Rather than have a single _precs_ table to resolve conflicts, it is
  2450. preferable to have several tables, so as to let the BNF part of the
  2451. grammar specify relative precedences where possible.
  2452. * Unless there is a very good reason to prefer `left' or `right', it
  2453. is usually preferable to mark operators as associative, using
  2454. `assoc'. For that reason `"+"' and `"*"' are defined above as
  2455. `assoc', although the language defines them formally as left
  2456. associative.
  2457. 
  2458. File: elisp, Node: SMIE Lexer, Next: SMIE Tricks, Prev: SMIE Grammar, Up: SMIE
  2459. 23.7.1.4 Defining Tokens
  2460. ........................
  2461. SMIE comes with a predefined lexical analyzer which uses syntax tables
  2462. in the following way: any sequence of characters that have word or
  2463. symbol syntax is considered a token, and so is any sequence of
  2464. characters that have punctuation syntax. This default lexer is often a
  2465. good starting point but is rarely actually correct for any given
  2466. language. For example, it will consider `"2,+3"' to be composed of 3
  2467. tokens: `"2"', `",+"', and `"3"'.
  2468. To describe the lexing rules of your language to SMIE, you need 2
  2469. functions, one to fetch the next token, and another to fetch the
  2470. previous token. Those functions will usually first skip whitespace and
  2471. comments and then look at the next chunk of text to see if it is a
  2472. special token. If so it should skip the token and return a description
  2473. of this token. Usually this is simply the string extracted from the
  2474. buffer, but it can be anything you want. For example:
  2475. (defvar sample-keywords-regexp
  2476. (regexp-opt '("+" "*" "," ";" ">" ">=" "<" "<=" ":=" "=")))
  2477. (defun sample-smie-forward-token ()
  2478. (forward-comment (point-max))
  2479. (cond
  2480. ((looking-at sample-keywords-regexp)
  2481. (goto-char (match-end 0))
  2482. (match-string-no-properties 0))
  2483. (t (buffer-substring-no-properties
  2484. (point)
  2485. (progn (skip-syntax-forward "w_")
  2486. (point))))))
  2487. (defun sample-smie-backward-token ()
  2488. (forward-comment (- (point)))
  2489. (cond
  2490. ((looking-back sample-keywords-regexp (- (point) 2) t)
  2491. (goto-char (match-beginning 0))
  2492. (match-string-no-properties 0))
  2493. (t (buffer-substring-no-properties
  2494. (point)
  2495. (progn (skip-syntax-backward "w_")
  2496. (point))))))
  2497. Notice how those lexers return the empty string when in front of
  2498. parentheses. This is because SMIE automatically takes care of the
  2499. parentheses defined in the syntax table. More specifically if the lexer
  2500. returns nil or an empty string, SMIE tries to handle the corresponding
  2501. text as a sexp according to syntax tables.
  2502. 
  2503. File: elisp, Node: SMIE Tricks, Next: SMIE Indentation, Prev: SMIE Lexer, Up: SMIE
  2504. 23.7.1.5 Living With a Weak Parser
  2505. ..................................
  2506. The parsing technique used by SMIE does not allow tokens to behave
  2507. differently in different contexts. For most programming languages, this
  2508. manifests itself by precedence conflicts when converting the BNF
  2509. grammar.
  2510. Sometimes, those conflicts can be worked around by expressing the
  2511. grammar slightly differently. For example, for Modula-2 it might seem
  2512. natural to have a BNF grammar that looks like this:
  2513. ...
  2514. (inst ("IF" exp "THEN" insts "ELSE" insts "END")
  2515. ("CASE" exp "OF" cases "END")
  2516. ...)
  2517. (cases (cases "|" cases)
  2518. (caselabel ":" insts)
  2519. ("ELSE" insts))
  2520. ...
  2521. But this will create conflicts for `"ELSE"': on the one hand, the IF
  2522. rule implies (among many other things) that `"ELSE" = "END"'; but on
  2523. the other hand, since `"ELSE"' appears within `cases', which appears
  2524. left of `"END"', we also have `"ELSE" > "END"'. We can solve the
  2525. conflict either by using:
  2526. ...
  2527. (inst ("IF" exp "THEN" insts "ELSE" insts "END")
  2528. ("CASE" exp "OF" cases "END")
  2529. ("CASE" exp "OF" cases "ELSE" insts "END")
  2530. ...)
  2531. (cases (cases "|" cases) (caselabel ":" insts))
  2532. ...
  2533. or
  2534. ...
  2535. (inst ("IF" exp "THEN" else "END")
  2536. ("CASE" exp "OF" cases "END")
  2537. ...)
  2538. (else (insts "ELSE" insts))
  2539. (cases (cases "|" cases) (caselabel ":" insts) (else))
  2540. ...
  2541. Reworking the grammar to try and solve conflicts has its downsides,
  2542. tho, because SMIE assumes that the grammar reflects the logical
  2543. structure of the code, so it is preferable to keep the BNF closer to
  2544. the intended abstract syntax tree.
  2545. Other times, after careful consideration you may conclude that those
  2546. conflicts are not serious and simply resolve them via the RESOLVERS
  2547. argument of `smie-bnf->prec2'. Usually this is because the grammar is
  2548. simply ambiguous: the conflict does not affect the set of programs
  2549. described by the grammar, but only the way those programs are parsed.
  2550. This is typically the case for separators and associative infix
  2551. operators, where you want to add a resolver like `'((assoc "|"))'.
  2552. Another case where this can happen is for the classic _dangling else_
  2553. problem, where you will use `'((assoc "else" "then"))'. It can also
  2554. happen for cases where the conflict is real and cannot really be
  2555. resolved, but it is unlikely to pose a problem in practice.
  2556. Finally, in many cases some conflicts will remain despite all
  2557. efforts to restructure the grammar. Do not despair: while the parser
  2558. cannot be made more clever, you can make the lexer as smart as you
  2559. want. So, the solution is then to look at the tokens involved in the
  2560. conflict and to split one of those tokens into 2 (or more) different
  2561. tokens. E.g. if the grammar needs to distinguish between two
  2562. incompatible uses of the token `"begin"', make the lexer return
  2563. different tokens (say `"begin-fun"' and `"begin-plain"') depending on
  2564. which kind of `"begin"' it finds. This pushes the work of
  2565. distinguishing the different cases to the lexer, which will thus have
  2566. to look at the surrounding text to find ad-hoc clues.
  2567. 
  2568. File: elisp, Node: SMIE Indentation, Next: SMIE Indentation Helpers, Prev: SMIE Tricks, Up: SMIE
  2569. 23.7.1.6 Specifying Indentation Rules
  2570. .....................................
  2571. Based on the provided grammar, SMIE will be able to provide automatic
  2572. indentation without any extra effort. But in practice, this default
  2573. indentation style will probably not be good enough. You will want to
  2574. tweak it in many different cases.
  2575. SMIE indentation is based on the idea that indentation rules should
  2576. be as local as possible. To this end, it relies on the idea of
  2577. _virtual_ indentation, which is the indentation that a particular
  2578. program point would have if it were at the beginning of a line. Of
  2579. course, if that program point is indeed at the beginning of a line, its
  2580. virtual indentation is its current indentation. But if not, then SMIE
  2581. uses the indentation algorithm to compute the virtual indentation of
  2582. that point. Now in practice, the virtual indentation of a program
  2583. point does not have to be identical to the indentation it would have if
  2584. we inserted a newline before it. To see how this works, the SMIE rule
  2585. for indentation after a `{' in C does not care whether the `{' is
  2586. standing on a line of its own or is at the end of the preceding line.
  2587. Instead, these different cases are handled in the indentation rule that
  2588. decides how to indent before a `{'.
  2589. Another important concept is the notion of _parent_: The _parent_ of
  2590. a token, is the head token of the nearest enclosing syntactic
  2591. construct. For example, the parent of an `else' is the `if' to which
  2592. it belongs, and the parent of an `if', in turn, is the lead token of
  2593. the surrounding construct. The command `backward-sexp' jumps from a
  2594. token to its parent, but there are some caveats: for _openers_ (tokens
  2595. which start a construct, like `if'), you need to start with point
  2596. before the token, while for others you need to start with point after
  2597. the token. `backward-sexp' stops with point before the parent token if
  2598. that is the _opener_ of the token of interest, and otherwise it stops
  2599. with point after the parent token.
  2600. SMIE indentation rules are specified using a function that takes two
  2601. arguments METHOD and ARG where the meaning of ARG and the expected
  2602. return value depend on METHOD.
  2603. METHOD can be:
  2604. * `:after', in which case ARG is a token and the function should
  2605. return the OFFSET to use for indentation after ARG.
  2606. * `:before', in which case ARG is a token and the function should
  2607. return the OFFSET to use to indent ARG itself.
  2608. * `:elem', in which case the function should return either the offset
  2609. to use to indent function arguments (if ARG is the symbol `arg')
  2610. or the basic indentation step (if ARG is the symbol `basic').
  2611. * `:list-intro', in which case ARG is a token and the function
  2612. should return non-`nil' if the token is followed by a list of
  2613. expressions (not separated by any token) rather than an expression.
  2614. When ARG is a token, the function is called with point just before
  2615. that token. A return value of nil always means to fallback on the
  2616. default behavior, so the function should return nil for arguments it
  2617. does not expect.
  2618. OFFSET can be:
  2619. * `nil': use the default indentation rule.
  2620. * `(column . COLUMN)': indent to column COLUMN.
  2621. * NUMBER: offset by NUMBER, relative to a base token which is the
  2622. current token for `:after' and its parent for `:before'.
  2623. 
  2624. File: elisp, Node: SMIE Indentation Helpers, Next: SMIE Indentation Example, Prev: SMIE Indentation, Up: SMIE
  2625. 23.7.1.7 Helper Functions for Indentation Rules
  2626. ...............................................
  2627. SMIE provides various functions designed specifically for use in the
  2628. indentation rules function (several of those functions break if used in
  2629. another context). These functions all start with the prefix
  2630. `smie-rule-'.
  2631. -- Function: smie-rule-bolp
  2632. Return non-`nil' if the current token is the first on the line.
  2633. -- Function: smie-rule-hanging-p
  2634. Return non-`nil' if the current token is _hanging_. A token is
  2635. _hanging_ if it is the last token on the line and if it is
  2636. preceded by other tokens: a lone token on a line is not hanging.
  2637. -- Function: smie-rule-next-p &rest tokens
  2638. Return non-`nil' if the next token is among TOKENS.
  2639. -- Function: smie-rule-prev-p &rest tokens
  2640. Return non-`nil' if the previous token is among TOKENS.
  2641. -- Function: smie-rule-parent-p &rest parents
  2642. Return non-`nil' if the current token's parent is among PARENTS.
  2643. -- Function: smie-rule-sibling-p
  2644. Return non-`nil' if the current token's parent is actually a
  2645. sibling. This is the case for example when the parent of a `","'
  2646. is just the previous `","'.
  2647. -- Function: smie-rule-parent &optional offset
  2648. Return the proper offset to align the current token with the
  2649. parent. If non-`nil', OFFSET should be an integer giving an
  2650. additional offset to apply.
  2651. -- Function: smie-rule-separator method
  2652. Indent current token as a _separator_.
  2653. By _separator_, we mean here a token whose sole purpose is to
  2654. separate various elements within some enclosing syntactic
  2655. construct, and which does not have any semantic significance in
  2656. itself (i.e. it would typically not exist as a node in an abstract
  2657. syntax tree).
  2658. Such a token is expected to have an associative syntax and be
  2659. closely tied to its syntactic parent. Typical examples are `","'
  2660. in lists of arguments (enclosed inside parentheses), or `";"' in
  2661. sequences of instructions (enclosed in a `{...}' or `begin...end'
  2662. block).
  2663. METHOD should be the method name that was passed to
  2664. `smie-rules-function'.
  2665. 
  2666. File: elisp, Node: SMIE Indentation Example, Prev: SMIE Indentation Helpers, Up: SMIE
  2667. 23.7.1.8 Sample Indentation Rules
  2668. .................................
  2669. Here is an example of an indentation function:
  2670. (defun sample-smie-rules (kind token)
  2671. (pcase (cons kind token)
  2672. (`(:elem . basic) sample-indent-basic)
  2673. (`(,_ . ",") (smie-rule-separator kind))
  2674. (`(:after . ":=") sample-indent-basic)
  2675. (`(:before . ,(or `"begin" `"(" `"{")))
  2676. (if (smie-rule-hanging-p) (smie-rule-parent)))
  2677. (`(:before . "if")
  2678. (and (not (smie-rule-bolp)) (smie-rule-prev-p "else")
  2679. (smie-rule-parent)))))
  2680. A few things to note:
  2681. * The first case indicates the basic indentation increment to use.
  2682. If `sample-indent-basic' is nil, then SMIE uses the global setting
  2683. `smie-indent-basic'. The major mode could have set
  2684. `smie-indent-basic' buffer-locally instead, but that is
  2685. discouraged.
  2686. * The rule for the token `","' make SMIE try to be more clever when
  2687. the comma separator is placed at the beginning of lines. It tries
  2688. to outdent the separator so as to align the code after the comma;
  2689. for example:
  2690. x = longfunctionname (
  2691. arg1
  2692. , arg2
  2693. );
  2694. * The rule for indentation after `":="' exists because otherwise
  2695. SMIE would treat `":="' as an infix operator and would align the
  2696. right argument with the left one.
  2697. * The rule for indentation before `"begin"' is an example of the use
  2698. of virtual indentation: This rule is used only when `"begin"' is
  2699. hanging, which can happen only when `"begin"' is not at the
  2700. beginning of a line. So this is not used when indenting `"begin"'
  2701. itself but only when indenting something relative to this
  2702. `"begin"'. Concretely, this rule changes the indentation from:
  2703. if x > 0 then begin
  2704. dosomething(x);
  2705. end
  2706. to
  2707. if x > 0 then begin
  2708. dosomething(x);
  2709. end
  2710. * The rule for indentation before `"if"' is similar to the one for
  2711. `"begin"', but where the purpose is to treat `"else if"' as a
  2712. single unit, so as to align a sequence of tests rather than indent
  2713. each test further to the right. This function does this only in
  2714. the case where the `"if"' is not placed on a separate line, hence
  2715. the `smie-rule-bolp' test.
  2716. If we know that the `"else"' is always aligned with its `"if"' and
  2717. is always at the beginning of a line, we can use a more efficient
  2718. rule:
  2719. ((equal token "if")
  2720. (and (not (smie-rule-bolp))
  2721. (smie-rule-prev-p "else")
  2722. (save-excursion
  2723. (sample-smie-backward-token)
  2724. (cons 'column (current-column)))))
  2725. The advantage of this formulation is that it reuses the
  2726. indentation of the previous `"else"', rather than going all the
  2727. way back to the first `"if"' of the sequence.
  2728. 
  2729. File: elisp, Node: Desktop Save Mode, Prev: Auto-Indentation, Up: Modes
  2730. 23.8 Desktop Save Mode
  2731. ======================
  2732. "Desktop Save Mode" is a feature to save the state of Emacs from one
  2733. session to another. The user-level commands for using Desktop Save
  2734. Mode are described in the GNU Emacs Manual (*note Saving Emacs
  2735. Sessions: (emacs)Saving Emacs Sessions.). Modes whose buffers visit a
  2736. file, don't have to do anything to use this feature.
  2737. For buffers not visiting a file to have their state saved, the major
  2738. mode must bind the buffer local variable `desktop-save-buffer' to a
  2739. non-`nil' value.
  2740. -- Variable: desktop-save-buffer
  2741. If this buffer-local variable is non-`nil', the buffer will have
  2742. its state saved in the desktop file at desktop save. If the value
  2743. is a function, it is called at desktop save with argument
  2744. DESKTOP-DIRNAME, and its value is saved in the desktop file along
  2745. with the state of the buffer for which it was called. When file
  2746. names are returned as part of the auxiliary information, they
  2747. should be formatted using the call
  2748. (desktop-file-name FILE-NAME DESKTOP-DIRNAME)
  2749. For buffers not visiting a file to be restored, the major mode must
  2750. define a function to do the job, and that function must be listed in
  2751. the alist `desktop-buffer-mode-handlers'.
  2752. -- Variable: desktop-buffer-mode-handlers
  2753. Alist with elements
  2754. (MAJOR-MODE . RESTORE-BUFFER-FUNCTION)
  2755. The function RESTORE-BUFFER-FUNCTION will be called with argument
  2756. list
  2757. (BUFFER-FILE-NAME BUFFER-NAME DESKTOP-BUFFER-MISC)
  2758. and it should return the restored buffer. Here
  2759. DESKTOP-BUFFER-MISC is the value returned by the function
  2760. optionally bound to `desktop-save-buffer'.
  2761. 
  2762. File: elisp, Node: Documentation, Next: Files, Prev: Modes, Up: Top
  2763. 24 Documentation
  2764. ****************
  2765. GNU Emacs has convenient built-in help facilities, most of which derive
  2766. their information from documentation strings associated with functions
  2767. and variables. This chapter describes how to access documentation
  2768. strings in Lisp programs. *Note Documentation Tips::, for how to write
  2769. good documentation strings.
  2770. Note that the documentation strings for Emacs are not the same thing
  2771. as the Emacs manual. Manuals have their own source files, written in
  2772. the Texinfo language; documentation strings are specified in the
  2773. definitions of the functions and variables they apply to. A collection
  2774. of documentation strings is not sufficient as a manual because a good
  2775. manual is not organized in that fashion; it is organized in terms of
  2776. topics of discussion.
  2777. For commands to display documentation strings, see *note Help:
  2778. (emacs)Help.
  2779. * Menu:
  2780. * Documentation Basics:: Where doc strings are defined and stored.
  2781. * Accessing Documentation:: How Lisp programs can access doc strings.
  2782. * Keys in Documentation:: Substituting current key bindings.
  2783. * Describing Characters:: Making printable descriptions of
  2784. non-printing characters and key sequences.
  2785. * Help Functions:: Subroutines used by Emacs help facilities.
  2786. 
  2787. File: elisp, Node: Documentation Basics, Next: Accessing Documentation, Up: Documentation
  2788. 24.1 Documentation Basics
  2789. =========================
  2790. A documentation string is written using the Lisp syntax for strings,
  2791. with double-quote characters surrounding the text of the string. This
  2792. is because it really is a Lisp string object. The string serves as
  2793. documentation when it is written in the proper place in the definition
  2794. of a function or variable. In a function definition, the documentation
  2795. string follows the argument list. In a variable definition, the
  2796. documentation string follows the initial value of the variable.
  2797. When you write a documentation string, make the first line a
  2798. complete sentence (or two complete sentences) that briefly describes
  2799. what the function or variable does. Some commands, such as `apropos',
  2800. show only the first line of a multi-line documentation string. Also,
  2801. you should not indent the second line of a documentation string, if it
  2802. has one, because that looks odd when you use `C-h f'
  2803. (`describe-function') or `C-h v' (`describe-variable') to view the
  2804. documentation string. There are many other conventions for
  2805. documentation strings; see *note Documentation Tips::.
  2806. Documentation strings can contain several special substrings, which
  2807. stand for key bindings to be looked up in the current keymaps when the
  2808. documentation is displayed. This allows documentation strings to refer
  2809. to the keys for related commands and be accurate even when a user
  2810. rearranges the key bindings. (*Note Keys in Documentation::.)
  2811. Emacs Lisp mode fills documentation strings to the width specified
  2812. by `emacs-lisp-docstring-fill-column'.
  2813. Exactly where a documentation string is stored depends on how its
  2814. function or variable was defined or loaded into memory:
  2815. * When you define a function (*note Lambda Expressions::, and *note
  2816. Function Documentation::), the documentation string is stored in
  2817. the function definition itself. You can also put function
  2818. documentation in the `function-documentation' property of a
  2819. function name. That is useful for function definitions which can't
  2820. hold a documentation string, such as keyboard macros.
  2821. * When you define a variable with a `defvar' or related form (*note
  2822. Defining Variables::), the documentation is stored in the
  2823. variable's `variable-documentation' property.
  2824. * To save memory, the documentation for preloaded functions and
  2825. variables (including primitive functions and autoloaded functions)
  2826. is not kept in memory, but in the file `emacs/etc/DOC-VERSION',
  2827. where VERSION is the Emacs version number (*note Version Info::).
  2828. * When a function or variable is loaded from a byte-compiled file
  2829. during the Emacs session, its documentation string is not loaded
  2830. into memory. Instead, Emacs looks it up in the byte-compiled file
  2831. as needed. *Note Docs and Compilation::.
  2832. Regardless of where the documentation string is stored, you can
  2833. retrieve it using the `documentation' or `documentation-property'
  2834. function, described in the next section.
  2835. 
  2836. File: elisp, Node: Accessing Documentation, Next: Keys in Documentation, Prev: Documentation Basics, Up: Documentation
  2837. 24.2 Access to Documentation Strings
  2838. ====================================
  2839. -- Function: documentation-property symbol property &optional verbatim
  2840. This function returns the documentation string recorded in
  2841. SYMBOL's property list under property PROPERTY. It is most often
  2842. used to look up the documentation strings of variables, for which
  2843. PROPERTY is `variable-documentation'. However, it can also be
  2844. used to look up other kinds of documentation, such as for
  2845. customization groups (but for function documentation, use the
  2846. `documentation' command, below).
  2847. If the value recorded in the property list refers to a
  2848. documentation string stored in a `DOC-VERSION' file or a
  2849. byte-compiled file, it looks up that string and returns it. If
  2850. the property value isn't `nil', isn't a string, and doesn't refer
  2851. to text in a file, then it is evaluated as a Lisp expression to
  2852. obtain a string.
  2853. The last thing this function does is pass the string through
  2854. `substitute-command-keys' to substitute actual key bindings (*note
  2855. Keys in Documentation::). However, it skips this step if VERBATIM
  2856. is non-`nil'.
  2857. (documentation-property 'command-line-processed
  2858. 'variable-documentation)
  2859. => "Non-nil once command line has been processed"
  2860. (symbol-plist 'command-line-processed)
  2861. => (variable-documentation 188902)
  2862. (documentation-property 'emacs 'group-documentation)
  2863. => "Customization of the One True Editor."
  2864. -- Function: documentation function &optional verbatim
  2865. This function returns the documentation string of FUNCTION. It
  2866. handles macros, named keyboard macros, and special forms, as well
  2867. as ordinary functions.
  2868. If FUNCTION is a symbol, this function first looks for the
  2869. `function-documentation' property of that symbol; if that has a
  2870. non-`nil' value, the documentation comes from that value (if the
  2871. value is not a string, it is evaluated). If FUNCTION is not a
  2872. symbol, or if it has no `function-documentation' property, then
  2873. `documentation' extracts the documentation string from the actual
  2874. function definition, reading it from a file if called for.
  2875. Finally, unless VERBATIM is non-`nil', it calls
  2876. `substitute-command-keys' so as to return a value containing the
  2877. actual (current) key bindings.
  2878. The function `documentation' signals a `void-function' error if
  2879. FUNCTION has no function definition. However, it is OK if the
  2880. function definition has no documentation string. In that case,
  2881. `documentation' returns `nil'.
  2882. -- Function: face-documentation face
  2883. This function returns the documentation string of FACE as a face.
  2884. Here is an example of using the two functions, `documentation' and
  2885. `documentation-property', to display the documentation strings for
  2886. several symbols in a `*Help*' buffer.
  2887. (defun describe-symbols (pattern)
  2888. "Describe the Emacs Lisp symbols matching PATTERN.
  2889. All symbols that have PATTERN in their name are described
  2890. in the `*Help*' buffer."
  2891. (interactive "sDescribe symbols matching: ")
  2892. (let ((describe-func
  2893. (function
  2894. (lambda (s)
  2895. ;; Print description of symbol.
  2896. (if (fboundp s) ; It is a function.
  2897. (princ
  2898. (format "%s\t%s\n%s\n\n" s
  2899. (if (commandp s)
  2900. (let ((keys (where-is-internal s)))
  2901. (if keys
  2902. (concat
  2903. "Keys: "
  2904. (mapconcat 'key-description
  2905. keys " "))
  2906. "Keys: none"))
  2907. "Function")
  2908. (or (documentation s)
  2909. "not documented"))))
  2910. (if (boundp s) ; It is a variable.
  2911. (princ
  2912. (format "%s\t%s\n%s\n\n" s
  2913. (if (user-variable-p s)
  2914. "Option " "Variable")
  2915. (or (documentation-property
  2916. s 'variable-documentation)
  2917. "not documented")))))))
  2918. sym-list)
  2919. ;; Build a list of symbols that match pattern.
  2920. (mapatoms (function
  2921. (lambda (sym)
  2922. (if (string-match pattern (symbol-name sym))
  2923. (setq sym-list (cons sym sym-list))))))
  2924. ;; Display the data.
  2925. (help-setup-xref (list 'describe-symbols pattern) (interactive-p))
  2926. (with-help-window (help-buffer)
  2927. (mapcar describe-func (sort sym-list 'string<)))))
  2928. The `describe-symbols' function works like `apropos', but provides
  2929. more information.
  2930. (describe-symbols "goal")
  2931. ---------- Buffer: *Help* ----------
  2932. goal-column Option
  2933. Semipermanent goal column for vertical motion, as set by ...
  2934. set-goal-column Keys: C-x C-n
  2935. Set the current horizontal position as a goal for C-n and C-p.
  2936. Those commands will move to this position in the line moved to
  2937. rather than trying to keep the same horizontal position.
  2938. With a non-nil argument, clears out the goal column
  2939. so that C-n and C-p resume vertical motion.
  2940. The goal column is stored in the variable `goal-column'.
  2941. temporary-goal-column Variable
  2942. Current goal column for vertical motion.
  2943. It is the column where point was
  2944. at the start of current run of vertical motion commands.
  2945. When the `track-eol' feature is doing its job, the value is 9999.
  2946. ---------- Buffer: *Help* ----------
  2947. -- Function: Snarf-documentation filename
  2948. This function is used when building Emacs, just before the runnable
  2949. Emacs is dumped. It finds the positions of the documentation
  2950. strings stored in the file FILENAME, and records those positions
  2951. into memory in the function definitions and variable property
  2952. lists. *Note Building Emacs::.
  2953. Emacs reads the file FILENAME from the `emacs/etc' directory.
  2954. When the dumped Emacs is later executed, the same file will be
  2955. looked for in the directory `doc-directory'. Usually FILENAME is
  2956. `"DOC-VERSION"'.
  2957. -- Variable: doc-directory
  2958. This variable holds the name of the directory which should contain
  2959. the file `"DOC-VERSION"' that contains documentation strings for
  2960. built-in and preloaded functions and variables.
  2961. In most cases, this is the same as `data-directory'. They may be
  2962. different when you run Emacs from the directory where you built it,
  2963. without actually installing it. *Note Definition of
  2964. data-directory::.
  2965. 
  2966. File: elisp, Node: Keys in Documentation, Next: Describing Characters, Prev: Accessing Documentation, Up: Documentation
  2967. 24.3 Substituting Key Bindings in Documentation
  2968. ===============================================
  2969. When documentation strings refer to key sequences, they should use the
  2970. current, actual key bindings. They can do so using certain special text
  2971. sequences described below. Accessing documentation strings in the usual
  2972. way substitutes current key binding information for these special
  2973. sequences. This works by calling `substitute-command-keys'. You can
  2974. also call that function yourself.
  2975. Here is a list of the special sequences and what they mean:
  2976. `\[COMMAND]'
  2977. stands for a key sequence that will invoke COMMAND, or `M-x
  2978. COMMAND' if COMMAND has no key bindings.
  2979. `\{MAPVAR}'
  2980. stands for a summary of the keymap which is the value of the
  2981. variable MAPVAR. The summary is made using `describe-bindings'.
  2982. `\<MAPVAR>'
  2983. stands for no text itself. It is used only for a side effect: it
  2984. specifies MAPVAR's value as the keymap for any following
  2985. `\[COMMAND]' sequences in this documentation string.
  2986. `\='
  2987. quotes the following character and is discarded; thus, `\=\[' puts
  2988. `\[' into the output, and `\=\=' puts `\=' into the output.
  2989. *Please note:* Each `\' must be doubled when written in a string in
  2990. Emacs Lisp.
  2991. -- Function: substitute-command-keys string
  2992. This function scans STRING for the above special sequences and
  2993. replaces them by what they stand for, returning the result as a
  2994. string. This permits display of documentation that refers
  2995. accurately to the user's own customized key bindings.
  2996. If a command has multiple bindings, this function normally uses the
  2997. first one it finds. You can specify one particular key binding by
  2998. assigning an `:advertised-binding' symbol property to the command,
  2999. like this:
  3000. (put 'undo :advertised-binding [?\C-/])
  3001. The `:advertised-binding' property also affects the binding shown
  3002. in menu items (*note Menu Bar::). The property is ignored if it
  3003. specifies a key binding that the command does not actually have.
  3004. Here are examples of the special sequences:
  3005. (substitute-command-keys
  3006. "To abort recursive edit, type: \\[abort-recursive-edit]")
  3007. => "To abort recursive edit, type: C-]"
  3008. (substitute-command-keys
  3009. "The keys that are defined for the minibuffer here are:
  3010. \\{minibuffer-local-must-match-map}")
  3011. => "The keys that are defined for the minibuffer here are:
  3012. ? minibuffer-completion-help
  3013. SPC minibuffer-complete-word
  3014. TAB minibuffer-complete
  3015. C-j minibuffer-complete-and-exit
  3016. RET minibuffer-complete-and-exit
  3017. C-g abort-recursive-edit
  3018. "
  3019. (substitute-command-keys
  3020. "To abort a recursive edit from the minibuffer, type\
  3021. \\<minibuffer-local-must-match-map>\\[abort-recursive-edit].")
  3022. => "To abort a recursive edit from the minibuffer, type C-g."
  3023. There are other special conventions for the text in documentation
  3024. strings--for instance, you can refer to functions, variables, and
  3025. sections of this manual. *Note Documentation Tips::, for details.
  3026. 
  3027. File: elisp, Node: Describing Characters, Next: Help Functions, Prev: Keys in Documentation, Up: Documentation
  3028. 24.4 Describing Characters for Help Messages
  3029. ============================================
  3030. These functions convert events, key sequences, or characters to textual
  3031. descriptions. These descriptions are useful for including arbitrary
  3032. text characters or key sequences in messages, because they convert
  3033. non-printing and whitespace characters to sequences of printing
  3034. characters. The description of a non-whitespace printing character is
  3035. the character itself.
  3036. -- Function: key-description sequence &optional prefix
  3037. This function returns a string containing the Emacs standard
  3038. notation for the input events in SEQUENCE. If PREFIX is
  3039. non-`nil', it is a sequence of input events leading up to SEQUENCE
  3040. and is included in the return value. Both arguments may be
  3041. strings, vectors or lists. *Note Input Events::, for more
  3042. information about valid events.
  3043. (key-description [?\M-3 delete])
  3044. => "M-3 <delete>"
  3045. (key-description [delete] "\M-3")
  3046. => "M-3 <delete>"
  3047. See also the examples for `single-key-description', below.
  3048. -- Function: single-key-description event &optional no-angles
  3049. This function returns a string describing EVENT in the standard
  3050. Emacs notation for keyboard input. A normal printing character
  3051. appears as itself, but a control character turns into a string
  3052. starting with `C-', a meta character turns into a string starting
  3053. with `M-', and space, tab, etc. appear as `SPC', `TAB', etc. A
  3054. function key symbol appears inside angle brackets `<...>'. An
  3055. event that is a list appears as the name of the symbol in the CAR
  3056. of the list, inside angle brackets.
  3057. If the optional argument NO-ANGLES is non-`nil', the angle
  3058. brackets around function keys and event symbols are omitted; this
  3059. is for compatibility with old versions of Emacs which didn't use
  3060. the brackets.
  3061. (single-key-description ?\C-x)
  3062. => "C-x"
  3063. (key-description "\C-x \M-y \n \t \r \f123")
  3064. => "C-x SPC M-y SPC C-j SPC TAB SPC RET SPC C-l 1 2 3"
  3065. (single-key-description 'delete)
  3066. => "<delete>"
  3067. (single-key-description 'C-mouse-1)
  3068. => "<C-mouse-1>"
  3069. (single-key-description 'C-mouse-1 t)
  3070. => "C-mouse-1"
  3071. -- Function: text-char-description character
  3072. This function returns a string describing CHARACTER in the
  3073. standard Emacs notation for characters that appear in text--like
  3074. `single-key-description', except that control characters are
  3075. represented with a leading caret (which is how control characters
  3076. in Emacs buffers are usually displayed). Another difference is
  3077. that `text-char-description' recognizes the 2**7 bit as the Meta
  3078. character, whereas `single-key-description' uses the 2**27 bit for
  3079. Meta.
  3080. (text-char-description ?\C-c)
  3081. => "^C"
  3082. (text-char-description ?\M-m)
  3083. => "\xed"
  3084. (text-char-description ?\C-\M-m)
  3085. => "\x8d"
  3086. (text-char-description (+ 128 ?m))
  3087. => "M-m"
  3088. (text-char-description (+ 128 ?\C-m))
  3089. => "M-^M"
  3090. -- Command: read-kbd-macro string &optional need-vector
  3091. This function is used mainly for operating on keyboard macros, but
  3092. it can also be used as a rough inverse for `key-description'. You
  3093. call it with a string containing key descriptions, separated by
  3094. spaces; it returns a string or vector containing the corresponding
  3095. events. (This may or may not be a single valid key sequence,
  3096. depending on what events you use; *note Key Sequences::.) If
  3097. NEED-VECTOR is non-`nil', the return value is always a vector.
  3098. 
  3099. File: elisp, Node: Help Functions, Prev: Describing Characters, Up: Documentation
  3100. 24.5 Help Functions
  3101. ===================
  3102. Emacs provides a variety of on-line help functions, all accessible to
  3103. the user as subcommands of the prefix `C-h'. For more information
  3104. about them, see *note Help: (emacs)Help. Here we describe some
  3105. program-level interfaces to the same information.
  3106. -- Command: apropos pattern &optional do-all
  3107. This function finds all "meaningful" symbols whose names contain a
  3108. match for the apropos pattern PATTERN. An apropos pattern is
  3109. either a word to match, a space-separated list of words of which at
  3110. least two must match, or a regular expression (if any special
  3111. regular expression characters occur). A symbol is "meaningful" if
  3112. it has a definition as a function, variable, or face, or has
  3113. properties.
  3114. The function returns a list of elements that look like this:
  3115. (SYMBOL SCORE FUNCTION-DOC VARIABLE-DOC
  3116. PLIST-DOC WIDGET-DOC FACE-DOC GROUP-DOC)
  3117. Here, SCORE is an integer measure of how important the symbol
  3118. seems to be as a match. Each of the remaining elements is a
  3119. documentation string, or `nil', for SYMBOL as a function,
  3120. variable, etc.
  3121. It also displays the symbols in a buffer named `*Apropos*', each
  3122. with a one-line description taken from the beginning of its
  3123. documentation string.
  3124. If DO-ALL is non-`nil', or if the user option `apropos-do-all' is
  3125. non-`nil', then `apropos' also shows key bindings for the
  3126. functions that are found; it also shows _all_ interned symbols,
  3127. not just meaningful ones (and it lists them in the return value as
  3128. well).
  3129. -- Variable: help-map
  3130. The value of this variable is a local keymap for characters
  3131. following the Help key, `C-h'.
  3132. -- Prefix Command: help-command
  3133. This symbol is not a function; its function definition cell holds
  3134. the keymap known as `help-map'. It is defined in `help.el' as
  3135. follows:
  3136. (define-key global-map (string help-char) 'help-command)
  3137. (fset 'help-command help-map)
  3138. -- User Option: help-char
  3139. The value of this variable is the help character--the character
  3140. that Emacs recognizes as meaning Help. By default, its value is
  3141. 8, which stands for `C-h'. When Emacs reads this character, if
  3142. `help-form' is a non-`nil' Lisp expression, it evaluates that
  3143. expression, and displays the result in a window if it is a string.
  3144. Usually the value of `help-form' is `nil'. Then the help
  3145. character has no special meaning at the level of command input, and
  3146. it becomes part of a key sequence in the normal way. The standard
  3147. key binding of `C-h' is a prefix key for several general-purpose
  3148. help features.
  3149. The help character is special after prefix keys, too. If it has no
  3150. binding as a subcommand of the prefix key, it runs
  3151. `describe-prefix-bindings', which displays a list of all the
  3152. subcommands of the prefix key.
  3153. -- User Option: help-event-list
  3154. The value of this variable is a list of event types that serve as
  3155. alternative "help characters". These events are handled just like
  3156. the event specified by `help-char'.
  3157. -- Variable: help-form
  3158. If this variable is non-`nil', its value is a form to evaluate
  3159. whenever the character `help-char' is read. If evaluating the form
  3160. produces a string, that string is displayed.
  3161. A command that calls `read-event', `read-char-choice', or
  3162. `read-char' probably should bind `help-form' to a non-`nil'
  3163. expression while it does input. (The time when you should not do
  3164. this is when `C-h' has some other meaning.) Evaluating this
  3165. expression should result in a string that explains what the input
  3166. is for and how to enter it properly.
  3167. Entry to the minibuffer binds this variable to the value of
  3168. `minibuffer-help-form' (*note Definition of
  3169. minibuffer-help-form::).
  3170. -- Variable: prefix-help-command
  3171. This variable holds a function to print help for a prefix key. The
  3172. function is called when the user types a prefix key followed by
  3173. the help character, and the help character has no binding after
  3174. that prefix. The variable's default value is
  3175. `describe-prefix-bindings'.
  3176. -- Command: describe-prefix-bindings
  3177. This function calls `describe-bindings' to display a list of all
  3178. the subcommands of the prefix key of the most recent key sequence.
  3179. The prefix described consists of all but the last event of that key
  3180. sequence. (The last event is, presumably, the help character.)
  3181. The following two functions are meant for modes that want to provide
  3182. help without relinquishing control, such as the "electric" modes.
  3183. Their names begin with `Helper' to distinguish them from the ordinary
  3184. help functions.
  3185. -- Command: Helper-describe-bindings
  3186. This command pops up a window displaying a help buffer containing a
  3187. listing of all of the key bindings from both the local and global
  3188. keymaps. It works by calling `describe-bindings'.
  3189. -- Command: Helper-help
  3190. This command provides help for the current mode. It prompts the
  3191. user in the minibuffer with the message `Help (Type ? for further
  3192. options)', and then provides assistance in finding out what the key
  3193. bindings are, and what the mode is intended for. It returns `nil'.
  3194. This can be customized by changing the map `Helper-help-map'.
  3195. -- Variable: data-directory
  3196. This variable holds the name of the directory in which Emacs finds
  3197. certain documentation and text files that come with Emacs.
  3198. -- Function: help-buffer
  3199. This function returns the name of the help buffer, which is
  3200. normally `*Help*'; if such a buffer does not exist, it is first
  3201. created.
  3202. -- Macro: with-help-window buffer-name body...
  3203. This macro evaluates the BODY forms, inserting any output they
  3204. produce into a buffer named BUFFER-NAME like
  3205. `with-output-to-temp-buffer' (*note Temporary Displays::).
  3206. (Usually, BUFFER-NAME should be the value returned by the function
  3207. `help-buffer'.) It also puts the specified buffer into Help mode
  3208. and displays a message telling the user how to quit and scroll the
  3209. help window.
  3210. -- Function: help-setup-xref item interactive-p
  3211. This function updates the cross reference data in the `*Help*'
  3212. buffer, which is used to regenerate the help information when the
  3213. user clicks on the `Back' or `Forward' buttons. Most commands
  3214. that use the `*Help*' buffer should invoke this function before
  3215. clearing the buffer. The ITEM argument should have the form
  3216. `(FUNCTION . ARGS)', where FUNCTION is a function to call, with
  3217. argument list ARGS, to regenerate the help buffer. The
  3218. INTERACTIVE-P argument is non-`nil' if the calling command was
  3219. invoked interactively; in that case, the stack of items for the
  3220. `*Help*' buffer's `Back' buttons is cleared.
  3221. *Note describe-symbols example::, for an example of using
  3222. `help-buffer', `with-help-window', and `help-setup-xref'.
  3223. -- Macro: make-help-screen fname help-line help-text help-map
  3224. This macro defines a help command named FNAME that acts like a
  3225. prefix key that shows a list of the subcommands it offers.
  3226. When invoked, FNAME displays HELP-TEXT in a window, then reads and
  3227. executes a key sequence according to HELP-MAP. The string
  3228. HELP-TEXT should describe the bindings available in HELP-MAP.
  3229. The command FNAME is defined to handle a few events itself, by
  3230. scrolling the display of HELP-TEXT. When FNAME reads one of those
  3231. special events, it does the scrolling and then reads another
  3232. event. When it reads an event that is not one of those few, and
  3233. which has a binding in HELP-MAP, it executes that key's binding and
  3234. then returns.
  3235. The argument HELP-LINE should be a single-line summary of the
  3236. alternatives in HELP-MAP. In the current version of Emacs, this
  3237. argument is used only if you set the option `three-step-help' to
  3238. `t'.
  3239. This macro is used in the command `help-for-help' which is the
  3240. binding of `C-h C-h'.
  3241. -- User Option: three-step-help
  3242. If this variable is non-`nil', commands defined with
  3243. `make-help-screen' display their HELP-LINE strings in the echo
  3244. area at first, and display the longer HELP-TEXT strings only if
  3245. the user types the help character again.
  3246. 
  3247. File: elisp, Node: Files, Next: Backups and Auto-Saving, Prev: Documentation, Up: Top
  3248. 25 Files
  3249. ********
  3250. This chapter describes the Emacs Lisp functions and variables to find,
  3251. create, view, save, and otherwise work with files and file directories.
  3252. A few other file-related functions are described in *note Buffers::,
  3253. and those related to backups and auto-saving are described in *note
  3254. Backups and Auto-Saving::.
  3255. Many of the file functions take one or more arguments that are file
  3256. names. A file name is actually a string. Most of these functions
  3257. expand file name arguments by calling `expand-file-name', so that `~'
  3258. is handled correctly, as are relative file names (including `../').
  3259. *Note File Name Expansion::.
  3260. In addition, certain "magic" file names are handled specially. For
  3261. example, when a remote file name is specified, Emacs accesses the file
  3262. over the network via an appropriate protocol (*note Remote Files:
  3263. (emacs)Remote Files.). This handling is done at a very low level, so
  3264. you may assume that all the functions described in this chapter accept
  3265. magic file names as file name arguments, except where noted. *Note
  3266. Magic File Names::, for details.
  3267. When file I/O functions signal Lisp errors, they usually use the
  3268. condition `file-error' (*note Handling Errors::). The error message is
  3269. in most cases obtained from the operating system, according to locale
  3270. `system-message-locale', and decoded using coding system
  3271. `locale-coding-system' (*note Locales::).
  3272. * Menu:
  3273. * Visiting Files:: Reading files into Emacs buffers for editing.
  3274. * Saving Buffers:: Writing changed buffers back into files.
  3275. * Reading from Files:: Reading files into buffers without visiting.
  3276. * Writing to Files:: Writing new files from parts of buffers.
  3277. * File Locks:: Locking and unlocking files, to prevent
  3278. simultaneous editing by two people.
  3279. * Information about Files:: Testing existence, accessibility, size of files.
  3280. * Changing Files:: Renaming files, changing permissions, etc.
  3281. * File Names:: Decomposing and expanding file names.
  3282. * Contents of Directories:: Getting a list of the files in a directory.
  3283. * Create/Delete Dirs:: Creating and Deleting Directories.
  3284. * Magic File Names:: Special handling for certain file names.
  3285. * Format Conversion:: Conversion to and from various file formats.
  3286. 
  3287. File: elisp, Node: Visiting Files, Next: Saving Buffers, Up: Files
  3288. 25.1 Visiting Files
  3289. ===================
  3290. Visiting a file means reading a file into a buffer. Once this is done,
  3291. we say that the buffer is "visiting" that file, and call the file "the
  3292. visited file" of the buffer.
  3293. A file and a buffer are two different things. A file is information
  3294. recorded permanently in the computer (unless you delete it). A buffer,
  3295. on the other hand, is information inside of Emacs that will vanish at
  3296. the end of the editing session (or when you kill the buffer). Usually,
  3297. a buffer contains information that you have copied from a file; then we
  3298. say the buffer is visiting that file. The copy in the buffer is what
  3299. you modify with editing commands. Such changes to the buffer do not
  3300. change the file; therefore, to make the changes permanent, you must
  3301. "save" the buffer, which means copying the altered buffer contents back
  3302. into the file.
  3303. In spite of the distinction between files and buffers, people often
  3304. refer to a file when they mean a buffer and vice-versa. Indeed, we say,
  3305. "I am editing a file", rather than, "I am editing a buffer that I will
  3306. soon save as a file of the same name". Humans do not usually need to
  3307. make the distinction explicit. When dealing with a computer program,
  3308. however, it is good to keep the distinction in mind.
  3309. * Menu:
  3310. * Visiting Functions:: The usual interface functions for visiting.
  3311. * Subroutines of Visiting:: Lower-level subroutines that they use.
  3312. 
  3313. File: elisp, Node: Visiting Functions, Next: Subroutines of Visiting, Up: Visiting Files
  3314. 25.1.1 Functions for Visiting Files
  3315. -----------------------------------
  3316. This section describes the functions normally used to visit files. For
  3317. historical reasons, these functions have names starting with `find-'
  3318. rather than `visit-'. *Note Buffer File Name::, for functions and
  3319. variables that access the visited file name of a buffer or that find an
  3320. existing buffer by its visited file name.
  3321. In a Lisp program, if you want to look at the contents of a file but
  3322. not alter it, the fastest way is to use `insert-file-contents' in a
  3323. temporary buffer. Visiting the file is not necessary and takes longer.
  3324. *Note Reading from Files::.
  3325. -- Command: find-file filename &optional wildcards
  3326. This command selects a buffer visiting the file FILENAME, using an
  3327. existing buffer if there is one, and otherwise creating a new
  3328. buffer and reading the file into it. It also returns that buffer.
  3329. Aside from some technical details, the body of the `find-file'
  3330. function is basically equivalent to:
  3331. (switch-to-buffer (find-file-noselect filename nil nil wildcards))
  3332. (See `switch-to-buffer' in *note Switching Buffers::.)
  3333. If WILDCARDS is non-`nil', which is always true in an interactive
  3334. call, then `find-file' expands wildcard characters in FILENAME and
  3335. visits all the matching files.
  3336. When `find-file' is called interactively, it prompts for FILENAME
  3337. in the minibuffer.
  3338. -- Command: find-file-literally filename
  3339. This command visits FILENAME, like `find-file' does, but it does
  3340. not perform any format conversions (*note Format Conversion::),
  3341. character code conversions (*note Coding Systems::), or end-of-line
  3342. conversions (*note End of line conversion: Coding System Basics.).
  3343. The buffer visiting the file is made unibyte, and its major mode is
  3344. Fundamental mode, regardless of the file name. File local variable
  3345. specifications in the file (*note File Local Variables::) are
  3346. ignored, and automatic decompression and adding a newline at the
  3347. end of the file due to `require-final-newline' (*note
  3348. require-final-newline: Saving Buffers.) are also disabled.
  3349. Note that if Emacs already has a buffer visiting the same file
  3350. non-literally, it will not visit the same file literally, but
  3351. instead just switch to the existing buffer. If you want to be
  3352. sure of accessing a file's contents literally, you should create a
  3353. temporary buffer and then read the file contents into it using
  3354. `insert-file-contents-literally' (*note Reading from Files::).
  3355. -- Function: find-file-noselect filename &optional nowarn rawfile
  3356. wildcards
  3357. This function is the guts of all the file-visiting functions. It
  3358. returns a buffer visiting the file FILENAME. You may make the
  3359. buffer current or display it in a window if you wish, but this
  3360. function does not do so.
  3361. The function returns an existing buffer if there is one; otherwise
  3362. it creates a new buffer and reads the file into it. When
  3363. `find-file-noselect' uses an existing buffer, it first verifies
  3364. that the file has not changed since it was last visited or saved in
  3365. that buffer. If the file has changed, this function asks the user
  3366. whether to reread the changed file. If the user says `yes', any
  3367. edits previously made in the buffer are lost.
  3368. Reading the file involves decoding the file's contents (*note
  3369. Coding Systems::), including end-of-line conversion, and format
  3370. conversion (*note Format Conversion::). If WILDCARDS is non-`nil',
  3371. then `find-file-noselect' expands wildcard characters in FILENAME
  3372. and visits all the matching files.
  3373. This function displays warning or advisory messages in various
  3374. peculiar cases, unless the optional argument NOWARN is non-`nil'.
  3375. For example, if it needs to create a buffer, and there is no file
  3376. named FILENAME, it displays the message `(New file)' in the echo
  3377. area, and leaves the buffer empty.
  3378. The `find-file-noselect' function normally calls `after-find-file'
  3379. after reading the file (*note Subroutines of Visiting::). That
  3380. function sets the buffer major mode, parses local variables, warns
  3381. the user if there exists an auto-save file more recent than the
  3382. file just visited, and finishes by running the functions in
  3383. `find-file-hook'.
  3384. If the optional argument RAWFILE is non-`nil', then
  3385. `after-find-file' is not called, and the
  3386. `find-file-not-found-functions' are not run in case of failure.
  3387. What's more, a non-`nil' RAWFILE value suppresses coding system
  3388. conversion and format conversion.
  3389. The `find-file-noselect' function usually returns the buffer that
  3390. is visiting the file FILENAME. But, if wildcards are actually
  3391. used and expanded, it returns a list of buffers that are visiting
  3392. the various files.
  3393. (find-file-noselect "/etc/fstab")
  3394. => #<buffer fstab>
  3395. -- Command: find-file-other-window filename &optional wildcards
  3396. This command selects a buffer visiting the file FILENAME, but does
  3397. so in a window other than the selected window. It may use another
  3398. existing window or split a window; see *note Switching Buffers::.
  3399. When this command is called interactively, it prompts for FILENAME.
  3400. -- Command: find-file-read-only filename &optional wildcards
  3401. This command selects a buffer visiting the file FILENAME, like
  3402. `find-file', but it marks the buffer as read-only. *Note Read
  3403. Only Buffers::, for related functions and variables.
  3404. When this command is called interactively, it prompts for FILENAME.
  3405. -- User Option: find-file-wildcards
  3406. If this variable is non-`nil', then the various `find-file'
  3407. commands check for wildcard characters and visit all the files that
  3408. match them (when invoked interactively or when their WILDCARDS
  3409. argument is non-`nil'). If this option is `nil', then the
  3410. `find-file' commands ignore their WILDCARDS argument and never
  3411. treat wildcard characters specially.
  3412. -- User Option: find-file-hook
  3413. The value of this variable is a list of functions to be called
  3414. after a file is visited. The file's local-variables specification
  3415. (if any) will have been processed before the hooks are run. The
  3416. buffer visiting the file is current when the hook functions are
  3417. run.
  3418. This variable is a normal hook. *Note Hooks::.
  3419. -- Variable: find-file-not-found-functions
  3420. The value of this variable is a list of functions to be called when
  3421. `find-file' or `find-file-noselect' is passed a nonexistent file
  3422. name. `find-file-noselect' calls these functions as soon as it
  3423. detects a nonexistent file. It calls them in the order of the
  3424. list, until one of them returns non-`nil'. `buffer-file-name' is
  3425. already set up.
  3426. This is not a normal hook because the values of the functions are
  3427. used, and in many cases only some of the functions are called.
  3428. -- Variable: find-file-literally
  3429. This buffer-local variable, if set to a non-`nil' value, makes
  3430. `save-buffer' behave as if the buffer were visiting its file
  3431. literally, i.e. without conversions of any kind. The command
  3432. `find-file-literally' sets this variable's local value, but other
  3433. equivalent functions and commands can do that as well, e.g. to
  3434. avoid automatic addition of a newline at the end of the file.
  3435. This variable is permanent local, so it is unaffected by changes
  3436. of major modes.
  3437. 
  3438. File: elisp, Node: Subroutines of Visiting, Prev: Visiting Functions, Up: Visiting Files
  3439. 25.1.2 Subroutines of Visiting
  3440. ------------------------------
  3441. The `find-file-noselect' function uses two important subroutines which
  3442. are sometimes useful in user Lisp code: `create-file-buffer' and
  3443. `after-find-file'. This section explains how to use them.
  3444. -- Function: create-file-buffer filename
  3445. This function creates a suitably named buffer for visiting
  3446. FILENAME, and returns it. It uses FILENAME (sans directory) as
  3447. the name if that name is free; otherwise, it appends a string such
  3448. as `<2>' to get an unused name. See also *note Creating Buffers::.
  3449. *Please note:* `create-file-buffer' does _not_ associate the new
  3450. buffer with a file and does not select the buffer. It also does
  3451. not use the default major mode.
  3452. (create-file-buffer "foo")
  3453. => #<buffer foo>
  3454. (create-file-buffer "foo")
  3455. => #<buffer foo<2>>
  3456. (create-file-buffer "foo")
  3457. => #<buffer foo<3>>
  3458. This function is used by `find-file-noselect'. It uses
  3459. `generate-new-buffer' (*note Creating Buffers::).
  3460. -- Function: after-find-file &optional error warn noauto
  3461. after-find-file-from-revert-buffer nomodes
  3462. This function sets the buffer major mode, and parses local
  3463. variables (*note Auto Major Mode::). It is called by
  3464. `find-file-noselect' and by the default revert function (*note
  3465. Reverting::).
  3466. If reading the file got an error because the file does not exist,
  3467. but its directory does exist, the caller should pass a non-`nil'
  3468. value for ERROR. In that case, `after-find-file' issues a warning:
  3469. `(New file)'. For more serious errors, the caller should usually
  3470. not call `after-find-file'.
  3471. If WARN is non-`nil', then this function issues a warning if an
  3472. auto-save file exists and is more recent than the visited file.
  3473. If NOAUTO is non-`nil', that says not to enable or disable
  3474. Auto-Save mode. The mode remains enabled if it was enabled before.
  3475. If AFTER-FIND-FILE-FROM-REVERT-BUFFER is non-`nil', that means
  3476. this call was from `revert-buffer'. This has no direct effect,
  3477. but some mode functions and hook functions check the value of this
  3478. variable.
  3479. If NOMODES is non-`nil', that means don't alter the buffer's major
  3480. mode, don't process local variables specifications in the file,
  3481. and don't run `find-file-hook'. This feature is used by
  3482. `revert-buffer' in some cases.
  3483. The last thing `after-find-file' does is call all the functions in
  3484. the list `find-file-hook'.
  3485. 
  3486. File: elisp, Node: Saving Buffers, Next: Reading from Files, Prev: Visiting Files, Up: Files
  3487. 25.2 Saving Buffers
  3488. ===================
  3489. When you edit a file in Emacs, you are actually working on a buffer
  3490. that is visiting that file--that is, the contents of the file are
  3491. copied into the buffer and the copy is what you edit. Changes to the
  3492. buffer do not change the file until you "save" the buffer, which means
  3493. copying the contents of the buffer into the file.
  3494. -- Command: save-buffer &optional backup-option
  3495. This function saves the contents of the current buffer in its
  3496. visited file if the buffer has been modified since it was last
  3497. visited or saved. Otherwise it does nothing.
  3498. `save-buffer' is responsible for making backup files. Normally,
  3499. BACKUP-OPTION is `nil', and `save-buffer' makes a backup file only
  3500. if this is the first save since visiting the file. Other values
  3501. for BACKUP-OPTION request the making of backup files in other
  3502. circumstances:
  3503. * With an argument of 4 or 64, reflecting 1 or 3 `C-u''s, the
  3504. `save-buffer' function marks this version of the file to be
  3505. backed up when the buffer is next saved.
  3506. * With an argument of 16 or 64, reflecting 2 or 3 `C-u''s, the
  3507. `save-buffer' function unconditionally backs up the previous
  3508. version of the file before saving it.
  3509. * With an argument of 0, unconditionally do _not_ make any
  3510. backup file.
  3511. -- Command: save-some-buffers &optional save-silently-p pred
  3512. This command saves some modified file-visiting buffers. Normally
  3513. it asks the user about each buffer. But if SAVE-SILENTLY-P is
  3514. non-`nil', it saves all the file-visiting buffers without querying
  3515. the user.
  3516. The optional PRED argument controls which buffers to ask about (or
  3517. to save silently if SAVE-SILENTLY-P is non-`nil'). If it is
  3518. `nil', that means to ask only about file-visiting buffers. If it
  3519. is `t', that means also offer to save certain other non-file
  3520. buffers--those that have a non-`nil' buffer-local value of
  3521. `buffer-offer-save' (*note Killing Buffers::). A user who says
  3522. `yes' to saving a non-file buffer is asked to specify the file
  3523. name to use. The `save-buffers-kill-emacs' function passes the
  3524. value `t' for PRED.
  3525. If PRED is neither `t' nor `nil', then it should be a function of
  3526. no arguments. It will be called in each buffer to decide whether
  3527. to offer to save that buffer. If it returns a non-`nil' value in
  3528. a certain buffer, that means do offer to save that buffer.
  3529. -- Command: write-file filename &optional confirm
  3530. This function writes the current buffer into file FILENAME, makes
  3531. the buffer visit that file, and marks it not modified. Then it
  3532. renames the buffer based on FILENAME, appending a string like `<2>'
  3533. if necessary to make a unique buffer name. It does most of this
  3534. work by calling `set-visited-file-name' (*note Buffer File Name::)
  3535. and `save-buffer'.
  3536. If CONFIRM is non-`nil', that means to ask for confirmation before
  3537. overwriting an existing file. Interactively, confirmation is
  3538. required, unless the user supplies a prefix argument.
  3539. If FILENAME is an existing directory, or a symbolic link to one,
  3540. `write-file' uses the name of the visited file, in directory
  3541. FILENAME. If the buffer is not visiting a file, it uses the
  3542. buffer name instead.
  3543. Saving a buffer runs several hooks. It also performs format
  3544. conversion (*note Format Conversion::).
  3545. -- Variable: write-file-functions
  3546. The value of this variable is a list of functions to be called
  3547. before writing out a buffer to its visited file. If one of them
  3548. returns non-`nil', the file is considered already written and the
  3549. rest of the functions are not called, nor is the usual code for
  3550. writing the file executed.
  3551. If a function in `write-file-functions' returns non-`nil', it is
  3552. responsible for making a backup file (if that is appropriate). To
  3553. do so, execute the following code:
  3554. (or buffer-backed-up (backup-buffer))
  3555. You might wish to save the file modes value returned by
  3556. `backup-buffer' and use that (if non-`nil') to set the mode bits
  3557. of the file that you write. This is what `save-buffer' normally
  3558. does. *Note Making Backup Files: Making Backups.
  3559. The hook functions in `write-file-functions' are also responsible
  3560. for encoding the data (if desired): they must choose a suitable
  3561. coding system and end-of-line conversion (*note Lisp and Coding
  3562. Systems::), perform the encoding (*note Explicit Encoding::), and
  3563. set `last-coding-system-used' to the coding system that was used
  3564. (*note Encoding and I/O::).
  3565. If you set this hook locally in a buffer, it is assumed to be
  3566. associated with the file or the way the contents of the buffer were
  3567. obtained. Thus the variable is marked as a permanent local, so
  3568. that changing the major mode does not alter a buffer-local value.
  3569. On the other hand, calling `set-visited-file-name' will reset it.
  3570. If this is not what you want, you might like to use
  3571. `write-contents-functions' instead.
  3572. Even though this is not a normal hook, you can use `add-hook' and
  3573. `remove-hook' to manipulate the list. *Note Hooks::.
  3574. -- Variable: write-contents-functions
  3575. This works just like `write-file-functions', but it is intended
  3576. for hooks that pertain to the buffer's contents, not to the
  3577. particular visited file or its location. Such hooks are usually
  3578. set up by major modes, as buffer-local bindings for this variable.
  3579. This variable automatically becomes buffer-local whenever it is
  3580. set; switching to a new major mode always resets this variable,
  3581. but calling `set-visited-file-name' does not.
  3582. If any of the functions in this hook returns non-`nil', the file
  3583. is considered already written and the rest are not called and
  3584. neither are the functions in `write-file-functions'.
  3585. -- User Option: before-save-hook
  3586. This normal hook runs before a buffer is saved in its visited file,
  3587. regardless of whether that is done normally or by one of the hooks
  3588. described above. For instance, the `copyright.el' program uses
  3589. this hook to make sure the file you are saving has the current
  3590. year in its copyright notice.
  3591. -- User Option: after-save-hook
  3592. This normal hook runs after a buffer has been saved in its visited
  3593. file. One use of this hook is in Fast Lock mode; it uses this
  3594. hook to save the highlighting information in a cache file.
  3595. -- User Option: file-precious-flag
  3596. If this variable is non-`nil', then `save-buffer' protects against
  3597. I/O errors while saving by writing the new file to a temporary
  3598. name instead of the name it is supposed to have, and then renaming
  3599. it to the intended name after it is clear there are no errors.
  3600. This procedure prevents problems such as a lack of disk space from
  3601. resulting in an invalid file.
  3602. As a side effect, backups are necessarily made by copying. *Note
  3603. Rename or Copy::. Yet, at the same time, saving a precious file
  3604. always breaks all hard links between the file you save and other
  3605. file names.
  3606. Some modes give this variable a non-`nil' buffer-local value in
  3607. particular buffers.
  3608. -- User Option: require-final-newline
  3609. This variable determines whether files may be written out that do
  3610. _not_ end with a newline. If the value of the variable is `t',
  3611. then `save-buffer' silently adds a newline at the end of the
  3612. buffer whenever it does not already end in one. If the value is
  3613. `visit', Emacs adds a missing newline just after it visits the
  3614. file. If the value is `visit-save', Emacs adds a missing newline
  3615. both on visiting and on saving. For any other non-`nil' value,
  3616. `save-buffer' asks the user whether to add a newline each time the
  3617. case arises.
  3618. If the value of the variable is `nil', then `save-buffer' doesn't
  3619. add newlines at all. `nil' is the default value, but a few major
  3620. modes set it to `t' in particular buffers.
  3621. See also the function `set-visited-file-name' (*note Buffer File
  3622. Name::).
  3623. 
  3624. File: elisp, Node: Reading from Files, Next: Writing to Files, Prev: Saving Buffers, Up: Files
  3625. 25.3 Reading from Files
  3626. =======================
  3627. You can copy a file from the disk and insert it into a buffer using the
  3628. `insert-file-contents' function. Don't use the user-level command
  3629. `insert-file' in a Lisp program, as that sets the mark.
  3630. -- Function: insert-file-contents filename &optional visit beg end
  3631. replace
  3632. This function inserts the contents of file FILENAME into the
  3633. current buffer after point. It returns a list of the absolute
  3634. file name and the length of the data inserted. An error is
  3635. signaled if FILENAME is not the name of a file that can be read.
  3636. This function checks the file contents against the defined file
  3637. formats, and converts the file contents if appropriate and also
  3638. calls the functions in the list `after-insert-file-functions'.
  3639. *Note Format Conversion::. Normally, one of the functions in the
  3640. `after-insert-file-functions' list determines the coding system
  3641. (*note Coding Systems::) used for decoding the file's contents,
  3642. including end-of-line conversion. However, if the file contains
  3643. null bytes, it is by default visited without any code conversions.
  3644. *Note inhibit-null-byte-detection: Lisp and Coding Systems.
  3645. If VISIT is non-`nil', this function additionally marks the buffer
  3646. as unmodified and sets up various fields in the buffer so that it
  3647. is visiting the file FILENAME: these include the buffer's visited
  3648. file name and its last save file modtime. This feature is used by
  3649. `find-file-noselect' and you probably should not use it yourself.
  3650. If BEG and END are non-`nil', they should be integers specifying
  3651. the portion of the file to insert. In this case, VISIT must be
  3652. `nil'. For example,
  3653. (insert-file-contents filename nil 0 500)
  3654. inserts the first 500 characters of a file.
  3655. If the argument REPLACE is non-`nil', it means to replace the
  3656. contents of the buffer (actually, just the accessible portion)
  3657. with the contents of the file. This is better than simply
  3658. deleting the buffer contents and inserting the whole file, because
  3659. (1) it preserves some marker positions and (2) it puts less data
  3660. in the undo list.
  3661. It is possible to read a special file (such as a FIFO or an I/O
  3662. device) with `insert-file-contents', as long as REPLACE and VISIT
  3663. are `nil'.
  3664. -- Function: insert-file-contents-literally filename &optional visit
  3665. beg end replace
  3666. This function works like `insert-file-contents' except that it
  3667. does not run `find-file-hook', and does not do format decoding,
  3668. character code conversion, automatic uncompression, and so on.
  3669. If you want to pass a file name to another process so that another
  3670. program can read the file, use the function `file-local-copy'; see
  3671. *note Magic File Names::.
  3672. 
  3673. File: elisp, Node: Writing to Files, Next: File Locks, Prev: Reading from Files, Up: Files
  3674. 25.4 Writing to Files
  3675. =====================
  3676. You can write the contents of a buffer, or part of a buffer, directly
  3677. to a file on disk using the `append-to-file' and `write-region'
  3678. functions. Don't use these functions to write to files that are being
  3679. visited; that could cause confusion in the mechanisms for visiting.
  3680. -- Command: append-to-file start end filename
  3681. This function appends the contents of the region delimited by
  3682. START and END in the current buffer to the end of file FILENAME.
  3683. If that file does not exist, it is created. This function returns
  3684. `nil'.
  3685. An error is signaled if FILENAME specifies a nonwritable file, or
  3686. a nonexistent file in a directory where files cannot be created.
  3687. When called from Lisp, this function is completely equivalent to:
  3688. (write-region start end filename t)
  3689. -- Command: write-region start end filename &optional append visit
  3690. lockname mustbenew
  3691. This function writes the region delimited by START and END in the
  3692. current buffer into the file specified by FILENAME.
  3693. If START is `nil', then the command writes the entire buffer
  3694. contents (_not_ just the accessible portion) to the file and
  3695. ignores END.
  3696. If START is a string, then `write-region' writes or appends that
  3697. string, rather than text from the buffer. END is ignored in this
  3698. case.
  3699. If APPEND is non-`nil', then the specified text is appended to the
  3700. existing file contents (if any). If APPEND is an integer,
  3701. `write-region' seeks to that byte offset from the start of the
  3702. file and writes the data from there.
  3703. If MUSTBENEW is non-`nil', then `write-region' asks for
  3704. confirmation if FILENAME names an existing file. If MUSTBENEW is
  3705. the symbol `excl', then `write-region' does not ask for
  3706. confirmation, but instead it signals an error
  3707. `file-already-exists' if the file already exists.
  3708. The test for an existing file, when MUSTBENEW is `excl', uses a
  3709. special system feature. At least for files on a local disk, there
  3710. is no chance that some other program could create a file of the
  3711. same name before Emacs does, without Emacs's noticing.
  3712. If VISIT is `t', then Emacs establishes an association between the
  3713. buffer and the file: the buffer is then visiting that file. It
  3714. also sets the last file modification time for the current buffer to
  3715. FILENAME's modtime, and marks the buffer as not modified. This
  3716. feature is used by `save-buffer', but you probably should not use
  3717. it yourself.
  3718. If VISIT is a string, it specifies the file name to visit. This
  3719. way, you can write the data to one file (FILENAME) while recording
  3720. the buffer as visiting another file (VISIT). The argument VISIT
  3721. is used in the echo area message and also for file locking; VISIT
  3722. is stored in `buffer-file-name'. This feature is used to
  3723. implement `file-precious-flag'; don't use it yourself unless you
  3724. really know what you're doing.
  3725. The optional argument LOCKNAME, if non-`nil', specifies the file
  3726. name to use for purposes of locking and unlocking, overriding
  3727. FILENAME and VISIT for that purpose.
  3728. The function `write-region' converts the data which it writes to
  3729. the appropriate file formats specified by `buffer-file-format' and
  3730. also calls the functions in the list
  3731. `write-region-annotate-functions'. *Note Format Conversion::.
  3732. Normally, `write-region' displays the message `Wrote FILENAME' in
  3733. the echo area. If VISIT is neither `t' nor `nil' nor a string,
  3734. then this message is inhibited. This feature is useful for
  3735. programs that use files for internal purposes, files that the user
  3736. does not need to know about.
  3737. -- Macro: with-temp-file file body...
  3738. The `with-temp-file' macro evaluates the BODY forms with a
  3739. temporary buffer as the current buffer; then, at the end, it
  3740. writes the buffer contents into file FILE. It kills the temporary
  3741. buffer when finished, restoring the buffer that was current before
  3742. the `with-temp-file' form. Then it returns the value of the last
  3743. form in BODY.
  3744. The current buffer is restored even in case of an abnormal exit via
  3745. `throw' or error (*note Nonlocal Exits::).
  3746. See also `with-temp-buffer' in *note The Current Buffer:
  3747. Definition of with-temp-buffer.
  3748. 
  3749. File: elisp, Node: File Locks, Next: Information about Files, Prev: Writing to Files, Up: Files
  3750. 25.5 File Locks
  3751. ===============
  3752. When two users edit the same file at the same time, they are likely to
  3753. interfere with each other. Emacs tries to prevent this situation from
  3754. arising by recording a "file lock" when a file is being modified.
  3755. (File locks are not implemented on Microsoft systems.) Emacs can then
  3756. detect the first attempt to modify a buffer visiting a file that is
  3757. locked by another Emacs job, and ask the user what to do. The file
  3758. lock is really a file, a symbolic link with a special name, stored in
  3759. the same directory as the file you are editing.
  3760. When you access files using NFS, there may be a small probability
  3761. that you and another user will both lock the same file "simultaneously".
  3762. If this happens, it is possible for the two users to make changes
  3763. simultaneously, but Emacs will still warn the user who saves second.
  3764. Also, the detection of modification of a buffer visiting a file changed
  3765. on disk catches some cases of simultaneous editing; see *note
  3766. Modification Time::.
  3767. -- Function: file-locked-p filename
  3768. This function returns `nil' if the file FILENAME is not locked.
  3769. It returns `t' if it is locked by this Emacs process, and it
  3770. returns the name of the user who has locked it if it is locked by
  3771. some other job.
  3772. (file-locked-p "foo")
  3773. => nil
  3774. -- Function: lock-buffer &optional filename
  3775. This function locks the file FILENAME, if the current buffer is
  3776. modified. The argument FILENAME defaults to the current buffer's
  3777. visited file. Nothing is done if the current buffer is not
  3778. visiting a file, or is not modified, or if the system does not
  3779. support locking.
  3780. -- Function: unlock-buffer
  3781. This function unlocks the file being visited in the current buffer,
  3782. if the buffer is modified. If the buffer is not modified, then
  3783. the file should not be locked, so this function does nothing. It
  3784. also does nothing if the current buffer is not visiting a file, or
  3785. if the system does not support locking.
  3786. File locking is not supported on some systems. On systems that do
  3787. not support it, the functions `lock-buffer', `unlock-buffer' and
  3788. `file-locked-p' do nothing and return `nil'.
  3789. -- Function: ask-user-about-lock file other-user
  3790. This function is called when the user tries to modify FILE, but it
  3791. is locked by another user named OTHER-USER. The default
  3792. definition of this function asks the user to say what to do. The
  3793. value this function returns determines what Emacs does next:
  3794. * A value of `t' says to grab the lock on the file. Then this
  3795. user may edit the file and OTHER-USER loses the lock.
  3796. * A value of `nil' says to ignore the lock and let this user
  3797. edit the file anyway.
  3798. * This function may instead signal a `file-locked' error, in
  3799. which case the change that the user was about to make does
  3800. not take place.
  3801. The error message for this error looks like this:
  3802. error--> File is locked: FILE OTHER-USER
  3803. where `file' is the name of the file and OTHER-USER is the
  3804. name of the user who has locked the file.
  3805. If you wish, you can replace the `ask-user-about-lock' function
  3806. with your own version that makes the decision in another way. The
  3807. code for its usual definition is in `userlock.el'.
  3808. 
  3809. File: elisp, Node: Information about Files, Next: Changing Files, Prev: File Locks, Up: Files
  3810. 25.6 Information about Files
  3811. ============================
  3812. The functions described in this section all operate on strings that
  3813. designate file names. With a few exceptions, all the functions have
  3814. names that begin with the word `file'. These functions all return
  3815. information about actual files or directories, so their arguments must
  3816. all exist as actual files or directories unless otherwise noted.
  3817. * Menu:
  3818. * Testing Accessibility:: Is a given file readable? Writable?
  3819. * Kinds of Files:: Is it a directory? A symbolic link?
  3820. * Truenames:: Eliminating symbolic links from a file name.
  3821. * File Attributes:: How large is it? Any other names? Etc.
  3822. * Locating Files:: How to find a file in standard places.
  3823. 
  3824. File: elisp, Node: Testing Accessibility, Next: Kinds of Files, Up: Information about Files
  3825. 25.6.1 Testing Accessibility
  3826. ----------------------------
  3827. These functions test for permission to access a file in specific ways.
  3828. Unless explicitly stated otherwise, they recursively follow symbolic
  3829. links for their file name arguments, at all levels (at the level of the
  3830. file itself and at all levels of parent directories).
  3831. -- Function: file-exists-p filename
  3832. This function returns `t' if a file named FILENAME appears to
  3833. exist. This does not mean you can necessarily read the file, only
  3834. that you can find out its attributes. (On Unix and GNU/Linux,
  3835. this is true if the file exists and you have execute permission on
  3836. the containing directories, regardless of the permissions of the
  3837. file itself.)
  3838. If the file does not exist, or if fascist access control policies
  3839. prevent you from finding the attributes of the file, this function
  3840. returns `nil'.
  3841. Directories are files, so `file-exists-p' returns `t' when given a
  3842. directory name. However, symbolic links are treated specially;
  3843. `file-exists-p' returns `t' for a symbolic link name only if the
  3844. target file exists.
  3845. -- Function: file-readable-p filename
  3846. This function returns `t' if a file named FILENAME exists and you
  3847. can read it. It returns `nil' otherwise.
  3848. (file-readable-p "files.texi")
  3849. => t
  3850. (file-exists-p "/usr/spool/mqueue")
  3851. => t
  3852. (file-readable-p "/usr/spool/mqueue")
  3853. => nil
  3854. -- Function: file-executable-p filename
  3855. This function returns `t' if a file named FILENAME exists and you
  3856. can execute it. It returns `nil' otherwise. On Unix and
  3857. GNU/Linux, if the file is a directory, execute permission means
  3858. you can check the existence and attributes of files inside the
  3859. directory, and open those files if their modes permit.
  3860. -- Function: file-writable-p filename
  3861. This function returns `t' if the file FILENAME can be written or
  3862. created by you, and `nil' otherwise. A file is writable if the
  3863. file exists and you can write it. It is creatable if it does not
  3864. exist, but the specified directory does exist and you can write in
  3865. that directory.
  3866. In the third example below, `foo' is not writable because the
  3867. parent directory does not exist, even though the user could create
  3868. such a directory.
  3869. (file-writable-p "~/foo")
  3870. => t
  3871. (file-writable-p "/foo")
  3872. => nil
  3873. (file-writable-p "~/no-such-dir/foo")
  3874. => nil
  3875. -- Function: file-accessible-directory-p dirname
  3876. This function returns `t' if you have permission to open existing
  3877. files in the directory whose name as a file is DIRNAME; otherwise
  3878. (or if there is no such directory), it returns `nil'. The value
  3879. of DIRNAME may be either a directory name (such as `/foo/') or the
  3880. file name of a file which is a directory (such as `/foo', without
  3881. the final slash).
  3882. Example: after the following,
  3883. (file-accessible-directory-p "/foo")
  3884. => nil
  3885. we can deduce that any attempt to read a file in `/foo/' will give
  3886. an error.
  3887. -- Function: access-file filename string
  3888. This function opens file FILENAME for reading, then closes it and
  3889. returns `nil'. However, if the open fails, it signals an error
  3890. using STRING as the error message text.
  3891. -- Function: file-ownership-preserved-p filename
  3892. This function returns `t' if deleting the file FILENAME and then
  3893. creating it anew would keep the file's owner unchanged. It also
  3894. returns `t' for nonexistent files.
  3895. If FILENAME is a symbolic link, then, unlike the other functions
  3896. discussed here, `file-ownership-preserved-p' does _not_ replace
  3897. FILENAME with its target. However, it does recursively follow
  3898. symbolic links at all levels of parent directories.
  3899. -- Function: file-newer-than-file-p filename1 filename2
  3900. This function returns `t' if the file FILENAME1 is newer than file
  3901. FILENAME2. If FILENAME1 does not exist, it returns `nil'. If
  3902. FILENAME1 does exist, but FILENAME2 does not, it returns `t'.
  3903. In the following example, assume that the file `aug-19' was written
  3904. on the 19th, `aug-20' was written on the 20th, and the file
  3905. `no-file' doesn't exist at all.
  3906. (file-newer-than-file-p "aug-19" "aug-20")
  3907. => nil
  3908. (file-newer-than-file-p "aug-20" "aug-19")
  3909. => t
  3910. (file-newer-than-file-p "aug-19" "no-file")
  3911. => t
  3912. (file-newer-than-file-p "no-file" "aug-19")
  3913. => nil
  3914. You can use `file-attributes' to get a file's last modification
  3915. time as a list of two numbers. *Note File Attributes::.
  3916. 
  3917. File: elisp, Node: Kinds of Files, Next: Truenames, Prev: Testing Accessibility, Up: Information about Files
  3918. 25.6.2 Distinguishing Kinds of Files
  3919. ------------------------------------
  3920. This section describes how to distinguish various kinds of files, such
  3921. as directories, symbolic links, and ordinary files.
  3922. -- Function: file-symlink-p filename
  3923. If the file FILENAME is a symbolic link, the `file-symlink-p'
  3924. function returns the (non-recursive) link target as a string.
  3925. (Determining the file name that the link points to from the target
  3926. is nontrivial.) First, this function recursively follows symbolic
  3927. links at all levels of parent directories.
  3928. If the file FILENAME is not a symbolic link (or there is no such
  3929. file), `file-symlink-p' returns `nil'.
  3930. (file-symlink-p "foo")
  3931. => nil
  3932. (file-symlink-p "sym-link")
  3933. => "foo"
  3934. (file-symlink-p "sym-link2")
  3935. => "sym-link"
  3936. (file-symlink-p "/bin")
  3937. => "/pub/bin"
  3938. The next two functions recursively follow symbolic links at all
  3939. levels for FILENAME.
  3940. -- Function: file-directory-p filename
  3941. This function returns `t' if FILENAME is the name of an existing
  3942. directory, `nil' otherwise.
  3943. (file-directory-p "~rms")
  3944. => t
  3945. (file-directory-p "~rms/lewis/files.texi")
  3946. => nil
  3947. (file-directory-p "~rms/lewis/no-such-file")
  3948. => nil
  3949. (file-directory-p "$HOME")
  3950. => nil
  3951. (file-directory-p
  3952. (substitute-in-file-name "$HOME"))
  3953. => t
  3954. -- Function: file-regular-p filename
  3955. This function returns `t' if the file FILENAME exists and is a
  3956. regular file (not a directory, named pipe, terminal, or other I/O
  3957. device).
  3958. -- Function: file-equal-p file1 file2
  3959. This function returns `t' if the files FILE1 and FILE2 name the
  3960. same file. If FILE1 or FILE2 does not exist, the return value is
  3961. unspecified.
  3962. -- Function: file-in-directory-p file dir
  3963. This function returns `t' if FILE is a file in directory DIR, or
  3964. in a subdirectory of DIR. It also returns `t' if FILE and DIR are
  3965. the same directory. It compares the `file-truename' values of the
  3966. two directories (*note Truenames::). If DIR does not name an
  3967. existing directory, the return value is `nil'.
  3968. 
  3969. File: elisp, Node: Truenames, Next: File Attributes, Prev: Kinds of Files, Up: Information about Files
  3970. 25.6.3 Truenames
  3971. ----------------
  3972. The "truename" of a file is the name that you get by following symbolic
  3973. links at all levels until none remain, then simplifying away `.' and
  3974. `..' appearing as name components. This results in a sort of canonical
  3975. name for the file. A file does not always have a unique truename; the
  3976. number of distinct truenames a file has is equal to the number of hard
  3977. links to the file. However, truenames are useful because they
  3978. eliminate symbolic links as a cause of name variation.
  3979. -- Function: file-truename filename
  3980. This function returns the truename of the file FILENAME. If the
  3981. argument is not an absolute file name, this function first expands
  3982. it against `default-directory'.
  3983. This function does not expand environment variables. Only
  3984. `substitute-in-file-name' does that. *Note Definition of
  3985. substitute-in-file-name::.
  3986. If you may need to follow symbolic links preceding `..' appearing
  3987. as a name component, you should make sure to call `file-truename'
  3988. without prior direct or indirect calls to `expand-file-name', as
  3989. otherwise the file name component immediately preceding `..' will
  3990. be "simplified away" before `file-truename' is called. To
  3991. eliminate the need for a call to `expand-file-name',
  3992. `file-truename' handles `~' in the same way that
  3993. `expand-file-name' does. *Note Functions that Expand Filenames:
  3994. File Name Expansion.
  3995. -- Function: file-chase-links filename &optional limit
  3996. This function follows symbolic links, starting with FILENAME,
  3997. until it finds a file name which is not the name of a symbolic
  3998. link. Then it returns that file name. This function does _not_
  3999. follow symbolic links at the level of parent directories.
  4000. If you specify a number for LIMIT, then after chasing through that
  4001. many links, the function just returns what it has even if that is
  4002. still a symbolic link.
  4003. To illustrate the difference between `file-chase-links' and
  4004. `file-truename', suppose that `/usr/foo' is a symbolic link to the
  4005. directory `/home/foo', and `/home/foo/hello' is an ordinary file (or at
  4006. least, not a symbolic link) or nonexistent. Then we would have:
  4007. (file-chase-links "/usr/foo/hello")
  4008. ;; This does not follow the links in the parent directories.
  4009. => "/usr/foo/hello"
  4010. (file-truename "/usr/foo/hello")
  4011. ;; Assuming that `/home' is not a symbolic link.
  4012. => "/home/foo/hello"
  4013. *Note Buffer File Name::, for related information.
  4014. 
  4015. File: elisp, Node: File Attributes, Next: Locating Files, Prev: Truenames, Up: Information about Files
  4016. 25.6.4 Other Information about Files
  4017. ------------------------------------
  4018. This section describes the functions for getting detailed information
  4019. about a file, other than its contents. This information includes the
  4020. mode bits that control access permissions, the owner and group numbers,
  4021. the number of names, the inode number, the size, and the times of
  4022. access and modification.
  4023. -- Function: file-modes filename
  4024. This function returns the "mode bits" describing the "file
  4025. permissions" of FILENAME, as an integer. It recursively follows
  4026. symbolic links in FILENAME at all levels. If FILENAME does not
  4027. exist, the return value is `nil'.
  4028. *Note File Permissions: (coreutils)File Permissions, for a
  4029. description of mode bits. If the low-order bit is 1, then the
  4030. file is executable by all users, if the second-lowest-order bit is
  4031. 1, then the file is writable by all users, etc. The highest value
  4032. returnable is 4095 (7777 octal), meaning that everyone has read,
  4033. write, and execute permission, that the SUID bit is set for both
  4034. others and group, and that the sticky bit is set.
  4035. (file-modes "~/junk/diffs")
  4036. => 492 ; Decimal integer.
  4037. (format "%o" 492)
  4038. => "754" ; Convert to octal.
  4039. (set-file-modes "~/junk/diffs" #o666)
  4040. => nil
  4041. % ls -l diffs
  4042. -rw-rw-rw- 1 lewis 0 3063 Oct 30 16:00 diffs
  4043. *Note Changing Files::, for functions that change file permissions,
  4044. such as `set-file-modes'.
  4045. *MS-DOS note:* On MS-DOS, there is no such thing as an
  4046. "executable" file mode bit. So `file-modes' considers a file
  4047. executable if its name ends in one of the standard executable
  4048. extensions, such as `.com', `.bat', `.exe', and some others.
  4049. Files that begin with the Unix-standard `#!' signature, such as
  4050. shell and Perl scripts, are also considered executable.
  4051. Directories are also reported as executable, for compatibility with
  4052. Unix. These conventions are also followed by `file-attributes',
  4053. below.
  4054. If the FILENAME argument to the next two functions is a symbolic
  4055. link, then these function do _not_ replace it with its target.
  4056. However, they both recursively follow symbolic links at all levels of
  4057. parent directories.
  4058. -- Function: file-nlinks filename
  4059. This functions returns the number of names (i.e., hard links) that
  4060. file FILENAME has. If the file does not exist, then this function
  4061. returns `nil'. Note that symbolic links have no effect on this
  4062. function, because they are not considered to be names of the files
  4063. they link to.
  4064. % ls -l foo*
  4065. -rw-rw-rw- 2 rms 4 Aug 19 01:27 foo
  4066. -rw-rw-rw- 2 rms 4 Aug 19 01:27 foo1
  4067. (file-nlinks "foo")
  4068. => 2
  4069. (file-nlinks "doesnt-exist")
  4070. => nil
  4071. -- Function: file-attributes filename &optional id-format
  4072. This function returns a list of attributes of file FILENAME. If
  4073. the specified file cannot be opened, it returns `nil'. The
  4074. optional parameter ID-FORMAT specifies the preferred format of
  4075. attributes UID and GID (see below)--the valid values are `'string'
  4076. and `'integer'. The latter is the default, but we plan to change
  4077. that, so you should specify a non-`nil' value for ID-FORMAT if you
  4078. use the returned UID or GID.
  4079. The elements of the list, in order, are:
  4080. 0. `t' for a directory, a string for a symbolic link (the name
  4081. linked to), or `nil' for a text file.
  4082. 1. The number of names the file has. Alternate names, also
  4083. known as hard links, can be created by using the
  4084. `add-name-to-file' function (*note Changing Files::).
  4085. 2. The file's UID, normally as a string. However, if it does
  4086. not correspond to a named user, the value is an integer or a
  4087. floating point number.
  4088. 3. The file's GID, likewise.
  4089. 4. The time of last access, as a list of two integers. The
  4090. first integer has the high-order 16 bits of time, the second
  4091. has the low 16 bits. (This is similar to the value of
  4092. `current-time'; see *note Time of Day::.) Note that on some
  4093. FAT-based filesystems, only the date of last access is
  4094. recorded, so this time will always hold the midnight of the
  4095. day of last access.
  4096. 5. The time of last modification as a list of two integers (as
  4097. above). This is the last time when the file's contents were
  4098. modified.
  4099. 6. The time of last status change as a list of two integers (as
  4100. above). This is the time of the last change to the file's
  4101. access mode bits, its owner and group, and other information
  4102. recorded in the filesystem for the file, beyond the file's
  4103. contents.
  4104. 7. The size of the file in bytes. If the size is too large to
  4105. fit in a Lisp integer, this is a floating point number.
  4106. 8. The file's modes, as a string of ten letters or dashes, as in
  4107. `ls -l'.
  4108. 9. `t' if the file's GID would change if file were deleted and
  4109. recreated; `nil' otherwise.
  4110. 10. The file's inode number. If possible, this is an integer.
  4111. If the inode number is too large to be represented as an
  4112. integer in Emacs Lisp but dividing it by 2^16 yields a
  4113. representable integer, then the value has the form `(HIGH .
  4114. LOW)', where LOW holds the low 16 bits. If the inode number
  4115. is too wide for even that, the value is of the form `(HIGH
  4116. MIDDLE . LOW)', where `high' holds the high bits, MIDDLE the
  4117. middle 24 bits, and LOW the low 16 bits.
  4118. 11. The filesystem number of the device that the file is on.
  4119. Depending on the magnitude of the value, this can be either
  4120. an integer or a cons cell, in the same manner as the inode
  4121. number. This element and the file's inode number together
  4122. give enough information to distinguish any two files on the
  4123. system--no two files can have the same values for both of
  4124. these numbers.
  4125. For example, here are the file attributes for `files.texi':
  4126. (file-attributes "files.texi" 'string)
  4127. => (nil 1 "lh" "users"
  4128. (19145 42977)
  4129. (19141 59576)
  4130. (18340 17300)
  4131. 122295 "-rw-rw-rw-"
  4132. nil (5888 2 . 43978)
  4133. (15479 . 46724))
  4134. and here is how the result is interpreted:
  4135. `nil'
  4136. is neither a directory nor a symbolic link.
  4137. `1'
  4138. has only one name (the name `files.texi' in the current
  4139. default directory).
  4140. `"lh"'
  4141. is owned by the user with name "lh".
  4142. `"users"'
  4143. is in the group with name "users".
  4144. `(19145 42977)'
  4145. was last accessed on Oct 5 2009, at 10:01:37.
  4146. `(19141 59576)'
  4147. last had its contents modified on Oct 2 2009, at 13:49:12.
  4148. `(18340 17300)'
  4149. last had its status changed on Feb 2 2008, at 12:19:00.
  4150. `122295'
  4151. is 122295 bytes long. (It may not contain 122295 characters,
  4152. though, if some of the bytes belong to multibyte sequences,
  4153. and also if the end-of-line format is CR-LF.)
  4154. `"-rw-rw-rw-"'
  4155. has a mode of read and write access for the owner, group, and
  4156. world.
  4157. `nil'
  4158. would retain the same GID if it were recreated.
  4159. `(5888 2 . 43978)'
  4160. has an inode number of 6473924464520138.
  4161. `(15479 . 46724)'
  4162. is on the file-system device whose number is 1014478468.
  4163. SELinux is a Linux kernel feature which provides more sophisticated
  4164. file access controls than ordinary "Unix-style" file permissions. If
  4165. Emacs has been compiled with SELinux support on a system with SELinux
  4166. enabled, you can use the function `file-selinux-context' to retrieve a
  4167. file's SELinux security context. For the function
  4168. `set-file-selinux-context', see *note Changing Files::.
  4169. -- Function: file-selinux-context filename
  4170. This function returns the SELinux security context of the file
  4171. FILENAME. This return value is a list of the form `(USER ROLE
  4172. TYPE RANGE)', whose elements are the context's user, role, type,
  4173. and range respectively, as Lisp strings. See the SELinux
  4174. documentation for details about what these actually mean.
  4175. If the file does not exist or is inaccessible, or if the system
  4176. does not support SELinux, or if Emacs was not compiled with SELinux
  4177. support, then the return value is `(nil nil nil nil)'.
  4178. 
  4179. File: elisp, Node: Locating Files, Prev: File Attributes, Up: Information about Files
  4180. 25.6.5 How to Locate Files in Standard Places
  4181. ---------------------------------------------
  4182. This section explains how to search for a file in a list of directories
  4183. (a "path"), or for an executable file in the standard list of
  4184. executable file directories.
  4185. To search for a user-specific configuration file, *Note Standard
  4186. File Names::, for the `locate-user-emacs-file' function.
  4187. -- Function: locate-file filename path &optional suffixes predicate
  4188. This function searches for a file whose name is FILENAME in a list
  4189. of directories given by PATH, trying the suffixes in SUFFIXES. If
  4190. it finds such a file, it returns the file's absolute file name
  4191. (*note Relative File Names::); otherwise it returns `nil'.
  4192. The optional argument SUFFIXES gives the list of file-name
  4193. suffixes to append to FILENAME when searching. `locate-file'
  4194. tries each possible directory with each of these suffixes. If
  4195. SUFFIXES is `nil', or `("")', then there are no suffixes, and
  4196. FILENAME is used only as-is. Typical values of SUFFIXES are
  4197. `exec-suffixes' (*note Subprocess Creation::), `load-suffixes',
  4198. `load-file-rep-suffixes' and the return value of the function
  4199. `get-load-suffixes' (*note Load Suffixes::).
  4200. Typical values for PATH are `exec-path' (*note Subprocess
  4201. Creation::) when looking for executable programs, or `load-path'
  4202. (*note Library Search::) when looking for Lisp files. If FILENAME
  4203. is absolute, PATH has no effect, but the suffixes in SUFFIXES are
  4204. still tried.
  4205. The optional argument PREDICATE, if non-`nil', specifies a
  4206. predicate function for testing whether a candidate file is
  4207. suitable. The predicate is passed the candidate file name as its
  4208. single argument. If PREDICATE is `nil' or omitted, `locate-file'
  4209. uses `file-readable-p' as the predicate. *Note Kinds of Files::,
  4210. for other useful predicates, e.g. `file-executable-p' and
  4211. `file-directory-p'.
  4212. For compatibility, PREDICATE can also be one of the symbols
  4213. `executable', `readable', `writable', `exists', or a list of one
  4214. or more of these symbols.
  4215. -- Function: executable-find program
  4216. This function searches for the executable file of the named
  4217. PROGRAM and returns the absolute file name of the executable,
  4218. including its file-name extensions, if any. It returns `nil' if
  4219. the file is not found. The functions searches in all the
  4220. directories in `exec-path', and tries all the file-name extensions
  4221. in `exec-suffixes' (*note Subprocess Creation::).
  4222. 
  4223. File: elisp, Node: Changing Files, Next: File Names, Prev: Information about Files, Up: Files
  4224. 25.7 Changing File Names and Attributes
  4225. =======================================
  4226. The functions in this section rename, copy, delete, link, and set the
  4227. modes (permissions) of files.
  4228. In the functions that have an argument NEWNAME, if a file by the
  4229. name of NEWNAME already exists, the actions taken depend on the value
  4230. of the argument OK-IF-ALREADY-EXISTS:
  4231. * Signal a `file-already-exists' error if OK-IF-ALREADY-EXISTS is
  4232. `nil'.
  4233. * Request confirmation if OK-IF-ALREADY-EXISTS is a number.
  4234. * Replace the old file without confirmation if OK-IF-ALREADY-EXISTS
  4235. is any other value.
  4236. The next four commands all recursively follow symbolic links at all
  4237. levels of parent directories for their first argument, but, if that
  4238. argument is itself a symbolic link, then only `copy-file' replaces it
  4239. with its (recursive) target.
  4240. -- Command: add-name-to-file oldname newname &optional
  4241. ok-if-already-exists
  4242. This function gives the file named OLDNAME the additional name
  4243. NEWNAME. This means that NEWNAME becomes a new "hard link" to
  4244. OLDNAME.
  4245. In the first part of the following example, we list two files,
  4246. `foo' and `foo3'.
  4247. % ls -li fo*
  4248. 81908 -rw-rw-rw- 1 rms 29 Aug 18 20:32 foo
  4249. 84302 -rw-rw-rw- 1 rms 24 Aug 18 20:31 foo3
  4250. Now we create a hard link, by calling `add-name-to-file', then list
  4251. the files again. This shows two names for one file, `foo' and
  4252. `foo2'.
  4253. (add-name-to-file "foo" "foo2")
  4254. => nil
  4255. % ls -li fo*
  4256. 81908 -rw-rw-rw- 2 rms 29 Aug 18 20:32 foo
  4257. 81908 -rw-rw-rw- 2 rms 29 Aug 18 20:32 foo2
  4258. 84302 -rw-rw-rw- 1 rms 24 Aug 18 20:31 foo3
  4259. Finally, we evaluate the following:
  4260. (add-name-to-file "foo" "foo3" t)
  4261. and list the files again. Now there are three names for one file:
  4262. `foo', `foo2', and `foo3'. The old contents of `foo3' are lost.
  4263. (add-name-to-file "foo1" "foo3")
  4264. => nil
  4265. % ls -li fo*
  4266. 81908 -rw-rw-rw- 3 rms 29 Aug 18 20:32 foo
  4267. 81908 -rw-rw-rw- 3 rms 29 Aug 18 20:32 foo2
  4268. 81908 -rw-rw-rw- 3 rms 29 Aug 18 20:32 foo3
  4269. This function is meaningless on operating systems where multiple
  4270. names for one file are not allowed. Some systems implement
  4271. multiple names by copying the file instead.
  4272. See also `file-nlinks' in *note File Attributes::.
  4273. -- Command: rename-file filename newname &optional ok-if-already-exists
  4274. This command renames the file FILENAME as NEWNAME.
  4275. If FILENAME has additional names aside from FILENAME, it continues
  4276. to have those names. In fact, adding the name NEWNAME with
  4277. `add-name-to-file' and then deleting FILENAME has the same effect
  4278. as renaming, aside from momentary intermediate states.
  4279. -- Command: copy-file oldname newname &optional ok-if-exists time
  4280. preserve-uid-gid preserve-selinux
  4281. This command copies the file OLDNAME to NEWNAME. An error is
  4282. signaled if OLDNAME does not exist. If NEWNAME names a directory,
  4283. it copies OLDNAME into that directory, preserving its final name
  4284. component.
  4285. If TIME is non-`nil', then this function gives the new file the
  4286. same last-modified time that the old one has. (This works on only
  4287. some operating systems.) If setting the time gets an error,
  4288. `copy-file' signals a `file-date-error' error. In an interactive
  4289. call, a prefix argument specifies a non-`nil' value for TIME.
  4290. This function copies the file modes, too.
  4291. If argument PRESERVE-UID-GID is `nil', we let the operating system
  4292. decide the user and group ownership of the new file (this is
  4293. usually set to the user running Emacs). If PRESERVE-UID-GID is
  4294. non-`nil', we attempt to copy the user and group ownership of the
  4295. file. This works only on some operating systems, and only if you
  4296. have the correct permissions to do so.
  4297. If the optional argument PRESERVE-SELINUX is non-`nil', and Emacs
  4298. has been compiled with SELinux support, this function attempts to
  4299. copy the file's SELinux context (*note File Attributes::).
  4300. -- Command: make-symbolic-link filename newname &optional ok-if-exists
  4301. This command makes a symbolic link to FILENAME, named NEWNAME.
  4302. This is like the shell command `ln -s FILENAME NEWNAME'.
  4303. This function is not available on systems that don't support
  4304. symbolic links.
  4305. -- Command: delete-file filename &optional trash
  4306. This command deletes the file FILENAME. If the file has multiple
  4307. names, it continues to exist under the other names. If FILENAME
  4308. is a symbolic link, `delete-file' deletes only the symbolic link
  4309. and not its target (though it does follow symbolic links at all
  4310. levels of parent directories).
  4311. A suitable kind of `file-error' error is signaled if the file does
  4312. not exist, or is not deletable. (On Unix and GNU/Linux, a file is
  4313. deletable if its directory is writable.)
  4314. If the optional argument TRASH is non-`nil' and the variable
  4315. `delete-by-moving-to-trash' is non-`nil', this command moves the
  4316. file into the system Trash instead of deleting it. *Note
  4317. Miscellaneous File Operations: (emacs)Misc File Ops. When called
  4318. interactively, TRASH is `t' if no prefix argument is given, and
  4319. `nil' otherwise.
  4320. See also `delete-directory' in *note Create/Delete Dirs::.
  4321. -- Command: set-file-modes filename mode
  4322. This function sets the "file mode" (or "file permissions") of
  4323. FILENAME to MODE. It recursively follows symbolic links at all
  4324. levels for FILENAME.
  4325. If called non-interactively, MODE must be an integer. Only the
  4326. lowest 12 bits of the integer are used; on most systems, only the
  4327. lowest 9 bits are meaningful. You can use the Lisp construct for
  4328. octal numbers to enter MODE. For example,
  4329. (set-file-modes #o644)
  4330. specifies that the file should be readable and writable for its
  4331. owner, readable for group members, and readable for all other
  4332. users. *Note File Permissions: (coreutils)File Permissions, for a
  4333. description of mode bit specifications.
  4334. Interactively, MODE is read from the minibuffer using
  4335. `read-file-modes' (see below), which lets the user type in either
  4336. an integer or a string representing the permissions symbolically.
  4337. *Note File Attributes::, for the function `file-modes', which
  4338. returns the permissions of a file.
  4339. -- Function: set-default-file-modes mode
  4340. This function sets the default file permissions for new files
  4341. created by Emacs and its subprocesses. Every file created with
  4342. Emacs initially has these permissions, or a subset of them
  4343. (`write-region' will not grant execute permissions even if the
  4344. default file permissions allow execution). On Unix and GNU/Linux,
  4345. the default permissions are given by the bitwise complement of the
  4346. "umask" value.
  4347. The argument MODE should be an integer which specifies the
  4348. permissions, similar to `set-file-modes' above. Only the lowest 9
  4349. bits are meaningful.
  4350. The default file permissions have no effect when you save a
  4351. modified version of an existing file; saving a file preserves its
  4352. existing permissions.
  4353. -- Function: default-file-modes
  4354. This function returns the default file permissions, as an integer.
  4355. -- Function: read-file-modes &optional prompt base-file
  4356. This function reads a set of file mode bits from the minibuffer.
  4357. The first optional argument PROMPT specifies a non-default prompt.
  4358. Second second optional argument BASE-FILE is the name of a file on
  4359. whose permissions to base the mode bits that this function returns,
  4360. if what the user types specifies mode bits relative to permissions
  4361. of an existing file.
  4362. If user input represents an octal number, this function returns
  4363. that number. If it is a complete symbolic specification of mode
  4364. bits, as in `"u=rwx"', the function converts it to the equivalent
  4365. numeric value using `file-modes-symbolic-to-number' and returns the
  4366. result. If the specification is relative, as in `"o+g"', then the
  4367. permissions on which the specification is based are taken from the
  4368. mode bits of BASE-FILE. If BASE-FILE is omitted or `nil', the
  4369. function uses `0' as the base mode bits. The complete and
  4370. relative specifications can be combined, as in
  4371. `"u+r,g+rx,o+r,g-w"'. *Note File Permissions: (coreutils)File
  4372. Permissions, for a description of file mode specifications.
  4373. -- Function: file-modes-symbolic-to-number modes &optional base-modes
  4374. This function converts a symbolic file mode specification in MODES
  4375. into the equivalent integer value. If the symbolic specification
  4376. is based on an existing file, that file's mode bits are taken from
  4377. the optional argument BASE-MODES; if that argument is omitted or
  4378. `nil', it defaults to 0, i.e. no access rights at all.
  4379. -- Function: set-file-times filename &optional time
  4380. This function sets the access and modification times of FILENAME
  4381. to TIME. The return value is `t' if the times are successfully
  4382. set, otherwise it is `nil'. TIME defaults to the current time and
  4383. must be in the format returned by `current-time' (*note Time of
  4384. Day::).
  4385. -- Function: set-file-selinux-context filename context
  4386. This function sets the SELinux security context of the file
  4387. FILENAME to CONTEXT. *Note File Attributes::, for a brief
  4388. description of SELinux contexts. The CONTEXT argument should be a
  4389. list `(USER ROLE TYPE RANGE)', like the return value of
  4390. `file-selinux-context'. The function does nothing if SELinux is
  4391. disabled, or if Emacs was compiled without SELinux support.
  4392. 
  4393. File: elisp, Node: File Names, Next: Contents of Directories, Prev: Changing Files, Up: Files
  4394. 25.8 File Names
  4395. ===============
  4396. Files are generally referred to by their names, in Emacs as elsewhere.
  4397. File names in Emacs are represented as strings. The functions that
  4398. operate on a file all expect a file name argument.
  4399. In addition to operating on files themselves, Emacs Lisp programs
  4400. often need to operate on file names; i.e., to take them apart and to use
  4401. part of a name to construct related file names. This section describes
  4402. how to manipulate file names.
  4403. The functions in this section do not actually access files, so they
  4404. can operate on file names that do not refer to an existing file or
  4405. directory.
  4406. On MS-DOS and MS-Windows, these functions (like the function that
  4407. actually operate on files) accept MS-DOS or MS-Windows file-name syntax,
  4408. where backslashes separate the components, as well as Unix syntax; but
  4409. they always return Unix syntax. This enables Lisp programs to specify
  4410. file names in Unix syntax and work properly on all systems without
  4411. change.
  4412. * Menu:
  4413. * File Name Components:: The directory part of a file name, and the rest.
  4414. * Relative File Names:: Some file names are relative to a current directory.
  4415. * Directory Names:: A directory's name as a directory
  4416. is different from its name as a file.
  4417. * File Name Expansion:: Converting relative file names to absolute ones.
  4418. * Unique File Names:: Generating names for temporary files.
  4419. * File Name Completion:: Finding the completions for a given file name.
  4420. * Standard File Names:: If your package uses a fixed file name,
  4421. how to handle various operating systems simply.
  4422. 
  4423. File: elisp, Node: File Name Components, Next: Relative File Names, Up: File Names
  4424. 25.8.1 File Name Components
  4425. ---------------------------
  4426. The operating system groups files into directories. To specify a file,
  4427. you must specify the directory and the file's name within that
  4428. directory. Therefore, Emacs considers a file name as having two main
  4429. parts: the "directory name" part, and the "nondirectory" part (or "file
  4430. name within the directory"). Either part may be empty. Concatenating
  4431. these two parts reproduces the original file name.
  4432. On most systems, the directory part is everything up to and including
  4433. the last slash (backslash is also allowed in input on MS-DOS or
  4434. MS-Windows); the nondirectory part is the rest.
  4435. For some purposes, the nondirectory part is further subdivided into
  4436. the name proper and the "version number". On most systems, only backup
  4437. files have version numbers in their names.
  4438. -- Function: file-name-directory filename
  4439. This function returns the directory part of FILENAME, as a
  4440. directory name (*note Directory Names::), or `nil' if FILENAME
  4441. does not include a directory part.
  4442. On GNU and Unix systems, a string returned by this function always
  4443. ends in a slash. On MS-DOS it can also end in a colon.
  4444. (file-name-directory "lewis/foo") ; Unix example
  4445. => "lewis/"
  4446. (file-name-directory "foo") ; Unix example
  4447. => nil
  4448. -- Function: file-name-nondirectory filename
  4449. This function returns the nondirectory part of FILENAME.
  4450. (file-name-nondirectory "lewis/foo")
  4451. => "foo"
  4452. (file-name-nondirectory "foo")
  4453. => "foo"
  4454. (file-name-nondirectory "lewis/")
  4455. => ""
  4456. -- Function: file-name-sans-versions filename &optional
  4457. keep-backup-version
  4458. This function returns FILENAME with any file version numbers,
  4459. backup version numbers, or trailing tildes discarded.
  4460. If KEEP-BACKUP-VERSION is non-`nil', then true file version
  4461. numbers understood as such by the file system are discarded from
  4462. the return value, but backup version numbers are kept.
  4463. (file-name-sans-versions "~rms/foo.~1~")
  4464. => "~rms/foo"
  4465. (file-name-sans-versions "~rms/foo~")
  4466. => "~rms/foo"
  4467. (file-name-sans-versions "~rms/foo")
  4468. => "~rms/foo"
  4469. -- Function: file-name-extension filename &optional period
  4470. This function returns FILENAME's final "extension", if any, after
  4471. applying `file-name-sans-versions' to remove any version/backup
  4472. part. The extension, in a file name, is the part that follows the
  4473. last `.' in the last name component (minus any version/backup
  4474. part).
  4475. This function returns `nil' for extensionless file names such as
  4476. `foo'. It returns `""' for null extensions, as in `foo.'. If the
  4477. last component of a file name begins with a `.', that `.' doesn't
  4478. count as the beginning of an extension. Thus, `.emacs''s
  4479. "extension" is `nil', not `.emacs'.
  4480. If PERIOD is non-`nil', then the returned value includes the
  4481. period that delimits the extension, and if FILENAME has no
  4482. extension, the value is `""'.
  4483. -- Function: file-name-sans-extension filename
  4484. This function returns FILENAME minus its extension, if any. The
  4485. version/backup part, if present, is only removed if the file has an
  4486. extension. For example,
  4487. (file-name-sans-extension "foo.lose.c")
  4488. => "foo.lose"
  4489. (file-name-sans-extension "big.hack/foo")
  4490. => "big.hack/foo"
  4491. (file-name-sans-extension "/my/home/.emacs")
  4492. => "/my/home/.emacs"
  4493. (file-name-sans-extension "/my/home/.emacs.el")
  4494. => "/my/home/.emacs"
  4495. (file-name-sans-extension "~/foo.el.~3~")
  4496. => "~/foo"
  4497. (file-name-sans-extension "~/foo.~3~")
  4498. => "~/foo.~3~"
  4499. Note that the `.~3~' in the two last examples is the backup part,
  4500. not an extension.
  4501. 
  4502. File: elisp, Node: Relative File Names, Next: Directory Names, Prev: File Name Components, Up: File Names
  4503. 25.8.2 Absolute and Relative File Names
  4504. ---------------------------------------
  4505. All the directories in the file system form a tree starting at the root
  4506. directory. A file name can specify all the directory names starting
  4507. from the root of the tree; then it is called an "absolute" file name.
  4508. Or it can specify the position of the file in the tree relative to a
  4509. default directory; then it is called a "relative" file name. On Unix
  4510. and GNU/Linux, an absolute file name starts with a `/' or a `~' (*note
  4511. abbreviate-file-name::), and a relative one does not. On MS-DOS and
  4512. MS-Windows, an absolute file name starts with a slash or a backslash,
  4513. or with a drive specification `X:/', where X is the "drive letter".
  4514. -- Function: file-name-absolute-p filename
  4515. This function returns `t' if file FILENAME is an absolute file
  4516. name, `nil' otherwise.
  4517. (file-name-absolute-p "~rms/foo")
  4518. => t
  4519. (file-name-absolute-p "rms/foo")
  4520. => nil
  4521. (file-name-absolute-p "/user/rms/foo")
  4522. => t
  4523. Given a possibly relative file name, you can convert it to an
  4524. absolute name using `expand-file-name' (*note File Name Expansion::).
  4525. This function converts absolute file names to relative names:
  4526. -- Function: file-relative-name filename &optional directory
  4527. This function tries to return a relative name that is equivalent to
  4528. FILENAME, assuming the result will be interpreted relative to
  4529. DIRECTORY (an absolute directory name or directory file name). If
  4530. DIRECTORY is omitted or `nil', it defaults to the current buffer's
  4531. default directory.
  4532. On some operating systems, an absolute file name begins with a
  4533. device name. On such systems, FILENAME has no relative equivalent
  4534. based on DIRECTORY if they start with two different device names.
  4535. In this case, `file-relative-name' returns FILENAME in absolute
  4536. form.
  4537. (file-relative-name "/foo/bar" "/foo/")
  4538. => "bar"
  4539. (file-relative-name "/foo/bar" "/hack/")
  4540. => "../foo/bar"
  4541. 
  4542. File: elisp, Node: Directory Names, Next: File Name Expansion, Prev: Relative File Names, Up: File Names
  4543. 25.8.3 Directory Names
  4544. ----------------------
  4545. A "directory name" is the name of a directory. A directory is actually
  4546. a kind of file, so it has a file name, which is related to the
  4547. directory name but not identical to it. (This is not quite the same as
  4548. the usual Unix terminology.) These two different names for the same
  4549. entity are related by a syntactic transformation. On GNU and Unix
  4550. systems, this is simple: a directory name ends in a slash, whereas the
  4551. directory's name as a file lacks that slash. On MS-DOS the
  4552. relationship is more complicated.
  4553. The difference between a directory name and its name as a file is
  4554. subtle but crucial. When an Emacs variable or function argument is
  4555. described as being a directory name, a file name of a directory is not
  4556. acceptable. When `file-name-directory' returns a string, that is
  4557. always a directory name.
  4558. The following two functions convert between directory names and file
  4559. names. They do nothing special with environment variable substitutions
  4560. such as `$HOME', and the constructs `~', `.' and `..'.
  4561. -- Function: file-name-as-directory filename
  4562. This function returns a string representing FILENAME in a form
  4563. that the operating system will interpret as the name of a
  4564. directory. On most systems, this means appending a slash to the
  4565. string (if it does not already end in one).
  4566. (file-name-as-directory "~rms/lewis")
  4567. => "~rms/lewis/"
  4568. -- Function: directory-file-name dirname
  4569. This function returns a string representing DIRNAME in a form that
  4570. the operating system will interpret as the name of a file. On most
  4571. systems, this means removing the final slash (or backslash) from
  4572. the string.
  4573. (directory-file-name "~lewis/")
  4574. => "~lewis"
  4575. Given a directory name, you can combine it with a relative file name
  4576. using `concat':
  4577. (concat DIRNAME RELFILE)
  4578. Be sure to verify that the file name is relative before doing that. If
  4579. you use an absolute file name, the results could be syntactically
  4580. invalid or refer to the wrong file.
  4581. If you want to use a directory file name in making such a
  4582. combination, you must first convert it to a directory name using
  4583. `file-name-as-directory':
  4584. (concat (file-name-as-directory DIRFILE) RELFILE)
  4585. Don't try concatenating a slash by hand, as in
  4586. ;;; Wrong!
  4587. (concat DIRFILE "/" RELFILE)
  4588. because this is not portable. Always use `file-name-as-directory'.
  4589. To convert a directory name to its abbreviation, use this function:
  4590. -- Function: abbreviate-file-name filename
  4591. This function returns an abbreviated form of FILENAME. It applies
  4592. the abbreviations specified in `directory-abbrev-alist' (*note
  4593. File Aliases: (emacs)File Aliases.), then substitutes `~' for the
  4594. user's home directory if the argument names a file in the home
  4595. directory or one of its subdirectories. If the home directory is
  4596. a root directory, it is not replaced with `~', because this does
  4597. not make the result shorter on many systems.
  4598. You can use this function for directory names and for file names,
  4599. because it recognizes abbreviations even as part of the name.
  4600. 
  4601. File: elisp, Node: File Name Expansion, Next: Unique File Names, Prev: Directory Names, Up: File Names
  4602. 25.8.4 Functions that Expand Filenames
  4603. --------------------------------------
  4604. "Expanding" a file name means converting a relative file name to an
  4605. absolute one. Since this is done relative to a default directory, you
  4606. must specify the default directory name as well as the file name to be
  4607. expanded. It also involves expanding abbreviations like `~/' (*note
  4608. abbreviate-file-name::), and eliminating redundancies like `./' and
  4609. `NAME/../'.
  4610. -- Function: expand-file-name filename &optional directory
  4611. This function converts FILENAME to an absolute file name. If
  4612. DIRECTORY is supplied, it is the default directory to start with
  4613. if FILENAME is relative. (The value of DIRECTORY should itself be
  4614. an absolute directory name or directory file name; it may start
  4615. with `~'.) Otherwise, the current buffer's value of
  4616. `default-directory' is used. For example:
  4617. (expand-file-name "foo")
  4618. => "/xcssun/users/rms/lewis/foo"
  4619. (expand-file-name "../foo")
  4620. => "/xcssun/users/rms/foo"
  4621. (expand-file-name "foo" "/usr/spool/")
  4622. => "/usr/spool/foo"
  4623. (expand-file-name "$HOME/foo")
  4624. => "/xcssun/users/rms/lewis/$HOME/foo"
  4625. If the part of the combined file name before the first slash is
  4626. `~', it expands to the value of the `HOME' environment variable
  4627. (usually your home directory). If the part before the first slash
  4628. is `~USER' and if USER is a valid login name, it expands to USER's
  4629. home directory.
  4630. Filenames containing `.' or `..' are simplified to their canonical
  4631. form:
  4632. (expand-file-name "bar/../foo")
  4633. => "/xcssun/users/rms/lewis/foo"
  4634. In some cases, a leading `..' component can remain in the output:
  4635. (expand-file-name "../home" "/")
  4636. => "/../home"
  4637. This is for the sake of filesystems that have the concept of a
  4638. "superroot" above the root directory `/'. On other filesystems,
  4639. `/../' is interpreted exactly the same as `/'.
  4640. Note that `expand-file-name' does _not_ expand environment
  4641. variables; only `substitute-in-file-name' does that.
  4642. Note also that `expand-file-name' does not follow symbolic links
  4643. at any level. This results in a difference between the way
  4644. `file-truename' and `expand-file-name' treat `..'. Assuming that
  4645. `/tmp/bar' is a symbolic link to the directory `/tmp/foo/bar' we
  4646. get:
  4647. (file-truename "/tmp/bar/../myfile")
  4648. => "/tmp/foo/myfile"
  4649. (expand-file-name "/tmp/bar/../myfile")
  4650. => "/tmp/myfile"
  4651. If you may need to follow symbolic links preceding `..', you
  4652. should make sure to call `file-truename' without prior direct or
  4653. indirect calls to `expand-file-name'. *Note Truenames::.
  4654. -- Variable: default-directory
  4655. The value of this buffer-local variable is the default directory
  4656. for the current buffer. It should be an absolute directory name;
  4657. it may start with `~'. This variable is buffer-local in every
  4658. buffer.
  4659. `expand-file-name' uses the default directory when its second
  4660. argument is `nil'.
  4661. The value is always a string ending with a slash.
  4662. default-directory
  4663. => "/user/lewis/manual/"
  4664. -- Function: substitute-in-file-name filename
  4665. This function replaces environment variable references in FILENAME
  4666. with the environment variable values. Following standard Unix
  4667. shell syntax, `$' is the prefix to substitute an environment
  4668. variable value. If the input contains `$$', that is converted to
  4669. `$'; this gives the user a way to "quote" a `$'.
  4670. The environment variable name is the series of alphanumeric
  4671. characters (including underscores) that follow the `$'. If the
  4672. character following the `$' is a `{', then the variable name is
  4673. everything up to the matching `}'.
  4674. Calling `substitute-in-file-name' on output produced by
  4675. `substitute-in-file-name' tends to give incorrect results. For
  4676. instance, use of `$$' to quote a single `$' won't work properly,
  4677. and `$' in an environment variable's value could lead to repeated
  4678. substitution. Therefore, programs that call this function and put
  4679. the output where it will be passed to this function need to double
  4680. all `$' characters to prevent subsequent incorrect results.
  4681. Here we assume that the environment variable `HOME', which holds
  4682. the user's home directory name, has value `/xcssun/users/rms'.
  4683. (substitute-in-file-name "$HOME/foo")
  4684. => "/xcssun/users/rms/foo"
  4685. After substitution, if a `~' or a `/' appears immediately after
  4686. another `/', the function discards everything before it (up
  4687. through the immediately preceding `/').
  4688. (substitute-in-file-name "bar/~/foo")
  4689. => "~/foo"
  4690. (substitute-in-file-name "/usr/local/$HOME/foo")
  4691. => "/xcssun/users/rms/foo"
  4692. ;; `/usr/local/' has been discarded.
  4693. 
  4694. File: elisp, Node: Unique File Names, Next: File Name Completion, Prev: File Name Expansion, Up: File Names
  4695. 25.8.5 Generating Unique File Names
  4696. -----------------------------------
  4697. Some programs need to write temporary files. Here is the usual way to
  4698. construct a name for such a file:
  4699. (make-temp-file NAME-OF-APPLICATION)
  4700. The job of `make-temp-file' is to prevent two different users or two
  4701. different jobs from trying to use the exact same file name.
  4702. -- Function: make-temp-file prefix &optional dir-flag suffix
  4703. This function creates a temporary file and returns its name. Emacs
  4704. creates the temporary file's name by adding to PREFIX some random
  4705. characters that are different in each Emacs job. The result is
  4706. guaranteed to be a newly created empty file. On MS-DOS, this
  4707. function can truncate the STRING prefix to fit into the 8+3
  4708. file-name limits. If PREFIX is a relative file name, it is
  4709. expanded against `temporary-file-directory'.
  4710. (make-temp-file "foo")
  4711. => "/tmp/foo232J6v"
  4712. When `make-temp-file' returns, the file has been created and is
  4713. empty. At that point, you should write the intended contents into
  4714. the file.
  4715. If DIR-FLAG is non-`nil', `make-temp-file' creates an empty
  4716. directory instead of an empty file. It returns the file name, not
  4717. the directory name, of that directory. *Note Directory Names::.
  4718. If SUFFIX is non-`nil', `make-temp-file' adds it at the end of the
  4719. file name.
  4720. To prevent conflicts among different libraries running in the same
  4721. Emacs, each Lisp program that uses `make-temp-file' should have its
  4722. own PREFIX. The number added to the end of PREFIX distinguishes
  4723. between the same application running in different Emacs jobs.
  4724. Additional added characters permit a large number of distinct
  4725. names even in one Emacs job.
  4726. The default directory for temporary files is controlled by the
  4727. variable `temporary-file-directory'. This variable gives the user a
  4728. uniform way to specify the directory for all temporary files. Some
  4729. programs use `small-temporary-file-directory' instead, if that is
  4730. non-`nil'. To use it, you should expand the prefix against the proper
  4731. directory before calling `make-temp-file'.
  4732. -- User Option: temporary-file-directory
  4733. This variable specifies the directory name for creating temporary
  4734. files. Its value should be a directory name (*note Directory
  4735. Names::), but it is good for Lisp programs to cope if the value is
  4736. a directory's file name instead. Using the value as the second
  4737. argument to `expand-file-name' is a good way to achieve that.
  4738. The default value is determined in a reasonable way for your
  4739. operating system; it is based on the `TMPDIR', `TMP' and `TEMP'
  4740. environment variables, with a fall-back to a system-dependent name
  4741. if none of these variables is defined.
  4742. Even if you do not use `make-temp-file' to create the temporary
  4743. file, you should still use this variable to decide which directory
  4744. to put the file in. However, if you expect the file to be small,
  4745. you should use `small-temporary-file-directory' first if that is
  4746. non-`nil'.
  4747. -- User Option: small-temporary-file-directory
  4748. This variable specifies the directory name for creating certain
  4749. temporary files, which are likely to be small.
  4750. If you want to write a temporary file which is likely to be small,
  4751. you should compute the directory like this:
  4752. (make-temp-file
  4753. (expand-file-name PREFIX
  4754. (or small-temporary-file-directory
  4755. temporary-file-directory)))
  4756. -- Function: make-temp-name base-name
  4757. This function generates a string that can be used as a unique file
  4758. name. The name starts with BASE-NAME, and has several random
  4759. characters appended to it, which are different in each Emacs job.
  4760. It is like `make-temp-file' except that (i) it just constructs a
  4761. name, and does not create a file, and (ii) BASE-NAME should be an
  4762. absolute file name (on MS-DOS, this function can truncate
  4763. BASE-NAME to fit into the 8+3 file-name limits).
  4764. *Warning:* In most cases, you should not use this function; use
  4765. `make-temp-file' instead! This function is susceptible to a race
  4766. condition, between the `make-temp-name' call and the creation of
  4767. the file, which in some cases may cause a security hole.
  4768. 
  4769. File: elisp, Node: File Name Completion, Next: Standard File Names, Prev: Unique File Names, Up: File Names
  4770. 25.8.6 File Name Completion
  4771. ---------------------------
  4772. This section describes low-level subroutines for completing a file
  4773. name. For higher level functions, see *note Reading File Names::.
  4774. -- Function: file-name-all-completions partial-filename directory
  4775. This function returns a list of all possible completions for a file
  4776. whose name starts with PARTIAL-FILENAME in directory DIRECTORY.
  4777. The order of the completions is the order of the files in the
  4778. directory, which is unpredictable and conveys no useful
  4779. information.
  4780. The argument PARTIAL-FILENAME must be a file name containing no
  4781. directory part and no slash (or backslash on some systems). The
  4782. current buffer's default directory is prepended to DIRECTORY, if
  4783. DIRECTORY is not absolute.
  4784. In the following example, suppose that `~rms/lewis' is the current
  4785. default directory, and has five files whose names begin with `f':
  4786. `foo', `file~', `file.c', `file.c.~1~', and `file.c.~2~'.
  4787. (file-name-all-completions "f" "")
  4788. => ("foo" "file~" "file.c.~2~"
  4789. "file.c.~1~" "file.c")
  4790. (file-name-all-completions "fo" "")
  4791. => ("foo")
  4792. -- Function: file-name-completion filename directory &optional
  4793. predicate
  4794. This function completes the file name FILENAME in directory
  4795. DIRECTORY. It returns the longest prefix common to all file names
  4796. in directory DIRECTORY that start with FILENAME. If PREDICATE is
  4797. non-`nil' then it ignores possible completions that don't satisfy
  4798. PREDICATE, after calling that function with one argument, the
  4799. expanded absolute file name.
  4800. If only one match exists and FILENAME matches it exactly, the
  4801. function returns `t'. The function returns `nil' if directory
  4802. DIRECTORY contains no name starting with FILENAME.
  4803. In the following example, suppose that the current default
  4804. directory has five files whose names begin with `f': `foo',
  4805. `file~', `file.c', `file.c.~1~', and `file.c.~2~'.
  4806. (file-name-completion "fi" "")
  4807. => "file"
  4808. (file-name-completion "file.c.~1" "")
  4809. => "file.c.~1~"
  4810. (file-name-completion "file.c.~1~" "")
  4811. => t
  4812. (file-name-completion "file.c.~3" "")
  4813. => nil
  4814. -- User Option: completion-ignored-extensions
  4815. `file-name-completion' usually ignores file names that end in any
  4816. string in this list. It does not ignore them when all the possible
  4817. completions end in one of these suffixes. This variable has no
  4818. effect on `file-name-all-completions'.
  4819. A typical value might look like this:
  4820. completion-ignored-extensions
  4821. => (".o" ".elc" "~" ".dvi")
  4822. If an element of `completion-ignored-extensions' ends in a slash
  4823. `/', it signals a directory. The elements which do _not_ end in a
  4824. slash will never match a directory; thus, the above value will not
  4825. filter out a directory named `foo.elc'.
  4826. 
  4827. File: elisp, Node: Standard File Names, Prev: File Name Completion, Up: File Names
  4828. 25.8.7 Standard File Names
  4829. --------------------------
  4830. Sometimes, an Emacs Lisp program needs to specify a standard file name
  4831. for a particular use--typically, to hold configuration data specified
  4832. by the current user. Usually, such files should be located in the
  4833. directory specified by `user-emacs-directory', which is `~/.emacs.d' by
  4834. default (*note Init File::). For example, abbrev definitions are
  4835. stored by default in `~/.emacs.d/abbrev_defs'. The easiest way to
  4836. specify such a file name is to use the function
  4837. `locate-user-emacs-file'.
  4838. -- Function: locate-user-emacs-file base-name &optional old-name
  4839. This function returns an absolute file name for an Emacs-specific
  4840. configuration or data file. The argument `base-name' should be a
  4841. relative file name. The return value is the absolute name of a
  4842. file in the directory specified by `user-emacs-directory'; if that
  4843. directory does not exist, this function creates it.
  4844. If the optional argument OLD-NAME is non-`nil', it specifies a
  4845. file in the user's home directory, `~/OLD-NAME'. If such a file
  4846. exists, the return value is the absolute name of that file,
  4847. instead of the file specified by BASE-NAME. This argument is
  4848. intended to be used by Emacs packages to provide backward
  4849. compatibility. For instance, prior to the introduction of
  4850. `user-emacs-directory', the abbrev file was located in
  4851. `~/.abbrev_defs'. Here is the definition of `abbrev-file-name':
  4852. (defcustom abbrev-file-name
  4853. (locate-user-emacs-file "abbrev_defs" ".abbrev_defs")
  4854. "Default name of file from which to read abbrevs."
  4855. ...
  4856. :type 'file)
  4857. A lower-level function for standardizing file names, which
  4858. `locate-user-emacs-file' uses as a subroutine, is
  4859. `convert-standard-filename'.
  4860. -- Function: convert-standard-filename filename
  4861. This function returns a file name based on FILENAME, which fits
  4862. the conventions of the current operating system.
  4863. On GNU and Unix systems, this simply returns FILENAME. On other
  4864. operating systems, it may enforce system-specific file name
  4865. conventions; for example, on MS-DOS this function performs a
  4866. variety of changes to enforce MS-DOS file name limitations,
  4867. including converting any leading `.' to `_' and truncating to three
  4868. characters after the `.'.
  4869. The recommended way to use this function is to specify a name which
  4870. fits the conventions of GNU and Unix systems, and pass it to
  4871. `convert-standard-filename'.
  4872. 
  4873. File: elisp, Node: Contents of Directories, Next: Create/Delete Dirs, Prev: File Names, Up: Files
  4874. 25.9 Contents of Directories
  4875. ============================
  4876. A directory is a kind of file that contains other files entered under
  4877. various names. Directories are a feature of the file system.
  4878. Emacs can list the names of the files in a directory as a Lisp list,
  4879. or display the names in a buffer using the `ls' shell command. In the
  4880. latter case, it can optionally display information about each file,
  4881. depending on the options passed to the `ls' command.
  4882. -- Function: directory-files directory &optional full-name
  4883. match-regexp nosort
  4884. This function returns a list of the names of the files in the
  4885. directory DIRECTORY. By default, the list is in alphabetical
  4886. order.
  4887. If FULL-NAME is non-`nil', the function returns the files'
  4888. absolute file names. Otherwise, it returns the names relative to
  4889. the specified directory.
  4890. If MATCH-REGEXP is non-`nil', this function returns only those
  4891. file names that contain a match for that regular expression--the
  4892. other file names are excluded from the list. On case-insensitive
  4893. filesystems, the regular expression matching is case-insensitive.
  4894. If NOSORT is non-`nil', `directory-files' does not sort the list,
  4895. so you get the file names in no particular order. Use this if you
  4896. want the utmost possible speed and don't care what order the files
  4897. are processed in. If the order of processing is visible to the
  4898. user, then the user will probably be happier if you do sort the
  4899. names.
  4900. (directory-files "~lewis")
  4901. => ("#foo#" "#foo.el#" "." ".."
  4902. "dired-mods.el" "files.texi"
  4903. "files.texi.~1~")
  4904. An error is signaled if DIRECTORY is not the name of a directory
  4905. that can be read.
  4906. -- Function: directory-files-and-attributes directory &optional
  4907. full-name match-regexp nosort id-format
  4908. This is similar to `directory-files' in deciding which files to
  4909. report on and how to report their names. However, instead of
  4910. returning a list of file names, it returns for each file a list
  4911. `(FILENAME . ATTRIBUTES)', where ATTRIBUTES is what
  4912. `file-attributes' would return for that file. The optional
  4913. argument ID-FORMAT has the same meaning as the corresponding
  4914. argument to `file-attributes' (*note Definition of
  4915. file-attributes::).
  4916. -- Function: file-expand-wildcards pattern &optional full
  4917. This function expands the wildcard pattern PATTERN, returning a
  4918. list of file names that match it.
  4919. If PATTERN is written as an absolute file name, the values are
  4920. absolute also.
  4921. If PATTERN is written as a relative file name, it is interpreted
  4922. relative to the current default directory. The file names
  4923. returned are normally also relative to the current default
  4924. directory. However, if FULL is non-`nil', they are absolute.
  4925. -- Function: insert-directory file switches &optional wildcard
  4926. full-directory-p
  4927. This function inserts (in the current buffer) a directory listing
  4928. for directory FILE, formatted with `ls' according to SWITCHES. It
  4929. leaves point after the inserted text. SWITCHES may be a string of
  4930. options, or a list of strings representing individual options.
  4931. The argument FILE may be either a directory name or a file
  4932. specification including wildcard characters. If WILDCARD is
  4933. non-`nil', that means treat FILE as a file specification with
  4934. wildcards.
  4935. If FULL-DIRECTORY-P is non-`nil', that means the directory listing
  4936. is expected to show the full contents of a directory. You should
  4937. specify `t' when FILE is a directory and switches do not contain
  4938. `-d'. (The `-d' option to `ls' says to describe a directory
  4939. itself as a file, rather than showing its contents.)
  4940. On most systems, this function works by running a directory listing
  4941. program whose name is in the variable `insert-directory-program'.
  4942. If WILDCARD is non-`nil', it also runs the shell specified by
  4943. `shell-file-name', to expand the wildcards.
  4944. MS-DOS and MS-Windows systems usually lack the standard Unix
  4945. program `ls', so this function emulates the standard Unix program
  4946. `ls' with Lisp code.
  4947. As a technical detail, when SWITCHES contains the long `--dired'
  4948. option, `insert-directory' treats it specially, for the sake of
  4949. dired. However, the normally equivalent short `-D' option is just
  4950. passed on to `insert-directory-program', as any other option.
  4951. -- Variable: insert-directory-program
  4952. This variable's value is the program to run to generate a
  4953. directory listing for the function `insert-directory'. It is
  4954. ignored on systems which generate the listing with Lisp code.
  4955. 
  4956. File: elisp, Node: Create/Delete Dirs, Next: Magic File Names, Prev: Contents of Directories, Up: Files
  4957. 25.10 Creating, Copying and Deleting Directories
  4958. ================================================
  4959. Most Emacs Lisp file-manipulation functions get errors when used on
  4960. files that are directories. For example, you cannot delete a directory
  4961. with `delete-file'. These special functions exist to create and delete
  4962. directories.
  4963. -- Command: make-directory dirname &optional parents
  4964. This command creates a directory named DIRNAME. If PARENTS is
  4965. non-`nil', as is always the case in an interactive call, that
  4966. means to create the parent directories first, if they don't
  4967. already exist.
  4968. `mkdir' is an alias for this.
  4969. -- Command: copy-directory dirname newname &optional keep-time parents
  4970. copy-contents
  4971. This command copies the directory named DIRNAME to NEWNAME. If
  4972. NEWNAME names an existing directory, DIRNAME will be copied to a
  4973. subdirectory there.
  4974. It always sets the file modes of the copied files to match the
  4975. corresponding original file.
  4976. The third argument KEEP-TIME non-`nil' means to preserve the
  4977. modification time of the copied files. A prefix arg makes
  4978. KEEP-TIME non-`nil'.
  4979. The fourth argument PARENTS says whether to create parent
  4980. directories if they don't exist. Interactively, this happens by
  4981. default.
  4982. The fifth argument COPY-CONTENTS, if non-`nil', means to copy the
  4983. contents of DIRNAME directly into NEWNAME if the latter is an
  4984. existing directory, instead of copying DIRNAME into it as a
  4985. subdirectory.
  4986. -- Command: delete-directory dirname &optional recursive trash
  4987. This command deletes the directory named DIRNAME. The function
  4988. `delete-file' does not work for files that are directories; you
  4989. must use `delete-directory' for them. If RECURSIVE is `nil', and
  4990. the directory contains any files, `delete-directory' signals an
  4991. error.
  4992. `delete-directory' only follows symbolic links at the level of
  4993. parent directories.
  4994. If the optional argument TRASH is non-`nil' and the variable
  4995. `delete-by-moving-to-trash' is non-`nil', this command moves the
  4996. file into the system Trash instead of deleting it. *Note
  4997. Miscellaneous File Operations: (emacs)Misc File Ops. When called
  4998. interactively, TRASH is `t' if no prefix argument is given, and
  4999. `nil' otherwise.
  5000. 
  5001. File: elisp, Node: Magic File Names, Next: Format Conversion, Prev: Create/Delete Dirs, Up: Files
  5002. 25.11 Making Certain File Names "Magic"
  5003. =======================================
  5004. You can implement special handling for certain file names. This is
  5005. called making those names "magic". The principal use for this feature
  5006. is in implementing remote file names (*note Remote Files: (emacs)Remote
  5007. Files.).
  5008. To define a kind of magic file name, you must supply a regular
  5009. expression to define the class of names (all those that match the
  5010. regular expression), plus a handler that implements all the primitive
  5011. Emacs file operations for file names that match.
  5012. The variable `file-name-handler-alist' holds a list of handlers,
  5013. together with regular expressions that determine when to apply each
  5014. handler. Each element has this form:
  5015. (REGEXP . HANDLER)
  5016. All the Emacs primitives for file access and file name transformation
  5017. check the given file name against `file-name-handler-alist'. If the
  5018. file name matches REGEXP, the primitives handle that file by calling
  5019. HANDLER.
  5020. The first argument given to HANDLER is the name of the primitive, as
  5021. a symbol; the remaining arguments are the arguments that were passed to
  5022. that primitive. (The first of these arguments is most often the file
  5023. name itself.) For example, if you do this:
  5024. (file-exists-p FILENAME)
  5025. and FILENAME has handler HANDLER, then HANDLER is called like this:
  5026. (funcall HANDLER 'file-exists-p FILENAME)
  5027. When a function takes two or more arguments that must be file names,
  5028. it checks each of those names for a handler. For example, if you do
  5029. this:
  5030. (expand-file-name FILENAME DIRNAME)
  5031. then it checks for a handler for FILENAME and then for a handler for
  5032. DIRNAME. In either case, the HANDLER is called like this:
  5033. (funcall HANDLER 'expand-file-name FILENAME DIRNAME)
  5034. The HANDLER then needs to figure out whether to handle FILENAME or
  5035. DIRNAME.
  5036. If the specified file name matches more than one handler, the one
  5037. whose match starts last in the file name gets precedence. This rule is
  5038. chosen so that handlers for jobs such as uncompression are handled
  5039. first, before handlers for jobs such as remote file access.
  5040. Here are the operations that a magic file name handler gets to
  5041. handle:
  5042. `access-file', `add-name-to-file', `byte-compiler-base-file-name',
  5043. `copy-directory', `copy-file', `delete-directory', `delete-file',
  5044. `diff-latest-backup-file', `directory-file-name', `directory-files',
  5045. `directory-files-and-attributes', `dired-compress-file',
  5046. `dired-uncache',
  5047. `expand-file-name', `file-accessible-directory-p', `file-attributes',
  5048. `file-directory-p', `file-executable-p', `file-exists-p',
  5049. `file-local-copy', `file-remote-p', `file-modes',
  5050. `file-name-all-completions', `file-name-as-directory',
  5051. `file-name-completion', `file-name-directory', `file-name-nondirectory',
  5052. `file-name-sans-versions', `file-newer-than-file-p',
  5053. `file-ownership-preserved-p', `file-readable-p', `file-regular-p',
  5054. `file-in-directory-p', `file-symlink-p', `file-truename',
  5055. `file-writable-p', `file-equal-p', `find-backup-file-name',
  5056. `get-file-buffer', `insert-directory', `insert-file-contents',
  5057. `load', `make-auto-save-file-name', `make-directory',
  5058. `make-directory-internal', `make-symbolic-link',
  5059. `process-file', `rename-file', `set-file-modes', `set-file-times',
  5060. `set-visited-file-modtime', `shell-command', `start-file-process',
  5061. `substitute-in-file-name',
  5062. `unhandled-file-name-directory', `vc-registered',
  5063. `verify-visited-file-modtime',
  5064. `write-region'.
  5065. Handlers for `insert-file-contents' typically need to clear the
  5066. buffer's modified flag, with `(set-buffer-modified-p nil)', if the
  5067. VISIT argument is non-`nil'. This also has the effect of unlocking the
  5068. buffer if it is locked.
  5069. The handler function must handle all of the above operations, and
  5070. possibly others to be added in the future. It need not implement all
  5071. these operations itself--when it has nothing special to do for a
  5072. certain operation, it can reinvoke the primitive, to handle the
  5073. operation "in the usual way". It should always reinvoke the primitive
  5074. for an operation it does not recognize. Here's one way to do this:
  5075. (defun my-file-handler (operation &rest args)
  5076. ;; First check for the specific operations
  5077. ;; that we have special handling for.
  5078. (cond ((eq operation 'insert-file-contents) ...)
  5079. ((eq operation 'write-region) ...)
  5080. ...
  5081. ;; Handle any operation we don't know about.
  5082. (t (let ((inhibit-file-name-handlers
  5083. (cons 'my-file-handler
  5084. (and (eq inhibit-file-name-operation operation)
  5085. inhibit-file-name-handlers)))
  5086. (inhibit-file-name-operation operation))
  5087. (apply operation args)))))
  5088. When a handler function decides to call the ordinary Emacs primitive
  5089. for the operation at hand, it needs to prevent the primitive from
  5090. calling the same handler once again, thus leading to an infinite
  5091. recursion. The example above shows how to do this, with the variables
  5092. `inhibit-file-name-handlers' and `inhibit-file-name-operation'. Be
  5093. careful to use them exactly as shown above; the details are crucial for
  5094. proper behavior in the case of multiple handlers, and for operations
  5095. that have two file names that may each have handlers.
  5096. Handlers that don't really do anything special for actual access to
  5097. the file--such as the ones that implement completion of host names for
  5098. remote file names--should have a non-`nil' `safe-magic' property. For
  5099. instance, Emacs normally "protects" directory names it finds in `PATH'
  5100. from becoming magic, if they look like magic file names, by prefixing
  5101. them with `/:'. But if the handler that would be used for them has a
  5102. non-`nil' `safe-magic' property, the `/:' is not added.
  5103. A file name handler can have an `operations' property to declare
  5104. which operations it handles in a nontrivial way. If this property has
  5105. a non-`nil' value, it should be a list of operations; then only those
  5106. operations will call the handler. This avoids inefficiency, but its
  5107. main purpose is for autoloaded handler functions, so that they won't be
  5108. loaded except when they have real work to do.
  5109. Simply deferring all operations to the usual primitives does not
  5110. work. For instance, if the file name handler applies to
  5111. `file-exists-p', then it must handle `load' itself, because the usual
  5112. `load' code won't work properly in that case. However, if the handler
  5113. uses the `operations' property to say it doesn't handle
  5114. `file-exists-p', then it need not handle `load' nontrivially.
  5115. -- Variable: inhibit-file-name-handlers
  5116. This variable holds a list of handlers whose use is presently
  5117. inhibited for a certain operation.
  5118. -- Variable: inhibit-file-name-operation
  5119. The operation for which certain handlers are presently inhibited.
  5120. -- Function: find-file-name-handler file operation
  5121. This function returns the handler function for file name FILE, or
  5122. `nil' if there is none. The argument OPERATION should be the
  5123. operation to be performed on the file--the value you will pass to
  5124. the handler as its first argument when you call it. If OPERATION
  5125. equals `inhibit-file-name-operation', or if it is not found in the
  5126. `operations' property of the handler, this function returns `nil'.
  5127. -- Function: file-local-copy filename
  5128. This function copies file FILENAME to an ordinary non-magic file
  5129. on the local machine, if it isn't on the local machine already.
  5130. Magic file names should handle the `file-local-copy' operation if
  5131. they refer to files on other machines. A magic file name that is
  5132. used for other purposes than remote file access should not handle
  5133. `file-local-copy'; then this function will treat the file as local.
  5134. If FILENAME is local, whether magic or not, this function does
  5135. nothing and returns `nil'. Otherwise it returns the file name of
  5136. the local copy file.
  5137. -- Function: file-remote-p filename &optional identification connected
  5138. This function tests whether FILENAME is a remote file. If
  5139. FILENAME is local (not remote), the return value is `nil'. If
  5140. FILENAME is indeed remote, the return value is a string that
  5141. identifies the remote system.
  5142. This identifier string can include a host name and a user name, as
  5143. well as characters designating the method used to access the remote
  5144. system. For example, the remote identifier string for the filename
  5145. `/sudo::/some/file' is `/sudo:root@localhost:'.
  5146. If `file-remote-p' returns the same identifier for two different
  5147. filenames, that means they are stored on the same file system and
  5148. can be accessed locally with respect to each other. This means,
  5149. for example, that it is possible to start a remote process
  5150. accessing both files at the same time. Implementers of file
  5151. handlers need to ensure this principle is valid.
  5152. IDENTIFICATION specifies which part of the identifier shall be
  5153. returned as string. IDENTIFICATION can be the symbol `method',
  5154. `user' or `host'; any other value is handled like `nil' and means
  5155. to return the complete identifier string. In the example above,
  5156. the remote `user' identifier string would be `root'.
  5157. If CONNECTED is non-`nil', this function returns `nil' even if
  5158. FILENAME is remote, if Emacs has no network connection to its
  5159. host. This is useful when you want to avoid the delay of making
  5160. connections when they don't exist.
  5161. -- Function: unhandled-file-name-directory filename
  5162. This function returns the name of a directory that is not magic.
  5163. It uses the directory part of FILENAME if that is not magic. For a
  5164. magic file name, it invokes the file name handler, which therefore
  5165. decides what value to return. If FILENAME is not accessible from
  5166. a local process, then the file name handler should indicate it by
  5167. returning `nil'.
  5168. This is useful for running a subprocess; every subprocess must
  5169. have a non-magic directory to serve as its current directory, and
  5170. this function is a good way to come up with one.
  5171. -- User Option: remote-file-name-inhibit-cache
  5172. The attributes of remote files can be cached for better
  5173. performance. If they are changed outside of Emacs's control, the
  5174. cached values become invalid, and must be reread.
  5175. When this variable is set to `nil', cached values are never
  5176. expired. Use this setting with caution, only if you are sure
  5177. nothing other than Emacs ever changes the remote files. If it is
  5178. set to `t', cached values are never used. This is the safest
  5179. value, but could result in performance degradation.
  5180. A compromise is to set it to a positive number. This means that
  5181. cached values are used for that amount of seconds since they were
  5182. cached. If a remote file is checked regularly, it might be a good
  5183. idea to let-bind this variable to a value less than the time period
  5184. between consecutive checks. For example:
  5185. (defun display-time-file-nonempty-p (file)
  5186. (let ((remote-file-name-inhibit-cache
  5187. (- display-time-interval 5)))
  5188. (and (file-exists-p file)
  5189. (< 0 (nth 7 (file-attributes
  5190. (file-chase-links file)))))))
  5191. 
  5192. File: elisp, Node: Format Conversion, Prev: Magic File Names, Up: Files
  5193. 25.12 File Format Conversion
  5194. ============================
  5195. Emacs performs several steps to convert the data in a buffer (text,
  5196. text properties, and possibly other information) to and from a
  5197. representation suitable for storing into a file. This section describes
  5198. the fundamental functions that perform this "format conversion", namely
  5199. `insert-file-contents' for reading a file into a buffer, and
  5200. `write-region' for writing a buffer into a file.
  5201. * Menu:
  5202. * Overview: Format Conversion Overview. `insert-file-contents' and `write-region'.
  5203. * Round-Trip: Format Conversion Round-Trip. Using `format-alist'.
  5204. * Piecemeal: Format Conversion Piecemeal. Specifying non-paired conversion.
  5205. 
  5206. File: elisp, Node: Format Conversion Overview, Next: Format Conversion Round-Trip, Up: Format Conversion
  5207. 25.12.1 Overview
  5208. ----------------
  5209. The function `insert-file-contents':
  5210. * initially, inserts bytes from the file into the buffer;
  5211. * decodes bytes to characters as appropriate;
  5212. * processes formats as defined by entries in `format-alist'; and
  5213. * calls functions in `after-insert-file-functions'.
  5214. The function `write-region':
  5215. * initially, calls functions in `write-region-annotate-functions';
  5216. * processes formats as defined by entries in `format-alist';
  5217. * encodes characters to bytes as appropriate; and
  5218. * modifies the file with the bytes.
  5219. This shows the symmetry of the lowest-level operations; reading and
  5220. writing handle things in opposite order. The rest of this section
  5221. describes the two facilities surrounding the three variables named
  5222. above, as well as some related functions. *note Coding Systems::, for
  5223. details on character encoding and decoding.
  5224. 
  5225. Local Variables:
  5226. coding: iso-8859-1
  5227. End: