elisp-2 292 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129
  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: Arrays, Next: Array Functions, Prev: Sequence Functions, Up: Sequences Arrays Vectors
  23. 6.2 Arrays
  24. ==========
  25. An "array" object has slots that hold a number of other Lisp objects,
  26. called the elements of the array. Any element of an array may be
  27. accessed in constant time. In contrast, the time to access an element
  28. of a list is proportional to the position of that element in the list.
  29. Emacs defines four types of array, all one-dimensional: "strings"
  30. (*note String Type::), "vectors" (*note Vector Type::), "bool-vectors"
  31. (*note Bool-Vector Type::), and "char-tables" (*note Char-Table
  32. Type::). Vectors and char-tables can hold elements of any type, but
  33. strings can only hold characters, and bool-vectors can only hold `t'
  34. and `nil'.
  35. All four kinds of array share these characteristics:
  36. * The first element of an array has index zero, the second element
  37. has index 1, and so on. This is called "zero-origin" indexing.
  38. For example, an array of four elements has indices 0, 1, 2, and 3.
  39. * The length of the array is fixed once you create it; you cannot
  40. change the length of an existing array.
  41. * For purposes of evaluation, the array is a constant--i.e., it
  42. evaluates to itself.
  43. * The elements of an array may be referenced or changed with the
  44. functions `aref' and `aset', respectively (*note Array
  45. Functions::).
  46. When you create an array, other than a char-table, you must specify
  47. its length. You cannot specify the length of a char-table, because that
  48. is determined by the range of character codes.
  49. In principle, if you want an array of text characters, you could use
  50. either a string or a vector. In practice, we always choose strings for
  51. such applications, for four reasons:
  52. * They occupy one-fourth the space of a vector of the same elements.
  53. * Strings are printed in a way that shows the contents more clearly
  54. as text.
  55. * Strings can hold text properties. *Note Text Properties::.
  56. * Many of the specialized editing and I/O facilities of Emacs accept
  57. only strings. For example, you cannot insert a vector of
  58. characters into a buffer the way you can insert a string. *Note
  59. Strings and Characters::.
  60. By contrast, for an array of keyboard input characters (such as a key
  61. sequence), a vector may be necessary, because many keyboard input
  62. characters are outside the range that will fit in a string. *Note Key
  63. Sequence Input::.
  64. 
  65. File: elisp, Node: Array Functions, Next: Vectors, Prev: Arrays, Up: Sequences Arrays Vectors
  66. 6.3 Functions that Operate on Arrays
  67. ====================================
  68. In this section, we describe the functions that accept all types of
  69. arrays.
  70. -- Function: arrayp object
  71. This function returns `t' if OBJECT is an array (i.e., a vector, a
  72. string, a bool-vector or a char-table).
  73. (arrayp [a])
  74. => t
  75. (arrayp "asdf")
  76. => t
  77. (arrayp (syntax-table)) ;; A char-table.
  78. => t
  79. -- Function: aref array index
  80. This function returns the INDEXth element of ARRAY. The first
  81. element is at index zero.
  82. (setq primes [2 3 5 7 11 13])
  83. => [2 3 5 7 11 13]
  84. (aref primes 4)
  85. => 11
  86. (aref "abcdefg" 1)
  87. => 98 ; `b' is ASCII code 98.
  88. See also the function `elt', in *note Sequence Functions::.
  89. -- Function: aset array index object
  90. This function sets the INDEXth element of ARRAY to be OBJECT. It
  91. returns OBJECT.
  92. (setq w [foo bar baz])
  93. => [foo bar baz]
  94. (aset w 0 'fu)
  95. => fu
  96. w
  97. => [fu bar baz]
  98. (setq x "asdfasfd")
  99. => "asdfasfd"
  100. (aset x 3 ?Z)
  101. => 90
  102. x
  103. => "asdZasfd"
  104. If ARRAY is a string and OBJECT is not a character, a
  105. `wrong-type-argument' error results. The function converts a
  106. unibyte string to multibyte if necessary to insert a character.
  107. -- Function: fillarray array object
  108. This function fills the array ARRAY with OBJECT, so that each
  109. element of ARRAY is OBJECT. It returns ARRAY.
  110. (setq a [a b c d e f g])
  111. => [a b c d e f g]
  112. (fillarray a 0)
  113. => [0 0 0 0 0 0 0]
  114. a
  115. => [0 0 0 0 0 0 0]
  116. (setq s "When in the course")
  117. => "When in the course"
  118. (fillarray s ?-)
  119. => "------------------"
  120. If ARRAY is a string and OBJECT is not a character, a
  121. `wrong-type-argument' error results.
  122. The general sequence functions `copy-sequence' and `length' are
  123. often useful for objects known to be arrays. *Note Sequence
  124. Functions::.
  125. 
  126. File: elisp, Node: Vectors, Next: Vector Functions, Prev: Array Functions, Up: Sequences Arrays Vectors
  127. 6.4 Vectors
  128. ===========
  129. A "vector" is a general-purpose array whose elements can be any Lisp
  130. objects. (By contrast, the elements of a string can only be
  131. characters. *Note Strings and Characters::.) Vectors are used in
  132. Emacs for many purposes: as key sequences (*note Key Sequences::), as
  133. symbol-lookup tables (*note Creating Symbols::), as part of the
  134. representation of a byte-compiled function (*note Byte Compilation::),
  135. and more.
  136. Like other arrays, vectors use zero-origin indexing: the first
  137. element has index 0.
  138. Vectors are printed with square brackets surrounding the elements.
  139. Thus, a vector whose elements are the symbols `a', `b' and `a' is
  140. printed as `[a b a]'. You can write vectors in the same way in Lisp
  141. input.
  142. A vector, like a string or a number, is considered a constant for
  143. evaluation: the result of evaluating it is the same vector. This does
  144. not evaluate or even examine the elements of the vector. *Note
  145. Self-Evaluating Forms::.
  146. Here are examples illustrating these principles:
  147. (setq avector [1 two '(three) "four" [five]])
  148. => [1 two (quote (three)) "four" [five]]
  149. (eval avector)
  150. => [1 two (quote (three)) "four" [five]]
  151. (eq avector (eval avector))
  152. => t
  153. 
  154. File: elisp, Node: Vector Functions, Next: Char-Tables, Prev: Vectors, Up: Sequences Arrays Vectors
  155. 6.5 Functions for Vectors
  156. =========================
  157. Here are some functions that relate to vectors:
  158. -- Function: vectorp object
  159. This function returns `t' if OBJECT is a vector.
  160. (vectorp [a])
  161. => t
  162. (vectorp "asdf")
  163. => nil
  164. -- Function: vector &rest objects
  165. This function creates and returns a vector whose elements are the
  166. arguments, OBJECTS.
  167. (vector 'foo 23 [bar baz] "rats")
  168. => [foo 23 [bar baz] "rats"]
  169. (vector)
  170. => []
  171. -- Function: make-vector length object
  172. This function returns a new vector consisting of LENGTH elements,
  173. each initialized to OBJECT.
  174. (setq sleepy (make-vector 9 'Z))
  175. => [Z Z Z Z Z Z Z Z Z]
  176. -- Function: vconcat &rest sequences
  177. This function returns a new vector containing all the elements of
  178. SEQUENCES. The arguments SEQUENCES may be true lists, vectors,
  179. strings or bool-vectors. If no SEQUENCES are given, an empty
  180. vector is returned.
  181. The value is a newly constructed vector that is not `eq' to any
  182. existing vector.
  183. (setq a (vconcat '(A B C) '(D E F)))
  184. => [A B C D E F]
  185. (eq a (vconcat a))
  186. => nil
  187. (vconcat)
  188. => []
  189. (vconcat [A B C] "aa" '(foo (6 7)))
  190. => [A B C 97 97 foo (6 7)]
  191. The `vconcat' function also allows byte-code function objects as
  192. arguments. This is a special feature to make it easy to access
  193. the entire contents of a byte-code function object. *Note
  194. Byte-Code Objects::.
  195. For other concatenation functions, see `mapconcat' in *note
  196. Mapping Functions::, `concat' in *note Creating Strings::, and
  197. `append' in *note Building Lists::.
  198. The `append' function also provides a way to convert a vector into a
  199. list with the same elements:
  200. (setq avector [1 two (quote (three)) "four" [five]])
  201. => [1 two (quote (three)) "four" [five]]
  202. (append avector nil)
  203. => (1 two (quote (three)) "four" [five])
  204. 
  205. File: elisp, Node: Char-Tables, Next: Bool-Vectors, Prev: Vector Functions, Up: Sequences Arrays Vectors
  206. 6.6 Char-Tables
  207. ===============
  208. A char-table is much like a vector, except that it is indexed by
  209. character codes. Any valid character code, without modifiers, can be
  210. used as an index in a char-table. You can access a char-table's
  211. elements with `aref' and `aset', as with any array. In addition, a
  212. char-table can have "extra slots" to hold additional data not
  213. associated with particular character codes. Like vectors, char-tables
  214. are constants when evaluated, and can hold elements of any type.
  215. Each char-table has a "subtype", a symbol, which serves two purposes:
  216. * The subtype provides an easy way to tell what the char-table is
  217. for. For instance, display tables are char-tables with
  218. `display-table' as the subtype, and syntax tables are char-tables
  219. with `syntax-table' as the subtype. The subtype can be queried
  220. using the function `char-table-subtype', described below.
  221. * The subtype controls the number of "extra slots" in the
  222. char-table. This number is specified by the subtype's
  223. `char-table-extra-slots' symbol property, which should be an
  224. integer between 0 and 10. If the subtype has no such symbol
  225. property, the char-table has no extra slots. *Note Property
  226. Lists::, for information about symbol properties.
  227. A char-table can have a "parent", which is another char-table. If
  228. it does, then whenever the char-table specifies `nil' for a particular
  229. character C, it inherits the value specified in the parent. In other
  230. words, `(aref CHAR-TABLE C)' returns the value from the parent of
  231. CHAR-TABLE if CHAR-TABLE itself specifies `nil'.
  232. A char-table can also have a "default value". If so, then `(aref
  233. CHAR-TABLE C)' returns the default value whenever the char-table does
  234. not specify any other non-`nil' value.
  235. -- Function: make-char-table subtype &optional init
  236. Return a newly-created char-table, with subtype SUBTYPE (a
  237. symbol). Each element is initialized to INIT, which defaults to
  238. `nil'. You cannot alter the subtype of a char-table after the
  239. char-table is created.
  240. There is no argument to specify the length of the char-table,
  241. because all char-tables have room for any valid character code as
  242. an index.
  243. If SUBTYPE has the `char-table-extra-slots' symbol property, that
  244. specifies the number of extra slots in the char-table. This
  245. should be an integer between 0 and 10; otherwise,
  246. `make-char-table' raises an error. If SUBTYPE has no
  247. `char-table-extra-slots' symbol property (*note Property Lists::),
  248. the char-table has no extra slots.
  249. -- Function: char-table-p object
  250. This function returns `t' if OBJECT is a char-table, and `nil'
  251. otherwise.
  252. -- Function: char-table-subtype char-table
  253. This function returns the subtype symbol of CHAR-TABLE.
  254. There is no special function to access default values in a
  255. char-table. To do that, use `char-table-range' (see below).
  256. -- Function: char-table-parent char-table
  257. This function returns the parent of CHAR-TABLE. The parent is
  258. always either `nil' or another char-table.
  259. -- Function: set-char-table-parent char-table new-parent
  260. This function sets the parent of CHAR-TABLE to NEW-PARENT.
  261. -- Function: char-table-extra-slot char-table n
  262. This function returns the contents of extra slot N of CHAR-TABLE.
  263. The number of extra slots in a char-table is determined by its
  264. subtype.
  265. -- Function: set-char-table-extra-slot char-table n value
  266. This function stores VALUE in extra slot N of CHAR-TABLE.
  267. A char-table can specify an element value for a single character
  268. code; it can also specify a value for an entire character set.
  269. -- Function: char-table-range char-table range
  270. This returns the value specified in CHAR-TABLE for a range of
  271. characters RANGE. Here are the possibilities for RANGE:
  272. `nil'
  273. Refers to the default value.
  274. CHAR
  275. Refers to the element for character CHAR (supposing CHAR is a
  276. valid character code).
  277. `(FROM . TO)'
  278. A cons cell refers to all the characters in the inclusive
  279. range `[FROM..TO]'.
  280. -- Function: set-char-table-range char-table range value
  281. This function sets the value in CHAR-TABLE for a range of
  282. characters RANGE. Here are the possibilities for RANGE:
  283. `nil'
  284. Refers to the default value.
  285. `t'
  286. Refers to the whole range of character codes.
  287. CHAR
  288. Refers to the element for character CHAR (supposing CHAR is a
  289. valid character code).
  290. `(FROM . TO)'
  291. A cons cell refers to all the characters in the inclusive
  292. range `[FROM..TO]'.
  293. -- Function: map-char-table function char-table
  294. This function calls its argument FUNCTION for each element of
  295. CHAR-TABLE that has a non-`nil' value. The call to FUNCTION is
  296. with two arguments, a key and a value. The key is a possible
  297. RANGE argument for `char-table-range'--either a valid character or
  298. a cons cell `(FROM . TO)', specifying a range of characters that
  299. share the same value. The value is what `(char-table-range
  300. CHAR-TABLE KEY)' returns.
  301. Overall, the key-value pairs passed to FUNCTION describe all the
  302. values stored in CHAR-TABLE.
  303. The return value is always `nil'; to make calls to
  304. `map-char-table' useful, FUNCTION should have side effects. For
  305. example, here is how to examine the elements of the syntax table:
  306. (let (accumulator)
  307. (map-char-table
  308. #'(lambda (key value)
  309. (setq accumulator
  310. (cons (list
  311. (if (consp key)
  312. (list (car key) (cdr key))
  313. key)
  314. value)
  315. accumulator)))
  316. (syntax-table))
  317. accumulator)
  318. =>
  319. (((2597602 4194303) (2)) ((2597523 2597601) (3))
  320. ... (65379 (5 . 65378)) (65378 (4 . 65379)) (65377 (1))
  321. ... (12 (0)) (11 (3)) (10 (12)) (9 (0)) ((0 8) (3)))
  322. 
  323. File: elisp, Node: Bool-Vectors, Next: Rings, Prev: Char-Tables, Up: Sequences Arrays Vectors
  324. 6.7 Bool-vectors
  325. ================
  326. A bool-vector is much like a vector, except that it stores only the
  327. values `t' and `nil'. If you try to store any non-`nil' value into an
  328. element of the bool-vector, the effect is to store `t' there. As with
  329. all arrays, bool-vector indices start from 0, and the length cannot be
  330. changed once the bool-vector is created. Bool-vectors are constants
  331. when evaluated.
  332. There are two special functions for working with bool-vectors; aside
  333. from that, you manipulate them with same functions used for other kinds
  334. of arrays.
  335. -- Function: make-bool-vector length initial
  336. Return a new bool-vector of LENGTH elements, each one initialized
  337. to INITIAL.
  338. -- Function: bool-vector-p object
  339. This returns `t' if OBJECT is a bool-vector, and `nil' otherwise.
  340. Here is an example of creating, examining, and updating a
  341. bool-vector. Note that the printed form represents up to 8 boolean
  342. values as a single character.
  343. (setq bv (make-bool-vector 5 t))
  344. => #&5"^_"
  345. (aref bv 1)
  346. => t
  347. (aset bv 3 nil)
  348. => nil
  349. bv
  350. => #&5"^W"
  351. These results make sense because the binary codes for control-_ and
  352. control-W are 11111 and 10111, respectively.
  353. 
  354. File: elisp, Node: Rings, Prev: Bool-Vectors, Up: Sequences Arrays Vectors
  355. 6.8 Managing a Fixed-Size Ring of Objects
  356. =========================================
  357. A "ring" is a fixed-size data structure that supports insertion,
  358. deletion, rotation, and modulo-indexed reference and traversal. An
  359. efficient ring data structure is implemented by the `ring' package. It
  360. provides the functions listed in this section.
  361. Note that several "rings" in Emacs, like the kill ring and the mark
  362. ring, are actually implemented as simple lists, _not_ using the `ring'
  363. package; thus the following functions won't work on them.
  364. -- Function: make-ring size
  365. This returns a new ring capable of holding SIZE objects. SIZE
  366. should be an integer.
  367. -- Function: ring-p object
  368. This returns `t' if OBJECT is a ring, `nil' otherwise.
  369. -- Function: ring-size ring
  370. This returns the maximum capacity of the RING.
  371. -- Function: ring-length ring
  372. This returns the number of objects that RING currently contains.
  373. The value will never exceed that returned by `ring-size'.
  374. -- Function: ring-elements ring
  375. This returns a list of the objects in RING, in order, newest first.
  376. -- Function: ring-copy ring
  377. This returns a new ring which is a copy of RING. The new ring
  378. contains the same (`eq') objects as RING.
  379. -- Function: ring-empty-p ring
  380. This returns `t' if RING is empty, `nil' otherwise.
  381. The newest element in the ring always has index 0. Higher indices
  382. correspond to older elements. Indices are computed modulo the ring
  383. length. Index -1 corresponds to the oldest element, -2 to the
  384. next-oldest, and so forth.
  385. -- Function: ring-ref ring index
  386. This returns the object in RING found at index INDEX. INDEX may
  387. be negative or greater than the ring length. If RING is empty,
  388. `ring-ref' signals an error.
  389. -- Function: ring-insert ring object
  390. This inserts OBJECT into RING, making it the newest element, and
  391. returns OBJECT.
  392. If the ring is full, insertion removes the oldest element to make
  393. room for the new element.
  394. -- Function: ring-remove ring &optional index
  395. Remove an object from RING, and return that object. The argument
  396. INDEX specifies which item to remove; if it is `nil', that means
  397. to remove the oldest item. If RING is empty, `ring-remove'
  398. signals an error.
  399. -- Function: ring-insert-at-beginning ring object
  400. This inserts OBJECT into RING, treating it as the oldest element.
  401. The return value is not significant.
  402. If the ring is full, this function removes the newest element to
  403. make room for the inserted element.
  404. If you are careful not to exceed the ring size, you can use the ring
  405. as a first-in-first-out queue. For example:
  406. (let ((fifo (make-ring 5)))
  407. (mapc (lambda (obj) (ring-insert fifo obj))
  408. '(0 one "two"))
  409. (list (ring-remove fifo) t
  410. (ring-remove fifo) t
  411. (ring-remove fifo)))
  412. => (0 t one t "two")
  413. 
  414. File: elisp, Node: Hash Tables, Next: Symbols, Prev: Sequences Arrays Vectors, Up: Top
  415. 7 Hash Tables
  416. *************
  417. A hash table is a very fast kind of lookup table, somewhat like an
  418. alist (*note Association Lists::) in that it maps keys to corresponding
  419. values. It differs from an alist in these ways:
  420. * Lookup in a hash table is extremely fast for large tables--in
  421. fact, the time required is essentially _independent_ of how many
  422. elements are stored in the table. For smaller tables (a few tens
  423. of elements) alists may still be faster because hash tables have a
  424. more-or-less constant overhead.
  425. * The correspondences in a hash table are in no particular order.
  426. * There is no way to share structure between two hash tables, the
  427. way two alists can share a common tail.
  428. Emacs Lisp provides a general-purpose hash table data type, along
  429. with a series of functions for operating on them. Hash tables have a
  430. special printed representation, which consists of `#s' followed by a
  431. list specifying the hash table properties and contents. *Note Creating
  432. Hash::. (Note that the term "hash notation", which refers to the
  433. initial `#' character used in the printed representations of objects
  434. with no read representation, has nothing to do with the term "hash
  435. table". *Note Printed Representation::.)
  436. Obarrays are also a kind of hash table, but they are a different type
  437. of object and are used only for recording interned symbols (*note
  438. Creating Symbols::).
  439. * Menu:
  440. * Creating Hash:: Functions to create hash tables.
  441. * Hash Access:: Reading and writing the hash table contents.
  442. * Defining Hash:: Defining new comparison methods.
  443. * Other Hash:: Miscellaneous.
  444. 
  445. File: elisp, Node: Creating Hash, Next: Hash Access, Up: Hash Tables
  446. 7.1 Creating Hash Tables
  447. ========================
  448. The principal function for creating a hash table is `make-hash-table'.
  449. -- Function: make-hash-table &rest keyword-args
  450. This function creates a new hash table according to the specified
  451. arguments. The arguments should consist of alternating keywords
  452. (particular symbols recognized specially) and values corresponding
  453. to them.
  454. Several keywords make sense in `make-hash-table', but the only two
  455. that you really need to know about are `:test' and `:weakness'.
  456. `:test TEST'
  457. This specifies the method of key lookup for this hash table.
  458. The default is `eql'; `eq' and `equal' are other alternatives:
  459. `eql'
  460. Keys which are numbers are "the same" if they are
  461. `equal', that is, if they are equal in value and either
  462. both are integers or both are floating point numbers;
  463. otherwise, two distinct objects are never "the same".
  464. `eq'
  465. Any two distinct Lisp objects are "different" as keys.
  466. `equal'
  467. Two Lisp objects are "the same", as keys, if they are
  468. equal according to `equal'.
  469. You can use `define-hash-table-test' (*note Defining Hash::)
  470. to define additional possibilities for TEST.
  471. `:weakness WEAK'
  472. The weakness of a hash table specifies whether the presence
  473. of a key or value in the hash table preserves it from garbage
  474. collection.
  475. The value, WEAK, must be one of `nil', `key', `value',
  476. `key-or-value', `key-and-value', or `t' which is an alias for
  477. `key-and-value'. If WEAK is `key' then the hash table does
  478. not prevent its keys from being collected as garbage (if they
  479. are not referenced anywhere else); if a particular key does
  480. get collected, the corresponding association is removed from
  481. the hash table.
  482. If WEAK is `value', then the hash table does not prevent
  483. values from being collected as garbage (if they are not
  484. referenced anywhere else); if a particular value does get
  485. collected, the corresponding association is removed from the
  486. hash table.
  487. If WEAK is `key-and-value' or `t', both the key and the value
  488. must be live in order to preserve the association. Thus, the
  489. hash table does not protect either keys or values from garbage
  490. collection; if either one is collected as garbage, that
  491. removes the association.
  492. If WEAK is `key-or-value', either the key or the value can
  493. preserve the association. Thus, associations are removed
  494. from the hash table when both their key and value would be
  495. collected as garbage (if not for references from weak hash
  496. tables).
  497. The default for WEAK is `nil', so that all keys and values
  498. referenced in the hash table are preserved from garbage
  499. collection.
  500. `:size SIZE'
  501. This specifies a hint for how many associations you plan to
  502. store in the hash table. If you know the approximate number,
  503. you can make things a little more efficient by specifying it
  504. this way. If you specify too small a size, the hash table
  505. will grow automatically when necessary, but doing that takes
  506. some extra time.
  507. The default size is 65.
  508. `:rehash-size REHASH-SIZE'
  509. When you add an association to a hash table and the table is
  510. "full", it grows automatically. This value specifies how to
  511. make the hash table larger, at that time.
  512. If REHASH-SIZE is an integer, it should be positive, and the
  513. hash table grows by adding that much to the nominal size. If
  514. REHASH-SIZE is a floating point number, it had better be
  515. greater than 1, and the hash table grows by multiplying the
  516. old size by that number.
  517. The default value is 1.5.
  518. `:rehash-threshold THRESHOLD'
  519. This specifies the criterion for when the hash table is
  520. "full" (so it should be made larger). The value, THRESHOLD,
  521. should be a positive floating point number, no greater than
  522. 1. The hash table is "full" whenever the actual number of
  523. entries exceeds this fraction of the nominal size. The
  524. default for THRESHOLD is 0.8.
  525. -- Function: makehash &optional test
  526. This is equivalent to `make-hash-table', but with a different style
  527. argument list. The argument TEST specifies the method of key
  528. lookup.
  529. This function is obsolete. Use `make-hash-table' instead.
  530. You can also create a new hash table using the printed representation
  531. for hash tables. The Lisp reader can read this printed representation,
  532. provided each element in the specified hash table has a valid read
  533. syntax (*note Printed Representation::). For instance, the following
  534. specifies a new hash table containing the keys `key1' and `key2' (both
  535. symbols) associated with `val1' (a symbol) and `300' (a number)
  536. respectively.
  537. #s(hash-table size 30 data (key1 val1 key2 300))
  538. The printed representation for a hash table consists of `#s' followed
  539. by a list beginning with `hash-table'. The rest of the list should
  540. consist of zero or more property-value pairs specifying the hash
  541. table's properties and initial contents. The properties and values are
  542. read literally. Valid property names are `size', `test', `weakness',
  543. `rehash-size', `rehash-threshold', and `data'. The `data' property
  544. should be a list of key-value pairs for the initial contents; the other
  545. properties have the same meanings as the matching `make-hash-table'
  546. keywords (`:size', `:test', etc.), described above.
  547. Note that you cannot specify a hash table whose initial contents
  548. include objects that have no read syntax, such as buffers and frames.
  549. Such objects may be added to the hash table after it is created.
  550. 
  551. File: elisp, Node: Hash Access, Next: Defining Hash, Prev: Creating Hash, Up: Hash Tables
  552. 7.2 Hash Table Access
  553. =====================
  554. This section describes the functions for accessing and storing
  555. associations in a hash table. In general, any Lisp object can be used
  556. as a hash key, unless the comparison method imposes limits. Any Lisp
  557. object can also be used as the value.
  558. -- Function: gethash key table &optional default
  559. This function looks up KEY in TABLE, and returns its associated
  560. VALUE--or DEFAULT, if KEY has no association in TABLE.
  561. -- Function: puthash key value table
  562. This function enters an association for KEY in TABLE, with value
  563. VALUE. If KEY already has an association in TABLE, VALUE replaces
  564. the old associated value.
  565. -- Function: remhash key table
  566. This function removes the association for KEY from TABLE, if there
  567. is one. If KEY has no association, `remhash' does nothing.
  568. Common Lisp note: In Common Lisp, `remhash' returns non-`nil' if
  569. it actually removed an association and `nil' otherwise. In Emacs
  570. Lisp, `remhash' always returns `nil'.
  571. -- Function: clrhash table
  572. This function removes all the associations from hash table TABLE,
  573. so that it becomes empty. This is also called "clearing" the hash
  574. table.
  575. Common Lisp note: In Common Lisp, `clrhash' returns the empty
  576. TABLE. In Emacs Lisp, it returns `nil'.
  577. -- Function: maphash function table
  578. This function calls FUNCTION once for each of the associations in
  579. TABLE. The function FUNCTION should accept two arguments--a KEY
  580. listed in TABLE, and its associated VALUE. `maphash' returns
  581. `nil'.
  582. 
  583. File: elisp, Node: Defining Hash, Next: Other Hash, Prev: Hash Access, Up: Hash Tables
  584. 7.3 Defining Hash Comparisons
  585. =============================
  586. You can define new methods of key lookup by means of
  587. `define-hash-table-test'. In order to use this feature, you need to
  588. understand how hash tables work, and what a "hash code" means.
  589. You can think of a hash table conceptually as a large array of many
  590. slots, each capable of holding one association. To look up a key,
  591. `gethash' first computes an integer, the hash code, from the key. It
  592. reduces this integer modulo the length of the array, to produce an
  593. index in the array. Then it looks in that slot, and if necessary in
  594. other nearby slots, to see if it has found the key being sought.
  595. Thus, to define a new method of key lookup, you need to specify both
  596. a function to compute the hash code from a key, and a function to
  597. compare two keys directly.
  598. -- Function: define-hash-table-test name test-fn hash-fn
  599. This function defines a new hash table test, named NAME.
  600. After defining NAME in this way, you can use it as the TEST
  601. argument in `make-hash-table'. When you do that, the hash table
  602. will use TEST-FN to compare key values, and HASH-FN to compute a
  603. "hash code" from a key value.
  604. The function TEST-FN should accept two arguments, two keys, and
  605. return non-`nil' if they are considered "the same".
  606. The function HASH-FN should accept one argument, a key, and return
  607. an integer that is the "hash code" of that key. For good results,
  608. the function should use the whole range of integer values for hash
  609. codes, including negative integers.
  610. The specified functions are stored in the property list of NAME
  611. under the property `hash-table-test'; the property value's form is
  612. `(TEST-FN HASH-FN)'.
  613. -- Function: sxhash obj
  614. This function returns a hash code for Lisp object OBJ. This is an
  615. integer which reflects the contents of OBJ and the other Lisp
  616. objects it points to.
  617. If two objects OBJ1 and OBJ2 are equal, then `(sxhash OBJ1)' and
  618. `(sxhash OBJ2)' are the same integer.
  619. If the two objects are not equal, the values returned by `sxhash'
  620. are usually different, but not always; once in a rare while, by
  621. luck, you will encounter two distinct-looking objects that give
  622. the same result from `sxhash'.
  623. This example creates a hash table whose keys are strings that are
  624. compared case-insensitively.
  625. (defun case-fold-string= (a b)
  626. (compare-strings a nil nil b nil nil t))
  627. (defun case-fold-string-hash (a)
  628. (sxhash (upcase a)))
  629. (define-hash-table-test 'case-fold
  630. 'case-fold-string= 'case-fold-string-hash)
  631. (make-hash-table :test 'case-fold)
  632. Here is how you could define a hash table test equivalent to the
  633. predefined test value `equal'. The keys can be any Lisp object, and
  634. equal-looking objects are considered the same key.
  635. (define-hash-table-test 'contents-hash 'equal 'sxhash)
  636. (make-hash-table :test 'contents-hash)
  637. 
  638. File: elisp, Node: Other Hash, Prev: Defining Hash, Up: Hash Tables
  639. 7.4 Other Hash Table Functions
  640. ==============================
  641. Here are some other functions for working with hash tables.
  642. -- Function: hash-table-p table
  643. This returns non-`nil' if TABLE is a hash table object.
  644. -- Function: copy-hash-table table
  645. This function creates and returns a copy of TABLE. Only the table
  646. itself is copied--the keys and values are shared.
  647. -- Function: hash-table-count table
  648. This function returns the actual number of entries in TABLE.
  649. -- Function: hash-table-test table
  650. This returns the TEST value that was given when TABLE was created,
  651. to specify how to hash and compare keys. See `make-hash-table'
  652. (*note Creating Hash::).
  653. -- Function: hash-table-weakness table
  654. This function returns the WEAK value that was specified for hash
  655. table TABLE.
  656. -- Function: hash-table-rehash-size table
  657. This returns the rehash size of TABLE.
  658. -- Function: hash-table-rehash-threshold table
  659. This returns the rehash threshold of TABLE.
  660. -- Function: hash-table-size table
  661. This returns the current nominal size of TABLE.
  662. 
  663. File: elisp, Node: Symbols, Next: Evaluation, Prev: Hash Tables, Up: Top
  664. 8 Symbols
  665. *********
  666. A "symbol" is an object with a unique name. This chapter describes
  667. symbols, their components, their property lists, and how they are
  668. created and interned. Separate chapters describe the use of symbols as
  669. variables and as function names; see *note Variables::, and *note
  670. Functions::. For the precise read syntax for symbols, see *note Symbol
  671. Type::.
  672. You can test whether an arbitrary Lisp object is a symbol with
  673. `symbolp':
  674. -- Function: symbolp object
  675. This function returns `t' if OBJECT is a symbol, `nil' otherwise.
  676. * Menu:
  677. * Symbol Components:: Symbols have names, values, function definitions
  678. and property lists.
  679. * Definitions:: A definition says how a symbol will be used.
  680. * Creating Symbols:: How symbols are kept unique.
  681. * Property Lists:: Each symbol has a property list
  682. for recording miscellaneous information.
  683. 
  684. File: elisp, Node: Symbol Components, Next: Definitions, Prev: Symbols, Up: Symbols
  685. 8.1 Symbol Components
  686. =====================
  687. Each symbol has four components (or "cells"), each of which references
  688. another object:
  689. Print name
  690. The symbol's name.
  691. Value
  692. The symbol's current value as a variable.
  693. Function
  694. The symbol's function definition. It can also hold a symbol, a
  695. keymap, or a keyboard macro.
  696. Property list
  697. The symbol's property list.
  698. The print name cell always holds a string, and cannot be changed. Each
  699. of the other three cells can be set to any Lisp object.
  700. The print name cell holds the string that is the name of a symbol.
  701. Since symbols are represented textually by their names, it is important
  702. not to have two symbols with the same name. The Lisp reader ensures
  703. this: every time it reads a symbol, it looks for an existing symbol
  704. with the specified name before it creates a new one. To get a symbol's
  705. name, use the function `symbol-name' (*note Creating Symbols::).
  706. The value cell holds a symbol's value as a variable, which is what
  707. you get if the symbol itself is evaluated as a Lisp expression. *Note
  708. Variables::, for details about how values are set and retrieved,
  709. including complications such as "local bindings" and "scoping rules".
  710. Most symbols can have any Lisp object as a value, but certain special
  711. symbols have values that cannot be changed; these include `nil' and
  712. `t', and any symbol whose name starts with `:' (those are called
  713. "keywords"). *Note Constant Variables::.
  714. The function cell holds a symbol's function definition. Often, we
  715. refer to "the function `foo'" when we really mean the function stored
  716. in the function cell of `foo'; we make the distinction explicit only
  717. when necessary. Typically, the function cell is used to hold a
  718. function (*note Functions::) or a macro (*note Macros::). However, it
  719. can also be used to hold a symbol (*note Function Indirection::),
  720. keyboard macro (*note Keyboard Macros::), keymap (*note Keymaps::), or
  721. autoload object (*note Autoloading::). To get the contents of a
  722. symbol's function cell, use the function `symbol-function' (*note
  723. Function Cells::).
  724. The property list cell normally should hold a correctly formatted
  725. property list. To get a symbol's property list, use the function
  726. `symbol-plist'. *Note Property Lists::.
  727. The function cell or the value cell may be "void", which means that
  728. the cell does not reference any object. (This is not the same thing as
  729. holding the symbol `void', nor the same as holding the symbol `nil'.)
  730. Examining a function or value cell that is void results in an error,
  731. such as `Symbol's value as variable is void'.
  732. Because each symbol has separate value and function cells, variables
  733. names and function names do not conflict. For example, the symbol
  734. `buffer-file-name' has a value (the name of the file being visited in
  735. the current buffer) as well as a function definition (a primitive
  736. function that returns the name of the file):
  737. buffer-file-name
  738. => "/gnu/elisp/symbols.texi"
  739. (symbol-function 'buffer-file-name)
  740. => #<subr buffer-file-name>
  741. 
  742. File: elisp, Node: Definitions, Next: Creating Symbols, Prev: Symbol Components, Up: Symbols
  743. 8.2 Defining Symbols
  744. ====================
  745. A "definition" is a special kind of Lisp expression that announces your
  746. intention to use a symbol in a particular way. It typically specifies
  747. a value or meaning for the symbol for one kind of use, plus
  748. documentation for its meaning when used in this way. Thus, when you
  749. define a symbol as a variable, you can supply an initial value for the
  750. variable, plus documentation for the variable.
  751. `defvar' and `defconst' are special forms that define a symbol as a
  752. "global variable"--a variable that can be accessed at any point in a
  753. Lisp program. *Note Variables::, for details about variables. To
  754. define a customizable variable, use the `defcustom' macro, which also
  755. calls `defvar' as a subroutine (*note Customization::).
  756. In principle, you can assign a variable value to any symbol with
  757. `setq', whether not it has first been defined as a variable. However,
  758. you ought to write a variable definition for each global variable that
  759. you want to use; otherwise, your Lisp program may not act correctly if
  760. it is evaluated with lexical scoping enabled (*note Variable Scoping::).
  761. `defun' defines a symbol as a function, creating a lambda expression
  762. and storing it in the function cell of the symbol. This lambda
  763. expression thus becomes the function definition of the symbol. (The
  764. term "function definition", meaning the contents of the function cell,
  765. is derived from the idea that `defun' gives the symbol its definition
  766. as a function.) `defsubst' and `defalias' are two other ways of
  767. defining a function. *Note Functions::.
  768. `defmacro' defines a symbol as a macro. It creates a macro object
  769. and stores it in the function cell of the symbol. Note that a given
  770. symbol can be a macro or a function, but not both at once, because both
  771. macro and function definitions are kept in the function cell, and that
  772. cell can hold only one Lisp object at any given time. *Note Macros::.
  773. As previously noted, Emacs Lisp allows the same symbol to be defined
  774. both as a variable (e.g. with `defvar') and as a function or macro
  775. (e.g. with `defun'). Such definitions do not conflict.
  776. These definition also act as guides for programming tools. For
  777. example, the `C-h f' and `C-h v' commands create help buffers
  778. containing links to the relevant variable, function, or macro
  779. definitions. *Note Name Help: (emacs)Name Help.
  780. 
  781. File: elisp, Node: Creating Symbols, Next: Property Lists, Prev: Definitions, Up: Symbols
  782. 8.3 Creating and Interning Symbols
  783. ==================================
  784. To understand how symbols are created in GNU Emacs Lisp, you must know
  785. how Lisp reads them. Lisp must ensure that it finds the same symbol
  786. every time it reads the same set of characters. Failure to do so would
  787. cause complete confusion.
  788. When the Lisp reader encounters a symbol, it reads all the characters
  789. of the name. Then it "hashes" those characters to find an index in a
  790. table called an "obarray". Hashing is an efficient method of looking
  791. something up. For example, instead of searching a telephone book cover
  792. to cover when looking up Jan Jones, you start with the J's and go from
  793. there. That is a simple version of hashing. Each element of the
  794. obarray is a "bucket" which holds all the symbols with a given hash
  795. code; to look for a given name, it is sufficient to look through all
  796. the symbols in the bucket for that name's hash code. (The same idea is
  797. used for general Emacs hash tables, but they are a different data type;
  798. see *note Hash Tables::.)
  799. If a symbol with the desired name is found, the reader uses that
  800. symbol. If the obarray does not contain a symbol with that name, the
  801. reader makes a new symbol and adds it to the obarray. Finding or adding
  802. a symbol with a certain name is called "interning" it, and the symbol
  803. is then called an "interned symbol".
  804. Interning ensures that each obarray has just one symbol with any
  805. particular name. Other like-named symbols may exist, but not in the
  806. same obarray. Thus, the reader gets the same symbols for the same
  807. names, as long as you keep reading with the same obarray.
  808. Interning usually happens automatically in the reader, but sometimes
  809. other programs need to do it. For example, after the `M-x' command
  810. obtains the command name as a string using the minibuffer, it then
  811. interns the string, to get the interned symbol with that name.
  812. No obarray contains all symbols; in fact, some symbols are not in any
  813. obarray. They are called "uninterned symbols". An uninterned symbol
  814. has the same four cells as other symbols; however, the only way to gain
  815. access to it is by finding it in some other object or as the value of a
  816. variable.
  817. Creating an uninterned symbol is useful in generating Lisp code,
  818. because an uninterned symbol used as a variable in the code you generate
  819. cannot clash with any variables used in other Lisp programs.
  820. In Emacs Lisp, an obarray is actually a vector. Each element of the
  821. vector is a bucket; its value is either an interned symbol whose name
  822. hashes to that bucket, or 0 if the bucket is empty. Each interned
  823. symbol has an internal link (invisible to the user) to the next symbol
  824. in the bucket. Because these links are invisible, there is no way to
  825. find all the symbols in an obarray except using `mapatoms' (below).
  826. The order of symbols in a bucket is not significant.
  827. In an empty obarray, every element is 0, so you can create an obarray
  828. with `(make-vector LENGTH 0)'. *This is the only valid way to create
  829. an obarray.* Prime numbers as lengths tend to result in good hashing;
  830. lengths one less than a power of two are also good.
  831. *Do not try to put symbols in an obarray yourself.* This does not
  832. work--only `intern' can enter a symbol in an obarray properly.
  833. Common Lisp note: Unlike Common Lisp, Emacs Lisp does not provide
  834. for interning a single symbol in several obarrays.
  835. Most of the functions below take a name and sometimes an obarray as
  836. arguments. A `wrong-type-argument' error is signaled if the name is
  837. not a string, or if the obarray is not a vector.
  838. -- Function: symbol-name symbol
  839. This function returns the string that is SYMBOL's name. For
  840. example:
  841. (symbol-name 'foo)
  842. => "foo"
  843. *Warning:* Changing the string by substituting characters does
  844. change the name of the symbol, but fails to update the obarray, so
  845. don't do it!
  846. -- Function: make-symbol name
  847. This function returns a newly-allocated, uninterned symbol whose
  848. name is NAME (which must be a string). Its value and function
  849. definition are void, and its property list is `nil'. In the
  850. example below, the value of `sym' is not `eq' to `foo' because it
  851. is a distinct uninterned symbol whose name is also `foo'.
  852. (setq sym (make-symbol "foo"))
  853. => foo
  854. (eq sym 'foo)
  855. => nil
  856. -- Function: intern name &optional obarray
  857. This function returns the interned symbol whose name is NAME. If
  858. there is no such symbol in the obarray OBARRAY, `intern' creates a
  859. new one, adds it to the obarray, and returns it. If OBARRAY is
  860. omitted, the value of the global variable `obarray' is used.
  861. (setq sym (intern "foo"))
  862. => foo
  863. (eq sym 'foo)
  864. => t
  865. (setq sym1 (intern "foo" other-obarray))
  866. => foo
  867. (eq sym1 'foo)
  868. => nil
  869. Common Lisp note: In Common Lisp, you can intern an existing symbol
  870. in an obarray. In Emacs Lisp, you cannot do this, because the
  871. argument to `intern' must be a string, not a symbol.
  872. -- Function: intern-soft name &optional obarray
  873. This function returns the symbol in OBARRAY whose name is NAME, or
  874. `nil' if OBARRAY has no symbol with that name. Therefore, you can
  875. use `intern-soft' to test whether a symbol with a given name is
  876. already interned. If OBARRAY is omitted, the value of the global
  877. variable `obarray' is used.
  878. The argument NAME may also be a symbol; in that case, the function
  879. returns NAME if NAME is interned in the specified obarray, and
  880. otherwise `nil'.
  881. (intern-soft "frazzle") ; No such symbol exists.
  882. => nil
  883. (make-symbol "frazzle") ; Create an uninterned one.
  884. => frazzle
  885. (intern-soft "frazzle") ; That one cannot be found.
  886. => nil
  887. (setq sym (intern "frazzle")) ; Create an interned one.
  888. => frazzle
  889. (intern-soft "frazzle") ; That one can be found!
  890. => frazzle
  891. (eq sym 'frazzle) ; And it is the same one.
  892. => t
  893. -- Variable: obarray
  894. This variable is the standard obarray for use by `intern' and
  895. `read'.
  896. -- Function: mapatoms function &optional obarray
  897. This function calls FUNCTION once with each symbol in the obarray
  898. OBARRAY. Then it returns `nil'. If OBARRAY is omitted, it
  899. defaults to the value of `obarray', the standard obarray for
  900. ordinary symbols.
  901. (setq count 0)
  902. => 0
  903. (defun count-syms (s)
  904. (setq count (1+ count)))
  905. => count-syms
  906. (mapatoms 'count-syms)
  907. => nil
  908. count
  909. => 1871
  910. See `documentation' in *note Accessing Documentation::, for another
  911. example using `mapatoms'.
  912. -- Function: unintern symbol obarray
  913. This function deletes SYMBOL from the obarray OBARRAY. If
  914. `symbol' is not actually in the obarray, `unintern' does nothing.
  915. If OBARRAY is `nil', the current obarray is used.
  916. If you provide a string instead of a symbol as SYMBOL, it stands
  917. for a symbol name. Then `unintern' deletes the symbol (if any) in
  918. the obarray which has that name. If there is no such symbol,
  919. `unintern' does nothing.
  920. If `unintern' does delete a symbol, it returns `t'. Otherwise it
  921. returns `nil'.
  922. 
  923. File: elisp, Node: Property Lists, Prev: Creating Symbols, Up: Symbols
  924. 8.4 Property Lists
  925. ==================
  926. A "property list" ("plist" for short) is a list of paired elements.
  927. Each of the pairs associates a property name (usually a symbol) with a
  928. property or value.
  929. Every symbol has a cell that stores a property list (*note Symbol
  930. Components::). This property list is used to record information about
  931. the symbol, such as its variable documentation and the name of the file
  932. where it was defined.
  933. Property lists can also be used in other contexts. For instance,
  934. you can assign property lists to character positions in a string or
  935. buffer. *Note Text Properties::.
  936. The property names and values in a property list can be any Lisp
  937. objects, but the names are usually symbols. Property list functions
  938. compare the property names using `eq'. Here is an example of a
  939. property list, found on the symbol `progn' when the compiler is loaded:
  940. (lisp-indent-function 0 byte-compile byte-compile-progn)
  941. Here `lisp-indent-function' and `byte-compile' are property names, and
  942. the other two elements are the corresponding values.
  943. * Menu:
  944. * Plists and Alists:: Comparison of the advantages of property
  945. lists and association lists.
  946. * Symbol Plists:: Functions to access symbols' property lists.
  947. * Other Plists:: Accessing property lists stored elsewhere.
  948. 
  949. File: elisp, Node: Plists and Alists, Next: Symbol Plists, Up: Property Lists
  950. 8.4.1 Property Lists and Association Lists
  951. ------------------------------------------
  952. Association lists (*note Association Lists::) are very similar to
  953. property lists. In contrast to association lists, the order of the
  954. pairs in the property list is not significant since the property names
  955. must be distinct.
  956. Property lists are better than association lists for attaching
  957. information to various Lisp function names or variables. If your
  958. program keeps all such information in one association list, it will
  959. typically need to search that entire list each time it checks for an
  960. association for a particular Lisp function name or variable, which
  961. could be slow. By contrast, if you keep the same information in the
  962. property lists of the function names or variables themselves, each
  963. search will scan only the length of one property list, which is usually
  964. short. This is why the documentation for a variable is recorded in a
  965. property named `variable-documentation'. The byte compiler likewise
  966. uses properties to record those functions needing special treatment.
  967. However, association lists have their own advantages. Depending on
  968. your application, it may be faster to add an association to the front of
  969. an association list than to update a property. All properties for a
  970. symbol are stored in the same property list, so there is a possibility
  971. of a conflict between different uses of a property name. (For this
  972. reason, it is a good idea to choose property names that are probably
  973. unique, such as by beginning the property name with the program's usual
  974. name-prefix for variables and functions.) An association list may be
  975. used like a stack where associations are pushed on the front of the list
  976. and later discarded; this is not possible with a property list.
  977. 
  978. File: elisp, Node: Symbol Plists, Next: Other Plists, Prev: Plists and Alists, Up: Property Lists
  979. 8.4.2 Property List Functions for Symbols
  980. -----------------------------------------
  981. -- Function: symbol-plist symbol
  982. This function returns the property list of SYMBOL.
  983. -- Function: setplist symbol plist
  984. This function sets SYMBOL's property list to PLIST. Normally,
  985. PLIST should be a well-formed property list, but this is not
  986. enforced. The return value is PLIST.
  987. (setplist 'foo '(a 1 b (2 3) c nil))
  988. => (a 1 b (2 3) c nil)
  989. (symbol-plist 'foo)
  990. => (a 1 b (2 3) c nil)
  991. For symbols in special obarrays, which are not used for ordinary
  992. purposes, it may make sense to use the property list cell in a
  993. nonstandard fashion; in fact, the abbrev mechanism does so (*note
  994. Abbrevs::).
  995. -- Function: get symbol property
  996. This function finds the value of the property named PROPERTY in
  997. SYMBOL's property list. If there is no such property, `nil' is
  998. returned. Thus, there is no distinction between a value of `nil'
  999. and the absence of the property.
  1000. The name PROPERTY is compared with the existing property names
  1001. using `eq', so any object is a legitimate property.
  1002. See `put' for an example.
  1003. -- Function: put symbol property value
  1004. This function puts VALUE onto SYMBOL's property list under the
  1005. property name PROPERTY, replacing any previous property value.
  1006. The `put' function returns VALUE.
  1007. (put 'fly 'verb 'transitive)
  1008. =>'transitive
  1009. (put 'fly 'noun '(a buzzing little bug))
  1010. => (a buzzing little bug)
  1011. (get 'fly 'verb)
  1012. => transitive
  1013. (symbol-plist 'fly)
  1014. => (verb transitive noun (a buzzing little bug))
  1015. 
  1016. File: elisp, Node: Other Plists, Prev: Symbol Plists, Up: Property Lists
  1017. 8.4.3 Property Lists Outside Symbols
  1018. ------------------------------------
  1019. These functions are useful for manipulating property lists not stored
  1020. in symbols:
  1021. -- Function: plist-get plist property
  1022. This returns the value of the PROPERTY property stored in the
  1023. property list PLIST. It accepts a malformed PLIST argument. If
  1024. PROPERTY is not found in the PLIST, it returns `nil'. For example,
  1025. (plist-get '(foo 4) 'foo)
  1026. => 4
  1027. (plist-get '(foo 4 bad) 'foo)
  1028. => 4
  1029. (plist-get '(foo 4 bad) 'bad)
  1030. => nil
  1031. (plist-get '(foo 4 bad) 'bar)
  1032. => nil
  1033. -- Function: plist-put plist property value
  1034. This stores VALUE as the value of the PROPERTY property in the
  1035. property list PLIST. It may modify PLIST destructively, or it may
  1036. construct a new list structure without altering the old. The
  1037. function returns the modified property list, so you can store that
  1038. back in the place where you got PLIST. For example,
  1039. (setq my-plist '(bar t foo 4))
  1040. => (bar t foo 4)
  1041. (setq my-plist (plist-put my-plist 'foo 69))
  1042. => (bar t foo 69)
  1043. (setq my-plist (plist-put my-plist 'quux '(a)))
  1044. => (bar t foo 69 quux (a))
  1045. You could define `put' in terms of `plist-put' as follows:
  1046. (defun put (symbol prop value)
  1047. (setplist symbol
  1048. (plist-put (symbol-plist symbol) prop value)))
  1049. -- Function: lax-plist-get plist property
  1050. Like `plist-get' except that it compares properties using `equal'
  1051. instead of `eq'.
  1052. -- Function: lax-plist-put plist property value
  1053. Like `plist-put' except that it compares properties using `equal'
  1054. instead of `eq'.
  1055. -- Function: plist-member plist property
  1056. This returns non-`nil' if PLIST contains the given PROPERTY.
  1057. Unlike `plist-get', this allows you to distinguish between a
  1058. missing property and a property with the value `nil'. The value
  1059. is actually the tail of PLIST whose `car' is PROPERTY.
  1060. 
  1061. File: elisp, Node: Evaluation, Next: Control Structures, Prev: Symbols, Up: Top
  1062. 9 Evaluation
  1063. ************
  1064. The "evaluation" of expressions in Emacs Lisp is performed by the "Lisp
  1065. interpreter"--a program that receives a Lisp object as input and
  1066. computes its "value as an expression". How it does this depends on the
  1067. data type of the object, according to rules described in this chapter.
  1068. The interpreter runs automatically to evaluate portions of your
  1069. program, but can also be called explicitly via the Lisp primitive
  1070. function `eval'.
  1071. * Menu:
  1072. * Intro Eval:: Evaluation in the scheme of things.
  1073. * Forms:: How various sorts of objects are evaluated.
  1074. * Quoting:: Avoiding evaluation (to put constants in the program).
  1075. * Backquote:: Easier construction of list structure.
  1076. * Eval:: How to invoke the Lisp interpreter explicitly.
  1077. 
  1078. File: elisp, Node: Intro Eval, Next: Forms, Up: Evaluation
  1079. 9.1 Introduction to Evaluation
  1080. ==============================
  1081. The Lisp interpreter, or evaluator, is the part of Emacs that computes
  1082. the value of an expression that is given to it. When a function
  1083. written in Lisp is called, the evaluator computes the value of the
  1084. function by evaluating the expressions in the function body. Thus,
  1085. running any Lisp program really means running the Lisp interpreter.
  1086. A Lisp object that is intended for evaluation is called a "form" or
  1087. "expression"(1). The fact that forms are data objects and not merely
  1088. text is one of the fundamental differences between Lisp-like languages
  1089. and typical programming languages. Any object can be evaluated, but in
  1090. practice only numbers, symbols, lists and strings are evaluated very
  1091. often.
  1092. In subsequent sections, we will describe the details of what
  1093. evaluation means for each kind of form.
  1094. It is very common to read a Lisp form and then evaluate the form,
  1095. but reading and evaluation are separate activities, and either can be
  1096. performed alone. Reading per se does not evaluate anything; it
  1097. converts the printed representation of a Lisp object to the object
  1098. itself. It is up to the caller of `read' to specify whether this
  1099. object is a form to be evaluated, or serves some entirely different
  1100. purpose. *Note Input Functions::.
  1101. Evaluation is a recursive process, and evaluating a form often
  1102. involves evaluating parts within that form. For instance, when you
  1103. evaluate a "function call" form such as `(car x)', Emacs first
  1104. evaluates the argument (the subform `x'). After evaluating the
  1105. argument, Emacs "executes" the function (`car'), and if the function is
  1106. written in Lisp, execution works by evaluating the "body" of the
  1107. function (in this example, however, `car' is not a Lisp function; it is
  1108. a primitive function implemented in C). *Note Functions::, for more
  1109. information about functions and function calls.
  1110. Evaluation takes place in a context called the "environment", which
  1111. consists of the current values and bindings of all Lisp variables
  1112. (*note Variables::).(2) Whenever a form refers to a variable without
  1113. creating a new binding for it, the variable evaluates to the value
  1114. given by the current environment. Evaluating a form may also
  1115. temporarily alter the environment by binding variables (*note Local
  1116. Variables::).
  1117. Evaluating a form may also make changes that persist; these changes
  1118. are called "side effects". An example of a form that produces a side
  1119. effect is `(setq foo 1)'.
  1120. Do not confuse evaluation with command key interpretation. The
  1121. editor command loop translates keyboard input into a command (an
  1122. interactively callable function) using the active keymaps, and then
  1123. uses `call-interactively' to execute that command. Executing the
  1124. command usually involves evaluation, if the command is written in Lisp;
  1125. however, this step is not considered a part of command key
  1126. interpretation. *Note Command Loop::.
  1127. ---------- Footnotes ----------
  1128. (1) It is sometimes also referred to as an "S-expression" or "sexp",
  1129. but we generally do not use this terminology in this manual.
  1130. (2) This definition of "environment" is specifically not intended to
  1131. include all the data that can affect the result of a program.
  1132. 
  1133. File: elisp, Node: Forms, Next: Quoting, Prev: Intro Eval, Up: Evaluation
  1134. 9.2 Kinds of Forms
  1135. ==================
  1136. A Lisp object that is intended to be evaluated is called a "form" (or
  1137. an "expression"). How Emacs evaluates a form depends on its data type.
  1138. Emacs has three different kinds of form that are evaluated differently:
  1139. symbols, lists, and "all other types". This section describes all
  1140. three kinds, one by one, starting with the "all other types" which are
  1141. self-evaluating forms.
  1142. * Menu:
  1143. * Self-Evaluating Forms:: Forms that evaluate to themselves.
  1144. * Symbol Forms:: Symbols evaluate as variables.
  1145. * Classifying Lists:: How to distinguish various sorts of list forms.
  1146. * Function Indirection:: When a symbol appears as the car of a list,
  1147. we find the real function via the symbol.
  1148. * Function Forms:: Forms that call functions.
  1149. * Macro Forms:: Forms that call macros.
  1150. * Special Forms:: "Special forms" are idiosyncratic primitives,
  1151. most of them extremely important.
  1152. * Autoloading:: Functions set up to load files
  1153. containing their real definitions.
  1154. 
  1155. File: elisp, Node: Self-Evaluating Forms, Next: Symbol Forms, Up: Forms
  1156. 9.2.1 Self-Evaluating Forms
  1157. ---------------------------
  1158. A "self-evaluating form" is any form that is not a list or symbol.
  1159. Self-evaluating forms evaluate to themselves: the result of evaluation
  1160. is the same object that was evaluated. Thus, the number 25 evaluates
  1161. to 25, and the string `"foo"' evaluates to the string `"foo"'.
  1162. Likewise, evaluating a vector does not cause evaluation of the elements
  1163. of the vector--it returns the same vector with its contents unchanged.
  1164. '123 ; A number, shown without evaluation.
  1165. => 123
  1166. 123 ; Evaluated as usual--result is the same.
  1167. => 123
  1168. (eval '123) ; Evaluated "by hand"--result is the same.
  1169. => 123
  1170. (eval (eval '123)) ; Evaluating twice changes nothing.
  1171. => 123
  1172. It is common to write numbers, characters, strings, and even vectors
  1173. in Lisp code, taking advantage of the fact that they self-evaluate.
  1174. However, it is quite unusual to do this for types that lack a read
  1175. syntax, because there's no way to write them textually. It is possible
  1176. to construct Lisp expressions containing these types by means of a Lisp
  1177. program. Here is an example:
  1178. ;; Build an expression containing a buffer object.
  1179. (setq print-exp (list 'print (current-buffer)))
  1180. => (print #<buffer eval.texi>)
  1181. ;; Evaluate it.
  1182. (eval print-exp)
  1183. -| #<buffer eval.texi>
  1184. => #<buffer eval.texi>
  1185. 
  1186. File: elisp, Node: Symbol Forms, Next: Classifying Lists, Prev: Self-Evaluating Forms, Up: Forms
  1187. 9.2.2 Symbol Forms
  1188. ------------------
  1189. When a symbol is evaluated, it is treated as a variable. The result is
  1190. the variable's value, if it has one. If the symbol has no value as a
  1191. variable, the Lisp interpreter signals an error. For more information
  1192. on the use of variables, see *note Variables::.
  1193. In the following example, we set the value of a symbol with `setq'.
  1194. Then we evaluate the symbol, and get back the value that `setq' stored.
  1195. (setq a 123)
  1196. => 123
  1197. (eval 'a)
  1198. => 123
  1199. a
  1200. => 123
  1201. The symbols `nil' and `t' are treated specially, so that the value
  1202. of `nil' is always `nil', and the value of `t' is always `t'; you
  1203. cannot set or bind them to any other values. Thus, these two symbols
  1204. act like self-evaluating forms, even though `eval' treats them like any
  1205. other symbol. A symbol whose name starts with `:' also self-evaluates
  1206. in the same way; likewise, its value ordinarily cannot be changed.
  1207. *Note Constant Variables::.
  1208. 
  1209. File: elisp, Node: Classifying Lists, Next: Function Indirection, Prev: Symbol Forms, Up: Forms
  1210. 9.2.3 Classification of List Forms
  1211. ----------------------------------
  1212. A form that is a nonempty list is either a function call, a macro call,
  1213. or a special form, according to its first element. These three kinds
  1214. of forms are evaluated in different ways, described below. The
  1215. remaining list elements constitute the "arguments" for the function,
  1216. macro, or special form.
  1217. The first step in evaluating a nonempty list is to examine its first
  1218. element. This element alone determines what kind of form the list is
  1219. and how the rest of the list is to be processed. The first element is
  1220. _not_ evaluated, as it would be in some Lisp dialects such as Scheme.
  1221. 
  1222. File: elisp, Node: Function Indirection, Next: Function Forms, Prev: Classifying Lists, Up: Forms
  1223. 9.2.4 Symbol Function Indirection
  1224. ---------------------------------
  1225. If the first element of the list is a symbol then evaluation examines
  1226. the symbol's function cell, and uses its contents instead of the
  1227. original symbol. If the contents are another symbol, this process,
  1228. called "symbol function indirection", is repeated until it obtains a
  1229. non-symbol. *Note Function Names::, for more information about symbol
  1230. function indirection.
  1231. One possible consequence of this process is an infinite loop, in the
  1232. event that a symbol's function cell refers to the same symbol. Or a
  1233. symbol may have a void function cell, in which case the subroutine
  1234. `symbol-function' signals a `void-function' error. But if neither of
  1235. these things happens, we eventually obtain a non-symbol, which ought to
  1236. be a function or other suitable object.
  1237. More precisely, we should now have a Lisp function (a lambda
  1238. expression), a byte-code function, a primitive function, a Lisp macro,
  1239. a special form, or an autoload object. Each of these types is a case
  1240. described in one of the following sections. If the object is not one
  1241. of these types, Emacs signals an `invalid-function' error.
  1242. The following example illustrates the symbol indirection process. We
  1243. use `fset' to set the function cell of a symbol and `symbol-function'
  1244. to get the function cell contents (*note Function Cells::).
  1245. Specifically, we store the symbol `car' into the function cell of
  1246. `first', and the symbol `first' into the function cell of `erste'.
  1247. ;; Build this function cell linkage:
  1248. ;; ------------- ----- ------- -------
  1249. ;; | #<subr car> | <-- | car | <-- | first | <-- | erste |
  1250. ;; ------------- ----- ------- -------
  1251. (symbol-function 'car)
  1252. => #<subr car>
  1253. (fset 'first 'car)
  1254. => car
  1255. (fset 'erste 'first)
  1256. => first
  1257. (erste '(1 2 3)) ; Call the function referenced by `erste'.
  1258. => 1
  1259. By contrast, the following example calls a function without any
  1260. symbol function indirection, because the first element is an anonymous
  1261. Lisp function, not a symbol.
  1262. ((lambda (arg) (erste arg))
  1263. '(1 2 3))
  1264. => 1
  1265. Executing the function itself evaluates its body; this does involve
  1266. symbol function indirection when calling `erste'.
  1267. This form is rarely used and is now deprecated. Instead, you should
  1268. write it as:
  1269. (funcall (lambda (arg) (erste arg))
  1270. '(1 2 3))
  1271. or just
  1272. (let ((arg '(1 2 3))) (erste arg))
  1273. The built-in function `indirect-function' provides an easy way to
  1274. perform symbol function indirection explicitly.
  1275. -- Function: indirect-function function &optional noerror
  1276. This function returns the meaning of FUNCTION as a function. If
  1277. FUNCTION is a symbol, then it finds FUNCTION's function definition
  1278. and starts over with that value. If FUNCTION is not a symbol,
  1279. then it returns FUNCTION itself.
  1280. This function signals a `void-function' error if the final symbol
  1281. is unbound and optional argument NOERROR is `nil' or omitted.
  1282. Otherwise, if NOERROR is non-`nil', it returns `nil' if the final
  1283. symbol is unbound.
  1284. It signals a `cyclic-function-indirection' error if there is a
  1285. loop in the chain of symbols.
  1286. Here is how you could define `indirect-function' in Lisp:
  1287. (defun indirect-function (function)
  1288. (if (symbolp function)
  1289. (indirect-function (symbol-function function))
  1290. function))
  1291. 
  1292. File: elisp, Node: Function Forms, Next: Macro Forms, Prev: Function Indirection, Up: Forms
  1293. 9.2.5 Evaluation of Function Forms
  1294. ----------------------------------
  1295. If the first element of a list being evaluated is a Lisp function
  1296. object, byte-code object or primitive function object, then that list is
  1297. a "function call". For example, here is a call to the function `+':
  1298. (+ 1 x)
  1299. The first step in evaluating a function call is to evaluate the
  1300. remaining elements of the list from left to right. The results are the
  1301. actual argument values, one value for each list element. The next step
  1302. is to call the function with this list of arguments, effectively using
  1303. the function `apply' (*note Calling Functions::). If the function is
  1304. written in Lisp, the arguments are used to bind the argument variables
  1305. of the function (*note Lambda Expressions::); then the forms in the
  1306. function body are evaluated in order, and the value of the last body
  1307. form becomes the value of the function call.
  1308. 
  1309. File: elisp, Node: Macro Forms, Next: Special Forms, Prev: Function Forms, Up: Forms
  1310. 9.2.6 Lisp Macro Evaluation
  1311. ---------------------------
  1312. If the first element of a list being evaluated is a macro object, then
  1313. the list is a "macro call". When a macro call is evaluated, the
  1314. elements of the rest of the list are _not_ initially evaluated.
  1315. Instead, these elements themselves are used as the arguments of the
  1316. macro. The macro definition computes a replacement form, called the
  1317. "expansion" of the macro, to be evaluated in place of the original
  1318. form. The expansion may be any sort of form: a self-evaluating
  1319. constant, a symbol, or a list. If the expansion is itself a macro call,
  1320. this process of expansion repeats until some other sort of form results.
  1321. Ordinary evaluation of a macro call finishes by evaluating the
  1322. expansion. However, the macro expansion is not necessarily evaluated
  1323. right away, or at all, because other programs also expand macro calls,
  1324. and they may or may not evaluate the expansions.
  1325. Normally, the argument expressions are not evaluated as part of
  1326. computing the macro expansion, but instead appear as part of the
  1327. expansion, so they are computed when the expansion is evaluated.
  1328. For example, given a macro defined as follows:
  1329. (defmacro cadr (x)
  1330. (list 'car (list 'cdr x)))
  1331. an expression such as `(cadr (assq 'handler list))' is a macro call,
  1332. and its expansion is:
  1333. (car (cdr (assq 'handler list)))
  1334. Note that the argument `(assq 'handler list)' appears in the expansion.
  1335. *Note Macros::, for a complete description of Emacs Lisp macros.
  1336. 
  1337. File: elisp, Node: Special Forms, Next: Autoloading, Prev: Macro Forms, Up: Forms
  1338. 9.2.7 Special Forms
  1339. -------------------
  1340. A "special form" is a primitive function specially marked so that its
  1341. arguments are not all evaluated. Most special forms define control
  1342. structures or perform variable bindings--things which functions cannot
  1343. do.
  1344. Each special form has its own rules for which arguments are evaluated
  1345. and which are used without evaluation. Whether a particular argument is
  1346. evaluated may depend on the results of evaluating other arguments.
  1347. Here is a list, in alphabetical order, of all of the special forms in
  1348. Emacs Lisp with a reference to where each is described.
  1349. `and'
  1350. *note Combining Conditions::
  1351. `catch'
  1352. *note Catch and Throw::
  1353. `cond'
  1354. *note Conditionals::
  1355. `condition-case'
  1356. *note Handling Errors::
  1357. `defconst'
  1358. *note Defining Variables::
  1359. `defmacro'
  1360. *note Defining Macros::
  1361. `defun'
  1362. *note Defining Functions::
  1363. `defvar'
  1364. *note Defining Variables::
  1365. `function'
  1366. *note Anonymous Functions::
  1367. `if'
  1368. *note Conditionals::
  1369. `interactive'
  1370. *note Interactive Call::
  1371. `let'
  1372. `let*'
  1373. *note Local Variables::
  1374. `or'
  1375. *note Combining Conditions::
  1376. `prog1'
  1377. `prog2'
  1378. `progn'
  1379. *note Sequencing::
  1380. `quote'
  1381. *note Quoting::
  1382. `save-current-buffer'
  1383. *note Current Buffer::
  1384. `save-excursion'
  1385. *note Excursions::
  1386. `save-restriction'
  1387. *note Narrowing::
  1388. `save-window-excursion'
  1389. *note Window Configurations::
  1390. `setq'
  1391. *note Setting Variables::
  1392. `setq-default'
  1393. *note Creating Buffer-Local::
  1394. `track-mouse'
  1395. *note Mouse Tracking::
  1396. `unwind-protect'
  1397. *note Nonlocal Exits::
  1398. `while'
  1399. *note Iteration::
  1400. `with-output-to-temp-buffer'
  1401. *note Temporary Displays::
  1402. Common Lisp note: Here are some comparisons of special forms in
  1403. GNU Emacs Lisp and Common Lisp. `setq', `if', and `catch' are
  1404. special forms in both Emacs Lisp and Common Lisp. `defun' is a
  1405. special form in Emacs Lisp, but a macro in Common Lisp.
  1406. `save-excursion' is a special form in Emacs Lisp, but doesn't
  1407. exist in Common Lisp. `throw' is a special form in Common Lisp
  1408. (because it must be able to throw multiple values), but it is a
  1409. function in Emacs Lisp (which doesn't have multiple values).
  1410. 
  1411. File: elisp, Node: Autoloading, Prev: Special Forms, Up: Forms
  1412. 9.2.8 Autoloading
  1413. -----------------
  1414. The "autoload" feature allows you to call a function or macro whose
  1415. function definition has not yet been loaded into Emacs. It specifies
  1416. which file contains the definition. When an autoload object appears as
  1417. a symbol's function definition, calling that symbol as a function
  1418. automatically loads the specified file; then it calls the real
  1419. definition loaded from that file. The way to arrange for an autoload
  1420. object to appear as a symbol's function definition is described in
  1421. *note Autoload::.
  1422. 
  1423. File: elisp, Node: Quoting, Next: Backquote, Prev: Forms, Up: Evaluation
  1424. 9.3 Quoting
  1425. ===========
  1426. The special form `quote' returns its single argument, as written,
  1427. without evaluating it. This provides a way to include constant symbols
  1428. and lists, which are not self-evaluating objects, in a program. (It is
  1429. not necessary to quote self-evaluating objects such as numbers, strings,
  1430. and vectors.)
  1431. -- Special Form: quote object
  1432. This special form returns OBJECT, without evaluating it.
  1433. Because `quote' is used so often in programs, Lisp provides a
  1434. convenient read syntax for it. An apostrophe character (`'') followed
  1435. by a Lisp object (in read syntax) expands to a list whose first element
  1436. is `quote', and whose second element is the object. Thus, the read
  1437. syntax `'x' is an abbreviation for `(quote x)'.
  1438. Here are some examples of expressions that use `quote':
  1439. (quote (+ 1 2))
  1440. => (+ 1 2)
  1441. (quote foo)
  1442. => foo
  1443. 'foo
  1444. => foo
  1445. ''foo
  1446. => (quote foo)
  1447. '(quote foo)
  1448. => (quote foo)
  1449. ['foo]
  1450. => [(quote foo)]
  1451. Other quoting constructs include `function' (*note Anonymous
  1452. Functions::), which causes an anonymous lambda expression written in
  1453. Lisp to be compiled, and ``' (*note Backquote::), which is used to quote
  1454. only part of a list, while computing and substituting other parts.
  1455. 
  1456. File: elisp, Node: Backquote, Next: Eval, Prev: Quoting, Up: Evaluation
  1457. 9.4 Backquote
  1458. =============
  1459. "Backquote constructs" allow you to quote a list, but selectively
  1460. evaluate elements of that list. In the simplest case, it is identical
  1461. to the special form `quote' (described in the previous section; *note
  1462. Quoting::). For example, these two forms yield identical results:
  1463. `(a list of (+ 2 3) elements)
  1464. => (a list of (+ 2 3) elements)
  1465. '(a list of (+ 2 3) elements)
  1466. => (a list of (+ 2 3) elements)
  1467. The special marker `,' inside of the argument to backquote indicates
  1468. a value that isn't constant. The Emacs Lisp evaluator evaluates the
  1469. argument of `,', and puts the value in the list structure:
  1470. `(a list of ,(+ 2 3) elements)
  1471. => (a list of 5 elements)
  1472. Substitution with `,' is allowed at deeper levels of the list structure
  1473. also. For example:
  1474. `(1 2 (3 ,(+ 4 5)))
  1475. => (1 2 (3 9))
  1476. You can also "splice" an evaluated value into the resulting list,
  1477. using the special marker `,@'. The elements of the spliced list become
  1478. elements at the same level as the other elements of the resulting list.
  1479. The equivalent code without using ``' is often unreadable. Here are
  1480. some examples:
  1481. (setq some-list '(2 3))
  1482. => (2 3)
  1483. (cons 1 (append some-list '(4) some-list))
  1484. => (1 2 3 4 2 3)
  1485. `(1 ,@some-list 4 ,@some-list)
  1486. => (1 2 3 4 2 3)
  1487. (setq list '(hack foo bar))
  1488. => (hack foo bar)
  1489. (cons 'use
  1490. (cons 'the
  1491. (cons 'words (append (cdr list) '(as elements)))))
  1492. => (use the words foo bar as elements)
  1493. `(use the words ,@(cdr list) as elements)
  1494. => (use the words foo bar as elements)
  1495. 
  1496. File: elisp, Node: Eval, Prev: Backquote, Up: Evaluation
  1497. 9.5 Eval
  1498. ========
  1499. Most often, forms are evaluated automatically, by virtue of their
  1500. occurrence in a program being run. On rare occasions, you may need to
  1501. write code that evaluates a form that is computed at run time, such as
  1502. after reading a form from text being edited or getting one from a
  1503. property list. On these occasions, use the `eval' function. Often
  1504. `eval' is not needed and something else should be used instead. For
  1505. example, to get the value of a variable, while `eval' works,
  1506. `symbol-value' is preferable; or rather than store expressions in a
  1507. property list that then need to go through `eval', it is better to
  1508. store functions instead that are then passed to `funcall'.
  1509. The functions and variables described in this section evaluate forms,
  1510. specify limits to the evaluation process, or record recently returned
  1511. values. Loading a file also does evaluation (*note Loading::).
  1512. It is generally cleaner and more flexible to store a function in a
  1513. data structure, and call it with `funcall' or `apply', than to store an
  1514. expression in the data structure and evaluate it. Using functions
  1515. provides the ability to pass information to them as arguments.
  1516. -- Function: eval form &optional lexical
  1517. This is the basic function for evaluating an expression. It
  1518. evaluates FORM in the current environment and returns the result.
  1519. How the evaluation proceeds depends on the type of the object
  1520. (*note Forms::).
  1521. The argument LEXICAL, if non-`nil', means to evaluate FORM using
  1522. lexical scoping rules for variables, instead of the default
  1523. dynamic scoping rules. *Note Lexical Binding::.
  1524. Since `eval' is a function, the argument expression that appears
  1525. in a call to `eval' is evaluated twice: once as preparation before
  1526. `eval' is called, and again by the `eval' function itself. Here
  1527. is an example:
  1528. (setq foo 'bar)
  1529. => bar
  1530. (setq bar 'baz)
  1531. => baz
  1532. ;; Here `eval' receives argument `foo'
  1533. (eval 'foo)
  1534. => bar
  1535. ;; Here `eval' receives argument `bar', which is the value of `foo'
  1536. (eval foo)
  1537. => baz
  1538. The number of currently active calls to `eval' is limited to
  1539. `max-lisp-eval-depth' (see below).
  1540. -- Command: eval-region start end &optional stream read-function
  1541. This function evaluates the forms in the current buffer in the
  1542. region defined by the positions START and END. It reads forms from
  1543. the region and calls `eval' on them until the end of the region is
  1544. reached, or until an error is signaled and not handled.
  1545. By default, `eval-region' does not produce any output. However,
  1546. if STREAM is non-`nil', any output produced by output functions
  1547. (*note Output Functions::), as well as the values that result from
  1548. evaluating the expressions in the region are printed using STREAM.
  1549. *Note Output Streams::.
  1550. If READ-FUNCTION is non-`nil', it should be a function, which is
  1551. used instead of `read' to read expressions one by one. This
  1552. function is called with one argument, the stream for reading
  1553. input. You can also use the variable `load-read-function' (*note
  1554. How Programs Do Loading: Definition of load-read-function.) to
  1555. specify this function, but it is more robust to use the
  1556. READ-FUNCTION argument.
  1557. `eval-region' does not move point. It always returns `nil'.
  1558. -- Command: eval-buffer &optional buffer-or-name stream filename
  1559. unibyte print
  1560. This is similar to `eval-region', but the arguments provide
  1561. different optional features. `eval-buffer' operates on the entire
  1562. accessible portion of buffer BUFFER-OR-NAME. BUFFER-OR-NAME can
  1563. be a buffer, a buffer name (a string), or `nil' (or omitted),
  1564. which means to use the current buffer. STREAM is used as in
  1565. `eval-region', unless STREAM is `nil' and PRINT non-`nil'. In
  1566. that case, values that result from evaluating the expressions are
  1567. still discarded, but the output of the output functions is printed
  1568. in the echo area. FILENAME is the file name to use for
  1569. `load-history' (*note Unloading::), and defaults to
  1570. `buffer-file-name' (*note Buffer File Name::). If UNIBYTE is
  1571. non-`nil', `read' converts strings to unibyte whenever possible.
  1572. `eval-current-buffer' is an alias for this command.
  1573. -- User Option: max-lisp-eval-depth
  1574. This variable defines the maximum depth allowed in calls to `eval',
  1575. `apply', and `funcall' before an error is signaled (with error
  1576. message `"Lisp nesting exceeds max-lisp-eval-depth"').
  1577. This limit, with the associated error when it is exceeded, is one
  1578. way Emacs Lisp avoids infinite recursion on an ill-defined
  1579. function. If you increase the value of `max-lisp-eval-depth' too
  1580. much, such code can cause stack overflow instead.
  1581. The depth limit counts internal uses of `eval', `apply', and
  1582. `funcall', such as for calling the functions mentioned in Lisp
  1583. expressions, and recursive evaluation of function call arguments
  1584. and function body forms, as well as explicit calls in Lisp code.
  1585. The default value of this variable is 400. If you set it to a
  1586. value less than 100, Lisp will reset it to 100 if the given value
  1587. is reached. Entry to the Lisp debugger increases the value, if
  1588. there is little room left, to make sure the debugger itself has
  1589. room to execute.
  1590. `max-specpdl-size' provides another limit on nesting. *Note Local
  1591. Variables: Definition of max-specpdl-size.
  1592. -- Variable: values
  1593. The value of this variable is a list of the values returned by all
  1594. the expressions that were read, evaluated, and printed from buffers
  1595. (including the minibuffer) by the standard Emacs commands which do
  1596. this. (Note that this does _not_ include evaluation in `*ielm*'
  1597. buffers, nor evaluation using `C-j' in `lisp-interaction-mode'.)
  1598. The elements are ordered most recent first.
  1599. (setq x 1)
  1600. => 1
  1601. (list 'A (1+ 2) auto-save-default)
  1602. => (A 3 t)
  1603. values
  1604. => ((A 3 t) 1 ...)
  1605. This variable is useful for referring back to values of forms
  1606. recently evaluated. It is generally a bad idea to print the value
  1607. of `values' itself, since this may be very long. Instead, examine
  1608. particular elements, like this:
  1609. ;; Refer to the most recent evaluation result.
  1610. (nth 0 values)
  1611. => (A 3 t)
  1612. ;; That put a new element on,
  1613. ;; so all elements move back one.
  1614. (nth 1 values)
  1615. => (A 3 t)
  1616. ;; This gets the element that was next-to-most-recent
  1617. ;; before this example.
  1618. (nth 3 values)
  1619. => 1
  1620. 
  1621. File: elisp, Node: Control Structures, Next: Variables, Prev: Evaluation, Up: Top
  1622. 10 Control Structures
  1623. *********************
  1624. A Lisp program consists of a set of "expressions", or "forms" (*note
  1625. Forms::). We control the order of execution of these forms by
  1626. enclosing them in "control structures". Control structures are special
  1627. forms which control when, whether, or how many times to execute the
  1628. forms they contain.
  1629. The simplest order of execution is sequential execution: first form
  1630. A, then form B, and so on. This is what happens when you write several
  1631. forms in succession in the body of a function, or at top level in a
  1632. file of Lisp code--the forms are executed in the order written. We
  1633. call this "textual order". For example, if a function body consists of
  1634. two forms A and B, evaluation of the function evaluates first A and
  1635. then B. The result of evaluating B becomes the value of the function.
  1636. Explicit control structures make possible an order of execution other
  1637. than sequential.
  1638. Emacs Lisp provides several kinds of control structure, including
  1639. other varieties of sequencing, conditionals, iteration, and (controlled)
  1640. jumps--all discussed below. The built-in control structures are
  1641. special forms since their subforms are not necessarily evaluated or not
  1642. evaluated sequentially. You can use macros to define your own control
  1643. structure constructs (*note Macros::).
  1644. * Menu:
  1645. * Sequencing:: Evaluation in textual order.
  1646. * Conditionals:: `if', `cond', `when', `unless'.
  1647. * Combining Conditions:: `and', `or', `not'.
  1648. * Iteration:: `while' loops.
  1649. * Nonlocal Exits:: Jumping out of a sequence.
  1650. 
  1651. File: elisp, Node: Sequencing, Next: Conditionals, Up: Control Structures
  1652. 10.1 Sequencing
  1653. ===============
  1654. Evaluating forms in the order they appear is the most common way
  1655. control passes from one form to another. In some contexts, such as in a
  1656. function body, this happens automatically. Elsewhere you must use a
  1657. control structure construct to do this: `progn', the simplest control
  1658. construct of Lisp.
  1659. A `progn' special form looks like this:
  1660. (progn A B C ...)
  1661. and it says to execute the forms A, B, C, and so on, in that order.
  1662. These forms are called the "body" of the `progn' form. The value of
  1663. the last form in the body becomes the value of the entire `progn'.
  1664. `(progn)' returns `nil'.
  1665. In the early days of Lisp, `progn' was the only way to execute two
  1666. or more forms in succession and use the value of the last of them. But
  1667. programmers found they often needed to use a `progn' in the body of a
  1668. function, where (at that time) only one form was allowed. So the body
  1669. of a function was made into an "implicit `progn'": several forms are
  1670. allowed just as in the body of an actual `progn'. Many other control
  1671. structures likewise contain an implicit `progn'. As a result, `progn'
  1672. is not used as much as it was many years ago. It is needed now most
  1673. often inside an `unwind-protect', `and', `or', or in the THEN-part of
  1674. an `if'.
  1675. -- Special Form: progn forms...
  1676. This special form evaluates all of the FORMS, in textual order,
  1677. returning the result of the final form.
  1678. (progn (print "The first form")
  1679. (print "The second form")
  1680. (print "The third form"))
  1681. -| "The first form"
  1682. -| "The second form"
  1683. -| "The third form"
  1684. => "The third form"
  1685. Two other constructs likewise evaluate a series of forms but return
  1686. different values:
  1687. -- Special Form: prog1 form1 forms...
  1688. This special form evaluates FORM1 and all of the FORMS, in textual
  1689. order, returning the result of FORM1.
  1690. (prog1 (print "The first form")
  1691. (print "The second form")
  1692. (print "The third form"))
  1693. -| "The first form"
  1694. -| "The second form"
  1695. -| "The third form"
  1696. => "The first form"
  1697. Here is a way to remove the first element from a list in the
  1698. variable `x', then return the value of that former element:
  1699. (prog1 (car x) (setq x (cdr x)))
  1700. -- Special Form: prog2 form1 form2 forms...
  1701. This special form evaluates FORM1, FORM2, and all of the following
  1702. FORMS, in textual order, returning the result of FORM2.
  1703. (prog2 (print "The first form")
  1704. (print "The second form")
  1705. (print "The third form"))
  1706. -| "The first form"
  1707. -| "The second form"
  1708. -| "The third form"
  1709. => "The second form"
  1710. 
  1711. File: elisp, Node: Conditionals, Next: Combining Conditions, Prev: Sequencing, Up: Control Structures
  1712. 10.2 Conditionals
  1713. =================
  1714. Conditional control structures choose among alternatives. Emacs Lisp
  1715. has four conditional forms: `if', which is much the same as in other
  1716. languages; `when' and `unless', which are variants of `if'; and `cond',
  1717. which is a generalized case statement.
  1718. -- Special Form: if condition then-form else-forms...
  1719. `if' chooses between the THEN-FORM and the ELSE-FORMS based on the
  1720. value of CONDITION. If the evaluated CONDITION is non-`nil',
  1721. THEN-FORM is evaluated and the result returned. Otherwise, the
  1722. ELSE-FORMS are evaluated in textual order, and the value of the
  1723. last one is returned. (The ELSE part of `if' is an example of an
  1724. implicit `progn'. *Note Sequencing::.)
  1725. If CONDITION has the value `nil', and no ELSE-FORMS are given,
  1726. `if' returns `nil'.
  1727. `if' is a special form because the branch that is not selected is
  1728. never evaluated--it is ignored. Thus, in this example, `true' is
  1729. not printed because `print' is never called:
  1730. (if nil
  1731. (print 'true)
  1732. 'very-false)
  1733. => very-false
  1734. -- Macro: when condition then-forms...
  1735. This is a variant of `if' where there are no ELSE-FORMS, and
  1736. possibly several THEN-FORMS. In particular,
  1737. (when CONDITION A B C)
  1738. is entirely equivalent to
  1739. (if CONDITION (progn A B C) nil)
  1740. -- Macro: unless condition forms...
  1741. This is a variant of `if' where there is no THEN-FORM:
  1742. (unless CONDITION A B C)
  1743. is entirely equivalent to
  1744. (if CONDITION nil
  1745. A B C)
  1746. -- Special Form: cond clause...
  1747. `cond' chooses among an arbitrary number of alternatives. Each
  1748. CLAUSE in the `cond' must be a list. The CAR of this list is the
  1749. CONDITION; the remaining elements, if any, the BODY-FORMS. Thus,
  1750. a clause looks like this:
  1751. (CONDITION BODY-FORMS...)
  1752. `cond' tries the clauses in textual order, by evaluating the
  1753. CONDITION of each clause. If the value of CONDITION is non-`nil',
  1754. the clause "succeeds"; then `cond' evaluates its BODY-FORMS, and
  1755. the value of the last of BODY-FORMS becomes the value of the
  1756. `cond'. The remaining clauses are ignored.
  1757. If the value of CONDITION is `nil', the clause "fails", so the
  1758. `cond' moves on to the following clause, trying its CONDITION.
  1759. If every CONDITION evaluates to `nil', so that every clause fails,
  1760. `cond' returns `nil'.
  1761. A clause may also look like this:
  1762. (CONDITION)
  1763. Then, if CONDITION is non-`nil' when tested, the value of
  1764. CONDITION becomes the value of the `cond' form.
  1765. The following example has four clauses, which test for the cases
  1766. where the value of `x' is a number, string, buffer and symbol,
  1767. respectively:
  1768. (cond ((numberp x) x)
  1769. ((stringp x) x)
  1770. ((bufferp x)
  1771. (setq temporary-hack x) ; multiple body-forms
  1772. (buffer-name x)) ; in one clause
  1773. ((symbolp x) (symbol-value x)))
  1774. Often we want to execute the last clause whenever none of the
  1775. previous clauses was successful. To do this, we use `t' as the
  1776. CONDITION of the last clause, like this: `(t BODY-FORMS)'. The
  1777. form `t' evaluates to `t', which is never `nil', so this clause
  1778. never fails, provided the `cond' gets to it at all. For example:
  1779. (setq a 5)
  1780. (cond ((eq a 'hack) 'foo)
  1781. (t "default"))
  1782. => "default"
  1783. This `cond' expression returns `foo' if the value of `a' is
  1784. `hack', and returns the string `"default"' otherwise.
  1785. Any conditional construct can be expressed with `cond' or with `if'.
  1786. Therefore, the choice between them is a matter of style. For example:
  1787. (if A B C)
  1788. ==
  1789. (cond (A B) (t C))
  1790. 
  1791. File: elisp, Node: Combining Conditions, Next: Iteration, Prev: Conditionals, Up: Control Structures
  1792. 10.3 Constructs for Combining Conditions
  1793. ========================================
  1794. This section describes three constructs that are often used together
  1795. with `if' and `cond' to express complicated conditions. The constructs
  1796. `and' and `or' can also be used individually as kinds of multiple
  1797. conditional constructs.
  1798. -- Function: not condition
  1799. This function tests for the falsehood of CONDITION. It returns
  1800. `t' if CONDITION is `nil', and `nil' otherwise. The function
  1801. `not' is identical to `null', and we recommend using the name
  1802. `null' if you are testing for an empty list.
  1803. -- Special Form: and conditions...
  1804. The `and' special form tests whether all the CONDITIONS are true.
  1805. It works by evaluating the CONDITIONS one by one in the order
  1806. written.
  1807. If any of the CONDITIONS evaluates to `nil', then the result of
  1808. the `and' must be `nil' regardless of the remaining CONDITIONS; so
  1809. `and' returns `nil' right away, ignoring the remaining CONDITIONS.
  1810. If all the CONDITIONS turn out non-`nil', then the value of the
  1811. last of them becomes the value of the `and' form. Just `(and)',
  1812. with no CONDITIONS, returns `t', appropriate because all the
  1813. CONDITIONS turned out non-`nil'. (Think about it; which one did
  1814. not?)
  1815. Here is an example. The first condition returns the integer 1,
  1816. which is not `nil'. Similarly, the second condition returns the
  1817. integer 2, which is not `nil'. The third condition is `nil', so
  1818. the remaining condition is never evaluated.
  1819. (and (print 1) (print 2) nil (print 3))
  1820. -| 1
  1821. -| 2
  1822. => nil
  1823. Here is a more realistic example of using `and':
  1824. (if (and (consp foo) (eq (car foo) 'x))
  1825. (message "foo is a list starting with x"))
  1826. Note that `(car foo)' is not executed if `(consp foo)' returns
  1827. `nil', thus avoiding an error.
  1828. `and' expressions can also be written using either `if' or `cond'.
  1829. Here's how:
  1830. (and ARG1 ARG2 ARG3)
  1831. ==
  1832. (if ARG1 (if ARG2 ARG3))
  1833. ==
  1834. (cond (ARG1 (cond (ARG2 ARG3))))
  1835. -- Special Form: or conditions...
  1836. The `or' special form tests whether at least one of the CONDITIONS
  1837. is true. It works by evaluating all the CONDITIONS one by one in
  1838. the order written.
  1839. If any of the CONDITIONS evaluates to a non-`nil' value, then the
  1840. result of the `or' must be non-`nil'; so `or' returns right away,
  1841. ignoring the remaining CONDITIONS. The value it returns is the
  1842. non-`nil' value of the condition just evaluated.
  1843. If all the CONDITIONS turn out `nil', then the `or' expression
  1844. returns `nil'. Just `(or)', with no CONDITIONS, returns `nil',
  1845. appropriate because all the CONDITIONS turned out `nil'. (Think
  1846. about it; which one did not?)
  1847. For example, this expression tests whether `x' is either `nil' or
  1848. the integer zero:
  1849. (or (eq x nil) (eq x 0))
  1850. Like the `and' construct, `or' can be written in terms of `cond'.
  1851. For example:
  1852. (or ARG1 ARG2 ARG3)
  1853. ==
  1854. (cond (ARG1)
  1855. (ARG2)
  1856. (ARG3))
  1857. You could almost write `or' in terms of `if', but not quite:
  1858. (if ARG1 ARG1
  1859. (if ARG2 ARG2
  1860. ARG3))
  1861. This is not completely equivalent because it can evaluate ARG1 or
  1862. ARG2 twice. By contrast, `(or ARG1 ARG2 ARG3)' never evaluates
  1863. any argument more than once.
  1864. 
  1865. File: elisp, Node: Iteration, Next: Nonlocal Exits, Prev: Combining Conditions, Up: Control Structures
  1866. 10.4 Iteration
  1867. ==============
  1868. Iteration means executing part of a program repetitively. For example,
  1869. you might want to repeat some computation once for each element of a
  1870. list, or once for each integer from 0 to N. You can do this in Emacs
  1871. Lisp with the special form `while':
  1872. -- Special Form: while condition forms...
  1873. `while' first evaluates CONDITION. If the result is non-`nil', it
  1874. evaluates FORMS in textual order. Then it reevaluates CONDITION,
  1875. and if the result is non-`nil', it evaluates FORMS again. This
  1876. process repeats until CONDITION evaluates to `nil'.
  1877. There is no limit on the number of iterations that may occur. The
  1878. loop will continue until either CONDITION evaluates to `nil' or
  1879. until an error or `throw' jumps out of it (*note Nonlocal Exits::).
  1880. The value of a `while' form is always `nil'.
  1881. (setq num 0)
  1882. => 0
  1883. (while (< num 4)
  1884. (princ (format "Iteration %d." num))
  1885. (setq num (1+ num)))
  1886. -| Iteration 0.
  1887. -| Iteration 1.
  1888. -| Iteration 2.
  1889. -| Iteration 3.
  1890. => nil
  1891. To write a "repeat...until" loop, which will execute something on
  1892. each iteration and then do the end-test, put the body followed by
  1893. the end-test in a `progn' as the first argument of `while', as
  1894. shown here:
  1895. (while (progn
  1896. (forward-line 1)
  1897. (not (looking-at "^$"))))
  1898. This moves forward one line and continues moving by lines until it
  1899. reaches an empty line. It is peculiar in that the `while' has no
  1900. body, just the end test (which also does the real work of moving
  1901. point).
  1902. The `dolist' and `dotimes' macros provide convenient ways to write
  1903. two common kinds of loops.
  1904. -- Macro: dolist (var list [result]) body...
  1905. This construct executes BODY once for each element of LIST,
  1906. binding the variable VAR locally to hold the current element.
  1907. Then it returns the value of evaluating RESULT, or `nil' if RESULT
  1908. is omitted. For example, here is how you could use `dolist' to
  1909. define the `reverse' function:
  1910. (defun reverse (list)
  1911. (let (value)
  1912. (dolist (elt list value)
  1913. (setq value (cons elt value)))))
  1914. -- Macro: dotimes (var count [result]) body...
  1915. This construct executes BODY once for each integer from 0
  1916. (inclusive) to COUNT (exclusive), binding the variable VAR to the
  1917. integer for the current iteration. Then it returns the value of
  1918. evaluating RESULT, or `nil' if RESULT is omitted. Here is an
  1919. example of using `dotimes' to do something 100 times:
  1920. (dotimes (i 100)
  1921. (insert "I will not obey absurd orders\n"))
  1922. 
  1923. File: elisp, Node: Nonlocal Exits, Prev: Iteration, Up: Control Structures
  1924. 10.5 Nonlocal Exits
  1925. ===================
  1926. A "nonlocal exit" is a transfer of control from one point in a program
  1927. to another remote point. Nonlocal exits can occur in Emacs Lisp as a
  1928. result of errors; you can also use them under explicit control.
  1929. Nonlocal exits unbind all variable bindings made by the constructs being
  1930. exited.
  1931. * Menu:
  1932. * Catch and Throw:: Nonlocal exits for the program's own purposes.
  1933. * Examples of Catch:: Showing how such nonlocal exits can be written.
  1934. * Errors:: How errors are signaled and handled.
  1935. * Cleanups:: Arranging to run a cleanup form if an error happens.
  1936. 
  1937. File: elisp, Node: Catch and Throw, Next: Examples of Catch, Up: Nonlocal Exits
  1938. 10.5.1 Explicit Nonlocal Exits: `catch' and `throw'
  1939. ---------------------------------------------------
  1940. Most control constructs affect only the flow of control within the
  1941. construct itself. The function `throw' is the exception to this rule
  1942. of normal program execution: it performs a nonlocal exit on request.
  1943. (There are other exceptions, but they are for error handling only.)
  1944. `throw' is used inside a `catch', and jumps back to that `catch'. For
  1945. example:
  1946. (defun foo-outer ()
  1947. (catch 'foo
  1948. (foo-inner)))
  1949. (defun foo-inner ()
  1950. ...
  1951. (if x
  1952. (throw 'foo t))
  1953. ...)
  1954. The `throw' form, if executed, transfers control straight back to the
  1955. corresponding `catch', which returns immediately. The code following
  1956. the `throw' is not executed. The second argument of `throw' is used as
  1957. the return value of the `catch'.
  1958. The function `throw' finds the matching `catch' based on the first
  1959. argument: it searches for a `catch' whose first argument is `eq' to the
  1960. one specified in the `throw'. If there is more than one applicable
  1961. `catch', the innermost one takes precedence. Thus, in the above
  1962. example, the `throw' specifies `foo', and the `catch' in `foo-outer'
  1963. specifies the same symbol, so that `catch' is the applicable one
  1964. (assuming there is no other matching `catch' in between).
  1965. Executing `throw' exits all Lisp constructs up to the matching
  1966. `catch', including function calls. When binding constructs such as
  1967. `let' or function calls are exited in this way, the bindings are
  1968. unbound, just as they are when these constructs exit normally (*note
  1969. Local Variables::). Likewise, `throw' restores the buffer and position
  1970. saved by `save-excursion' (*note Excursions::), and the narrowing
  1971. status saved by `save-restriction' and the window selection saved by
  1972. `save-window-excursion' (*note Window Configurations::). It also runs
  1973. any cleanups established with the `unwind-protect' special form when it
  1974. exits that form (*note Cleanups::).
  1975. The `throw' need not appear lexically within the `catch' that it
  1976. jumps to. It can equally well be called from another function called
  1977. within the `catch'. As long as the `throw' takes place chronologically
  1978. after entry to the `catch', and chronologically before exit from it, it
  1979. has access to that `catch'. This is why `throw' can be used in
  1980. commands such as `exit-recursive-edit' that throw back to the editor
  1981. command loop (*note Recursive Editing::).
  1982. Common Lisp note: Most other versions of Lisp, including Common
  1983. Lisp, have several ways of transferring control nonsequentially:
  1984. `return', `return-from', and `go', for example. Emacs Lisp has
  1985. only `throw'.
  1986. -- Special Form: catch tag body...
  1987. `catch' establishes a return point for the `throw' function. The
  1988. return point is distinguished from other such return points by
  1989. TAG, which may be any Lisp object except `nil'. The argument TAG
  1990. is evaluated normally before the return point is established.
  1991. With the return point in effect, `catch' evaluates the forms of the
  1992. BODY in textual order. If the forms execute normally (without
  1993. error or nonlocal exit) the value of the last body form is
  1994. returned from the `catch'.
  1995. If a `throw' is executed during the execution of BODY, specifying
  1996. the same value TAG, the `catch' form exits immediately; the value
  1997. it returns is whatever was specified as the second argument of
  1998. `throw'.
  1999. -- Function: throw tag value
  2000. The purpose of `throw' is to return from a return point previously
  2001. established with `catch'. The argument TAG is used to choose
  2002. among the various existing return points; it must be `eq' to the
  2003. value specified in the `catch'. If multiple return points match
  2004. TAG, the innermost one is used.
  2005. The argument VALUE is used as the value to return from that
  2006. `catch'.
  2007. If no return point is in effect with tag TAG, then a `no-catch'
  2008. error is signaled with data `(TAG VALUE)'.
  2009. 
  2010. File: elisp, Node: Examples of Catch, Next: Errors, Prev: Catch and Throw, Up: Nonlocal Exits
  2011. 10.5.2 Examples of `catch' and `throw'
  2012. --------------------------------------
  2013. One way to use `catch' and `throw' is to exit from a doubly nested
  2014. loop. (In most languages, this would be done with a "goto".) Here we
  2015. compute `(foo I J)' for I and J varying from 0 to 9:
  2016. (defun search-foo ()
  2017. (catch 'loop
  2018. (let ((i 0))
  2019. (while (< i 10)
  2020. (let ((j 0))
  2021. (while (< j 10)
  2022. (if (foo i j)
  2023. (throw 'loop (list i j)))
  2024. (setq j (1+ j))))
  2025. (setq i (1+ i))))))
  2026. If `foo' ever returns non-`nil', we stop immediately and return a list
  2027. of I and J. If `foo' always returns `nil', the `catch' returns
  2028. normally, and the value is `nil', since that is the result of the
  2029. `while'.
  2030. Here are two tricky examples, slightly different, showing two return
  2031. points at once. First, two return points with the same tag, `hack':
  2032. (defun catch2 (tag)
  2033. (catch tag
  2034. (throw 'hack 'yes)))
  2035. => catch2
  2036. (catch 'hack
  2037. (print (catch2 'hack))
  2038. 'no)
  2039. -| yes
  2040. => no
  2041. Since both return points have tags that match the `throw', it goes to
  2042. the inner one, the one established in `catch2'. Therefore, `catch2'
  2043. returns normally with value `yes', and this value is printed. Finally
  2044. the second body form in the outer `catch', which is `'no', is evaluated
  2045. and returned from the outer `catch'.
  2046. Now let's change the argument given to `catch2':
  2047. (catch 'hack
  2048. (print (catch2 'quux))
  2049. 'no)
  2050. => yes
  2051. We still have two return points, but this time only the outer one has
  2052. the tag `hack'; the inner one has the tag `quux' instead. Therefore,
  2053. `throw' makes the outer `catch' return the value `yes'. The function
  2054. `print' is never called, and the body-form `'no' is never evaluated.
  2055. 
  2056. File: elisp, Node: Errors, Next: Cleanups, Prev: Examples of Catch, Up: Nonlocal Exits
  2057. 10.5.3 Errors
  2058. -------------
  2059. When Emacs Lisp attempts to evaluate a form that, for some reason,
  2060. cannot be evaluated, it "signals" an "error".
  2061. When an error is signaled, Emacs's default reaction is to print an
  2062. error message and terminate execution of the current command. This is
  2063. the right thing to do in most cases, such as if you type `C-f' at the
  2064. end of the buffer.
  2065. In complicated programs, simple termination may not be what you want.
  2066. For example, the program may have made temporary changes in data
  2067. structures, or created temporary buffers that should be deleted before
  2068. the program is finished. In such cases, you would use `unwind-protect'
  2069. to establish "cleanup expressions" to be evaluated in case of error.
  2070. (*Note Cleanups::.) Occasionally, you may wish the program to continue
  2071. execution despite an error in a subroutine. In these cases, you would
  2072. use `condition-case' to establish "error handlers" to recover control
  2073. in case of error.
  2074. Resist the temptation to use error handling to transfer control from
  2075. one part of the program to another; use `catch' and `throw' instead.
  2076. *Note Catch and Throw::.
  2077. * Menu:
  2078. * Signaling Errors:: How to report an error.
  2079. * Processing of Errors:: What Emacs does when you report an error.
  2080. * Handling Errors:: How you can trap errors and continue execution.
  2081. * Error Symbols:: How errors are classified for trapping them.
  2082. 
  2083. File: elisp, Node: Signaling Errors, Next: Processing of Errors, Up: Errors
  2084. 10.5.3.1 How to Signal an Error
  2085. ...............................
  2086. "Signaling" an error means beginning error processing. Error
  2087. processing normally aborts all or part of the running program and
  2088. returns to a point that is set up to handle the error (*note Processing
  2089. of Errors::). Here we describe how to signal an error.
  2090. Most errors are signaled "automatically" within Lisp primitives
  2091. which you call for other purposes, such as if you try to take the CAR
  2092. of an integer or move forward a character at the end of the buffer.
  2093. You can also signal errors explicitly with the functions `error' and
  2094. `signal'.
  2095. Quitting, which happens when the user types `C-g', is not considered
  2096. an error, but it is handled almost like an error. *Note Quitting::.
  2097. Every error specifies an error message, one way or another. The
  2098. message should state what is wrong ("File does not exist"), not how
  2099. things ought to be ("File must exist"). The convention in Emacs Lisp
  2100. is that error messages should start with a capital letter, but should
  2101. not end with any sort of punctuation.
  2102. -- Function: error format-string &rest args
  2103. This function signals an error with an error message constructed by
  2104. applying `format' (*note Formatting Strings::) to FORMAT-STRING
  2105. and ARGS.
  2106. These examples show typical uses of `error':
  2107. (error "That is an error -- try something else")
  2108. error--> That is an error -- try something else
  2109. (error "You have committed %d errors" 10)
  2110. error--> You have committed 10 errors
  2111. `error' works by calling `signal' with two arguments: the error
  2112. symbol `error', and a list containing the string returned by
  2113. `format'.
  2114. *Warning:* If you want to use your own string as an error message
  2115. verbatim, don't just write `(error STRING)'. If STRING contains
  2116. `%', it will be interpreted as a format specifier, with
  2117. undesirable results. Instead, use `(error "%s" STRING)'.
  2118. -- Function: signal error-symbol data
  2119. This function signals an error named by ERROR-SYMBOL. The
  2120. argument DATA is a list of additional Lisp objects relevant to the
  2121. circumstances of the error.
  2122. The argument ERROR-SYMBOL must be an "error symbol"--a symbol
  2123. bearing a property `error-conditions' whose value is a list of
  2124. condition names. This is how Emacs Lisp classifies different
  2125. sorts of errors. *Note Error Symbols::, for a description of error
  2126. symbols, error conditions and condition names.
  2127. If the error is not handled, the two arguments are used in printing
  2128. the error message. Normally, this error message is provided by the
  2129. `error-message' property of ERROR-SYMBOL. If DATA is non-`nil',
  2130. this is followed by a colon and a comma separated list of the
  2131. unevaluated elements of DATA. For `error', the error message is
  2132. the CAR of DATA (that must be a string). Subcategories of
  2133. `file-error' are handled specially.
  2134. The number and significance of the objects in DATA depends on
  2135. ERROR-SYMBOL. For example, with a `wrong-type-argument' error,
  2136. there should be two objects in the list: a predicate that
  2137. describes the type that was expected, and the object that failed
  2138. to fit that type.
  2139. Both ERROR-SYMBOL and DATA are available to any error handlers
  2140. that handle the error: `condition-case' binds a local variable to
  2141. a list of the form `(ERROR-SYMBOL . DATA)' (*note Handling
  2142. Errors::).
  2143. The function `signal' never returns.
  2144. (signal 'wrong-number-of-arguments '(x y))
  2145. error--> Wrong number of arguments: x, y
  2146. (signal 'no-such-error '("My unknown error condition"))
  2147. error--> peculiar error: "My unknown error condition"
  2148. Common Lisp note: Emacs Lisp has nothing like the Common Lisp
  2149. concept of continuable errors.
  2150. 
  2151. File: elisp, Node: Processing of Errors, Next: Handling Errors, Prev: Signaling Errors, Up: Errors
  2152. 10.5.3.2 How Emacs Processes Errors
  2153. ...................................
  2154. When an error is signaled, `signal' searches for an active "handler"
  2155. for the error. A handler is a sequence of Lisp expressions designated
  2156. to be executed if an error happens in part of the Lisp program. If the
  2157. error has an applicable handler, the handler is executed, and control
  2158. resumes following the handler. The handler executes in the environment
  2159. of the `condition-case' that established it; all functions called
  2160. within that `condition-case' have already been exited, and the handler
  2161. cannot return to them.
  2162. If there is no applicable handler for the error, it terminates the
  2163. current command and returns control to the editor command loop. (The
  2164. command loop has an implicit handler for all kinds of errors.) The
  2165. command loop's handler uses the error symbol and associated data to
  2166. print an error message. You can use the variable
  2167. `command-error-function' to control how this is done:
  2168. -- Variable: command-error-function
  2169. This variable, if non-`nil', specifies a function to use to handle
  2170. errors that return control to the Emacs command loop. The
  2171. function should take three arguments: DATA, a list of the same
  2172. form that `condition-case' would bind to its variable; CONTEXT, a
  2173. string describing the situation in which the error occurred, or
  2174. (more often) `nil'; and CALLER, the Lisp function which called the
  2175. primitive that signaled the error.
  2176. An error that has no explicit handler may call the Lisp debugger.
  2177. The debugger is enabled if the variable `debug-on-error' (*note Error
  2178. Debugging::) is non-`nil'. Unlike error handlers, the debugger runs in
  2179. the environment of the error, so that you can examine values of
  2180. variables precisely as they were at the time of the error.
  2181. 
  2182. File: elisp, Node: Handling Errors, Next: Error Symbols, Prev: Processing of Errors, Up: Errors
  2183. 10.5.3.3 Writing Code to Handle Errors
  2184. ......................................
  2185. The usual effect of signaling an error is to terminate the command that
  2186. is running and return immediately to the Emacs editor command loop.
  2187. You can arrange to trap errors occurring in a part of your program by
  2188. establishing an error handler, with the special form `condition-case'.
  2189. A simple example looks like this:
  2190. (condition-case nil
  2191. (delete-file filename)
  2192. (error nil))
  2193. This deletes the file named FILENAME, catching any error and returning
  2194. `nil' if an error occurs. (You can use the macro `ignore-errors' for a
  2195. simple case like this; see below.)
  2196. The `condition-case' construct is often used to trap errors that are
  2197. predictable, such as failure to open a file in a call to
  2198. `insert-file-contents'. It is also used to trap errors that are
  2199. totally unpredictable, such as when the program evaluates an expression
  2200. read from the user.
  2201. The second argument of `condition-case' is called the "protected
  2202. form". (In the example above, the protected form is a call to
  2203. `delete-file'.) The error handlers go into effect when this form
  2204. begins execution and are deactivated when this form returns. They
  2205. remain in effect for all the intervening time. In particular, they are
  2206. in effect during the execution of functions called by this form, in
  2207. their subroutines, and so on. This is a good thing, since, strictly
  2208. speaking, errors can be signaled only by Lisp primitives (including
  2209. `signal' and `error') called by the protected form, not by the
  2210. protected form itself.
  2211. The arguments after the protected form are handlers. Each handler
  2212. lists one or more "condition names" (which are symbols) to specify
  2213. which errors it will handle. The error symbol specified when an error
  2214. is signaled also defines a list of condition names. A handler applies
  2215. to an error if they have any condition names in common. In the example
  2216. above, there is one handler, and it specifies one condition name,
  2217. `error', which covers all errors.
  2218. The search for an applicable handler checks all the established
  2219. handlers starting with the most recently established one. Thus, if two
  2220. nested `condition-case' forms offer to handle the same error, the inner
  2221. of the two gets to handle it.
  2222. If an error is handled by some `condition-case' form, this
  2223. ordinarily prevents the debugger from being run, even if
  2224. `debug-on-error' says this error should invoke the debugger.
  2225. If you want to be able to debug errors that are caught by a
  2226. `condition-case', set the variable `debug-on-signal' to a non-`nil'
  2227. value. You can also specify that a particular handler should let the
  2228. debugger run first, by writing `debug' among the conditions, like this:
  2229. (condition-case nil
  2230. (delete-file filename)
  2231. ((debug error) nil))
  2232. The effect of `debug' here is only to prevent `condition-case' from
  2233. suppressing the call to the debugger. Any given error will invoke the
  2234. debugger only if `debug-on-error' and the other usual filtering
  2235. mechanisms say it should. *Note Error Debugging::.
  2236. -- Macro: condition-case-unless-debug var protected-form handlers...
  2237. The macro `condition-case-unless-debug' provides another way to
  2238. handle debugging of such forms. It behaves exactly like
  2239. `condition-case', unless the variable `debug-on-error' is
  2240. non-`nil', in which case it does not handle any errors at all.
  2241. Once Emacs decides that a certain handler handles the error, it
  2242. returns control to that handler. To do so, Emacs unbinds all variable
  2243. bindings made by binding constructs that are being exited, and executes
  2244. the cleanups of all `unwind-protect' forms that are being exited. Once
  2245. control arrives at the handler, the body of the handler executes
  2246. normally.
  2247. After execution of the handler body, execution returns from the
  2248. `condition-case' form. Because the protected form is exited completely
  2249. before execution of the handler, the handler cannot resume execution at
  2250. the point of the error, nor can it examine variable bindings that were
  2251. made within the protected form. All it can do is clean up and proceed.
  2252. Error signaling and handling have some resemblance to `throw' and
  2253. `catch' (*note Catch and Throw::), but they are entirely separate
  2254. facilities. An error cannot be caught by a `catch', and a `throw'
  2255. cannot be handled by an error handler (though using `throw' when there
  2256. is no suitable `catch' signals an error that can be handled).
  2257. -- Special Form: condition-case var protected-form handlers...
  2258. This special form establishes the error handlers HANDLERS around
  2259. the execution of PROTECTED-FORM. If PROTECTED-FORM executes
  2260. without error, the value it returns becomes the value of the
  2261. `condition-case' form; in this case, the `condition-case' has no
  2262. effect. The `condition-case' form makes a difference when an
  2263. error occurs during PROTECTED-FORM.
  2264. Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'.
  2265. Here CONDITIONS is an error condition name to be handled, or a
  2266. list of condition names (which can include `debug' to allow the
  2267. debugger to run before the handler); BODY is one or more Lisp
  2268. expressions to be executed when this handler handles an error.
  2269. Here are examples of handlers:
  2270. (error nil)
  2271. (arith-error (message "Division by zero"))
  2272. ((arith-error file-error)
  2273. (message
  2274. "Either division by zero or failure to open a file"))
  2275. Each error that occurs has an "error symbol" that describes what
  2276. kind of error it is. The `error-conditions' property of this
  2277. symbol is a list of condition names (*note Error Symbols::). Emacs
  2278. searches all the active `condition-case' forms for a handler that
  2279. specifies one or more of these condition names; the innermost
  2280. matching `condition-case' handles the error. Within this
  2281. `condition-case', the first applicable handler handles the error.
  2282. After executing the body of the handler, the `condition-case'
  2283. returns normally, using the value of the last form in the handler
  2284. body as the overall value.
  2285. The argument VAR is a variable. `condition-case' does not bind
  2286. this variable when executing the PROTECTED-FORM, only when it
  2287. handles an error. At that time, it binds VAR locally to an "error
  2288. description", which is a list giving the particulars of the error.
  2289. The error description has the form `(ERROR-SYMBOL . DATA)'. The
  2290. handler can refer to this list to decide what to do. For example,
  2291. if the error is for failure opening a file, the file name is the
  2292. second element of DATA--the third element of the error description.
  2293. If VAR is `nil', that means no variable is bound. Then the error
  2294. symbol and associated data are not available to the handler.
  2295. Sometimes it is necessary to re-throw a signal caught by
  2296. `condition-case', for some outer-level handler to catch. Here's
  2297. how to do that:
  2298. (signal (car err) (cdr err))
  2299. where `err' is the error description variable, the first argument
  2300. to `condition-case' whose error condition you want to re-throw.
  2301. *Note Definition of signal::.
  2302. -- Function: error-message-string error-descriptor
  2303. This function returns the error message string for a given error
  2304. descriptor. It is useful if you want to handle an error by
  2305. printing the usual error message for that error. *Note Definition
  2306. of signal::.
  2307. Here is an example of using `condition-case' to handle the error
  2308. that results from dividing by zero. The handler displays the error
  2309. message (but without a beep), then returns a very large number.
  2310. (defun safe-divide (dividend divisor)
  2311. (condition-case err
  2312. ;; Protected form.
  2313. (/ dividend divisor)
  2314. ;; The handler.
  2315. (arith-error ; Condition.
  2316. ;; Display the usual message for this error.
  2317. (message "%s" (error-message-string err))
  2318. 1000000)))
  2319. => safe-divide
  2320. (safe-divide 5 0)
  2321. -| Arithmetic error: (arith-error)
  2322. => 1000000
  2323. The handler specifies condition name `arith-error' so that it will
  2324. handle only division-by-zero errors. Other kinds of errors will not be
  2325. handled (by this `condition-case'). Thus:
  2326. (safe-divide nil 3)
  2327. error--> Wrong type argument: number-or-marker-p, nil
  2328. Here is a `condition-case' that catches all kinds of errors,
  2329. including those from `error':
  2330. (setq baz 34)
  2331. => 34
  2332. (condition-case err
  2333. (if (eq baz 35)
  2334. t
  2335. ;; This is a call to the function `error'.
  2336. (error "Rats! The variable %s was %s, not 35" 'baz baz))
  2337. ;; This is the handler; it is not a form.
  2338. (error (princ (format "The error was: %s" err))
  2339. 2))
  2340. -| The error was: (error "Rats! The variable baz was 34, not 35")
  2341. => 2
  2342. -- Macro: ignore-errors body...
  2343. This construct executes BODY, ignoring any errors that occur
  2344. during its execution. If the execution is without error,
  2345. `ignore-errors' returns the value of the last form in BODY;
  2346. otherwise, it returns `nil'.
  2347. Here's the example at the beginning of this subsection rewritten
  2348. using `ignore-errors':
  2349. (ignore-errors
  2350. (delete-file filename))
  2351. -- Macro: with-demoted-errors body...
  2352. This macro is like a milder version of `ignore-errors'. Rather
  2353. than suppressing errors altogether, it converts them into messages.
  2354. Use this form around code that is not expected to signal errors,
  2355. but should be robust if one does occur. Note that this macro uses
  2356. `condition-case-unless-debug' rather than `condition-case'.
  2357. 
  2358. File: elisp, Node: Error Symbols, Prev: Handling Errors, Up: Errors
  2359. 10.5.3.4 Error Symbols and Condition Names
  2360. ..........................................
  2361. When you signal an error, you specify an "error symbol" to specify the
  2362. kind of error you have in mind. Each error has one and only one error
  2363. symbol to categorize it. This is the finest classification of errors
  2364. defined by the Emacs Lisp language.
  2365. These narrow classifications are grouped into a hierarchy of wider
  2366. classes called "error conditions", identified by "condition names".
  2367. The narrowest such classes belong to the error symbols themselves: each
  2368. error symbol is also a condition name. There are also condition names
  2369. for more extensive classes, up to the condition name `error' which
  2370. takes in all kinds of errors (but not `quit'). Thus, each error has
  2371. one or more condition names: `error', the error symbol if that is
  2372. distinct from `error', and perhaps some intermediate classifications.
  2373. In order for a symbol to be an error symbol, it must have an
  2374. `error-conditions' property which gives a list of condition names.
  2375. This list defines the conditions that this kind of error belongs to.
  2376. (The error symbol itself, and the symbol `error', should always be
  2377. members of this list.) Thus, the hierarchy of condition names is
  2378. defined by the `error-conditions' properties of the error symbols.
  2379. Because quitting is not considered an error, the value of the
  2380. `error-conditions' property of `quit' is just `(quit)'.
  2381. In addition to the `error-conditions' list, the error symbol should
  2382. have an `error-message' property whose value is a string to be printed
  2383. when that error is signaled but not handled. If the error symbol has
  2384. no `error-message' property or if the `error-message' property exists,
  2385. but is not a string, the error message `peculiar error' is used. *Note
  2386. Definition of signal::.
  2387. Here is how we define a new error symbol, `new-error':
  2388. (put 'new-error
  2389. 'error-conditions
  2390. '(error my-own-errors new-error))
  2391. => (error my-own-errors new-error)
  2392. (put 'new-error 'error-message "A new error")
  2393. => "A new error"
  2394. This error has three condition names: `new-error', the narrowest
  2395. classification; `my-own-errors', which we imagine is a wider
  2396. classification; and `error', which is the widest of all.
  2397. The error string should start with a capital letter but it should
  2398. not end with a period. This is for consistency with the rest of Emacs.
  2399. Naturally, Emacs will never signal `new-error' on its own; only an
  2400. explicit call to `signal' (*note Definition of signal::) in your code
  2401. can do this:
  2402. (signal 'new-error '(x y))
  2403. error--> A new error: x, y
  2404. This error can be handled through any of the three condition names.
  2405. This example handles `new-error' and any other errors in the class
  2406. `my-own-errors':
  2407. (condition-case foo
  2408. (bar nil t)
  2409. (my-own-errors nil))
  2410. The significant way that errors are classified is by their condition
  2411. names--the names used to match errors with handlers. An error symbol
  2412. serves only as a convenient way to specify the intended error message
  2413. and list of condition names. It would be cumbersome to give `signal' a
  2414. list of condition names rather than one error symbol.
  2415. By contrast, using only error symbols without condition names would
  2416. seriously decrease the power of `condition-case'. Condition names make
  2417. it possible to categorize errors at various levels of generality when
  2418. you write an error handler. Using error symbols alone would eliminate
  2419. all but the narrowest level of classification.
  2420. *Note Standard Errors::, for a list of the main error symbols and
  2421. their conditions.
  2422. 
  2423. File: elisp, Node: Cleanups, Prev: Errors, Up: Nonlocal Exits
  2424. 10.5.4 Cleaning Up from Nonlocal Exits
  2425. --------------------------------------
  2426. The `unwind-protect' construct is essential whenever you temporarily
  2427. put a data structure in an inconsistent state; it permits you to make
  2428. the data consistent again in the event of an error or throw. (Another
  2429. more specific cleanup construct that is used only for changes in buffer
  2430. contents is the atomic change group; *note Atomic Changes::.)
  2431. -- Special Form: unwind-protect body-form cleanup-forms...
  2432. `unwind-protect' executes BODY-FORM with a guarantee that the
  2433. CLEANUP-FORMS will be evaluated if control leaves BODY-FORM, no
  2434. matter how that happens. BODY-FORM may complete normally, or
  2435. execute a `throw' out of the `unwind-protect', or cause an error;
  2436. in all cases, the CLEANUP-FORMS will be evaluated.
  2437. If BODY-FORM finishes normally, `unwind-protect' returns the value
  2438. of BODY-FORM, after it evaluates the CLEANUP-FORMS. If BODY-FORM
  2439. does not finish, `unwind-protect' does not return any value in the
  2440. normal sense.
  2441. Only BODY-FORM is protected by the `unwind-protect'. If any of
  2442. the CLEANUP-FORMS themselves exits nonlocally (via a `throw' or an
  2443. error), `unwind-protect' is _not_ guaranteed to evaluate the rest
  2444. of them. If the failure of one of the CLEANUP-FORMS has the
  2445. potential to cause trouble, then protect it with another
  2446. `unwind-protect' around that form.
  2447. The number of currently active `unwind-protect' forms counts,
  2448. together with the number of local variable bindings, against the
  2449. limit `max-specpdl-size' (*note Local Variables: Definition of
  2450. max-specpdl-size.).
  2451. For example, here we make an invisible buffer for temporary use, and
  2452. make sure to kill it before finishing:
  2453. (let ((buffer (get-buffer-create " *temp*")))
  2454. (with-current-buffer buffer
  2455. (unwind-protect
  2456. BODY-FORM
  2457. (kill-buffer buffer))))
  2458. You might think that we could just as well write `(kill-buffer
  2459. (current-buffer))' and dispense with the variable `buffer'. However,
  2460. the way shown above is safer, if BODY-FORM happens to get an error
  2461. after switching to a different buffer! (Alternatively, you could write
  2462. a `save-current-buffer' around BODY-FORM, to ensure that the temporary
  2463. buffer becomes current again in time to kill it.)
  2464. Emacs includes a standard macro called `with-temp-buffer' which
  2465. expands into more or less the code shown above (*note Current Buffer:
  2466. Definition of with-temp-buffer.). Several of the macros defined in
  2467. this manual use `unwind-protect' in this way.
  2468. Here is an actual example derived from an FTP package. It creates a
  2469. process (*note Processes::) to try to establish a connection to a remote
  2470. machine. As the function `ftp-login' is highly susceptible to numerous
  2471. problems that the writer of the function cannot anticipate, it is
  2472. protected with a form that guarantees deletion of the process in the
  2473. event of failure. Otherwise, Emacs might fill up with useless
  2474. subprocesses.
  2475. (let ((win nil))
  2476. (unwind-protect
  2477. (progn
  2478. (setq process (ftp-setup-buffer host file))
  2479. (if (setq win (ftp-login process host user password))
  2480. (message "Logged in")
  2481. (error "Ftp login failed")))
  2482. (or win (and process (delete-process process)))))
  2483. This example has a small bug: if the user types `C-g' to quit, and
  2484. the quit happens immediately after the function `ftp-setup-buffer'
  2485. returns but before the variable `process' is set, the process will not
  2486. be killed. There is no easy way to fix this bug, but at least it is
  2487. very unlikely.
  2488. 
  2489. File: elisp, Node: Variables, Next: Functions, Prev: Control Structures, Up: Top
  2490. 11 Variables
  2491. ************
  2492. A "variable" is a name used in a program to stand for a value. In
  2493. Lisp, each variable is represented by a Lisp symbol (*note Symbols::).
  2494. The variable name is simply the symbol's name, and the variable's value
  2495. is stored in the symbol's value cell(1). *Note Symbol Components::.
  2496. In Emacs Lisp, the use of a symbol as a variable is independent of its
  2497. use as a function name.
  2498. As previously noted in this manual, a Lisp program is represented
  2499. primarily by Lisp objects, and only secondarily as text. The textual
  2500. form of a Lisp program is given by the read syntax of the Lisp objects
  2501. that constitute the program. Hence, the textual form of a variable in
  2502. a Lisp program is written using the read syntax for the symbol
  2503. representing the variable.
  2504. * Menu:
  2505. * Global Variables:: Variable values that exist permanently, everywhere.
  2506. * Constant Variables:: Certain "variables" have values that never change.
  2507. * Local Variables:: Variable values that exist only temporarily.
  2508. * Void Variables:: Symbols that lack values.
  2509. * Defining Variables:: A definition says a symbol is used as a variable.
  2510. * Tips for Defining:: Things you should think about when you
  2511. define a variable.
  2512. * Accessing Variables:: Examining values of variables whose names
  2513. are known only at run time.
  2514. * Setting Variables:: Storing new values in variables.
  2515. * Variable Scoping:: How Lisp chooses among local and global values.
  2516. * Buffer-Local Variables:: Variable values in effect only in one buffer.
  2517. * File Local Variables:: Handling local variable lists in files.
  2518. * Directory Local Variables:: Local variables common to all files in a directory.
  2519. * Variable Aliases:: Variables that are aliases for other variables.
  2520. * Variables with Restricted Values:: Non-constant variables whose value can
  2521. _not_ be an arbitrary Lisp object.
  2522. ---------- Footnotes ----------
  2523. (1) To be precise, under the default "dynamic binding" rules the
  2524. value cell always holds the variable's current value, but this is not
  2525. the case under "lexical binding" rules. *Note Variable Scoping::, for
  2526. details.
  2527. 
  2528. File: elisp, Node: Global Variables, Next: Constant Variables, Up: Variables
  2529. 11.1 Global Variables
  2530. =====================
  2531. The simplest way to use a variable is "globally". This means that the
  2532. variable has just one value at a time, and this value is in effect (at
  2533. least for the moment) throughout the Lisp system. The value remains in
  2534. effect until you specify a new one. When a new value replaces the old
  2535. one, no trace of the old value remains in the variable.
  2536. You specify a value for a symbol with `setq'. For example,
  2537. (setq x '(a b))
  2538. gives the variable `x' the value `(a b)'. Note that `setq' is a
  2539. special form (*note Special Forms::); it does not evaluate its first
  2540. argument, the name of the variable, but it does evaluate the second
  2541. argument, the new value.
  2542. Once the variable has a value, you can refer to it by using the
  2543. symbol itself as an expression. Thus,
  2544. x => (a b)
  2545. assuming the `setq' form shown above has already been executed.
  2546. If you do set the same variable again, the new value replaces the old
  2547. one:
  2548. x
  2549. => (a b)
  2550. (setq x 4)
  2551. => 4
  2552. x
  2553. => 4
  2554. 
  2555. File: elisp, Node: Constant Variables, Next: Local Variables, Prev: Global Variables, Up: Variables
  2556. 11.2 Variables that Never Change
  2557. ================================
  2558. In Emacs Lisp, certain symbols normally evaluate to themselves. These
  2559. include `nil' and `t', as well as any symbol whose name starts with `:'
  2560. (these are called "keywords"). These symbols cannot be rebound, nor
  2561. can their values be changed. Any attempt to set or bind `nil' or `t'
  2562. signals a `setting-constant' error. The same is true for a keyword (a
  2563. symbol whose name starts with `:'), if it is interned in the standard
  2564. obarray, except that setting such a symbol to itself is not an error.
  2565. nil == 'nil
  2566. => nil
  2567. (setq nil 500)
  2568. error--> Attempt to set constant symbol: nil
  2569. -- Function: keywordp object
  2570. function returns `t' if OBJECT is a symbol whose name starts with
  2571. `:', interned in the standard obarray, and returns `nil' otherwise.
  2572. These constants are fundamentally different from the "constants"
  2573. defined using the `defconst' special form (*note Defining Variables::).
  2574. A `defconst' form serves to inform human readers that you do not intend
  2575. to change the value of a variable, but Emacs does not raise an error if
  2576. you actually change it.
  2577. 
  2578. File: elisp, Node: Local Variables, Next: Void Variables, Prev: Constant Variables, Up: Variables
  2579. 11.3 Local Variables
  2580. ====================
  2581. Global variables have values that last until explicitly superseded with
  2582. new values. Sometimes it is useful to give a variable a "local
  2583. value"--a value that takes effect only within a certain part of a Lisp
  2584. program. When a variable has a local value, we say that it is "locally
  2585. bound" to that value, and that it is a "local variable".
  2586. For example, when a function is called, its argument variables
  2587. receive local values, which are the actual arguments supplied to the
  2588. function call; these local bindings take effect within the body of the
  2589. function. To take another example, the `let' special form explicitly
  2590. establishes local bindings for specific variables, which take effect
  2591. within the body of the `let' form.
  2592. We also speak of the "global binding", which is where (conceptually)
  2593. the global value is kept.
  2594. Establishing a local binding saves away the variable's previous
  2595. value (or lack of one). We say that the previous value is "shadowed".
  2596. Both global and local values may be shadowed. If a local binding is in
  2597. effect, using `setq' on the local variable stores the specified value
  2598. in the local binding. When that local binding is no longer in effect,
  2599. the previously shadowed value (or lack of one) comes back.
  2600. A variable can have more than one local binding at a time (e.g. if
  2601. there are nested `let' forms that bind the variable). The "current
  2602. binding" is the local binding that is actually in effect. It
  2603. determines the value returned by evaluating the variable symbol, and it
  2604. is the binding acted on by `setq'.
  2605. For most purposes, you can think of the current binding as the
  2606. "innermost" local binding, or the global binding if there is no local
  2607. binding. To be more precise, a rule called the "scoping rule"
  2608. determines where in a program a local binding takes effect. The
  2609. default scoping rule in Emacs Lisp is called "dynamic scoping", which
  2610. simply states that the current binding at any given point in the
  2611. execution of a program is the most recently-created binding for that
  2612. variable that still exists. For details about dynamic scoping, and an
  2613. alternative scoping rule called "lexical scoping", *Note Variable
  2614. Scoping::.
  2615. The special forms `let' and `let*' exist to create local bindings:
  2616. -- Special Form: let (bindings...) forms...
  2617. This special form sets up local bindings for a certain set of
  2618. variables, as specified by BINDINGS, and then evaluates all of the
  2619. FORMS in textual order. Its return value is the value of the last
  2620. form in FORMS.
  2621. Each of the BINDINGS is either (i) a symbol, in which case that
  2622. symbol is locally bound to `nil'; or (ii) a list of the form
  2623. `(SYMBOL VALUE-FORM)', in which case SYMBOL is locally bound to
  2624. the result of evaluating VALUE-FORM. If VALUE-FORM is omitted,
  2625. `nil' is used.
  2626. All of the VALUE-FORMs in BINDINGS are evaluated in the order they
  2627. appear and _before_ binding any of the symbols to them. Here is
  2628. an example of this: `z' is bound to the old value of `y', which is
  2629. 2, not the new value of `y', which is 1.
  2630. (setq y 2)
  2631. => 2
  2632. (let ((y 1)
  2633. (z y))
  2634. (list y z))
  2635. => (1 2)
  2636. -- Special Form: let* (bindings...) forms...
  2637. This special form is like `let', but it binds each variable right
  2638. after computing its local value, before computing the local value
  2639. for the next variable. Therefore, an expression in BINDINGS can
  2640. refer to the preceding symbols bound in this `let*' form. Compare
  2641. the following example with the example above for `let'.
  2642. (setq y 2)
  2643. => 2
  2644. (let* ((y 1)
  2645. (z y)) ; Use the just-established value of `y'.
  2646. (list y z))
  2647. => (1 1)
  2648. Here is a complete list of the other facilities that create local
  2649. bindings:
  2650. * Function calls (*note Functions::).
  2651. * Macro calls (*note Macros::).
  2652. * `condition-case' (*note Errors::).
  2653. Variables can also have buffer-local bindings (*note Buffer-Local
  2654. Variables::); a few variables have terminal-local bindings (*note
  2655. Multiple Terminals::). These kinds of bindings work somewhat like
  2656. ordinary local bindings, but they are localized depending on "where"
  2657. you are in Emacs.
  2658. -- User Option: max-specpdl-size
  2659. This variable defines the limit on the total number of local
  2660. variable bindings and `unwind-protect' cleanups (see *note
  2661. Cleaning Up from Nonlocal Exits: Cleanups.) that are allowed
  2662. before Emacs signals an error (with data `"Variable binding depth
  2663. exceeds max-specpdl-size"').
  2664. This limit, with the associated error when it is exceeded, is one
  2665. way that Lisp avoids infinite recursion on an ill-defined function.
  2666. `max-lisp-eval-depth' provides another limit on depth of nesting.
  2667. *Note Eval: Definition of max-lisp-eval-depth.
  2668. The default value is 1300. Entry to the Lisp debugger increases
  2669. the value, if there is little room left, to make sure the debugger
  2670. itself has room to execute.
  2671. 
  2672. File: elisp, Node: Void Variables, Next: Defining Variables, Prev: Local Variables, Up: Variables
  2673. 11.4 When a Variable is "Void"
  2674. ==============================
  2675. We say that a variable is void if its symbol has an unassigned value
  2676. cell (*note Symbol Components::). Under Emacs Lisp's default dynamic
  2677. binding rules (*note Variable Scoping::), the value cell stores the
  2678. variable's current (local or global) value. Note that an unassigned
  2679. value cell is _not_ the same as having `nil' in the value cell. The
  2680. symbol `nil' is a Lisp object and can be the value of a variable, just
  2681. as any other object can be; but it is still a value. If a variable is
  2682. void, trying to evaluate the variable signals a `void-variable' error
  2683. rather than a value.
  2684. Under lexical binding rules, the value cell only holds the
  2685. variable's global value, i.e. the value outside of any lexical binding
  2686. construct. When a variable is lexically bound, the local value is
  2687. determined by the lexical environment; the variable may have a local
  2688. value if its symbol's value cell is unassigned.
  2689. -- Function: makunbound symbol
  2690. This function empties out the value cell of SYMBOL, making the
  2691. variable void. It returns SYMBOL.
  2692. If SYMBOL has a dynamic local binding, `makunbound' voids the
  2693. current binding, and this voidness lasts only as long as the local
  2694. binding is in effect. Afterwards, the previously shadowed local or
  2695. global binding is reexposed; then the variable will no longer be
  2696. void, unless the reexposed binding is void too.
  2697. Here are some examples (assuming dynamic binding is in effect):
  2698. (setq x 1) ; Put a value in the global binding.
  2699. => 1
  2700. (let ((x 2)) ; Locally bind it.
  2701. (makunbound 'x) ; Void the local binding.
  2702. x)
  2703. error--> Symbol's value as variable is void: x
  2704. x ; The global binding is unchanged.
  2705. => 1
  2706. (let ((x 2)) ; Locally bind it.
  2707. (let ((x 3)) ; And again.
  2708. (makunbound 'x) ; Void the innermost-local binding.
  2709. x)) ; And refer: it's void.
  2710. error--> Symbol's value as variable is void: x
  2711. (let ((x 2))
  2712. (let ((x 3))
  2713. (makunbound 'x)) ; Void inner binding, then remove it.
  2714. x) ; Now outer `let' binding is visible.
  2715. => 2
  2716. -- Function: boundp variable
  2717. This function returns `t' if VARIABLE (a symbol) is not void, and
  2718. `nil' if it is void.
  2719. Here are some examples (assuming dynamic binding is in effect):
  2720. (boundp 'abracadabra) ; Starts out void.
  2721. => nil
  2722. (let ((abracadabra 5)) ; Locally bind it.
  2723. (boundp 'abracadabra))
  2724. => t
  2725. (boundp 'abracadabra) ; Still globally void.
  2726. => nil
  2727. (setq abracadabra 5) ; Make it globally nonvoid.
  2728. => 5
  2729. (boundp 'abracadabra)
  2730. => t
  2731. 
  2732. File: elisp, Node: Defining Variables, Next: Tips for Defining, Prev: Void Variables, Up: Variables
  2733. 11.5 Defining Global Variables
  2734. ==============================
  2735. A "variable definition" is a construct that announces your intention to
  2736. use a symbol as a global variable. It uses the special forms `defvar'
  2737. or `defconst', which are documented below.
  2738. A variable definition serves three purposes. First, it informs
  2739. people who read the code that the symbol is _intended_ to be used a
  2740. certain way (as a variable). Second, it informs the Lisp system of
  2741. this, optionally supplying an initial value and a documentation string.
  2742. Third, it provides information to programming tools such as `etags',
  2743. allowing them to find where the variable was defined.
  2744. The difference between `defconst' and `defvar' is mainly a matter of
  2745. intent, serving to inform human readers of whether the value should
  2746. ever change. Emacs Lisp does not actually prevent you from changing
  2747. the value of a variable defined with `defconst'. One notable
  2748. difference between the two forms is that `defconst' unconditionally
  2749. initializes the variable, whereas `defvar' initializes it only if it is
  2750. originally void.
  2751. To define a customizable variable, you should use `defcustom' (which
  2752. calls `defvar' as a subroutine). *Note Customization::.
  2753. -- Special Form: defvar symbol [value [doc-string]]
  2754. This special form defines SYMBOL as a variable. Note that SYMBOL
  2755. is not evaluated; the symbol to be defined should appear
  2756. explicitly in the `defvar' form. The variable is marked as
  2757. "special", meaning that it should always be dynamically bound
  2758. (*note Variable Scoping::).
  2759. If SYMBOL is void and VALUE is specified, `defvar' evaluates VALUE
  2760. and sets SYMBOL to the result. But if SYMBOL already has a value
  2761. (i.e. it is not void), VALUE is not even evaluated, and SYMBOL's
  2762. value remains unchanged. If VALUE is omitted, the value of SYMBOL
  2763. is not changed in any case.
  2764. If SYMBOL has a buffer-local binding in the current buffer,
  2765. `defvar' operates on the default value, which is
  2766. buffer-independent, not the current (buffer-local) binding. It
  2767. sets the default value if the default value is void. *Note
  2768. Buffer-Local Variables::.
  2769. When you evaluate a top-level `defvar' form with `C-M-x' in Emacs
  2770. Lisp mode (`eval-defun'), a special feature of `eval-defun'
  2771. arranges to set the variable unconditionally, without testing
  2772. whether its value is void.
  2773. If the DOC-STRING argument is supplied, it specifies the
  2774. documentation string for the variable (stored in the symbol's
  2775. `variable-documentation' property). *Note Documentation::.
  2776. Here are some examples. This form defines `foo' but does not
  2777. initialize it:
  2778. (defvar foo)
  2779. => foo
  2780. This example initializes the value of `bar' to `23', and gives it
  2781. a documentation string:
  2782. (defvar bar 23
  2783. "The normal weight of a bar.")
  2784. => bar
  2785. The `defvar' form returns SYMBOL, but it is normally used at top
  2786. level in a file where its value does not matter.
  2787. -- Special Form: defconst symbol value [doc-string]
  2788. This special form defines SYMBOL as a value and initializes it.
  2789. It informs a person reading your code that SYMBOL has a standard
  2790. global value, established here, that should not be changed by the
  2791. user or by other programs. Note that SYMBOL is not evaluated; the
  2792. symbol to be defined must appear explicitly in the `defconst'.
  2793. The `defconst' form, like `defvar', marks the variable as
  2794. "special", meaning that it should always be dynamically bound
  2795. (*note Variable Scoping::). In addition, it marks the variable as
  2796. risky (*note File Local Variables::).
  2797. `defconst' always evaluates VALUE, and sets the value of SYMBOL to
  2798. the result. If SYMBOL does have a buffer-local binding in the
  2799. current buffer, `defconst' sets the default value, not the
  2800. buffer-local value. (But you should not be making buffer-local
  2801. bindings for a symbol that is defined with `defconst'.)
  2802. An example of the use of `defconst' is Emacs's definition of
  2803. `float-pi'--the mathematical constant pi, which ought not to be
  2804. changed by anyone (attempts by the Indiana State Legislature
  2805. notwithstanding). As the second form illustrates, however,
  2806. `defconst' is only advisory.
  2807. (defconst float-pi 3.141592653589793 "The value of Pi.")
  2808. => float-pi
  2809. (setq float-pi 3)
  2810. => float-pi
  2811. float-pi
  2812. => 3
  2813. *Warning:* If you use a `defconst' or `defvar' special form while
  2814. the variable has a local binding (made with `let', or a function
  2815. argument), it sets the local binding rather than the global binding.
  2816. This is not what you usually want. To prevent this, use these special
  2817. forms at top level in a file, where normally no local binding is in
  2818. effect, and make sure to load the file before making a local binding
  2819. for the variable.
  2820. 
  2821. File: elisp, Node: Tips for Defining, Next: Accessing Variables, Prev: Defining Variables, Up: Variables
  2822. 11.6 Tips for Defining Variables Robustly
  2823. =========================================
  2824. When you define a variable whose value is a function, or a list of
  2825. functions, use a name that ends in `-function' or `-functions',
  2826. respectively.
  2827. There are several other variable name conventions; here is a
  2828. complete list:
  2829. `...-hook'
  2830. The variable is a normal hook (*note Hooks::).
  2831. `...-function'
  2832. The value is a function.
  2833. `...-functions'
  2834. The value is a list of functions.
  2835. `...-form'
  2836. The value is a form (an expression).
  2837. `...-forms'
  2838. The value is a list of forms (expressions).
  2839. `...-predicate'
  2840. The value is a predicate--a function of one argument that returns
  2841. non-`nil' for "good" arguments and `nil' for "bad" arguments.
  2842. `...-flag'
  2843. The value is significant only as to whether it is `nil' or not.
  2844. Since such variables often end up acquiring more values over time,
  2845. this convention is not strongly recommended.
  2846. `...-program'
  2847. The value is a program name.
  2848. `...-command'
  2849. The value is a whole shell command.
  2850. `...-switches'
  2851. The value specifies options for a command.
  2852. When you define a variable, always consider whether you should mark
  2853. it as "safe" or "risky"; see *note File Local Variables::.
  2854. When defining and initializing a variable that holds a complicated
  2855. value (such as a keymap with bindings in it), it's best to put the
  2856. entire computation of the value into the `defvar', like this:
  2857. (defvar my-mode-map
  2858. (let ((map (make-sparse-keymap)))
  2859. (define-key map "\C-c\C-a" 'my-command)
  2860. ...
  2861. map)
  2862. DOCSTRING)
  2863. This method has several benefits. First, if the user quits while
  2864. loading the file, the variable is either still uninitialized or
  2865. initialized properly, never in-between. If it is still uninitialized,
  2866. reloading the file will initialize it properly. Second, reloading the
  2867. file once the variable is initialized will not alter it; that is
  2868. important if the user has run hooks to alter part of the contents (such
  2869. as, to rebind keys). Third, evaluating the `defvar' form with `C-M-x'
  2870. will reinitialize the map completely.
  2871. Putting so much code in the `defvar' form has one disadvantage: it
  2872. puts the documentation string far away from the line which names the
  2873. variable. Here's a safe way to avoid that:
  2874. (defvar my-mode-map nil
  2875. DOCSTRING)
  2876. (unless my-mode-map
  2877. (let ((map (make-sparse-keymap)))
  2878. (define-key map "\C-c\C-a" 'my-command)
  2879. ...
  2880. (setq my-mode-map map)))
  2881. This has all the same advantages as putting the initialization inside
  2882. the `defvar', except that you must type `C-M-x' twice, once on each
  2883. form, if you do want to reinitialize the variable.
  2884. 
  2885. File: elisp, Node: Accessing Variables, Next: Setting Variables, Prev: Tips for Defining, Up: Variables
  2886. 11.7 Accessing Variable Values
  2887. ==============================
  2888. The usual way to reference a variable is to write the symbol which
  2889. names it. *Note Symbol Forms::.
  2890. Occasionally, you may want to reference a variable which is only
  2891. determined at run time. In that case, you cannot specify the variable
  2892. name in the text of the program. You can use the `symbol-value'
  2893. function to extract the value.
  2894. -- Function: symbol-value symbol
  2895. This function returns the value stored in SYMBOL's value cell.
  2896. This is where the variable's current (dynamic) value is stored. If
  2897. the variable has no local binding, this is simply its global value.
  2898. If the variable is void, a `void-variable' error is signaled.
  2899. If the variable is lexically bound, the value reported by
  2900. `symbol-value' is not necessarily the same as the variable's
  2901. lexical value, which is determined by the lexical environment
  2902. rather than the symbol's value cell. *Note Variable Scoping::.
  2903. (setq abracadabra 5)
  2904. => 5
  2905. (setq foo 9)
  2906. => 9
  2907. ;; Here the symbol `abracadabra'
  2908. ;; is the symbol whose value is examined.
  2909. (let ((abracadabra 'foo))
  2910. (symbol-value 'abracadabra))
  2911. => foo
  2912. ;; Here, the value of `abracadabra',
  2913. ;; which is `foo',
  2914. ;; is the symbol whose value is examined.
  2915. (let ((abracadabra 'foo))
  2916. (symbol-value abracadabra))
  2917. => 9
  2918. (symbol-value 'abracadabra)
  2919. => 5
  2920. 
  2921. File: elisp, Node: Setting Variables, Next: Variable Scoping, Prev: Accessing Variables, Up: Variables
  2922. 11.8 Setting Variable Values
  2923. ============================
  2924. The usual way to change the value of a variable is with the special
  2925. form `setq'. When you need to compute the choice of variable at run
  2926. time, use the function `set'.
  2927. -- Special Form: setq [symbol form]...
  2928. This special form is the most common method of changing a
  2929. variable's value. Each SYMBOL is given a new value, which is the
  2930. result of evaluating the corresponding FORM. The current binding
  2931. of the symbol is changed.
  2932. `setq' does not evaluate SYMBOL; it sets the symbol that you
  2933. write. We say that this argument is "automatically quoted". The
  2934. `q' in `setq' stands for "quoted".
  2935. The value of the `setq' form is the value of the last FORM.
  2936. (setq x (1+ 2))
  2937. => 3
  2938. x ; `x' now has a global value.
  2939. => 3
  2940. (let ((x 5))
  2941. (setq x 6) ; The local binding of `x' is set.
  2942. x)
  2943. => 6
  2944. x ; The global value is unchanged.
  2945. => 3
  2946. Note that the first FORM is evaluated, then the first SYMBOL is
  2947. set, then the second FORM is evaluated, then the second SYMBOL is
  2948. set, and so on:
  2949. (setq x 10 ; Notice that `x' is set before
  2950. y (1+ x)) ; the value of `y' is computed.
  2951. => 11
  2952. -- Function: set symbol value
  2953. This function puts VALUE in the value cell of SYMBOL. Since it is
  2954. a function rather than a special form, the expression written for
  2955. SYMBOL is evaluated to obtain the symbol to set. The return value
  2956. is VALUE.
  2957. When dynamic variable binding is in effect (the default), `set'
  2958. has the same effect as `setq', apart from the fact that `set'
  2959. evaluates its SYMBOL argument whereas `setq' does not. But when a
  2960. variable is lexically bound, `set' affects its _dynamic_ value,
  2961. whereas `setq' affects its current (lexical) value. *Note
  2962. Variable Scoping::.
  2963. (set one 1)
  2964. error--> Symbol's value as variable is void: one
  2965. (set 'one 1)
  2966. => 1
  2967. (set 'two 'one)
  2968. => one
  2969. (set two 2) ; `two' evaluates to symbol `one'.
  2970. => 2
  2971. one ; So it is `one' that was set.
  2972. => 2
  2973. (let ((one 1)) ; This binding of `one' is set,
  2974. (set 'one 3) ; not the global value.
  2975. one)
  2976. => 3
  2977. one
  2978. => 2
  2979. If SYMBOL is not actually a symbol, a `wrong-type-argument' error
  2980. is signaled.
  2981. (set '(x y) 'z)
  2982. error--> Wrong type argument: symbolp, (x y)
  2983. 
  2984. File: elisp, Node: Variable Scoping, Next: Buffer-Local Variables, Prev: Setting Variables, Up: Variables
  2985. 11.9 Scoping Rules for Variable Bindings
  2986. ========================================
  2987. When you create a local binding for a variable, that binding takes
  2988. effect only within a limited portion of the program (*note Local
  2989. Variables::). This section describes exactly what this means.
  2990. Each local binding has a certain "scope" and "extent". "Scope"
  2991. refers to _where_ in the textual source code the binding can be
  2992. accessed. "Extent" refers to _when_, as the program is executing, the
  2993. binding exists.
  2994. By default, the local bindings that Emacs creates are "dynamic
  2995. bindings". Such a binding has "indefinite scope", meaning that any
  2996. part of the program can potentially access the variable binding. It
  2997. also has "dynamic extent", meaning that the binding lasts only while
  2998. the binding construct (such as the body of a `let' form) is being
  2999. executed.
  3000. Emacs can optionally create "lexical bindings". A lexical binding
  3001. has "lexical scope", meaning that any reference to the variable must be
  3002. located textually within the binding construct. It also has
  3003. "indefinite extent", meaning that under some circumstances the binding
  3004. can live on even after the binding construct has finished executing, by
  3005. means of special objects called "closures".
  3006. The following subsections describe dynamic binding and lexical
  3007. binding in greater detail, and how to enable lexical binding in Emacs
  3008. Lisp programs.
  3009. * Menu:
  3010. * Dynamic Binding:: The default for binding local variables in Emacs.
  3011. * Dynamic Binding Tips:: Avoiding problems with dynamic binding.
  3012. * Lexical Binding:: A different type of local variable binding.
  3013. * Using Lexical Binding:: How to enable lexical binding.
  3014. 
  3015. File: elisp, Node: Dynamic Binding, Next: Dynamic Binding Tips, Up: Variable Scoping
  3016. 11.9.1 Dynamic Binding
  3017. ----------------------
  3018. By default, the local variable bindings made by Emacs are dynamic
  3019. bindings. When a variable is dynamically bound, its current binding at
  3020. any point in the execution of the Lisp program is simply the most
  3021. recently-created dynamic local binding for that symbol, or the global
  3022. binding if there is no such local binding.
  3023. Dynamic bindings have indefinite scope and dynamic extent, as shown
  3024. by the following example:
  3025. (defvar x -99) ; `x' receives an initial value of -99.
  3026. (defun getx ()
  3027. x) ; `x' is used "free" in this function.
  3028. (let ((x 1)) ; `x' is dynamically bound.
  3029. (getx))
  3030. => 1
  3031. ;; After the `let' form finishes, `x' reverts to its
  3032. ;; previous value, which is -99.
  3033. (getx)
  3034. => -99
  3035. The function `getx' refers to `x'. This is a "free" reference, in the
  3036. sense that there is no binding for `x' within that `defun' construct
  3037. itself. When we call `getx' from within a `let' form in which `x' is
  3038. (dynamically) bound, it retrieves the local value of `x' (i.e. 1). But
  3039. when we call `getx' outside the `let' form, it retrieves the global
  3040. value of `x' (i.e. -99).
  3041. Here is another example, which illustrates setting a dynamically
  3042. bound variable using `setq':
  3043. (defvar x -99) ; `x' receives an initial value of -99.
  3044. (defun addx ()
  3045. (setq x (1+ x))) ; Add 1 to `x' and return its new value.
  3046. (let ((x 1))
  3047. (addx)
  3048. (addx))
  3049. => 3 ; The two `addx' calls add to `x' twice.
  3050. ;; After the `let' form finishes, `x' reverts to its
  3051. ;; previous value, which is -99.
  3052. (addx)
  3053. => -98
  3054. Dynamic binding is implemented in Emacs Lisp in a simple way. Each
  3055. symbol has a value cell, which specifies its current dynamic value (or
  3056. absence of value). *Note Symbol Components::. When a symbol is given
  3057. a dynamic local binding, Emacs records the contents of the value cell
  3058. (or absence thereof) in a stack, and stores the new local value in the
  3059. value cell. When the binding construct finishes executing, Emacs pops
  3060. the old value off the stack, and puts it in the value cell.
  3061. 
  3062. File: elisp, Node: Dynamic Binding Tips, Next: Lexical Binding, Prev: Dynamic Binding, Up: Variable Scoping
  3063. 11.9.2 Proper Use of Dynamic Binding
  3064. ------------------------------------
  3065. Dynamic binding is a powerful feature, as it allows programs to refer
  3066. to variables that are not defined within their local textual scope.
  3067. However, if used without restraint, this can also make programs hard to
  3068. understand. There are two clean ways to use this technique:
  3069. * If a variable has no global definition, use it as a local variable
  3070. only within a binding construct, e.g. the body of the `let' form
  3071. where the variable was bound, or the body of the function for an
  3072. argument variable. If this convention is followed consistently
  3073. throughout a program, the value of the variable will not affect,
  3074. nor be affected by, any uses of the same variable symbol elsewhere
  3075. in the program.
  3076. * Otherwise, define the variable with `defvar', `defconst', or
  3077. `defcustom'. *Note Defining Variables::. Usually, the definition
  3078. should be at top-level in an Emacs Lisp file. As far as possible,
  3079. it should include a documentation string which explains the
  3080. meaning and purpose of the variable. You should also choose the
  3081. variable's name to avoid name conflicts (*note Coding
  3082. Conventions::).
  3083. Then you can bind the variable anywhere in a program, knowing
  3084. reliably what the effect will be. Wherever you encounter the
  3085. variable, it will be easy to refer back to the definition, e.g.
  3086. via the `C-h v' command (provided the variable definition has been
  3087. loaded into Emacs). *Note Name Help: (emacs)Name Help.
  3088. For example, it is common to use local bindings for customizable
  3089. variables like `case-fold-search':
  3090. (defun search-for-abc ()
  3091. "Search for the string \"abc\", ignoring case differences."
  3092. (let ((case-fold-search nil))
  3093. (re-search-forward "abc")))
  3094. 
  3095. File: elisp, Node: Lexical Binding, Next: Using Lexical Binding, Prev: Dynamic Binding Tips, Up: Variable Scoping
  3096. 11.9.3 Lexical Binding
  3097. ----------------------
  3098. Optionally, you can create lexical bindings in Emacs Lisp. A lexically
  3099. bound variable has "lexical scope", meaning that any reference to the
  3100. variable must be located textually within the binding construct.
  3101. Here is an example (*note Using Lexical Binding::, for how to
  3102. actually enable lexical binding):
  3103. (let ((x 1)) ; `x' is lexically bound.
  3104. (+ x 3))
  3105. => 4
  3106. (defun getx ()
  3107. x) ; `x' is used "free" in this function.
  3108. (let ((x 1)) ; `x' is lexically bound.
  3109. (getx))
  3110. error--> Symbol's value as variable is void: x
  3111. Here, the variable `x' has no global value. When it is lexically bound
  3112. within a `let' form, it can be used in the textual confines of that
  3113. `let' form. But it can _not_ be used from within a `getx' function
  3114. called from the `let' form, since the function definition of `getx'
  3115. occurs outside the `let' form itself.
  3116. Here is how lexical binding works. Each binding construct defines a
  3117. "lexical environment", specifying the symbols that are bound within the
  3118. construct and their local values. When the Lisp evaluator wants the
  3119. current value of a variable, it looks first in the lexical environment;
  3120. if the variable is not specified in there, it looks in the symbol's
  3121. value cell, where the dynamic value is stored.
  3122. Lexical bindings have indefinite extent. Even after a binding
  3123. construct has finished executing, its lexical environment can be "kept
  3124. around" in Lisp objects called "closures". A closure is created when
  3125. you define a named or anonymous function with lexical binding enabled.
  3126. *Note Closures::, for details.
  3127. When a closure is called as a function, any lexical variable
  3128. references within its definition use the retained lexical environment.
  3129. Here is an example:
  3130. (defvar my-ticker nil) ; We will use this dynamically bound
  3131. ; variable to store a closure.
  3132. (let ((x 0)) ; `x' is lexically bound.
  3133. (setq my-ticker (lambda ()
  3134. (setq x (1+ x)))))
  3135. => (closure ((x . 0) t) ()
  3136. (1+ x))
  3137. (funcall my-ticker)
  3138. => 1
  3139. (funcall my-ticker)
  3140. => 2
  3141. (funcall my-ticker)
  3142. => 3
  3143. x ; Note that `x' has no global value.
  3144. error--> Symbol's value as variable is void: x
  3145. The `let' binding defines a lexical environment in which the variable
  3146. `x' is locally bound to 0. Within this binding construct, we define a
  3147. lambda expression which increments `x' by one and returns the
  3148. incremented value. This lambda expression is automatically turned into
  3149. a closure, in which the lexical environment lives on even after the
  3150. `let' binding construct has exited. Each time we evaluate the closure,
  3151. it increments `x', using the binding of `x' in that lexical environment.
  3152. Note that functions like `symbol-value', `boundp', and `set' only
  3153. retrieve or modify a variable's dynamic binding (i.e. the contents of
  3154. its symbol's value cell). Also, the code in the body of a `defun' or
  3155. `defmacro' cannot refer to surrounding lexical variables.
  3156. Currently, lexical binding is not much used within the Emacs
  3157. sources. However, we expect its importance to increase in the future.
  3158. Lexical binding opens up a lot more opportunities for optimization, so
  3159. Emacs Lisp code that makes use of lexical binding is likely to run
  3160. faster in future Emacs versions. Such code is also much more friendly
  3161. to concurrency, which we want to add to Emacs in the near future.
  3162. 
  3163. File: elisp, Node: Using Lexical Binding, Prev: Lexical Binding, Up: Variable Scoping
  3164. 11.9.4 Using Lexical Binding
  3165. ----------------------------
  3166. When loading an Emacs Lisp file or evaluating a Lisp buffer, lexical
  3167. binding is enabled if the buffer-local variable `lexical-binding' is
  3168. non-`nil':
  3169. -- Variable: lexical-binding
  3170. If this buffer-local variable is non-`nil', Emacs Lisp files and
  3171. buffers are evaluated using lexical binding instead of dynamic
  3172. binding. (However, special variables are still dynamically bound;
  3173. see below.) If `nil', dynamic binding is used for all local
  3174. variables. This variable is typically set for a whole Emacs Lisp
  3175. file, as a file local variable (*note File Local Variables::).
  3176. Note that unlike other such variables, this one must be set in the
  3177. first line of a file.
  3178. When evaluating Emacs Lisp code directly using an `eval' call, lexical
  3179. binding is enabled if the LEXICAL argument to `eval' is non-`nil'.
  3180. *Note Eval::.
  3181. Even when lexical binding is enabled, certain variables will
  3182. continue to be dynamically bound. These are called "special
  3183. variables". Every variable that has been defined with `defvar',
  3184. `defcustom' or `defconst' is a special variable (*note Defining
  3185. Variables::). All other variables are subject to lexical binding.
  3186. -- Function: special-variable-p SYMBOL
  3187. This function returns non-`nil' if SYMBOL is a special variable
  3188. (i.e. it has a `defvar', `defcustom', or `defconst' variable
  3189. definition). Otherwise, the return value is `nil'.
  3190. The use of a special variable as a formal argument in a function is
  3191. discouraged. Doing so gives rise to unspecified behavior when lexical
  3192. binding mode is enabled (it may use lexical binding sometimes, and
  3193. dynamic binding other times).
  3194. Converting an Emacs Lisp program to lexical binding is pretty easy.
  3195. First, add a file-local variable setting of `lexical-binding' to `t' in
  3196. the Emacs Lisp source file. Second, check that every variable in the
  3197. program which needs to be dynamically bound has a variable definition,
  3198. so that it is not inadvertently bound lexically.
  3199. A simple way to find out which variables need a variable definition
  3200. is to byte-compile the source file. *Note Byte Compilation::. If a
  3201. non-special variable is used outside of a `let' form, the byte-compiler
  3202. will warn about reference or assignment to a "free variable". If a
  3203. non-special variable is bound but not used within a `let' form, the
  3204. byte-compiler will warn about an "unused lexical variable". The
  3205. byte-compiler will also issue a warning if you use a special variable
  3206. as a function argument.
  3207. (To silence byte-compiler warnings about unused variables, just use
  3208. a variable name that start with an underscore. The byte-compiler
  3209. interprets this as an indication that this is a variable known not to
  3210. be used.)
  3211. 
  3212. File: elisp, Node: Buffer-Local Variables, Next: File Local Variables, Prev: Variable Scoping, Up: Variables
  3213. 11.10 Buffer-Local Variables
  3214. ============================
  3215. Global and local variable bindings are found in most programming
  3216. languages in one form or another. Emacs, however, also supports
  3217. additional, unusual kinds of variable binding, such as "buffer-local"
  3218. bindings, which apply only in one buffer. Having different values for
  3219. a variable in different buffers is an important customization method.
  3220. (Variables can also have bindings that are local to each terminal.
  3221. *Note Multiple Terminals::.)
  3222. * Menu:
  3223. * Intro to Buffer-Local:: Introduction and concepts.
  3224. * Creating Buffer-Local:: Creating and destroying buffer-local bindings.
  3225. * Default Value:: The default value is seen in buffers
  3226. that don't have their own buffer-local values.
  3227. 
  3228. File: elisp, Node: Intro to Buffer-Local, Next: Creating Buffer-Local, Up: Buffer-Local Variables
  3229. 11.10.1 Introduction to Buffer-Local Variables
  3230. ----------------------------------------------
  3231. A buffer-local variable has a buffer-local binding associated with a
  3232. particular buffer. The binding is in effect when that buffer is
  3233. current; otherwise, it is not in effect. If you set the variable while
  3234. a buffer-local binding is in effect, the new value goes in that binding,
  3235. so its other bindings are unchanged. This means that the change is
  3236. visible only in the buffer where you made it.
  3237. The variable's ordinary binding, which is not associated with any
  3238. specific buffer, is called the "default binding". In most cases, this
  3239. is the global binding.
  3240. A variable can have buffer-local bindings in some buffers but not in
  3241. other buffers. The default binding is shared by all the buffers that
  3242. don't have their own bindings for the variable. (This includes all
  3243. newly-created buffers.) If you set the variable in a buffer that does
  3244. not have a buffer-local binding for it, this sets the default binding,
  3245. so the new value is visible in all the buffers that see the default
  3246. binding.
  3247. The most common use of buffer-local bindings is for major modes to
  3248. change variables that control the behavior of commands. For example, C
  3249. mode and Lisp mode both set the variable `paragraph-start' to specify
  3250. that only blank lines separate paragraphs. They do this by making the
  3251. variable buffer-local in the buffer that is being put into C mode or
  3252. Lisp mode, and then setting it to the new value for that mode. *Note
  3253. Major Modes::.
  3254. The usual way to make a buffer-local binding is with
  3255. `make-local-variable', which is what major mode commands typically use.
  3256. This affects just the current buffer; all other buffers (including
  3257. those yet to be created) will continue to share the default value unless
  3258. they are explicitly given their own buffer-local bindings.
  3259. A more powerful operation is to mark the variable as "automatically
  3260. buffer-local" by calling `make-variable-buffer-local'. You can think
  3261. of this as making the variable local in all buffers, even those yet to
  3262. be created. More precisely, the effect is that setting the variable
  3263. automatically makes the variable local to the current buffer if it is
  3264. not already so. All buffers start out by sharing the default value of
  3265. the variable as usual, but setting the variable creates a buffer-local
  3266. binding for the current buffer. The new value is stored in the
  3267. buffer-local binding, leaving the default binding untouched. This
  3268. means that the default value cannot be changed with `setq' in any
  3269. buffer; the only way to change it is with `setq-default'.
  3270. *Warning:* When a variable has buffer-local bindings in one or more
  3271. buffers, `let' rebinds the binding that's currently in effect. For
  3272. instance, if the current buffer has a buffer-local value, `let'
  3273. temporarily rebinds that. If no buffer-local bindings are in effect,
  3274. `let' rebinds the default value. If inside the `let' you then change
  3275. to a different current buffer in which a different binding is in effect,
  3276. you won't see the `let' binding any more. And if you exit the `let'
  3277. while still in the other buffer, you won't see the unbinding occur
  3278. (though it will occur properly). Here is an example to illustrate:
  3279. (setq foo 'g)
  3280. (set-buffer "a")
  3281. (make-local-variable 'foo)
  3282. (setq foo 'a)
  3283. (let ((foo 'temp))
  3284. ;; foo => 'temp ; let binding in buffer `a'
  3285. (set-buffer "b")
  3286. ;; foo => 'g ; the global value since foo is not local in `b'
  3287. BODY...)
  3288. foo => 'g ; exiting restored the local value in buffer `a',
  3289. ; but we don't see that in buffer `b'
  3290. (set-buffer "a") ; verify the local value was restored
  3291. foo => 'a
  3292. Note that references to `foo' in BODY access the buffer-local binding
  3293. of buffer `b'.
  3294. When a file specifies local variable values, these become
  3295. buffer-local values when you visit the file. *Note File Variables:
  3296. (emacs)File Variables.
  3297. A buffer-local variable cannot be made terminal-local (*note
  3298. Multiple Terminals::).
  3299. 
  3300. File: elisp, Node: Creating Buffer-Local, Next: Default Value, Prev: Intro to Buffer-Local, Up: Buffer-Local Variables
  3301. 11.10.2 Creating and Deleting Buffer-Local Bindings
  3302. ---------------------------------------------------
  3303. -- Command: make-local-variable variable
  3304. This function creates a buffer-local binding in the current buffer
  3305. for VARIABLE (a symbol). Other buffers are not affected. The
  3306. value returned is VARIABLE.
  3307. The buffer-local value of VARIABLE starts out as the same value
  3308. VARIABLE previously had. If VARIABLE was void, it remains void.
  3309. ;; In buffer `b1':
  3310. (setq foo 5) ; Affects all buffers.
  3311. => 5
  3312. (make-local-variable 'foo) ; Now it is local in `b1'.
  3313. => foo
  3314. foo ; That did not change
  3315. => 5 ; the value.
  3316. (setq foo 6) ; Change the value
  3317. => 6 ; in `b1'.
  3318. foo
  3319. => 6
  3320. ;; In buffer `b2', the value hasn't changed.
  3321. (with-current-buffer "b2"
  3322. foo)
  3323. => 5
  3324. Making a variable buffer-local within a `let'-binding for that
  3325. variable does not work reliably, unless the buffer in which you do
  3326. this is not current either on entry to or exit from the `let'.
  3327. This is because `let' does not distinguish between different kinds
  3328. of bindings; it knows only which variable the binding was made for.
  3329. If the variable is terminal-local (*note Multiple Terminals::),
  3330. this function signals an error. Such variables cannot have
  3331. buffer-local bindings as well.
  3332. *Warning:* do not use `make-local-variable' for a hook variable.
  3333. The hook variables are automatically made buffer-local as needed
  3334. if you use the LOCAL argument to `add-hook' or `remove-hook'.
  3335. -- Command: make-variable-buffer-local variable
  3336. This function marks VARIABLE (a symbol) automatically
  3337. buffer-local, so that any subsequent attempt to set it will make it
  3338. local to the current buffer at the time. Unlike
  3339. `make-local-variable', with which it is often confused, this
  3340. cannot be undone, and affects the behavior of the variable in all
  3341. buffers.
  3342. A peculiar wrinkle of this feature is that binding the variable
  3343. (with `let' or other binding constructs) does not create a
  3344. buffer-local binding for it. Only setting the variable (with
  3345. `set' or `setq'), while the variable does not have a `let'-style
  3346. binding that was made in the current buffer, does so.
  3347. If VARIABLE does not have a default value, then calling this
  3348. command will give it a default value of `nil'. If VARIABLE
  3349. already has a default value, that value remains unchanged.
  3350. Subsequently calling `makunbound' on VARIABLE will result in a
  3351. void buffer-local value and leave the default value unaffected.
  3352. The value returned is VARIABLE.
  3353. *Warning:* Don't assume that you should use
  3354. `make-variable-buffer-local' for user-option variables, simply
  3355. because users _might_ want to customize them differently in
  3356. different buffers. Users can make any variable local, when they
  3357. wish to. It is better to leave the choice to them.
  3358. The time to use `make-variable-buffer-local' is when it is crucial
  3359. that no two buffers ever share the same binding. For example,
  3360. when a variable is used for internal purposes in a Lisp program
  3361. which depends on having separate values in separate buffers, then
  3362. using `make-variable-buffer-local' can be the best solution.
  3363. -- Function: local-variable-p variable &optional buffer
  3364. This returns `t' if VARIABLE is buffer-local in buffer BUFFER
  3365. (which defaults to the current buffer); otherwise, `nil'.
  3366. -- Function: local-variable-if-set-p variable &optional buffer
  3367. This returns `t' if VARIABLE will become buffer-local in buffer
  3368. BUFFER (which defaults to the current buffer) if it is set there.
  3369. -- Function: buffer-local-value variable buffer
  3370. This function returns the buffer-local binding of VARIABLE (a
  3371. symbol) in buffer BUFFER. If VARIABLE does not have a
  3372. buffer-local binding in buffer BUFFER, it returns the default
  3373. value (*note Default Value::) of VARIABLE instead.
  3374. -- Function: buffer-local-variables &optional buffer
  3375. This function returns a list describing the buffer-local variables
  3376. in buffer BUFFER. (If BUFFER is omitted, the current buffer is
  3377. used.) Normally, each list element has the form `(SYM . VAL)',
  3378. where SYM is a buffer-local variable (a symbol) and VAL is its
  3379. buffer-local value. But when a variable's buffer-local binding in
  3380. BUFFER is void, its list element is just SYM.
  3381. (make-local-variable 'foobar)
  3382. (makunbound 'foobar)
  3383. (make-local-variable 'bind-me)
  3384. (setq bind-me 69)
  3385. (setq lcl (buffer-local-variables))
  3386. ;; First, built-in variables local in all buffers:
  3387. => ((mark-active . nil)
  3388. (buffer-undo-list . nil)
  3389. (mode-name . "Fundamental")
  3390. ...
  3391. ;; Next, non-built-in buffer-local variables.
  3392. ;; This one is buffer-local and void:
  3393. foobar
  3394. ;; This one is buffer-local and nonvoid:
  3395. (bind-me . 69))
  3396. Note that storing new values into the CDRs of cons cells in this
  3397. list does _not_ change the buffer-local values of the variables.
  3398. -- Command: kill-local-variable variable
  3399. This function deletes the buffer-local binding (if any) for
  3400. VARIABLE (a symbol) in the current buffer. As a result, the
  3401. default binding of VARIABLE becomes visible in this buffer. This
  3402. typically results in a change in the value of VARIABLE, since the
  3403. default value is usually different from the buffer-local value just
  3404. eliminated.
  3405. If you kill the buffer-local binding of a variable that
  3406. automatically becomes buffer-local when set, this makes the
  3407. default value visible in the current buffer. However, if you set
  3408. the variable again, that will once again create a buffer-local
  3409. binding for it.
  3410. `kill-local-variable' returns VARIABLE.
  3411. This function is a command because it is sometimes useful to kill
  3412. one buffer-local variable interactively, just as it is useful to
  3413. create buffer-local variables interactively.
  3414. -- Function: kill-all-local-variables
  3415. This function eliminates all the buffer-local variable bindings of
  3416. the current buffer except for variables marked as "permanent" and
  3417. local hook functions that have a non-`nil' `permanent-local-hook'
  3418. property (*note Setting Hooks::). As a result, the buffer will see
  3419. the default values of most variables.
  3420. This function also resets certain other information pertaining to
  3421. the buffer: it sets the local keymap to `nil', the syntax table to
  3422. the value of `(standard-syntax-table)', the case table to
  3423. `(standard-case-table)', and the abbrev table to the value of
  3424. `fundamental-mode-abbrev-table'.
  3425. The very first thing this function does is run the normal hook
  3426. `change-major-mode-hook' (see below).
  3427. Every major mode command begins by calling this function, which
  3428. has the effect of switching to Fundamental mode and erasing most
  3429. of the effects of the previous major mode. To ensure that this
  3430. does its job, the variables that major modes set should not be
  3431. marked permanent.
  3432. `kill-all-local-variables' returns `nil'.
  3433. -- Variable: change-major-mode-hook
  3434. The function `kill-all-local-variables' runs this normal hook
  3435. before it does anything else. This gives major modes a way to
  3436. arrange for something special to be done if the user switches to a
  3437. different major mode. It is also useful for buffer-specific minor
  3438. modes that should be forgotten if the user changes the major mode.
  3439. For best results, make this variable buffer-local, so that it will
  3440. disappear after doing its job and will not interfere with the
  3441. subsequent major mode. *Note Hooks::.
  3442. A buffer-local variable is "permanent" if the variable name (a
  3443. symbol) has a `permanent-local' property that is non-`nil'. Such
  3444. variables are unaffected by `kill-all-local-variables', and their local
  3445. bindings are therefore not cleared by changing major modes. Permanent
  3446. locals are appropriate for data pertaining to where the file came from
  3447. or how to save it, rather than with how to edit the contents.
  3448. 
  3449. File: elisp, Node: Default Value, Prev: Creating Buffer-Local, Up: Buffer-Local Variables
  3450. 11.10.3 The Default Value of a Buffer-Local Variable
  3451. ----------------------------------------------------
  3452. The global value of a variable with buffer-local bindings is also
  3453. called the "default" value, because it is the value that is in effect
  3454. whenever neither the current buffer nor the selected frame has its own
  3455. binding for the variable.
  3456. The functions `default-value' and `setq-default' access and change a
  3457. variable's default value regardless of whether the current buffer has a
  3458. buffer-local binding. For example, you could use `setq-default' to
  3459. change the default setting of `paragraph-start' for most buffers; and
  3460. this would work even when you are in a C or Lisp mode buffer that has a
  3461. buffer-local value for this variable.
  3462. The special forms `defvar' and `defconst' also set the default value
  3463. (if they set the variable at all), rather than any buffer-local value.
  3464. -- Function: default-value symbol
  3465. This function returns SYMBOL's default value. This is the value
  3466. that is seen in buffers and frames that do not have their own
  3467. values for this variable. If SYMBOL is not buffer-local, this is
  3468. equivalent to `symbol-value' (*note Accessing Variables::).
  3469. -- Function: default-boundp symbol
  3470. The function `default-boundp' tells you whether SYMBOL's default
  3471. value is nonvoid. If `(default-boundp 'foo)' returns `nil', then
  3472. `(default-value 'foo)' would get an error.
  3473. `default-boundp' is to `default-value' as `boundp' is to
  3474. `symbol-value'.
  3475. -- Special Form: setq-default [symbol form]...
  3476. This special form gives each SYMBOL a new default value, which is
  3477. the result of evaluating the corresponding FORM. It does not
  3478. evaluate SYMBOL, but does evaluate FORM. The value of the
  3479. `setq-default' form is the value of the last FORM.
  3480. If a SYMBOL is not buffer-local for the current buffer, and is not
  3481. marked automatically buffer-local, `setq-default' has the same
  3482. effect as `setq'. If SYMBOL is buffer-local for the current
  3483. buffer, then this changes the value that other buffers will see
  3484. (as long as they don't have a buffer-local value), but not the
  3485. value that the current buffer sees.
  3486. ;; In buffer `foo':
  3487. (make-local-variable 'buffer-local)
  3488. => buffer-local
  3489. (setq buffer-local 'value-in-foo)
  3490. => value-in-foo
  3491. (setq-default buffer-local 'new-default)
  3492. => new-default
  3493. buffer-local
  3494. => value-in-foo
  3495. (default-value 'buffer-local)
  3496. => new-default
  3497. ;; In (the new) buffer `bar':
  3498. buffer-local
  3499. => new-default
  3500. (default-value 'buffer-local)
  3501. => new-default
  3502. (setq buffer-local 'another-default)
  3503. => another-default
  3504. (default-value 'buffer-local)
  3505. => another-default
  3506. ;; Back in buffer `foo':
  3507. buffer-local
  3508. => value-in-foo
  3509. (default-value 'buffer-local)
  3510. => another-default
  3511. -- Function: set-default symbol value
  3512. This function is like `setq-default', except that SYMBOL is an
  3513. ordinary evaluated argument.
  3514. (set-default (car '(a b c)) 23)
  3515. => 23
  3516. (default-value 'a)
  3517. => 23
  3518. 
  3519. File: elisp, Node: File Local Variables, Next: Directory Local Variables, Prev: Buffer-Local Variables, Up: Variables
  3520. 11.11 File Local Variables
  3521. ==========================
  3522. A file can specify local variable values; Emacs uses these to create
  3523. buffer-local bindings for those variables in the buffer visiting that
  3524. file. *Note Local Variables in Files: (emacs)File variables, for basic
  3525. information about file-local variables. This section describes the
  3526. functions and variables that affect how file-local variables are
  3527. processed.
  3528. If a file-local variable could specify an arbitrary function or Lisp
  3529. expression that would be called later, visiting a file could take over
  3530. your Emacs. Emacs protects against this by automatically setting only
  3531. those file-local variables whose specified values are known to be safe.
  3532. Other file-local variables are set only if the user agrees.
  3533. For additional safety, `read-circle' is temporarily bound to `nil'
  3534. when Emacs reads file-local variables (*note Input Functions::). This
  3535. prevents the Lisp reader from recognizing circular and shared Lisp
  3536. structures (*note Circular Objects::).
  3537. -- User Option: enable-local-variables
  3538. This variable controls whether to process file-local variables.
  3539. The possible values are:
  3540. `t' (the default)
  3541. Set the safe variables, and query (once) about any unsafe
  3542. variables.
  3543. `:safe'
  3544. Set only the safe variables and do not query.
  3545. `:all'
  3546. Set all the variables and do not query.
  3547. `nil'
  3548. Don't set any variables.
  3549. anything else
  3550. Query (once) about all the variables.
  3551. -- Variable: inhibit-local-variables-regexps
  3552. This is a list of regular expressions. If a file has a name
  3553. matching an element of this list, then it is not scanned for any
  3554. form of file-local variable. For examples of why you might want
  3555. to use this, *note Auto Major Mode::.
  3556. -- Function: hack-local-variables &optional mode-only
  3557. This function parses, and binds or evaluates as appropriate, any
  3558. local variables specified by the contents of the current buffer.
  3559. The variable `enable-local-variables' has its effect here.
  3560. However, this function does not look for the `mode:' local
  3561. variable in the `-*-' line. `set-auto-mode' does that, also taking
  3562. `enable-local-variables' into account (*note Auto Major Mode::).
  3563. This function works by walking the alist stored in
  3564. `file-local-variables-alist' and applying each local variable in
  3565. turn. It calls `before-hack-local-variables-hook' and
  3566. `hack-local-variables-hook' before and after applying the
  3567. variables, respectively. It only calls the before-hook if the
  3568. alist is non-`nil'; it always calls the other hook. This function
  3569. ignores a `mode' element if it specifies the same major mode as
  3570. the buffer already has.
  3571. If the optional argument MODE-ONLY is non-`nil', then all this
  3572. function does is return a symbol specifying the major mode, if the
  3573. `-*-' line or the local variables list specifies one, and `nil'
  3574. otherwise. It does not set the mode nor any other file-local
  3575. variable.
  3576. -- Variable: file-local-variables-alist
  3577. This buffer-local variable holds the alist of file-local variable
  3578. settings. Each element of the alist is of the form
  3579. `(VAR . VALUE)', where VAR is a symbol of the local variable and
  3580. VALUE is its value. When Emacs visits a file, it first collects
  3581. all the file-local variables into this alist, and then the
  3582. `hack-local-variables' function applies them one by one.
  3583. -- Variable: before-hack-local-variables-hook
  3584. Emacs calls this hook immediately before applying file-local
  3585. variables stored in `file-local-variables-alist'.
  3586. -- Variable: hack-local-variables-hook
  3587. Emacs calls this hook immediately after it finishes applying
  3588. file-local variables stored in `file-local-variables-alist'.
  3589. You can specify safe values for a variable with a
  3590. `safe-local-variable' property. The property has to be a function of
  3591. one argument; any value is safe if the function returns non-`nil' given
  3592. that value. Many commonly-encountered file variables have
  3593. `safe-local-variable' properties; these include `fill-column',
  3594. `fill-prefix', and `indent-tabs-mode'. For boolean-valued variables
  3595. that are safe, use `booleanp' as the property value. Lambda
  3596. expressions should be quoted so that `describe-variable' can display
  3597. the predicate.
  3598. When defining a user option using `defcustom', you can set its
  3599. `safe-local-variable' property by adding the arguments `:safe FUNCTION'
  3600. to `defcustom' (*note Variable Definitions::).
  3601. -- User Option: safe-local-variable-values
  3602. This variable provides another way to mark some variable values as
  3603. safe. It is a list of cons cells `(VAR . VAL)', where VAR is a
  3604. variable name and VAL is a value which is safe for that variable.
  3605. When Emacs asks the user whether or not to obey a set of file-local
  3606. variable specifications, the user can choose to mark them as safe.
  3607. Doing so adds those variable/value pairs to
  3608. `safe-local-variable-values', and saves it to the user's custom
  3609. file.
  3610. -- Function: safe-local-variable-p sym val
  3611. This function returns non-`nil' if it is safe to give SYM the
  3612. value VAL, based on the above criteria.
  3613. Some variables are considered "risky". If a variable is risky, it
  3614. is never entered automatically into `safe-local-variable-values'; Emacs
  3615. always queries before setting a risky variable, unless the user
  3616. explicitly allows a value by customizing `safe-local-variable-values'
  3617. directly.
  3618. Any variable whose name has a non-`nil' `risky-local-variable'
  3619. property is considered risky. When you define a user option using
  3620. `defcustom', you can set its `risky-local-variable' property by adding
  3621. the arguments `:risky VALUE' to `defcustom' (*note Variable
  3622. Definitions::). In addition, any variable whose name ends in any of
  3623. `-command', `-frame-alist', `-function', `-functions', `-hook',
  3624. `-hooks', `-form', `-forms', `-map', `-map-alist', `-mode-alist',
  3625. `-program', or `-predicate' is automatically considered risky. The
  3626. variables `font-lock-keywords', `font-lock-keywords' followed by a
  3627. digit, and `font-lock-syntactic-keywords' are also considered risky.
  3628. -- Function: risky-local-variable-p sym
  3629. This function returns non-`nil' if SYM is a risky variable, based
  3630. on the above criteria.
  3631. -- Variable: ignored-local-variables
  3632. This variable holds a list of variables that should not be given
  3633. local values by files. Any value specified for one of these
  3634. variables is completely ignored.
  3635. The `Eval:' "variable" is also a potential loophole, so Emacs
  3636. normally asks for confirmation before handling it.
  3637. -- User Option: enable-local-eval
  3638. This variable controls processing of `Eval:' in `-*-' lines or
  3639. local variables lists in files being visited. A value of `t'
  3640. means process them unconditionally; `nil' means ignore them;
  3641. anything else means ask the user what to do for each file. The
  3642. default value is `maybe'.
  3643. -- User Option: safe-local-eval-forms
  3644. This variable holds a list of expressions that are safe to
  3645. evaluate when found in the `Eval:' "variable" in a file local
  3646. variables list.
  3647. If the expression is a function call and the function has a
  3648. `safe-local-eval-function' property, the property value determines
  3649. whether the expression is safe to evaluate. The property value can be
  3650. a predicate to call to test the expression, a list of such predicates
  3651. (it's safe if any predicate succeeds), or `t' (always safe provided the
  3652. arguments are constant).
  3653. Text properties are also potential loopholes, since their values
  3654. could include functions to call. So Emacs discards all text properties
  3655. from string values specified for file-local variables.
  3656. 
  3657. File: elisp, Node: Directory Local Variables, Next: Variable Aliases, Prev: File Local Variables, Up: Variables
  3658. 11.12 Directory Local Variables
  3659. ===============================
  3660. A directory can specify local variable values common to all files in
  3661. that directory; Emacs uses these to create buffer-local bindings for
  3662. those variables in buffers visiting any file in that directory. This
  3663. is useful when the files in the directory belong to some "project" and
  3664. therefore share the same local variables.
  3665. There are two different methods for specifying directory local
  3666. variables: by putting them in a special file, or by defining a "project
  3667. class" for that directory.
  3668. -- Constant: dir-locals-file
  3669. This constant is the name of the file where Emacs expects to find
  3670. the directory-local variables. The name of the file is
  3671. `.dir-locals.el'(1). A file by that name in a directory causes
  3672. Emacs to apply its settings to any file in that directory or any
  3673. of its subdirectories (optionally, you can exclude subdirectories;
  3674. see below). If some of the subdirectories have their own
  3675. `.dir-locals.el' files, Emacs uses the settings from the deepest
  3676. file it finds starting from the file's directory and moving up the
  3677. directory tree. The file specifies local variables as a specially
  3678. formatted list; see *note Per-directory Local Variables:
  3679. (emacs)Directory Variables, for more details.
  3680. -- Function: hack-dir-local-variables
  3681. This function reads the `.dir-locals.el' file and stores the
  3682. directory-local variables in `file-local-variables-alist' that is
  3683. local to the buffer visiting any file in the directory, without
  3684. applying them. It also stores the directory-local settings in
  3685. `dir-locals-class-alist', where it defines a special class for the
  3686. directory in which `.dir-locals.el' file was found. This function
  3687. works by calling `dir-locals-set-class-variables' and
  3688. `dir-locals-set-directory-class', described below.
  3689. -- Function: hack-dir-local-variables-non-file-buffer
  3690. This function looks for directory-local variables, and immediately
  3691. applies them in the current buffer. It is intended to be called in
  3692. the mode commands for non-file buffers, such as Dired buffers, to
  3693. let them obey directory-local variable settings. For non-file
  3694. buffers, Emacs looks for directory-local variables in
  3695. `default-directory' and its parent directories.
  3696. -- Function: dir-locals-set-class-variables class variables
  3697. This function defines a set of variable settings for the named
  3698. CLASS, which is a symbol. You can later assign the class to one
  3699. or more directories, and Emacs will apply those variable settings
  3700. to all files in those directories. The list in VARIABLES can be of
  3701. one of the two forms: `(MAJOR-MODE . ALIST)' or `(DIRECTORY .
  3702. LIST)'. With the first form, if the file's buffer turns on a mode
  3703. that is derived from MAJOR-MODE, then the all the variables in the
  3704. associated ALIST are applied; ALIST should be of the form `(NAME .
  3705. VALUE)'. A special value `nil' for MAJOR-MODE means the settings
  3706. are applicable to any mode. In ALIST, you can use a special NAME:
  3707. `subdirs'. If the associated value is `nil', the alist is only
  3708. applied to files in the relevant directory, not to those in any
  3709. subdirectories.
  3710. With the second form of VARIABLES, if DIRECTORY is the initial
  3711. substring of the file's directory, then LIST is applied
  3712. recursively by following the above rules; LIST should be of one of
  3713. the two forms accepted by this function in VARIABLES.
  3714. -- Function: dir-locals-set-directory-class directory class &optional
  3715. mtime
  3716. This function assigns CLASS to all the files in `directory' and
  3717. its subdirectories. Thereafter, all the variable settings
  3718. specified for CLASS will be applied to any visited file in
  3719. DIRECTORY and its children. CLASS must have been already defined
  3720. by `dir-locals-set-class-variables'.
  3721. Emacs uses this function internally when it loads directory
  3722. variables from a `.dir-locals.el' file. In that case, the optional
  3723. argument MTIME holds the file modification time (as returned by
  3724. `file-attributes'). Emacs uses this time to check stored local
  3725. variables are still valid. If you are assigning a class directly,
  3726. not via a file, this argument should be `nil'.
  3727. -- Variable: dir-locals-class-alist
  3728. This alist holds the class symbols and the associated variable
  3729. settings. It is updated by `dir-locals-set-class-variables'.
  3730. -- Variable: dir-locals-directory-cache
  3731. This alist holds directory names, their assigned class names, and
  3732. modification times of the associated directory local variables file
  3733. (if there is one). The function `dir-locals-set-directory-class'
  3734. updates this list.
  3735. ---------- Footnotes ----------
  3736. (1) The MS-DOS version of Emacs uses `_dir-locals.el' instead, due to
  3737. limitations of the DOS filesystems.
  3738. 
  3739. File: elisp, Node: Variable Aliases, Next: Variables with Restricted Values, Prev: Directory Local Variables, Up: Variables
  3740. 11.13 Variable Aliases
  3741. ======================
  3742. It is sometimes useful to make two variables synonyms, so that both
  3743. variables always have the same value, and changing either one also
  3744. changes the other. Whenever you change the name of a variable--either
  3745. because you realize its old name was not well chosen, or because its
  3746. meaning has partly changed--it can be useful to keep the old name as an
  3747. _alias_ of the new one for compatibility. You can do this with
  3748. `defvaralias'.
  3749. -- Function: defvaralias new-alias base-variable &optional docstring
  3750. This function defines the symbol NEW-ALIAS as a variable alias for
  3751. symbol BASE-VARIABLE. This means that retrieving the value of
  3752. NEW-ALIAS returns the value of BASE-VARIABLE, and changing the
  3753. value of NEW-ALIAS changes the value of BASE-VARIABLE. The two
  3754. aliased variable names always share the same value and the same
  3755. bindings.
  3756. If the DOCSTRING argument is non-`nil', it specifies the
  3757. documentation for NEW-ALIAS; otherwise, the alias gets the same
  3758. documentation as BASE-VARIABLE has, if any, unless BASE-VARIABLE
  3759. is itself an alias, in which case NEW-ALIAS gets the documentation
  3760. of the variable at the end of the chain of aliases.
  3761. This function returns BASE-VARIABLE.
  3762. Variable aliases are convenient for replacing an old name for a
  3763. variable with a new name. `make-obsolete-variable' declares that the
  3764. old name is obsolete and therefore that it may be removed at some stage
  3765. in the future.
  3766. -- Function: make-obsolete-variable obsolete-name current-name when
  3767. &optional access-type
  3768. This function makes the byte compiler warn that the variable
  3769. OBSOLETE-NAME is obsolete. If CURRENT-NAME is a symbol, it is the
  3770. variable's new name; then the warning message says to use
  3771. CURRENT-NAME instead of OBSOLETE-NAME. If CURRENT-NAME is a
  3772. string, this is the message and there is no replacement variable.
  3773. WHEN should be a string indicating when the variable was first
  3774. made obsolete (usually a version number string).
  3775. The optional argument ACCESS-TYPE, if non-`nil', should should
  3776. specify the kind of access that will trigger obsolescence
  3777. warnings; it can be either `get' or `set'.
  3778. You can make two variables synonyms and declare one obsolete at the
  3779. same time using the macro `define-obsolete-variable-alias'.
  3780. -- Macro: define-obsolete-variable-alias obsolete-name current-name
  3781. &optional when docstring
  3782. This macro marks the variable OBSOLETE-NAME as obsolete and also
  3783. makes it an alias for the variable CURRENT-NAME. It is equivalent
  3784. to the following:
  3785. (defvaralias OBSOLETE-NAME CURRENT-NAME DOCSTRING)
  3786. (make-obsolete-variable OBSOLETE-NAME CURRENT-NAME WHEN)
  3787. -- Function: indirect-variable variable
  3788. This function returns the variable at the end of the chain of
  3789. aliases of VARIABLE. If VARIABLE is not a symbol, or if VARIABLE
  3790. is not defined as an alias, the function returns VARIABLE.
  3791. This function signals a `cyclic-variable-indirection' error if
  3792. there is a loop in the chain of symbols.
  3793. (defvaralias 'foo 'bar)
  3794. (indirect-variable 'foo)
  3795. => bar
  3796. (indirect-variable 'bar)
  3797. => bar
  3798. (setq bar 2)
  3799. bar
  3800. => 2
  3801. foo
  3802. => 2
  3803. (setq foo 0)
  3804. bar
  3805. => 0
  3806. foo
  3807. => 0
  3808. 
  3809. File: elisp, Node: Variables with Restricted Values, Prev: Variable Aliases, Up: Variables
  3810. 11.14 Variables with Restricted Values
  3811. ======================================
  3812. Ordinary Lisp variables can be assigned any value that is a valid Lisp
  3813. object. However, certain Lisp variables are not defined in Lisp, but
  3814. in C. Most of these variables are defined in the C code using
  3815. `DEFVAR_LISP'. Like variables defined in Lisp, these can take on any
  3816. value. However, some variables are defined using `DEFVAR_INT' or
  3817. `DEFVAR_BOOL'. *Note Writing Emacs Primitives: Defining Lisp variables
  3818. in C, in particular the description of functions of the type
  3819. `syms_of_FILENAME', for a brief discussion of the C implementation.
  3820. Variables of type `DEFVAR_BOOL' can only take on the values `nil' or
  3821. `t'. Attempting to assign them any other value will set them to `t':
  3822. (let ((display-hourglass 5))
  3823. display-hourglass)
  3824. => t
  3825. -- Variable: byte-boolean-vars
  3826. This variable holds a list of all variables of type `DEFVAR_BOOL'.
  3827. Variables of type `DEFVAR_INT' can only take on integer values.
  3828. Attempting to assign them any other value will result in an error:
  3829. (setq undo-limit 1000.0)
  3830. error--> Wrong type argument: integerp, 1000.0
  3831. 
  3832. File: elisp, Node: Functions, Next: Macros, Prev: Variables, Up: Top
  3833. 12 Functions
  3834. ************
  3835. A Lisp program is composed mainly of Lisp functions. This chapter
  3836. explains what functions are, how they accept arguments, and how to
  3837. define them.
  3838. * Menu:
  3839. * What Is a Function:: Lisp functions vs. primitives; terminology.
  3840. * Lambda Expressions:: How functions are expressed as Lisp objects.
  3841. * Function Names:: A symbol can serve as the name of a function.
  3842. * Defining Functions:: Lisp expressions for defining functions.
  3843. * Calling Functions:: How to use an existing function.
  3844. * Mapping Functions:: Applying a function to each element of a list, etc.
  3845. * Anonymous Functions:: Lambda expressions are functions with no names.
  3846. * Function Cells:: Accessing or setting the function definition
  3847. of a symbol.
  3848. * Closures:: Functions that enclose a lexical environment.
  3849. * Obsolete Functions:: Declaring functions obsolete.
  3850. * Inline Functions:: Functions that the compiler will expand inline.
  3851. * Declaring Functions:: Telling the compiler that a function is defined.
  3852. * Function Safety:: Determining whether a function is safe to call.
  3853. * Related Topics:: Cross-references to specific Lisp primitives
  3854. that have a special bearing on how functions work.
  3855. 
  3856. File: elisp, Node: What Is a Function, Next: Lambda Expressions, Up: Functions
  3857. 12.1 What Is a Function?
  3858. ========================
  3859. In a general sense, a function is a rule for carrying out a computation
  3860. given input values called "arguments". The result of the computation
  3861. is called the "value" or "return value" of the function. The
  3862. computation can also have side effects, such as lasting changes in the
  3863. values of variables or the contents of data structures.
  3864. In most computer languages, every function has a name. But in Lisp,
  3865. a function in the strictest sense has no name: it is an object which
  3866. can _optionally_ be associated with a symbol (e.g. `car') that serves
  3867. as the function name. *Note Function Names::. When a function has
  3868. been given a name, we usually also refer to that symbol as a "function"
  3869. (e.g. we refer to "the function `car'"). In this manual, the
  3870. distinction between a function name and the function object itself is
  3871. usually unimportant, but we will take note wherever it is relevant.
  3872. Certain function-like objects, called "special forms" and "macros",
  3873. also accept arguments to carry out computations. However, as explained
  3874. below, these are not considered functions in Emacs Lisp.
  3875. Here are important terms for functions and function-like objects:
  3876. "lambda expression"
  3877. A function (in the strict sense, i.e. a function object) which is
  3878. written in Lisp. These are described in the following section.
  3879. *Note Lambda Expressions::.
  3880. "primitive"
  3881. A function which is callable from Lisp but is actually written in
  3882. C. Primitives are also called "built-in functions", or "subrs".
  3883. Examples include functions like `car' and `append'. In addition,
  3884. all special forms (see below) are also considered primitives.
  3885. Usually, a function is implemented as a primitive because it is a
  3886. fundamental part of Lisp (e.g. `car'), or because it provides a
  3887. low-level interface to operating system services, or because it
  3888. needs to run fast. Unlike functions defined in Lisp, primitives
  3889. can be modified or added only by changing the C sources and
  3890. recompiling Emacs. See *note Writing Emacs Primitives::.
  3891. "special form"
  3892. A primitive that is like a function but does not evaluate all of
  3893. its arguments in the usual way. It may evaluate only some of the
  3894. arguments, or may evaluate them in an unusual order, or several
  3895. times. Examples include `if', `and', and `while'. *Note Special
  3896. Forms::.
  3897. "macro"
  3898. A construct defined in Lisp, which differs from a function in that
  3899. it translates a Lisp expression into another expression which is
  3900. to be evaluated instead of the original expression. Macros enable
  3901. Lisp programmers to do the sorts of things that special forms can
  3902. do. *Note Macros::.
  3903. "command"
  3904. An object which can be invoked via the `command-execute'
  3905. primitive, usually due to the user typing in a key sequence
  3906. "bound" to that command. *Note Interactive Call::. A command is
  3907. usually a function; if the function is written in Lisp, it is made
  3908. into a command by an `interactive' form in the function definition
  3909. (*note Defining Commands::). Commands that are functions can also
  3910. be called from Lisp expressions, just like other functions.
  3911. Keyboard macros (strings and vectors) are commands also, even
  3912. though they are not functions. *Note Keyboard Macros::. We say
  3913. that a symbol is a command if its function cell contains a command
  3914. (*note Symbol Components::); such a "named command" can be invoked
  3915. with `M-x'.
  3916. "closure"
  3917. A function object that is much like a lambda expression, except
  3918. that it also encloses an "environment" of lexical variable
  3919. bindings. *Note Closures::.
  3920. "byte-code function"
  3921. A function that has been compiled by the byte compiler. *Note
  3922. Byte-Code Type::.
  3923. "autoload object"
  3924. A place-holder for a real function. If the autoload object is
  3925. called, Emacs loads the file containing the definition of the real
  3926. function, and then calls the real function. *Note Autoload::.
  3927. You can use the function `functionp' to test if an object is a
  3928. function:
  3929. -- Function: functionp object
  3930. This function returns `t' if OBJECT is any kind of function, i.e.
  3931. can be passed to `funcall'. Note that `functionp' returns `t' for
  3932. symbols that are function names, and returns `nil' for special
  3933. forms.
  3934. Unlike `functionp', the next three functions do _not_ treat a symbol as
  3935. its function definition.
  3936. -- Function: subrp object
  3937. This function returns `t' if OBJECT is a built-in function (i.e.,
  3938. a Lisp primitive).
  3939. (subrp 'message) ; `message' is a symbol,
  3940. => nil ; not a subr object.
  3941. (subrp (symbol-function 'message))
  3942. => t
  3943. -- Function: byte-code-function-p object
  3944. This function returns `t' if OBJECT is a byte-code function. For
  3945. example:
  3946. (byte-code-function-p (symbol-function 'next-line))
  3947. => t
  3948. -- Function: subr-arity subr
  3949. This function provides information about the argument list of a
  3950. primitive, SUBR. The returned value is a pair `(MIN . MAX)'. MIN
  3951. is the minimum number of args. MAX is the maximum number or the
  3952. symbol `many', for a function with `&rest' arguments, or the
  3953. symbol `unevalled' if SUBR is a special form.
  3954. 
  3955. File: elisp, Node: Lambda Expressions, Next: Function Names, Prev: What Is a Function, Up: Functions
  3956. 12.2 Lambda Expressions
  3957. =======================
  3958. A lambda expression is a function object written in Lisp. Here is an
  3959. example:
  3960. (lambda (x)
  3961. "Return the hyperbolic cosine of X."
  3962. (* 0.5 (+ (exp x) (exp (- x)))))
  3963. In Emacs Lisp, such a list is valid as an expression--it evaluates to
  3964. itself. But its main use is not to be evaluated as an expression, but
  3965. to be called as a function.
  3966. A lambda expression, by itself, has no name; it is an "anonymous
  3967. function". Although lambda expressions can be used this way (*note
  3968. Anonymous Functions::), they are more commonly associated with symbols
  3969. to make "named functions" (*note Function Names::). Before going into
  3970. these details, the following subsections describe the components of a
  3971. lambda expression and what they do.
  3972. * Menu:
  3973. * Lambda Components:: The parts of a lambda expression.
  3974. * Simple Lambda:: A simple example.
  3975. * Argument List:: Details and special features of argument lists.
  3976. * Function Documentation:: How to put documentation in a function.
  3977. 
  3978. File: elisp, Node: Lambda Components, Next: Simple Lambda, Up: Lambda Expressions
  3979. 12.2.1 Components of a Lambda Expression
  3980. ----------------------------------------
  3981. A lambda expression is a list that looks like this:
  3982. (lambda (ARG-VARIABLES...)
  3983. [DOCUMENTATION-STRING]
  3984. [INTERACTIVE-DECLARATION]
  3985. BODY-FORMS...)
  3986. The first element of a lambda expression is always the symbol
  3987. `lambda'. This indicates that the list represents a function. The
  3988. reason functions are defined to start with `lambda' is so that other
  3989. lists, intended for other uses, will not accidentally be valid as
  3990. functions.
  3991. The second element is a list of symbols--the argument variable names.
  3992. This is called the "lambda list". When a Lisp function is called, the
  3993. argument values are matched up against the variables in the lambda
  3994. list, which are given local bindings with the values provided. *Note
  3995. Local Variables::.
  3996. The documentation string is a Lisp string object placed within the
  3997. function definition to describe the function for the Emacs help
  3998. facilities. *Note Function Documentation::.
  3999. The interactive declaration is a list of the form `(interactive
  4000. CODE-STRING)'. This declares how to provide arguments if the function
  4001. is used interactively. Functions with this declaration are called
  4002. "commands"; they can be called using `M-x' or bound to a key.
  4003. Functions not intended to be called in this way should not have
  4004. interactive declarations. *Note Defining Commands::, for how to write
  4005. an interactive declaration.
  4006. The rest of the elements are the "body" of the function: the Lisp
  4007. code to do the work of the function (or, as a Lisp programmer would say,
  4008. "a list of Lisp forms to evaluate"). The value returned by the
  4009. function is the value returned by the last element of the body.
  4010. 
  4011. File: elisp, Node: Simple Lambda, Next: Argument List, Prev: Lambda Components, Up: Lambda Expressions
  4012. 12.2.2 A Simple Lambda Expression Example
  4013. -----------------------------------------
  4014. Consider the following example:
  4015. (lambda (a b c) (+ a b c))
  4016. We can call this function by passing it to `funcall', like this:
  4017. (funcall (lambda (a b c) (+ a b c))
  4018. 1 2 3)
  4019. This call evaluates the body of the lambda expression with the variable
  4020. `a' bound to 1, `b' bound to 2, and `c' bound to 3. Evaluation of the
  4021. body adds these three numbers, producing the result 6; therefore, this
  4022. call to the function returns the value 6.
  4023. Note that the arguments can be the results of other function calls,
  4024. as in this example:
  4025. (funcall (lambda (a b c) (+ a b c))
  4026. 1 (* 2 3) (- 5 4))
  4027. This evaluates the arguments `1', `(* 2 3)', and `(- 5 4)' from left to
  4028. right. Then it applies the lambda expression to the argument values 1,
  4029. 6 and 1 to produce the value 8.
  4030. As these examples show, you can use a form with a lambda expression
  4031. as its CAR to make local variables and give them values. In the old
  4032. days of Lisp, this technique was the only way to bind and initialize
  4033. local variables. But nowadays, it is clearer to use the special form
  4034. `let' for this purpose (*note Local Variables::). Lambda expressions
  4035. are mainly used as anonymous functions for passing as arguments to
  4036. other functions (*note Anonymous Functions::), or stored as symbol
  4037. function definitions to produce named functions (*note Function
  4038. Names::).
  4039. 
  4040. File: elisp, Node: Argument List, Next: Function Documentation, Prev: Simple Lambda, Up: Lambda Expressions
  4041. 12.2.3 Other Features of Argument Lists
  4042. ---------------------------------------
  4043. Our simple sample function, `(lambda (a b c) (+ a b c))', specifies
  4044. three argument variables, so it must be called with three arguments: if
  4045. you try to call it with only two arguments or four arguments, you get a
  4046. `wrong-number-of-arguments' error.
  4047. It is often convenient to write a function that allows certain
  4048. arguments to be omitted. For example, the function `substring' accepts
  4049. three arguments--a string, the start index and the end index--but the
  4050. third argument defaults to the LENGTH of the string if you omit it. It
  4051. is also convenient for certain functions to accept an indefinite number
  4052. of arguments, as the functions `list' and `+' do.
  4053. To specify optional arguments that may be omitted when a function is
  4054. called, simply include the keyword `&optional' before the optional
  4055. arguments. To specify a list of zero or more extra arguments, include
  4056. the keyword `&rest' before one final argument.
  4057. Thus, the complete syntax for an argument list is as follows:
  4058. (REQUIRED-VARS...
  4059. [&optional OPTIONAL-VARS...]
  4060. [&rest REST-VAR])
  4061. The square brackets indicate that the `&optional' and `&rest' clauses,
  4062. and the variables that follow them, are optional.
  4063. A call to the function requires one actual argument for each of the
  4064. REQUIRED-VARS. There may be actual arguments for zero or more of the
  4065. OPTIONAL-VARS, and there cannot be any actual arguments beyond that
  4066. unless the lambda list uses `&rest'. In that case, there may be any
  4067. number of extra actual arguments.
  4068. If actual arguments for the optional and rest variables are omitted,
  4069. then they always default to `nil'. There is no way for the function to
  4070. distinguish between an explicit argument of `nil' and an omitted
  4071. argument. However, the body of the function is free to consider `nil'
  4072. an abbreviation for some other meaningful value. This is what
  4073. `substring' does; `nil' as the third argument to `substring' means to
  4074. use the length of the string supplied.
  4075. Common Lisp note: Common Lisp allows the function to specify what
  4076. default value to use when an optional argument is omitted; Emacs
  4077. Lisp always uses `nil'. Emacs Lisp does not support "supplied-p"
  4078. variables that tell you whether an argument was explicitly passed.
  4079. For example, an argument list that looks like this:
  4080. (a b &optional c d &rest e)
  4081. binds `a' and `b' to the first two actual arguments, which are
  4082. required. If one or two more arguments are provided, `c' and `d' are
  4083. bound to them respectively; any arguments after the first four are
  4084. collected into a list and `e' is bound to that list. If there are only
  4085. two arguments, `c' is `nil'; if two or three arguments, `d' is `nil';
  4086. if four arguments or fewer, `e' is `nil'.
  4087. There is no way to have required arguments following optional
  4088. ones--it would not make sense. To see why this must be so, suppose
  4089. that `c' in the example were optional and `d' were required. Suppose
  4090. three actual arguments are given; which variable would the third
  4091. argument be for? Would it be used for the C, or for D? One can argue
  4092. for both possibilities. Similarly, it makes no sense to have any more
  4093. arguments (either required or optional) after a `&rest' argument.
  4094. Here are some examples of argument lists and proper calls:
  4095. (funcall (lambda (n) (1+ n)) ; One required:
  4096. 1) ; requires exactly one argument.
  4097. => 2
  4098. (funcall (lambda (n &optional n1) ; One required and one optional:
  4099. (if n1 (+ n n1) (1+ n))) ; 1 or 2 arguments.
  4100. 1 2)
  4101. => 3
  4102. (funcall (lambda (n &rest ns) ; One required and one rest:
  4103. (+ n (apply '+ ns))) ; 1 or more arguments.
  4104. 1 2 3 4 5)
  4105. => 15
  4106. 
  4107. File: elisp, Node: Function Documentation, Prev: Argument List, Up: Lambda Expressions
  4108. 12.2.4 Documentation Strings of Functions
  4109. -----------------------------------------
  4110. A lambda expression may optionally have a "documentation string" just
  4111. after the lambda list. This string does not affect execution of the
  4112. function; it is a kind of comment, but a systematized comment which
  4113. actually appears inside the Lisp world and can be used by the Emacs
  4114. help facilities. *Note Documentation::, for how the documentation
  4115. string is accessed.
  4116. It is a good idea to provide documentation strings for all the
  4117. functions in your program, even those that are called only from within
  4118. your program. Documentation strings are like comments, except that they
  4119. are easier to access.
  4120. The first line of the documentation string should stand on its own,
  4121. because `apropos' displays just this first line. It should consist of
  4122. one or two complete sentences that summarize the function's purpose.
  4123. The start of the documentation string is usually indented in the
  4124. source file, but since these spaces come before the starting
  4125. double-quote, they are not part of the string. Some people make a
  4126. practice of indenting any additional lines of the string so that the
  4127. text lines up in the program source. _That is a mistake._ The
  4128. indentation of the following lines is inside the string; what looks
  4129. nice in the source code will look ugly when displayed by the help
  4130. commands.
  4131. You may wonder how the documentation string could be optional, since
  4132. there are required components of the function that follow it (the body).
  4133. Since evaluation of a string returns that string, without any side
  4134. effects, it has no effect if it is not the last form in the body.
  4135. Thus, in practice, there is no confusion between the first form of the
  4136. body and the documentation string; if the only body form is a string
  4137. then it serves both as the return value and as the documentation.
  4138. The last line of the documentation string can specify calling
  4139. conventions different from the actual function arguments. Write text
  4140. like this:
  4141. \(fn ARGLIST)
  4142. following a blank line, at the beginning of the line, with no newline
  4143. following it inside the documentation string. (The `\' is used to
  4144. avoid confusing the Emacs motion commands.) The calling convention
  4145. specified in this way appears in help messages in place of the one
  4146. derived from the actual arguments of the function.
  4147. This feature is particularly useful for macro definitions, since the
  4148. arguments written in a macro definition often do not correspond to the
  4149. way users think of the parts of the macro call.
  4150. 
  4151. File: elisp, Node: Function Names, Next: Defining Functions, Prev: Lambda Expressions, Up: Functions
  4152. 12.3 Naming a Function
  4153. ======================
  4154. A symbol can serve as the name of a function. This happens when the
  4155. symbol's "function cell" (*note Symbol Components::) contains a
  4156. function object (e.g. a lambda expression). Then the symbol itself
  4157. becomes a valid, callable function, equivalent to the function object
  4158. in its function cell.
  4159. The contents of the function cell are also called the symbol's
  4160. "function definition". The procedure of using a symbol's function
  4161. definition in place of the symbol is called "symbol function
  4162. indirection"; see *note Function Indirection::. If you have not given a
  4163. symbol a function definition, its function cell is said to be "void",
  4164. and it cannot be used as a function.
  4165. In practice, nearly all functions have names, and are referred to by
  4166. their names. You can create a named Lisp function by defining a lambda
  4167. expression and putting it in a function cell (*note Function Cells::).
  4168. However, it is more common to use the `defun' special form, described
  4169. in the next section. *Note Defining Functions::.
  4170. We give functions names because it is convenient to refer to them by
  4171. their names in Lisp expressions. Also, a named Lisp function can
  4172. easily refer to itself--it can be recursive. Furthermore, primitives
  4173. can only be referred to textually by their names, since primitive
  4174. function objects (*note Primitive Function Type::) have no read syntax.
  4175. A function need not have a unique name. A given function object
  4176. _usually_ appears in the function cell of only one symbol, but this is
  4177. just a convention. It is easy to store it in several symbols using
  4178. `fset'; then each of the symbols is a valid name for the same function.
  4179. Note that a symbol used as a function name may also be used as a
  4180. variable; these two uses of a symbol are independent and do not
  4181. conflict. (This is not the case in some dialects of Lisp, like Scheme.)
  4182. 
  4183. File: elisp, Node: Defining Functions, Next: Calling Functions, Prev: Function Names, Up: Functions
  4184. 12.4 Defining Functions
  4185. =======================
  4186. We usually give a name to a function when it is first created. This is
  4187. called "defining a function", and it is done with the `defun' special
  4188. form.
  4189. -- Special Form: defun name argument-list body-forms...
  4190. `defun' is the usual way to define new Lisp functions. It defines
  4191. the symbol NAME as a function that looks like this:
  4192. (lambda ARGUMENT-LIST . BODY-FORMS)
  4193. `defun' stores this lambda expression in the function cell of
  4194. NAME. It returns the value NAME, but usually we ignore this value.
  4195. As described previously, ARGUMENT-LIST is a list of argument names
  4196. and may include the keywords `&optional' and `&rest'. Also, the
  4197. first two of the BODY-FORMS may be a documentation string and an
  4198. interactive declaration. *Note Lambda Components::.
  4199. Here are some examples:
  4200. (defun foo () 5)
  4201. => foo
  4202. (foo)
  4203. => 5
  4204. (defun bar (a &optional b &rest c)
  4205. (list a b c))
  4206. => bar
  4207. (bar 1 2 3 4 5)
  4208. => (1 2 (3 4 5))
  4209. (bar 1)
  4210. => (1 nil nil)
  4211. (bar)
  4212. error--> Wrong number of arguments.
  4213. (defun capitalize-backwards ()
  4214. "Upcase the last letter of the word at point."
  4215. (interactive)
  4216. (backward-word 1)
  4217. (forward-word 1)
  4218. (backward-char 1)
  4219. (capitalize-word 1))
  4220. => capitalize-backwards
  4221. Be careful not to redefine existing functions unintentionally.
  4222. `defun' redefines even primitive functions such as `car' without
  4223. any hesitation or notification. Emacs does not prevent you from
  4224. doing this, because redefining a function is sometimes done
  4225. deliberately, and there is no way to distinguish deliberate
  4226. redefinition from unintentional redefinition.
  4227. -- Function: defalias name definition &optional docstring
  4228. This special form defines the symbol NAME as a function, with
  4229. definition DEFINITION (which can be any valid Lisp function). It
  4230. returns DEFINITION.
  4231. If DOCSTRING is non-`nil', it becomes the function documentation
  4232. of NAME. Otherwise, any documentation provided by DEFINITION is
  4233. used.
  4234. The proper place to use `defalias' is where a specific function
  4235. name is being defined--especially where that name appears
  4236. explicitly in the source file being loaded. This is because
  4237. `defalias' records which file defined the function, just like
  4238. `defun' (*note Unloading::).
  4239. By contrast, in programs that manipulate function definitions for
  4240. other purposes, it is better to use `fset', which does not keep
  4241. such records. *Note Function Cells::.
  4242. You cannot create a new primitive function with `defun' or
  4243. `defalias', but you can use them to change the function definition of
  4244. any symbol, even one such as `car' or `x-popup-menu' whose normal
  4245. definition is a primitive. However, this is risky: for instance, it is
  4246. next to impossible to redefine `car' without breaking Lisp completely.
  4247. Redefining an obscure function such as `x-popup-menu' is less
  4248. dangerous, but it still may not work as you expect. If there are calls
  4249. to the primitive from C code, they call the primitive's C definition
  4250. directly, so changing the symbol's definition will have no effect on
  4251. them.
  4252. See also `defsubst', which defines a function like `defun' and tells
  4253. the Lisp compiler to perform inline expansion on it. *Note Inline
  4254. Functions::.
  4255. 
  4256. File: elisp, Node: Calling Functions, Next: Mapping Functions, Prev: Defining Functions, Up: Functions
  4257. 12.5 Calling Functions
  4258. ======================
  4259. Defining functions is only half the battle. Functions don't do
  4260. anything until you "call" them, i.e., tell them to run. Calling a
  4261. function is also known as "invocation".
  4262. The most common way of invoking a function is by evaluating a list.
  4263. For example, evaluating the list `(concat "a" "b")' calls the function
  4264. `concat' with arguments `"a"' and `"b"'. *Note Evaluation::, for a
  4265. description of evaluation.
  4266. When you write a list as an expression in your program, you specify
  4267. which function to call, and how many arguments to give it, in the text
  4268. of the program. Usually that's just what you want. Occasionally you
  4269. need to compute at run time which function to call. To do that, use
  4270. the function `funcall'. When you also need to determine at run time
  4271. how many arguments to pass, use `apply'.
  4272. -- Function: funcall function &rest arguments
  4273. `funcall' calls FUNCTION with ARGUMENTS, and returns whatever
  4274. FUNCTION returns.
  4275. Since `funcall' is a function, all of its arguments, including
  4276. FUNCTION, are evaluated before `funcall' is called. This means
  4277. that you can use any expression to obtain the function to be
  4278. called. It also means that `funcall' does not see the expressions
  4279. you write for the ARGUMENTS, only their values. These values are
  4280. _not_ evaluated a second time in the act of calling FUNCTION; the
  4281. operation of `funcall' is like the normal procedure for calling a
  4282. function, once its arguments have already been evaluated.
  4283. The argument FUNCTION must be either a Lisp function or a
  4284. primitive function. Special forms and macros are not allowed,
  4285. because they make sense only when given the "unevaluated" argument
  4286. expressions. `funcall' cannot provide these because, as we saw
  4287. above, it never knows them in the first place.
  4288. (setq f 'list)
  4289. => list
  4290. (funcall f 'x 'y 'z)
  4291. => (x y z)
  4292. (funcall f 'x 'y '(z))
  4293. => (x y (z))
  4294. (funcall 'and t nil)
  4295. error--> Invalid function: #<subr and>
  4296. Compare these examples with the examples of `apply'.
  4297. -- Function: apply function &rest arguments
  4298. `apply' calls FUNCTION with ARGUMENTS, just like `funcall' but
  4299. with one difference: the last of ARGUMENTS is a list of objects,
  4300. which are passed to FUNCTION as separate arguments, rather than a
  4301. single list. We say that `apply' "spreads" this list so that each
  4302. individual element becomes an argument.
  4303. `apply' returns the result of calling FUNCTION. As with
  4304. `funcall', FUNCTION must either be a Lisp function or a primitive
  4305. function; special forms and macros do not make sense in `apply'.
  4306. (setq f 'list)
  4307. => list
  4308. (apply f 'x 'y 'z)
  4309. error--> Wrong type argument: listp, z
  4310. (apply '+ 1 2 '(3 4))
  4311. => 10
  4312. (apply '+ '(1 2 3 4))
  4313. => 10
  4314. (apply 'append '((a b c) nil (x y z) nil))
  4315. => (a b c x y z)
  4316. For an interesting example of using `apply', see *note Definition
  4317. of mapcar::.
  4318. Sometimes it is useful to fix some of the function's arguments at
  4319. certain values, and leave the rest of arguments for when the function
  4320. is actually called. The act of fixing some of the function's arguments
  4321. is called "partial application" of the function(1). The result is a
  4322. new function that accepts the rest of arguments and calls the original
  4323. function with all the arguments combined.
  4324. Here's how to do partial application in Emacs Lisp:
  4325. -- Function: apply-partially func &rest args
  4326. This function returns a new function which, when called, will call
  4327. FUNC with the list of arguments composed from ARGS and additional
  4328. arguments specified at the time of the call. If FUNC accepts N
  4329. arguments, then a call to `apply-partially' with `M < N' arguments
  4330. will produce a new function of `N - M' arguments.
  4331. Here's how we could define the built-in function `1+', if it
  4332. didn't exist, using `apply-partially' and `+', another built-in
  4333. function:
  4334. (defalias '1+ (apply-partially '+ 1)
  4335. "Increment argument by one.")
  4336. (1+ 10)
  4337. => 11
  4338. It is common for Lisp functions to accept functions as arguments or
  4339. find them in data structures (especially in hook variables and property
  4340. lists) and call them using `funcall' or `apply'. Functions that accept
  4341. function arguments are often called "functionals".
  4342. Sometimes, when you call a functional, it is useful to supply a no-op
  4343. function as the argument. Here are two different kinds of no-op
  4344. function:
  4345. -- Function: identity arg
  4346. This function returns ARG and has no side effects.
  4347. -- Function: ignore &rest args
  4348. This function ignores any arguments and returns `nil'.
  4349. Some functions are user-visible "commands", which can be called
  4350. interactively (usually by a key sequence). It is possible to invoke
  4351. such a command exactly as though it was called interactively, by using
  4352. the `call-interactively' function. *Note Interactive Call::.
  4353. ---------- Footnotes ----------
  4354. (1) This is related to, but different from "currying", which
  4355. transforms a function that takes multiple arguments in such a way that
  4356. it can be called as a chain of functions, each one with a single
  4357. argument.
  4358. 
  4359. File: elisp, Node: Mapping Functions, Next: Anonymous Functions, Prev: Calling Functions, Up: Functions
  4360. 12.6 Mapping Functions
  4361. ======================
  4362. A "mapping function" applies a given function (_not_ a special form or
  4363. macro) to each element of a list or other collection. Emacs Lisp has
  4364. several such functions; this section describes `mapcar', `mapc', and
  4365. `mapconcat', which map over a list. *Note Definition of mapatoms::,
  4366. for the function `mapatoms' which maps over the symbols in an obarray.
  4367. *Note Definition of maphash::, for the function `maphash' which maps
  4368. over key/value associations in a hash table.
  4369. These mapping functions do not allow char-tables because a char-table
  4370. is a sparse array whose nominal range of indices is very large. To map
  4371. over a char-table in a way that deals properly with its sparse nature,
  4372. use the function `map-char-table' (*note Char-Tables::).
  4373. -- Function: mapcar function sequence
  4374. `mapcar' applies FUNCTION to each element of SEQUENCE in turn, and
  4375. returns a list of the results.
  4376. The argument SEQUENCE can be any kind of sequence except a
  4377. char-table; that is, a list, a vector, a bool-vector, or a string.
  4378. The result is always a list. The length of the result is the same
  4379. as the length of SEQUENCE. For example:
  4380. (mapcar 'car '((a b) (c d) (e f)))
  4381. => (a c e)
  4382. (mapcar '1+ [1 2 3])
  4383. => (2 3 4)
  4384. (mapcar 'string "abc")
  4385. => ("a" "b" "c")
  4386. ;; Call each function in `my-hooks'.
  4387. (mapcar 'funcall my-hooks)
  4388. (defun mapcar* (function &rest args)
  4389. "Apply FUNCTION to successive cars of all ARGS.
  4390. Return the list of results."
  4391. ;; If no list is exhausted,
  4392. (if (not (memq nil args))
  4393. ;; apply function to CARs.
  4394. (cons (apply function (mapcar 'car args))
  4395. (apply 'mapcar* function
  4396. ;; Recurse for rest of elements.
  4397. (mapcar 'cdr args)))))
  4398. (mapcar* 'cons '(a b c) '(1 2 3 4))
  4399. => ((a . 1) (b . 2) (c . 3))
  4400. -- Function: mapc function sequence
  4401. `mapc' is like `mapcar' except that FUNCTION is used for
  4402. side-effects only--the values it returns are ignored, not collected
  4403. into a list. `mapc' always returns SEQUENCE.
  4404. -- Function: mapconcat function sequence separator
  4405. `mapconcat' applies FUNCTION to each element of SEQUENCE: the
  4406. results, which must be strings, are concatenated. Between each
  4407. pair of result strings, `mapconcat' inserts the string SEPARATOR.
  4408. Usually SEPARATOR contains a space or comma or other suitable
  4409. punctuation.
  4410. The argument FUNCTION must be a function that can take one
  4411. argument and return a string. The argument SEQUENCE can be any
  4412. kind of sequence except a char-table; that is, a list, a vector, a
  4413. bool-vector, or a string.
  4414. (mapconcat 'symbol-name
  4415. '(The cat in the hat)
  4416. " ")
  4417. => "The cat in the hat"
  4418. (mapconcat (function (lambda (x) (format "%c" (1+ x))))
  4419. "HAL-8000"
  4420. "")
  4421. => "IBM.9111"
  4422. 
  4423. File: elisp, Node: Anonymous Functions, Next: Function Cells, Prev: Mapping Functions, Up: Functions
  4424. 12.7 Anonymous Functions
  4425. ========================
  4426. Although functions are usually defined with `defun' and given names at
  4427. the same time, it is sometimes convenient to use an explicit lambda
  4428. expression--an "anonymous function". Anonymous functions are valid
  4429. wherever function names are. They are often assigned as variable
  4430. values, or as arguments to functions; for instance, you might pass one
  4431. as the FUNCTION argument to `mapcar', which applies that function to
  4432. each element of a list (*note Mapping Functions::). *Note
  4433. describe-symbols example::, for a realistic example of this.
  4434. When defining a lambda expression that is to be used as an anonymous
  4435. function, you can in principle use any method to construct the list.
  4436. But typically you should use the `lambda' macro, or the `function'
  4437. special form, or the `#'' read syntax:
  4438. -- Macro: lambda args body...
  4439. This macro returns an anonymous function with argument list ARGS
  4440. and body forms given by BODY. In effect, this macro makes
  4441. `lambda' forms "self-quoting": evaluating a form whose CAR is
  4442. `lambda' yields the form itself:
  4443. (lambda (x) (* x x))
  4444. => (lambda (x) (* x x))
  4445. The `lambda' form has one other effect: it tells the Emacs
  4446. evaluator and byte-compiler that its argument is a function, by
  4447. using `function' as a subroutine (see below).
  4448. -- Special Form: function function-object
  4449. This special form returns FUNCTION-OBJECT without evaluating it.
  4450. In this, it is similar to `quote' (*note Quoting::). But unlike
  4451. `quote', it also serves as a note to the Emacs evaluator and
  4452. byte-compiler that FUNCTION-OBJECT is intended to be used as a
  4453. function. Assuming FUNCTION-OBJECT is a valid lambda expression,
  4454. this has two effects:
  4455. * When the code is byte-compiled, FUNCTION-OBJECT is compiled
  4456. into a byte-code function object (*note Byte Compilation::).
  4457. * When lexical binding is enabled, FUNCTION-OBJECT is converted
  4458. into a closure. *Note Closures::.
  4459. The read syntax `#'' is a short-hand for using `function'. The
  4460. following forms are all equivalent:
  4461. (lambda (x) (* x x))
  4462. (function (lambda (x) (* x x)))
  4463. #'(lambda (x) (* x x))
  4464. In the following example, we define a `change-property' function
  4465. that takes a function as its third argument, followed by a
  4466. `double-property' function that makes use of `change-property' by
  4467. passing it an anonymous function:
  4468. (defun change-property (symbol prop function)
  4469. (let ((value (get symbol prop)))
  4470. (put symbol prop (funcall function value))))
  4471. (defun double-property (symbol prop)
  4472. (change-property symbol prop (lambda (x) (* 2 x))))
  4473. Note that we do not quote the `lambda' form.
  4474. If you compile the above code, the anonymous function is also
  4475. compiled. This would not happen if, say, you had constructed the
  4476. anonymous function by quoting it as a list:
  4477. (defun double-property (symbol prop)
  4478. (change-property symbol prop '(lambda (x) (* 2 x))))
  4479. In that case, the anonymous function is kept as a lambda expression in
  4480. the compiled code. The byte-compiler cannot assume this list is a
  4481. function, even though it looks like one, since it does not know that
  4482. `change-property' intends to use it as a function.
  4483. 
  4484. File: elisp, Node: Function Cells, Next: Closures, Prev: Anonymous Functions, Up: Functions
  4485. 12.8 Accessing Function Cell Contents
  4486. =====================================
  4487. The "function definition" of a symbol is the object stored in the
  4488. function cell of the symbol. The functions described here access, test,
  4489. and set the function cell of symbols.
  4490. See also the function `indirect-function'. *Note Definition of
  4491. indirect-function::.
  4492. -- Function: symbol-function symbol
  4493. This returns the object in the function cell of SYMBOL. If the
  4494. symbol's function cell is void, a `void-function' error is
  4495. signaled.
  4496. This function does not check that the returned object is a
  4497. legitimate function.
  4498. (defun bar (n) (+ n 2))
  4499. => bar
  4500. (symbol-function 'bar)
  4501. => (lambda (n) (+ n 2))
  4502. (fset 'baz 'bar)
  4503. => bar
  4504. (symbol-function 'baz)
  4505. => bar
  4506. If you have never given a symbol any function definition, we say that
  4507. that symbol's function cell is "void". In other words, the function
  4508. cell does not have any Lisp object in it. If you try to call such a
  4509. symbol as a function, it signals a `void-function' error.
  4510. Note that void is not the same as `nil' or the symbol `void'. The
  4511. symbols `nil' and `void' are Lisp objects, and can be stored into a
  4512. function cell just as any other object can be (and they can be valid
  4513. functions if you define them in turn with `defun'). A void function
  4514. cell contains no object whatsoever.
  4515. You can test the voidness of a symbol's function definition with
  4516. `fboundp'. After you have given a symbol a function definition, you
  4517. can make it void once more using `fmakunbound'.
  4518. -- Function: fboundp symbol
  4519. This function returns `t' if the symbol has an object in its
  4520. function cell, `nil' otherwise. It does not check that the object
  4521. is a legitimate function.
  4522. -- Function: fmakunbound symbol
  4523. This function makes SYMBOL's function cell void, so that a
  4524. subsequent attempt to access this cell will cause a
  4525. `void-function' error. It returns SYMBOL. (See also
  4526. `makunbound', in *note Void Variables::.)
  4527. (defun foo (x) x)
  4528. => foo
  4529. (foo 1)
  4530. =>1
  4531. (fmakunbound 'foo)
  4532. => foo
  4533. (foo 1)
  4534. error--> Symbol's function definition is void: foo
  4535. -- Function: fset symbol definition
  4536. This function stores DEFINITION in the function cell of SYMBOL.
  4537. The result is DEFINITION. Normally DEFINITION should be a
  4538. function or the name of a function, but this is not checked. The
  4539. argument SYMBOL is an ordinary evaluated argument.
  4540. The primary use of this function is as a subroutine by constructs
  4541. that define or alter functions, like `defadvice' (*note Advising
  4542. Functions::). (If `defun' were not a primitive, it could be
  4543. written as a Lisp macro using `fset'.) You can also use it to
  4544. give a symbol a function definition that is not a list, e.g. a
  4545. keyboard macro (*note Keyboard Macros::):
  4546. ;; Define a named keyboard macro.
  4547. (fset 'kill-two-lines "\^u2\^k")
  4548. => "\^u2\^k"
  4549. It you wish to use `fset' to make an alternate name for a
  4550. function, consider using `defalias' instead. *Note Definition of
  4551. defalias::.
  4552. 
  4553. File: elisp, Node: Closures, Next: Obsolete Functions, Prev: Function Cells, Up: Functions
  4554. 12.9 Closures
  4555. =============
  4556. As explained in *note Variable Scoping::, Emacs can optionally enable
  4557. lexical binding of variables. When lexical binding is enabled, any
  4558. named function that you create (e.g. with `defun'), as well as any
  4559. anonymous function that you create using the `lambda' macro or the
  4560. `function' special form or the `#'' syntax (*note Anonymous
  4561. Functions::), is automatically converted into a "closure".
  4562. A closure is a function that also carries a record of the lexical
  4563. environment that existed when the function was defined. When it is
  4564. invoked, any lexical variable references within its definition use the
  4565. retained lexical environment. In all other respects, closures behave
  4566. much like ordinary functions; in particular, they can be called in the
  4567. same way as ordinary functions.
  4568. *Note Lexical Binding::, for an example of using a closure.
  4569. Currently, an Emacs Lisp closure object is represented by a list
  4570. with the symbol `closure' as the first element, a list representing the
  4571. lexical environment as the second element, and the argument list and
  4572. body forms as the remaining elements:
  4573. ;; lexical binding is enabled.
  4574. (lambda (x) (* x x))
  4575. => (closure (t) (x) (* x x))
  4576. However, the fact that the internal structure of a closure is "exposed"
  4577. to the rest of the Lisp world is considered an internal implementation
  4578. detail. For this reason, we recommend against directly examining or
  4579. altering the structure of closure objects.
  4580. 
  4581. File: elisp, Node: Obsolete Functions, Next: Inline Functions, Prev: Closures, Up: Functions
  4582. 12.10 Declaring Functions Obsolete
  4583. ==================================
  4584. You can use `make-obsolete' to declare a function obsolete. This
  4585. indicates that the function may be removed at some stage in the future.
  4586. -- Function: make-obsolete obsolete-name current-name &optional when
  4587. This function makes the byte compiler warn that the function
  4588. OBSOLETE-NAME is obsolete. If CURRENT-NAME is a symbol, the
  4589. warning message says to use CURRENT-NAME instead of OBSOLETE-NAME.
  4590. CURRENT-NAME does not need to be an alias for OBSOLETE-NAME; it
  4591. can be a different function with similar functionality. If
  4592. CURRENT-NAME is a string, it is the warning message.
  4593. If provided, WHEN should be a string indicating when the function
  4594. was first made obsolete--for example, a date or a release number.
  4595. You can define a function as an alias and declare it obsolete at the
  4596. same time using the macro `define-obsolete-function-alias':
  4597. -- Macro: define-obsolete-function-alias obsolete-name current-name
  4598. &optional when docstring
  4599. This macro marks the function OBSOLETE-NAME obsolete and also
  4600. defines it as an alias for the function CURRENT-NAME. It is
  4601. equivalent to the following:
  4602. (defalias OBSOLETE-NAME CURRENT-NAME DOCSTRING)
  4603. (make-obsolete OBSOLETE-NAME CURRENT-NAME WHEN)
  4604. In addition, you can mark a certain a particular calling convention
  4605. for a function as obsolete:
  4606. -- Function: set-advertised-calling-convention function signature when
  4607. This function specifies the argument list SIGNATURE as the correct
  4608. way to call FUNCTION. This causes the Emacs byte compiler to
  4609. issue a warning whenever it comes across an Emacs Lisp program
  4610. that calls FUNCTION any other way (however, it will still allow
  4611. the code to be byte compiled). WHEN should be a string indicating
  4612. when the variable was first made obsolete (usually a version
  4613. number string).
  4614. For instance, in old versions of Emacs the `sit-for' function
  4615. accepted three arguments, like this
  4616. (sit-for seconds milliseconds nodisp)
  4617. However, calling `sit-for' this way is considered obsolete (*note
  4618. Waiting::). The old calling convention is deprecated like this:
  4619. (set-advertised-calling-convention
  4620. 'sit-for '(seconds &optional nodisp) "22.1")
  4621. 
  4622. File: elisp, Node: Inline Functions, Next: Declaring Functions, Prev: Obsolete Functions, Up: Functions
  4623. 12.11 Inline Functions
  4624. ======================
  4625. -- Macro: defsubst name argument-list body-forms...
  4626. Define an inline function. The syntax is exactly the same as
  4627. `defun' (*note Defining Functions::).
  4628. You can define an "inline function" by using `defsubst' instead of
  4629. `defun'. An inline function works just like an ordinary function
  4630. except for one thing: when you byte-compile a call to the function
  4631. (*note Byte Compilation::), the function's definition is expanded into
  4632. the caller.
  4633. Making a function inline often makes its function calls run faster.
  4634. But it also has disadvantages. For one thing, it reduces flexibility;
  4635. if you change the definition of the function, calls already inlined
  4636. still use the old definition until you recompile them.
  4637. Another disadvantage is that making a large function inline can
  4638. increase the size of compiled code both in files and in memory. Since
  4639. the speed advantage of inline functions is greatest for small
  4640. functions, you generally should not make large functions inline.
  4641. Also, inline functions do not behave well with respect to debugging,
  4642. tracing, and advising (*note Advising Functions::). Since ease of
  4643. debugging and the flexibility of redefining functions are important
  4644. features of Emacs, you should not make a function inline, even if it's
  4645. small, unless its speed is really crucial, and you've timed the code to
  4646. verify that using `defun' actually has performance problems.
  4647. It's possible to define a macro to expand into the same code that an
  4648. inline function would execute (*note Macros::). But the macro would be
  4649. limited to direct use in expressions--a macro cannot be called with
  4650. `apply', `mapcar' and so on. Also, it takes some work to convert an
  4651. ordinary function into a macro. To convert it into an inline function
  4652. is easy; just replace `defun' with `defsubst'. Since each argument of
  4653. an inline function is evaluated exactly once, you needn't worry about
  4654. how many times the body uses the arguments, as you do for macros.
  4655. After an inline function is defined, its inline expansion can be
  4656. performed later on in the same file, just like macros.
  4657. 
  4658. File: elisp, Node: Declaring Functions, Next: Function Safety, Prev: Inline Functions, Up: Functions
  4659. 12.12 Telling the Compiler that a Function is Defined
  4660. =====================================================
  4661. Byte-compiling a file often produces warnings about functions that the
  4662. compiler doesn't know about (*note Compiler Errors::). Sometimes this
  4663. indicates a real problem, but usually the functions in question are
  4664. defined in other files which would be loaded if that code is run. For
  4665. example, byte-compiling `fortran.el' used to warn:
  4666. In end of data:
  4667. fortran.el:2152:1:Warning: the function `gud-find-c-expr' is not
  4668. known to be defined.
  4669. In fact, `gud-find-c-expr' is only used in the function that Fortran
  4670. mode uses for the local value of `gud-find-expr-function', which is a
  4671. callback from GUD; if it is called, the GUD functions will be loaded.
  4672. When you know that such a warning does not indicate a real problem, it
  4673. is good to suppress the warning. That makes new warnings which might
  4674. mean real problems more visible. You do that with `declare-function'.
  4675. All you need to do is add a `declare-function' statement before the
  4676. first use of the function in question:
  4677. (declare-function gud-find-c-expr "gud.el" nil)
  4678. This says that `gud-find-c-expr' is defined in `gud.el' (the `.el'
  4679. can be omitted). The compiler takes for granted that that file really
  4680. defines the function, and does not check.
  4681. The optional third argument specifies the argument list of
  4682. `gud-find-c-expr'. In this case, it takes no arguments (`nil' is
  4683. different from not specifying a value). In other cases, this might be
  4684. something like `(file &optional overwrite)'. You don't have to specify
  4685. the argument list, but if you do the byte compiler can check that the
  4686. calls match the declaration.
  4687. -- Macro: declare-function function file &optional arglist fileonly
  4688. Tell the byte compiler to assume that FUNCTION is defined, with
  4689. arguments ARGLIST, and that the definition should come from the
  4690. file FILE. FILEONLY non-`nil' means only check that FILE exists,
  4691. not that it actually defines FUNCTION.
  4692. To verify that these functions really are declared where
  4693. `declare-function' says they are, use `check-declare-file' to check all
  4694. `declare-function' calls in one source file, or use
  4695. `check-declare-directory' check all the files in and under a certain
  4696. directory.
  4697. These commands find the file that ought to contain a function's
  4698. definition using `locate-library'; if that finds no file, they expand
  4699. the definition file name relative to the directory of the file that
  4700. contains the `declare-function' call.
  4701. You can also say that a function is a primitive by specifying a file
  4702. name ending in `.c' or `.m'. This is useful only when you call a
  4703. primitive that is defined only on certain systems. Most primitives are
  4704. always defined, so they will never give you a warning.
  4705. Sometimes a file will optionally use functions from an external
  4706. package. If you prefix the filename in the `declare-function'
  4707. statement with `ext:', then it will be checked if it is found,
  4708. otherwise skipped without error.
  4709. There are some function definitions that `check-declare' does not
  4710. understand (e.g. `defstruct' and some other macros). In such cases,
  4711. you can pass a non-`nil' FILEONLY argument to `declare-function',
  4712. meaning to only check that the file exists, not that it actually
  4713. defines the function. Note that to do this without having to specify
  4714. an argument list, you should set the ARGLIST argument to `t' (because
  4715. `nil' means an empty argument list, as opposed to an unspecified one).
  4716. 
  4717. File: elisp, Node: Function Safety, Next: Related Topics, Prev: Declaring Functions, Up: Functions
  4718. 12.13 Determining whether a Function is Safe to Call
  4719. ====================================================
  4720. Some major modes such as SES call functions that are stored in user
  4721. files. (*note (ses)Top::, for more information on SES.) User files
  4722. sometimes have poor pedigrees--you can get a spreadsheet from someone
  4723. you've just met, or you can get one through email from someone you've
  4724. never met. So it is risky to call a function whose source code is
  4725. stored in a user file until you have determined that it is safe.
  4726. -- Function: unsafep form &optional unsafep-vars
  4727. Returns `nil' if FORM is a "safe" Lisp expression, or returns a
  4728. list that describes why it might be unsafe. The argument
  4729. UNSAFEP-VARS is a list of symbols known to have temporary bindings
  4730. at this point; it is mainly used for internal recursive calls.
  4731. The current buffer is an implicit argument, which provides a list
  4732. of buffer-local bindings.
  4733. Being quick and simple, `unsafep' does a very light analysis and
  4734. rejects many Lisp expressions that are actually safe. There are no
  4735. known cases where `unsafep' returns `nil' for an unsafe expression.
  4736. However, a "safe" Lisp expression can return a string with a `display'
  4737. property, containing an associated Lisp expression to be executed after
  4738. the string is inserted into a buffer. This associated expression can
  4739. be a virus. In order to be safe, you must delete properties from all
  4740. strings calculated by user code before inserting them into buffers.
  4741. 
  4742. File: elisp, Node: Related Topics, Prev: Function Safety, Up: Functions
  4743. 12.14 Other Topics Related to Functions
  4744. =======================================
  4745. Here is a table of several functions that do things related to function
  4746. calling and function definitions. They are documented elsewhere, but
  4747. we provide cross references here.
  4748. `apply'
  4749. See *note Calling Functions::.
  4750. `autoload'
  4751. See *note Autoload::.
  4752. `call-interactively'
  4753. See *note Interactive Call::.
  4754. `called-interactively-p'
  4755. See *note Distinguish Interactive::.
  4756. `commandp'
  4757. See *note Interactive Call::.
  4758. `documentation'
  4759. See *note Accessing Documentation::.
  4760. `eval'
  4761. See *note Eval::.
  4762. `funcall'
  4763. See *note Calling Functions::.
  4764. `function'
  4765. See *note Anonymous Functions::.
  4766. `ignore'
  4767. See *note Calling Functions::.
  4768. `indirect-function'
  4769. See *note Function Indirection::.
  4770. `interactive'
  4771. See *note Using Interactive::.
  4772. `interactive-p'
  4773. See *note Distinguish Interactive::.
  4774. `mapatoms'
  4775. See *note Creating Symbols::.
  4776. `mapcar'
  4777. See *note Mapping Functions::.
  4778. `map-char-table'
  4779. See *note Char-Tables::.
  4780. `mapconcat'
  4781. See *note Mapping Functions::.
  4782. `undefined'
  4783. See *note Functions for Key Lookup::.
  4784. 
  4785. File: elisp, Node: Macros, Next: Customization, Prev: Functions, Up: Top
  4786. 13 Macros
  4787. *********
  4788. "Macros" enable you to define new control constructs and other language
  4789. features. A macro is defined much like a function, but instead of
  4790. telling how to compute a value, it tells how to compute another Lisp
  4791. expression which will in turn compute the value. We call this
  4792. expression the "expansion" of the macro.
  4793. Macros can do this because they operate on the unevaluated
  4794. expressions for the arguments, not on the argument values as functions
  4795. do. They can therefore construct an expansion containing these
  4796. argument expressions or parts of them.
  4797. If you are using a macro to do something an ordinary function could
  4798. do, just for the sake of speed, consider using an inline function
  4799. instead. *Note Inline Functions::.
  4800. * Menu:
  4801. * Simple Macro:: A basic example.
  4802. * Expansion:: How, when and why macros are expanded.
  4803. * Compiling Macros:: How macros are expanded by the compiler.
  4804. * Defining Macros:: How to write a macro definition.
  4805. * Problems with Macros:: Don't evaluate the macro arguments too many times.
  4806. Don't hide the user's variables.
  4807. * Indenting Macros:: Specifying how to indent macro calls.
  4808. 
  4809. File: elisp, Node: Simple Macro, Next: Expansion, Up: Macros
  4810. 13.1 A Simple Example of a Macro
  4811. ================================
  4812. Suppose we would like to define a Lisp construct to increment a
  4813. variable value, much like the `++' operator in C. We would like to
  4814. write `(inc x)' and have the effect of `(setq x (1+ x))'. Here's a
  4815. macro definition that does the job:
  4816. (defmacro inc (var)
  4817. (list 'setq var (list '1+ var)))
  4818. When this is called with `(inc x)', the argument VAR is the symbol
  4819. `x'--_not_ the _value_ of `x', as it would be in a function. The body
  4820. of the macro uses this to construct the expansion, which is `(setq x
  4821. (1+ x))'. Once the macro definition returns this expansion, Lisp
  4822. proceeds to evaluate it, thus incrementing `x'.
  4823. 
  4824. File: elisp, Node: Expansion, Next: Compiling Macros, Prev: Simple Macro, Up: Macros
  4825. 13.2 Expansion of a Macro Call
  4826. ==============================
  4827. A macro call looks just like a function call in that it is a list which
  4828. starts with the name of the macro. The rest of the elements of the list
  4829. are the arguments of the macro.
  4830. Evaluation of the macro call begins like evaluation of a function
  4831. call except for one crucial difference: the macro arguments are the
  4832. actual expressions appearing in the macro call. They are not evaluated
  4833. before they are given to the macro definition. By contrast, the
  4834. arguments of a function are results of evaluating the elements of the
  4835. function call list.
  4836. Having obtained the arguments, Lisp invokes the macro definition just
  4837. as a function is invoked. The argument variables of the macro are bound
  4838. to the argument values from the macro call, or to a list of them in the
  4839. case of a `&rest' argument. And the macro body executes and returns
  4840. its value just as a function body does.
  4841. The second crucial difference between macros and functions is that
  4842. the value returned by the macro body is an alternate Lisp expression,
  4843. also known as the "expansion" of the macro. The Lisp interpreter
  4844. proceeds to evaluate the expansion as soon as it comes back from the
  4845. macro.
  4846. Since the expansion is evaluated in the normal manner, it may contain
  4847. calls to other macros. It may even be a call to the same macro, though
  4848. this is unusual.
  4849. You can see the expansion of a given macro call by calling
  4850. `macroexpand'.
  4851. -- Function: macroexpand form &optional environment
  4852. This function expands FORM, if it is a macro call. If the result
  4853. is another macro call, it is expanded in turn, until something
  4854. which is not a macro call results. That is the value returned by
  4855. `macroexpand'. If FORM is not a macro call to begin with, it is
  4856. returned as given.
  4857. Note that `macroexpand' does not look at the subexpressions of
  4858. FORM (although some macro definitions may do so). Even if they
  4859. are macro calls themselves, `macroexpand' does not expand them.
  4860. The function `macroexpand' does not expand calls to inline
  4861. functions. Normally there is no need for that, since a call to an
  4862. inline function is no harder to understand than a call to an
  4863. ordinary function.
  4864. If ENVIRONMENT is provided, it specifies an alist of macro
  4865. definitions that shadow the currently defined macros. Byte
  4866. compilation uses this feature.
  4867. (defmacro inc (var)
  4868. (list 'setq var (list '1+ var)))
  4869. => inc
  4870. (macroexpand '(inc r))
  4871. => (setq r (1+ r))
  4872. (defmacro inc2 (var1 var2)
  4873. (list 'progn (list 'inc var1) (list 'inc var2)))
  4874. => inc2
  4875. (macroexpand '(inc2 r s))
  4876. => (progn (inc r) (inc s)) ; `inc' not expanded here.
  4877. -- Function: macroexpand-all form &optional environment
  4878. `macroexpand-all' expands macros like `macroexpand', but will look
  4879. for and expand all macros in FORM, not just at the top-level. If
  4880. no macros are expanded, the return value is `eq' to FORM.
  4881. Repeating the example used for `macroexpand' above with
  4882. `macroexpand-all', we see that `macroexpand-all' _does_ expand the
  4883. embedded calls to `inc':
  4884. (macroexpand-all '(inc2 r s))
  4885. => (progn (setq r (1+ r)) (setq s (1+ s)))
  4886. 
  4887. File: elisp, Node: Compiling Macros, Next: Defining Macros, Prev: Expansion, Up: Macros
  4888. 13.3 Macros and Byte Compilation
  4889. ================================
  4890. You might ask why we take the trouble to compute an expansion for a
  4891. macro and then evaluate the expansion. Why not have the macro body
  4892. produce the desired results directly? The reason has to do with
  4893. compilation.
  4894. When a macro call appears in a Lisp program being compiled, the Lisp
  4895. compiler calls the macro definition just as the interpreter would, and
  4896. receives an expansion. But instead of evaluating this expansion, it
  4897. compiles the expansion as if it had appeared directly in the program.
  4898. As a result, the compiled code produces the value and side effects
  4899. intended for the macro, but executes at full compiled speed. This would
  4900. not work if the macro body computed the value and side effects
  4901. itself--they would be computed at compile time, which is not useful.
  4902. In order for compilation of macro calls to work, the macros must
  4903. already be defined in Lisp when the calls to them are compiled. The
  4904. compiler has a special feature to help you do this: if a file being
  4905. compiled contains a `defmacro' form, the macro is defined temporarily
  4906. for the rest of the compilation of that file.
  4907. Byte-compiling a file also executes any `require' calls at top-level
  4908. in the file, so you can ensure that necessary macro definitions are
  4909. available during compilation by requiring the files that define them
  4910. (*note Named Features::). To avoid loading the macro definition files
  4911. when someone _runs_ the compiled program, write `eval-when-compile'
  4912. around the `require' calls (*note Eval During Compile::).
  4913. 
  4914. File: elisp, Node: Defining Macros, Next: Problems with Macros, Prev: Compiling Macros, Up: Macros
  4915. 13.4 Defining Macros
  4916. ====================
  4917. A Lisp macro is a list whose CAR is `macro'. Its CDR should be a
  4918. function; expansion of the macro works by applying the function (with
  4919. `apply') to the list of unevaluated argument-expressions from the macro
  4920. call.
  4921. It is possible to use an anonymous Lisp macro just like an anonymous
  4922. function, but this is never done, because it does not make sense to pass
  4923. an anonymous macro to functionals such as `mapcar'. In practice, all
  4924. Lisp macros have names, and they are usually defined with the special
  4925. form `defmacro'.
  4926. -- Special Form: defmacro name argument-list body-forms...
  4927. `defmacro' defines the symbol NAME as a macro that looks like this:
  4928. (macro lambda ARGUMENT-LIST . BODY-FORMS)
  4929. (Note that the CDR of this list is a function--a lambda
  4930. expression.) This macro object is stored in the function cell of
  4931. NAME. The value returned by evaluating the `defmacro' form is
  4932. NAME, but usually we ignore this value.
  4933. The shape and meaning of ARGUMENT-LIST is the same as in a
  4934. function, and the keywords `&rest' and `&optional' may be used
  4935. (*note Argument List::). Macros may have a documentation string,
  4936. but any `interactive' declaration is ignored since macros cannot be
  4937. called interactively.
  4938. Macros often need to construct large list structures from a mixture
  4939. of constants and nonconstant parts. To make this easier, use the ``'
  4940. syntax (*note Backquote::). For example:
  4941. (defmacro t-becomes-nil (variable)
  4942. `(if (eq ,variable t)
  4943. (setq ,variable nil)))
  4944. (t-becomes-nil foo)
  4945. == (if (eq foo t) (setq foo nil))
  4946. The body of a macro definition can include a `declare' form, which
  4947. can specify how <TAB> should indent macro calls, and how to step
  4948. through them for Edebug.
  4949. -- Macro: declare SPECS...
  4950. A `declare' form is used in a macro definition to specify various
  4951. additional information about it. The following specifications are
  4952. currently supported:
  4953. `(debug EDEBUG-FORM-SPEC)'
  4954. Specify how to step through macro calls for Edebug. *Note
  4955. Instrumenting Macro Calls::.
  4956. `(indent INDENT-SPEC)'
  4957. Specify how to indent calls to this macro. *Note Indenting
  4958. Macros::, for more details.
  4959. `(doc-string NUMBER)'
  4960. Specify which element of the macro is the documentation
  4961. string, if any.
  4962. A `declare' form only has its special effect in the body of a
  4963. `defmacro' form if it immediately follows the documentation
  4964. string, if present, or the argument list otherwise. (Strictly
  4965. speaking, _several_ `declare' forms can follow the documentation
  4966. string or argument list, but since a `declare' form can have
  4967. several SPECS, they can always be combined into a single form.)
  4968. When used at other places in a `defmacro' form, or outside a
  4969. `defmacro' form, `declare' just returns `nil' without evaluating
  4970. any SPECS.
  4971. No macro absolutely needs a `declare' form, because that form has no
  4972. effect on how the macro expands, on what the macro means in the
  4973. program. It only affects the secondary features listed above.
  4974. 
  4975. File: elisp, Node: Problems with Macros, Next: Indenting Macros, Prev: Defining Macros, Up: Macros
  4976. 13.5 Common Problems Using Macros
  4977. =================================
  4978. Macro expansion can have counterintuitive consequences. This section
  4979. describes some important consequences that can lead to trouble, and
  4980. rules to follow to avoid trouble.
  4981. * Menu:
  4982. * Wrong Time:: Do the work in the expansion, not in the macro.
  4983. * Argument Evaluation:: The expansion should evaluate each macro arg once.
  4984. * Surprising Local Vars:: Local variable bindings in the expansion
  4985. require special care.
  4986. * Eval During Expansion:: Don't evaluate them; put them in the expansion.
  4987. * Repeated Expansion:: Avoid depending on how many times expansion is done.
  4988. 
  4989. File: elisp, Node: Wrong Time, Next: Argument Evaluation, Up: Problems with Macros
  4990. 13.5.1 Wrong Time
  4991. -----------------
  4992. The most common problem in writing macros is doing some of the real
  4993. work prematurely--while expanding the macro, rather than in the
  4994. expansion itself. For instance, one real package had this macro
  4995. definition:
  4996. (defmacro my-set-buffer-multibyte (arg)
  4997. (if (fboundp 'set-buffer-multibyte)
  4998. (set-buffer-multibyte arg)))
  4999. With this erroneous macro definition, the program worked fine when
  5000. interpreted but failed when compiled. This macro definition called
  5001. `set-buffer-multibyte' during compilation, which was wrong, and then
  5002. did nothing when the compiled package was run. The definition that the
  5003. programmer really wanted was this:
  5004. (defmacro my-set-buffer-multibyte (arg)
  5005. (if (fboundp 'set-buffer-multibyte)
  5006. `(set-buffer-multibyte ,arg)))
  5007. This macro expands, if appropriate, into a call to
  5008. `set-buffer-multibyte' that will be executed when the compiled program
  5009. is actually run.
  5010. 
  5011. File: elisp, Node: Argument Evaluation, Next: Surprising Local Vars, Prev: Wrong Time, Up: Problems with Macros
  5012. 13.5.2 Evaluating Macro Arguments Repeatedly
  5013. --------------------------------------------
  5014. When defining a macro you must pay attention to the number of times the
  5015. arguments will be evaluated when the expansion is executed. The
  5016. following macro (used to facilitate iteration) illustrates the problem.
  5017. This macro allows us to write a "for" loop construct.
  5018. (defmacro for (var from init to final do &rest body)
  5019. "Execute a simple \"for\" loop.
  5020. For example, (for i from 1 to 10 do (print i))."
  5021. (list 'let (list (list var init))
  5022. (cons 'while
  5023. (cons (list '<= var final)
  5024. (append body (list (list 'inc var)))))))
  5025. => for
  5026. (for i from 1 to 3 do
  5027. (setq square (* i i))
  5028. (princ (format "\n%d %d" i square)))
  5029. ==>
  5030. (let ((i 1))
  5031. (while (<= i 3)
  5032. (setq square (* i i))
  5033. (princ (format "\n%d %d" i square))
  5034. (inc i)))
  5035. -|1 1
  5036. -|2 4
  5037. -|3 9
  5038. => nil
  5039. The arguments `from', `to', and `do' in this macro are "syntactic
  5040. sugar"; they are entirely ignored. The idea is that you will write
  5041. noise words (such as `from', `to', and `do') in those positions in the
  5042. macro call.
  5043. Here's an equivalent definition simplified through use of backquote:
  5044. (defmacro for (var from init to final do &rest body)
  5045. "Execute a simple \"for\" loop.
  5046. For example, (for i from 1 to 10 do (print i))."
  5047. `(let ((,var ,init))
  5048. (while (<= ,var ,final)
  5049. ,@body
  5050. (inc ,var))))
  5051. Both forms of this definition (with backquote and without) suffer
  5052. from the defect that FINAL is evaluated on every iteration. If FINAL
  5053. is a constant, this is not a problem. If it is a more complex form,
  5054. say `(long-complex-calculation x)', this can slow down the execution
  5055. significantly. If FINAL has side effects, executing it more than once
  5056. is probably incorrect.
  5057. A well-designed macro definition takes steps to avoid this problem by
  5058. producing an expansion that evaluates the argument expressions exactly
  5059. once unless repeated evaluation is part of the intended purpose of the
  5060. macro. Here is a correct expansion for the `for' macro:
  5061. (let ((i 1)
  5062. (max 3))
  5063. (while (<= i max)
  5064. (setq square (* i i))
  5065. (princ (format "%d %d" i square))
  5066. (inc i)))
  5067. Here is a macro definition that creates this expansion:
  5068. (defmacro for (var from init to final do &rest body)
  5069. "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  5070. `(let ((,var ,init)
  5071. (max ,final))
  5072. (while (<= ,var max)
  5073. ,@body
  5074. (inc ,var))))
  5075. Unfortunately, this fix introduces another problem, described in the
  5076. following section.
  5077. 
  5078. File: elisp, Node: Surprising Local Vars, Next: Eval During Expansion, Prev: Argument Evaluation, Up: Problems with Macros
  5079. 13.5.3 Local Variables in Macro Expansions
  5080. ------------------------------------------
  5081. In the previous section, the definition of `for' was fixed as follows
  5082. to make the expansion evaluate the macro arguments the proper number of
  5083. times:
  5084. (defmacro for (var from init to final do &rest body)
  5085. "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  5086. `(let ((,var ,init)
  5087. (max ,final))
  5088. (while (<= ,var max)
  5089. ,@body
  5090. (inc ,var))))
  5091. The new definition of `for' has a new problem: it introduces a local
  5092. variable named `max' which the user does not expect. This causes
  5093. trouble in examples such as the following:
  5094. (let ((max 0))
  5095. (for x from 0 to 10 do
  5096. (let ((this (frob x)))
  5097. (if (< max this)
  5098. (setq max this)))))
  5099. The references to `max' inside the body of the `for', which are
  5100. supposed to refer to the user's binding of `max', really access the
  5101. binding made by `for'.
  5102. The way to correct this is to use an uninterned symbol instead of
  5103. `max' (*note Creating Symbols::). The uninterned symbol can be bound
  5104. and referred to just like any other symbol, but since it is created by
  5105. `for', we know that it cannot already appear in the user's program.
  5106. Since it is not interned, there is no way the user can put it into the
  5107. program later. It will never appear anywhere except where put by
  5108. `for'. Here is a definition of `for' that works this way:
  5109. (defmacro for (var from init to final do &rest body)
  5110. "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  5111. (let ((tempvar (make-symbol "max")))
  5112. `(let ((,var ,init)
  5113. (,tempvar ,final))
  5114. (while (<= ,var ,tempvar)
  5115. ,@body
  5116. (inc ,var)))))
  5117. This creates an uninterned symbol named `max' and puts it in the
  5118. expansion instead of the usual interned symbol `max' that appears in
  5119. expressions ordinarily.
  5120. 
  5121. File: elisp, Node: Eval During Expansion, Next: Repeated Expansion, Prev: Surprising Local Vars, Up: Problems with Macros
  5122. 13.5.4 Evaluating Macro Arguments in Expansion
  5123. ----------------------------------------------
  5124. Another problem can happen if the macro definition itself evaluates any
  5125. of the macro argument expressions, such as by calling `eval' (*note
  5126. Eval::). If the argument is supposed to refer to the user's variables,
  5127. you may have trouble if the user happens to use a variable with the
  5128. same name as one of the macro arguments. Inside the macro body, the
  5129. macro argument binding is the most local binding of this variable, so
  5130. any references inside the form being evaluated do refer to it. Here is
  5131. an example:
  5132. (defmacro foo (a)
  5133. (list 'setq (eval a) t))
  5134. => foo
  5135. (setq x 'b)
  5136. (foo x) ==> (setq b t)
  5137. => t ; and `b' has been set.
  5138. ;; but
  5139. (setq a 'c)
  5140. (foo a) ==> (setq a t)
  5141. => t ; but this set `a', not `c'.
  5142. It makes a difference whether the user's variable is named `a' or
  5143. `x', because `a' conflicts with the macro argument variable `a'.
  5144. Another problem with calling `eval' in a macro definition is that it
  5145. probably won't do what you intend in a compiled program. The byte
  5146. compiler runs macro definitions while compiling the program, when the
  5147. program's own computations (which you might have wished to access with
  5148. `eval') don't occur and its local variable bindings don't exist.
  5149. To avoid these problems, *don't evaluate an argument expression
  5150. while computing the macro expansion*. Instead, substitute the
  5151. expression into the macro expansion, so that its value will be computed
  5152. as part of executing the expansion. This is how the other examples in
  5153. this chapter work.
  5154. 
  5155. File: elisp, Node: Repeated Expansion, Prev: Eval During Expansion, Up: Problems with Macros
  5156. 13.5.5 How Many Times is the Macro Expanded?
  5157. --------------------------------------------
  5158. Occasionally problems result from the fact that a macro call is
  5159. expanded each time it is evaluated in an interpreted function, but is
  5160. expanded only once (during compilation) for a compiled function. If the
  5161. macro definition has side effects, they will work differently depending
  5162. on how many times the macro is expanded.
  5163. Therefore, you should avoid side effects in computation of the macro
  5164. expansion, unless you really know what you are doing.
  5165. One special kind of side effect can't be avoided: constructing Lisp
  5166. objects. Almost all macro expansions include constructed lists; that is
  5167. the whole point of most macros. This is usually safe; there is just one
  5168. case where you must be careful: when the object you construct is part
  5169. of a quoted constant in the macro expansion.
  5170. If the macro is expanded just once, in compilation, then the object
  5171. is constructed just once, during compilation. But in interpreted
  5172. execution, the macro is expanded each time the macro call runs, and this
  5173. means a new object is constructed each time.
  5174. In most clean Lisp code, this difference won't matter. It can matter
  5175. only if you perform side-effects on the objects constructed by the macro
  5176. definition. Thus, to avoid trouble, *avoid side effects on objects
  5177. constructed by macro definitions*. Here is an example of how such side
  5178. effects can get you into trouble:
  5179. (defmacro empty-object ()
  5180. (list 'quote (cons nil nil)))
  5181. (defun initialize (condition)
  5182. (let ((object (empty-object)))
  5183. (if condition
  5184. (setcar object condition))
  5185. object))
  5186. If `initialize' is interpreted, a new list `(nil)' is constructed each
  5187. time `initialize' is called. Thus, no side effect survives between
  5188. calls. If `initialize' is compiled, then the macro `empty-object' is
  5189. expanded during compilation, producing a single "constant" `(nil)' that
  5190. is reused and altered each time `initialize' is called.
  5191. One way to avoid pathological cases like this is to think of
  5192. `empty-object' as a funny kind of constant, not as a memory allocation
  5193. construct. You wouldn't use `setcar' on a constant such as `'(nil)',
  5194. so naturally you won't use it on `(empty-object)' either.
  5195. 
  5196. File: elisp, Node: Indenting Macros, Prev: Problems with Macros, Up: Macros
  5197. 13.6 Indenting Macros
  5198. =====================
  5199. Within a macro definition, you can use the `declare' form (*note
  5200. Defining Macros::) to specify how <TAB> should indent calls to the
  5201. macro. An indentation specification is written like this:
  5202. (declare (indent INDENT-SPEC))
  5203. Here are the possibilities for INDENT-SPEC:
  5204. `nil'
  5205. This is the same as no property--use the standard indentation
  5206. pattern.
  5207. `defun'
  5208. Handle this function like a `def' construct: treat the second line
  5209. as the start of a "body".
  5210. an integer, NUMBER
  5211. The first NUMBER arguments of the function are "distinguished"
  5212. arguments; the rest are considered the body of the expression. A
  5213. line in the expression is indented according to whether the first
  5214. argument on it is distinguished or not. If the argument is part
  5215. of the body, the line is indented `lisp-body-indent' more columns
  5216. than the open-parenthesis starting the containing expression. If
  5217. the argument is distinguished and is either the first or second
  5218. argument, it is indented _twice_ that many extra columns. If the
  5219. argument is distinguished and not the first or second argument,
  5220. the line uses the standard pattern.
  5221. a symbol, SYMBOL
  5222. SYMBOL should be a function name; that function is called to
  5223. calculate the indentation of a line within this expression. The
  5224. function receives two arguments:
  5225. STATE
  5226. The value returned by `parse-partial-sexp' (a Lisp primitive
  5227. for indentation and nesting computation) when it parses up to
  5228. the beginning of this line.
  5229. POS
  5230. The position at which the line being indented begins.
  5231. It should return either a number, which is the number of columns of
  5232. indentation for that line, or a list whose car is such a number.
  5233. The difference between returning a number and returning a list is
  5234. that a number says that all following lines at the same nesting
  5235. level should be indented just like this one; a list says that
  5236. following lines might call for different indentations. This makes
  5237. a difference when the indentation is being computed by `C-M-q'; if
  5238. the value is a number, `C-M-q' need not recalculate indentation
  5239. for the following lines until the end of the list.
  5240. 
  5241. File: elisp, Node: Customization, Next: Loading, Prev: Macros, Up: Top
  5242. 14 Customization Settings
  5243. *************************
  5244. This chapter describes how to declare customizable variables and
  5245. customization groups for classifying them. We use the term
  5246. "customization item" to include customizable variables, customization
  5247. groups, as well as faces.
  5248. *Note Defining Faces::, for the `defface' macro, which is used for
  5249. declaring customizable faces.
  5250. * Menu:
  5251. * Common Keywords:: Common keyword arguments for all kinds of
  5252. customization declarations.
  5253. * Group Definitions:: Writing customization group definitions.
  5254. * Variable Definitions:: Declaring user options.
  5255. * Customization Types:: Specifying the type of a user option.
  5256. * Applying Customizations:: Functions to apply customization settings.
  5257. * Custom Themes:: Writing Custom themes.
  5258. 
  5259. File: elisp, Node: Common Keywords, Next: Group Definitions, Up: Customization
  5260. 14.1 Common Item Keywords
  5261. =========================
  5262. The customization declarations that we will describe in the next few
  5263. sections (`defcustom', `defgroup', etc.) all accept keyword arguments
  5264. for specifying various information. This section describes keywords
  5265. that apply to all types of customization declarations.
  5266. All of these keywords, except `:tag', can be used more than once in
  5267. a given item. Each use of the keyword has an independent effect. The
  5268. keyword `:tag' is an exception because any given item can only display
  5269. one name.
  5270. `:tag LABEL'
  5271. Use LABEL, a string, instead of the item's name, to label the item
  5272. in customization menus and buffers. *Don't use a tag which is
  5273. substantially different from the item's real name; that would
  5274. cause confusion.*
  5275. `:group GROUP'
  5276. Put this customization item in group GROUP. When you use `:group'
  5277. in a `defgroup', it makes the new group a subgroup of GROUP.
  5278. If you use this keyword more than once, you can put a single item
  5279. into more than one group. Displaying any of those groups will
  5280. show this item. Please don't overdo this, since the result would
  5281. be annoying.
  5282. `:link LINK-DATA'
  5283. Include an external link after the documentation string for this
  5284. item. This is a sentence containing an active field which
  5285. references some other documentation.
  5286. There are several alternatives you can use for LINK-DATA:
  5287. `(custom-manual INFO-NODE)'
  5288. Link to an Info node; INFO-NODE is a string which specifies
  5289. the node name, as in `"(emacs)Top"'. The link appears as
  5290. `[Manual]' in the customization buffer and enters the built-in
  5291. Info reader on INFO-NODE.
  5292. `(info-link INFO-NODE)'
  5293. Like `custom-manual' except that the link appears in the
  5294. customization buffer with the Info node name.
  5295. `(url-link URL)'
  5296. Link to a web page; URL is a string which specifies the URL.
  5297. The link appears in the customization buffer as URL and
  5298. invokes the WWW browser specified by
  5299. `browse-url-browser-function'.
  5300. `(emacs-commentary-link LIBRARY)'
  5301. Link to the commentary section of a library; LIBRARY is a
  5302. string which specifies the library name.
  5303. `(emacs-library-link LIBRARY)'
  5304. Link to an Emacs Lisp library file; LIBRARY is a string which
  5305. specifies the library name.
  5306. `(file-link FILE)'
  5307. Link to a file; FILE is a string which specifies the name of
  5308. the file to visit with `find-file' when the user invokes this
  5309. link.
  5310. `(function-link FUNCTION)'
  5311. Link to the documentation of a function; FUNCTION is a string
  5312. which specifies the name of the function to describe with
  5313. `describe-function' when the user invokes this link.
  5314. `(variable-link VARIABLE)'
  5315. Link to the documentation of a variable; VARIABLE is a string
  5316. which specifies the name of the variable to describe with
  5317. `describe-variable' when the user invokes this link.
  5318. `(custom-group-link GROUP)'
  5319. Link to another customization group. Invoking it creates a
  5320. new customization buffer for GROUP.
  5321. You can specify the text to use in the customization buffer by
  5322. adding `:tag NAME' after the first element of the LINK-DATA; for
  5323. example, `(info-link :tag "foo" "(emacs)Top")' makes a link to the
  5324. Emacs manual which appears in the buffer as `foo'.
  5325. You can use this keyword more than once, to add multiple links.
  5326. `:load FILE'
  5327. Load file FILE (a string) before displaying this customization
  5328. item (*note Loading::). Loading is done with `load', and only if
  5329. the file is not already loaded.
  5330. `:require FEATURE'
  5331. Execute `(require 'FEATURE)' when your saved customizations set
  5332. the value of this item. FEATURE should be a symbol.
  5333. The most common reason to use `:require' is when a variable enables
  5334. a feature such as a minor mode, and just setting the variable
  5335. won't have any effect unless the code which implements the mode is
  5336. loaded.
  5337. `:version VERSION'
  5338. This keyword specifies that the item was first introduced in Emacs
  5339. version VERSION, or that its default value was changed in that
  5340. version. The value VERSION must be a string.
  5341. `:package-version '(PACKAGE . VERSION)'
  5342. This keyword specifies that the item was first introduced in
  5343. PACKAGE version VERSION, or that its meaning or default value was
  5344. changed in that version. This keyword takes priority over
  5345. `:version'.
  5346. PACKAGE should be the official name of the package, as a symbol
  5347. (e.g. `MH-E'). VERSION should be a string. If the package
  5348. PACKAGE is released as part of Emacs, PACKAGE and VERSION should
  5349. appear in the value of `customize-package-emacs-version-alist'.
  5350. Packages distributed as part of Emacs that use the
  5351. `:package-version' keyword must also update the
  5352. `customize-package-emacs-version-alist' variable.
  5353. -- Variable: customize-package-emacs-version-alist
  5354. This alist provides a mapping for the versions of Emacs that are
  5355. associated with versions of a package listed in the
  5356. `:package-version' keyword. Its elements are:
  5357. (PACKAGE (PVERSION . EVERSION)...)
  5358. For each PACKAGE, which is a symbol, there are one or more
  5359. elements that contain a package version PVERSION with an
  5360. associated Emacs version EVERSION. These versions are strings.
  5361. For example, the MH-E package updates this alist with the
  5362. following:
  5363. (add-to-list 'customize-package-emacs-version-alist
  5364. '(MH-E ("6.0" . "22.1") ("6.1" . "22.1") ("7.0" . "22.1")
  5365. ("7.1" . "22.1") ("7.2" . "22.1") ("7.3" . "22.1")
  5366. ("7.4" . "22.1") ("8.0" . "22.1")))
  5367. The value of PACKAGE needs to be unique and it needs to match the
  5368. PACKAGE value appearing in the `:package-version' keyword. Since
  5369. the user might see the value in an error message, a good choice is
  5370. the official name of the package, such as MH-E or Gnus.
  5371. 
  5372. File: elisp, Node: Group Definitions, Next: Variable Definitions, Prev: Common Keywords, Up: Customization
  5373. 14.2 Defining Customization Groups
  5374. ==================================
  5375. Each Emacs Lisp package should have one main customization group which
  5376. contains all the options, faces and other groups in the package. If the
  5377. package has a small number of options and faces, use just one group and
  5378. put everything in it. When there are more than twelve or so options and
  5379. faces, then you should structure them into subgroups, and put the
  5380. subgroups under the package's main customization group. It is OK to
  5381. put some of the options and faces in the package's main group alongside
  5382. the subgroups.
  5383. The package's main or only group should be a member of one or more of
  5384. the standard customization groups. (To display the full list of them,
  5385. use `M-x customize'.) Choose one or more of them (but not too many),
  5386. and add your group to each of them using the `:group' keyword.
  5387. The way to declare new customization groups is with `defgroup'.
  5388. -- Macro: defgroup group members doc [keyword value]...
  5389. Declare GROUP as a customization group containing MEMBERS. Do not
  5390. quote the symbol GROUP. The argument DOC specifies the
  5391. documentation string for the group.
  5392. The argument MEMBERS is a list specifying an initial set of
  5393. customization items to be members of the group. However, most
  5394. often MEMBERS is `nil', and you specify the group's members by
  5395. using the `:group' keyword when defining those members.
  5396. If you want to specify group members through MEMBERS, each element
  5397. should have the form `(NAME WIDGET)'. Here NAME is a symbol, and
  5398. WIDGET is a widget type for editing that symbol. Useful widgets
  5399. are `custom-variable' for a variable, `custom-face' for a face,
  5400. and `custom-group' for a group.
  5401. When you introduce a new group into Emacs, use the `:version'
  5402. keyword in the `defgroup'; then you need not use it for the
  5403. individual members of the group.
  5404. In addition to the common keywords (*note Common Keywords::), you
  5405. can also use this keyword in `defgroup':
  5406. `:prefix PREFIX'
  5407. If the name of an item in the group starts with PREFIX, and
  5408. the customizable variable `custom-unlispify-remove-prefixes'
  5409. is non-`nil', the item's tag will omit PREFIX. A group can
  5410. have any number of prefixes.
  5411. -- User Option: custom-unlispify-remove-prefixes
  5412. If this variable is non-`nil', the prefixes specified by a group's
  5413. `:prefix' keyword are omitted from tag names, whenever the user
  5414. customizes the group.
  5415. The default value is `nil', i.e. the prefix-discarding feature is
  5416. disabled. This is because discarding prefixes often leads to
  5417. confusing names for options and faces.
  5418. 
  5419. File: elisp, Node: Variable Definitions, Next: Customization Types, Prev: Group Definitions, Up: Customization
  5420. 14.3 Defining Customization Variables
  5421. =====================================
  5422. -- Macro: defcustom option standard doc [keyword value]...
  5423. This macro declares OPTION as a user option (i.e. a customizable
  5424. variable). You should not quote OPTION.
  5425. The argument STANDARD is an expression that specifies the standard
  5426. value for OPTION. Evaluating the `defcustom' form evaluates
  5427. STANDARD, but does not necessarily install the standard value. If
  5428. OPTION already has a default value, `defcustom' does not change
  5429. it. If the user has saved a customization for OPTION, `defcustom'
  5430. installs the user's customized value as OPTION's default value.
  5431. If neither of those cases applies, `defcustom' installs the result
  5432. of evaluating STANDARD as the default value.
  5433. The expression STANDARD can be evaluated at various other times,
  5434. too--whenever the customization facility needs to know OPTION's
  5435. standard value. So be sure to use an expression which is harmless
  5436. to evaluate at any time.
  5437. The argument DOC specifies the documentation string for the
  5438. variable.
  5439. Every `defcustom' should specify `:group' at least once.
  5440. When you evaluate a `defcustom' form with `C-M-x' in Emacs Lisp
  5441. mode (`eval-defun'), a special feature of `eval-defun' arranges to
  5442. set the variable unconditionally, without testing whether its
  5443. value is void. (The same feature applies to `defvar'.) *Note
  5444. Defining Variables::.
  5445. If you put a `defcustom' in a pre-loaded Emacs Lisp file (*note
  5446. Building Emacs::), the standard value installed at dump time might
  5447. be incorrect, e.g. because another variable that it depends on has
  5448. not been assigned the right value yet. In that case, use
  5449. `custom-reevaluate-setting', described below, to re-evaluate the
  5450. standard value after Emacs starts up.
  5451. `defcustom' accepts the following additional keywords:
  5452. `:type TYPE'
  5453. Use TYPE as the data type for this option. It specifies which
  5454. values are legitimate, and how to display the value. *Note
  5455. Customization Types::, for more information.
  5456. `:options VALUE-LIST'
  5457. Specify the list of reasonable values for use in this option. The
  5458. user is not restricted to using only these values, but they are
  5459. offered as convenient alternatives.
  5460. This is meaningful only for certain types, currently including
  5461. `hook', `plist' and `alist'. See the definition of the individual
  5462. types for a description of how to use `:options'.
  5463. `:set SETFUNCTION'
  5464. Specify SETFUNCTION as the way to change the value of this option
  5465. when using the Customize interface. The function SETFUNCTION
  5466. should take two arguments, a symbol (the option name) and the new
  5467. value, and should do whatever is necessary to update the value
  5468. properly for this option (which may not mean simply setting the
  5469. option as a Lisp variable). The default for SETFUNCTION is
  5470. `set-default'.
  5471. If you specify this keyword, the variable's documentation string
  5472. should describe how to do the same job in hand-written Lisp code.
  5473. `:get GETFUNCTION'
  5474. Specify GETFUNCTION as the way to extract the value of this
  5475. option. The function GETFUNCTION should take one argument, a
  5476. symbol, and should return whatever customize should use as the
  5477. "current value" for that symbol (which need not be the symbol's
  5478. Lisp value). The default is `default-value'.
  5479. You have to really understand the workings of Custom to use `:get'
  5480. correctly. It is meant for values that are treated in Custom as
  5481. variables but are not actually stored in Lisp variables. It is
  5482. almost surely a mistake to specify GETFUNCTION for a value that
  5483. really is stored in a Lisp variable.
  5484. `:initialize FUNCTION'
  5485. FUNCTION should be a function used to initialize the variable when
  5486. the `defcustom' is evaluated. It should take two arguments, the
  5487. option name (a symbol) and the value. Here are some predefined
  5488. functions meant for use in this way:
  5489. `custom-initialize-set'
  5490. Use the variable's `:set' function to initialize the
  5491. variable, but do not reinitialize it if it is already
  5492. non-void.
  5493. `custom-initialize-default'
  5494. Like `custom-initialize-set', but use the function
  5495. `set-default' to set the variable, instead of the variable's
  5496. `:set' function. This is the usual choice for a variable
  5497. whose `:set' function enables or disables a minor mode; with
  5498. this choice, defining the variable will not call the minor
  5499. mode function, but customizing the variable will do so.
  5500. `custom-initialize-reset'
  5501. Always use the `:set' function to initialize the variable. If
  5502. the variable is already non-void, reset it by calling the
  5503. `:set' function using the current value (returned by the
  5504. `:get' method). This is the default `:initialize' function.
  5505. `custom-initialize-changed'
  5506. Use the `:set' function to initialize the variable, if it is
  5507. already set or has been customized; otherwise, just use
  5508. `set-default'.
  5509. `custom-initialize-safe-set'
  5510. `custom-initialize-safe-default'
  5511. These functions behave like `custom-initialize-set'
  5512. (`custom-initialize-default', respectively), but catch errors.
  5513. If an error occurs during initialization, they set the
  5514. variable to `nil' using `set-default', and signal no error.
  5515. These functions are meant for options defined in pre-loaded
  5516. files, where the STANDARD expression may signal an error
  5517. because some required variable or function is not yet
  5518. defined. The value normally gets updated in `startup.el',
  5519. ignoring the value computed by `defcustom'. After startup,
  5520. if one unsets the value and reevaluates the `defcustom', the
  5521. STANDARD expression can be evaluated without error.
  5522. `:risky VALUE'
  5523. Set the variable's `risky-local-variable' property to VALUE (*note
  5524. File Local Variables::).
  5525. `:safe FUNCTION'
  5526. Set the variable's `safe-local-variable' property to FUNCTION
  5527. (*note File Local Variables::).
  5528. `:set-after VARIABLES'
  5529. When setting variables according to saved customizations, make
  5530. sure to set the variables VARIABLES before this one; i.e., delay
  5531. setting this variable until after those others have been handled.
  5532. Use `:set-after' if setting this variable won't work properly
  5533. unless those other variables already have their intended values.
  5534. It is useful to specify the `:require' keyword for an option that
  5535. "turns on" a certain feature. This causes Emacs to load the feature,
  5536. if it is not already loaded, whenever the option is set. *Note Common
  5537. Keywords::. Here is an example, from the library `saveplace.el':
  5538. (defcustom save-place nil
  5539. "Non-nil means automatically save place in each file..."
  5540. :type 'boolean
  5541. :require 'saveplace
  5542. :group 'save-place)
  5543. If a customization item has a type such as `hook' or `alist', which
  5544. supports `:options', you can add additional values to the list from
  5545. outside the `defcustom' declaration by calling
  5546. `custom-add-frequent-value'. For example, if you define a function
  5547. `my-lisp-mode-initialization' intended to be called from
  5548. `emacs-lisp-mode-hook', you might want to add that to the list of
  5549. reasonable values for `emacs-lisp-mode-hook', but not by editing its
  5550. definition. You can do it thus:
  5551. (custom-add-frequent-value 'emacs-lisp-mode-hook
  5552. 'my-lisp-mode-initialization)
  5553. -- Function: custom-add-frequent-value symbol value
  5554. For the customization option SYMBOL, add VALUE to the list of
  5555. reasonable values.
  5556. The precise effect of adding a value depends on the customization
  5557. type of SYMBOL.
  5558. Internally, `defcustom' uses the symbol property `standard-value' to
  5559. record the expression for the standard value, `saved-value' to record
  5560. the value saved by the user with the customization buffer, and
  5561. `customized-value' to record the value set by the user with the
  5562. customization buffer, but not saved. *Note Property Lists::. These
  5563. properties are lists, the car of which is an expression that evaluates
  5564. to the value.
  5565. -- Function: custom-reevaluate-setting symbol
  5566. This function re-evaluates the standard value of SYMBOL, which
  5567. should be a user option declared via `defcustom'. If the variable
  5568. was customized, this function re-evaluates the saved value
  5569. instead. Then it sets the user option to that value (using the
  5570. option's `:set' property if that is defined).
  5571. This is useful for customizable options that are defined before
  5572. their value could be computed correctly. For example, during
  5573. startup Emacs calls this function for some user options that were
  5574. defined in pre-loaded Emacs Lisp files, but whose initial values
  5575. depend on information available only at run-time.
  5576. -- Function: custom-variable-p arg
  5577. This function returns non-`nil' if ARG is a customizable variable.
  5578. A customizable variable is either a variable that has a
  5579. `standard-value' or `custom-autoload' property (usually meaning it
  5580. was declared with `defcustom'), or an alias for another
  5581. customizable variable.
  5582. -- Function: user-variable-p arg
  5583. This function is like `custom-variable-p', except it also returns
  5584. `t' if the first character of the variable's documentation string
  5585. is the character `*'. That is an obsolete way of indicating a
  5586. user option, so for most purposes you may consider
  5587. `user-variable-p' as equivalent to `custom-variable-p'.
  5588. 
  5589. File: elisp, Node: Customization Types, Next: Applying Customizations, Prev: Variable Definitions, Up: Customization
  5590. 14.4 Customization Types
  5591. ========================
  5592. When you define a user option with `defcustom', you must specify its
  5593. "customization type". That is a Lisp object which describes (1) which
  5594. values are legitimate and (2) how to display the value in the
  5595. customization buffer for editing.
  5596. You specify the customization type in `defcustom' with the `:type'
  5597. keyword. The argument of `:type' is evaluated, but only once when the
  5598. `defcustom' is executed, so it isn't useful for the value to vary.
  5599. Normally we use a quoted constant. For example:
  5600. (defcustom diff-command "diff"
  5601. "The command to use to run diff."
  5602. :type '(string)
  5603. :group 'diff)
  5604. In general, a customization type is a list whose first element is a
  5605. symbol, one of the customization type names defined in the following
  5606. sections. After this symbol come a number of arguments, depending on
  5607. the symbol. Between the type symbol and its arguments, you can
  5608. optionally write keyword-value pairs (*note Type Keywords::).
  5609. Some type symbols do not use any arguments; those are called "simple
  5610. types". For a simple type, if you do not use any keyword-value pairs,
  5611. you can omit the parentheses around the type symbol. For example just
  5612. `string' as a customization type is equivalent to `(string)'.
  5613. All customization types are implemented as widgets; see *note
  5614. Introduction: (widget)Top, for details.
  5615. * Menu:
  5616. * Simple Types:: Simple customization types: sexp, integer, etc.
  5617. * Composite Types:: Build new types from other types or data.
  5618. * Splicing into Lists:: Splice elements into list with `:inline'.
  5619. * Type Keywords:: Keyword-argument pairs in a customization type.
  5620. * Defining New Types:: Give your type a name.
  5621. 
  5622. Local Variables:
  5623. coding: iso-8859-1
  5624. End: