1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129 |
- This is /home/cyd/emacs/doc/lispref/../../info/elisp, produced by
- makeinfo version 4.13 from /home/cyd/emacs/doc/lispref/elisp.texi.
- This is the `GNU Emacs Lisp Reference Manual' corresponding to Emacs
- version 24.2.
- Copyright (C) 1990-1996, 1998-2012 Free Software Foundation, Inc.
- Permission is granted to copy, distribute and/or modify this
- document under the terms of the GNU Free Documentation License,
- Version 1.3 or any later version published by the Free Software
- Foundation; with the Invariant Sections being "GNU General Public
- License," with the Front-Cover texts being "A GNU Manual," and
- with the Back-Cover Texts as in (a) below. A copy of the license
- is included in the section entitled "GNU Free Documentation
- License."
- (a) The FSF's Back-Cover Text is: "You have the freedom to copy and
- modify this GNU manual. Buying copies from the FSF supports it in
- developing GNU and promoting software freedom."
- INFO-DIR-SECTION GNU Emacs Lisp
- START-INFO-DIR-ENTRY
- * Elisp: (elisp). The Emacs Lisp Reference Manual.
- END-INFO-DIR-ENTRY
- File: elisp, Node: Arrays, Next: Array Functions, Prev: Sequence Functions, Up: Sequences Arrays Vectors
- 6.2 Arrays
- ==========
- An "array" object has slots that hold a number of other Lisp objects,
- called the elements of the array. Any element of an array may be
- accessed in constant time. In contrast, the time to access an element
- of a list is proportional to the position of that element in the list.
- Emacs defines four types of array, all one-dimensional: "strings"
- (*note String Type::), "vectors" (*note Vector Type::), "bool-vectors"
- (*note Bool-Vector Type::), and "char-tables" (*note Char-Table
- Type::). Vectors and char-tables can hold elements of any type, but
- strings can only hold characters, and bool-vectors can only hold `t'
- and `nil'.
- All four kinds of array share these characteristics:
- * The first element of an array has index zero, the second element
- has index 1, and so on. This is called "zero-origin" indexing.
- For example, an array of four elements has indices 0, 1, 2, and 3.
- * The length of the array is fixed once you create it; you cannot
- change the length of an existing array.
- * For purposes of evaluation, the array is a constant--i.e., it
- evaluates to itself.
- * The elements of an array may be referenced or changed with the
- functions `aref' and `aset', respectively (*note Array
- Functions::).
- When you create an array, other than a char-table, you must specify
- its length. You cannot specify the length of a char-table, because that
- is determined by the range of character codes.
- In principle, if you want an array of text characters, you could use
- either a string or a vector. In practice, we always choose strings for
- such applications, for four reasons:
- * They occupy one-fourth the space of a vector of the same elements.
- * Strings are printed in a way that shows the contents more clearly
- as text.
- * Strings can hold text properties. *Note Text Properties::.
- * Many of the specialized editing and I/O facilities of Emacs accept
- only strings. For example, you cannot insert a vector of
- characters into a buffer the way you can insert a string. *Note
- Strings and Characters::.
- By contrast, for an array of keyboard input characters (such as a key
- sequence), a vector may be necessary, because many keyboard input
- characters are outside the range that will fit in a string. *Note Key
- Sequence Input::.
- File: elisp, Node: Array Functions, Next: Vectors, Prev: Arrays, Up: Sequences Arrays Vectors
- 6.3 Functions that Operate on Arrays
- ====================================
- In this section, we describe the functions that accept all types of
- arrays.
- -- Function: arrayp object
- This function returns `t' if OBJECT is an array (i.e., a vector, a
- string, a bool-vector or a char-table).
- (arrayp [a])
- => t
- (arrayp "asdf")
- => t
- (arrayp (syntax-table)) ;; A char-table.
- => t
- -- Function: aref array index
- This function returns the INDEXth element of ARRAY. The first
- element is at index zero.
- (setq primes [2 3 5 7 11 13])
- => [2 3 5 7 11 13]
- (aref primes 4)
- => 11
- (aref "abcdefg" 1)
- => 98 ; `b' is ASCII code 98.
- See also the function `elt', in *note Sequence Functions::.
- -- Function: aset array index object
- This function sets the INDEXth element of ARRAY to be OBJECT. It
- returns OBJECT.
- (setq w [foo bar baz])
- => [foo bar baz]
- (aset w 0 'fu)
- => fu
- w
- => [fu bar baz]
- (setq x "asdfasfd")
- => "asdfasfd"
- (aset x 3 ?Z)
- => 90
- x
- => "asdZasfd"
- If ARRAY is a string and OBJECT is not a character, a
- `wrong-type-argument' error results. The function converts a
- unibyte string to multibyte if necessary to insert a character.
- -- Function: fillarray array object
- This function fills the array ARRAY with OBJECT, so that each
- element of ARRAY is OBJECT. It returns ARRAY.
- (setq a [a b c d e f g])
- => [a b c d e f g]
- (fillarray a 0)
- => [0 0 0 0 0 0 0]
- a
- => [0 0 0 0 0 0 0]
- (setq s "When in the course")
- => "When in the course"
- (fillarray s ?-)
- => "------------------"
- If ARRAY is a string and OBJECT is not a character, a
- `wrong-type-argument' error results.
- The general sequence functions `copy-sequence' and `length' are
- often useful for objects known to be arrays. *Note Sequence
- Functions::.
- File: elisp, Node: Vectors, Next: Vector Functions, Prev: Array Functions, Up: Sequences Arrays Vectors
- 6.4 Vectors
- ===========
- A "vector" is a general-purpose array whose elements can be any Lisp
- objects. (By contrast, the elements of a string can only be
- characters. *Note Strings and Characters::.) Vectors are used in
- Emacs for many purposes: as key sequences (*note Key Sequences::), as
- symbol-lookup tables (*note Creating Symbols::), as part of the
- representation of a byte-compiled function (*note Byte Compilation::),
- and more.
- Like other arrays, vectors use zero-origin indexing: the first
- element has index 0.
- Vectors are printed with square brackets surrounding the elements.
- Thus, a vector whose elements are the symbols `a', `b' and `a' is
- printed as `[a b a]'. You can write vectors in the same way in Lisp
- input.
- A vector, like a string or a number, is considered a constant for
- evaluation: the result of evaluating it is the same vector. This does
- not evaluate or even examine the elements of the vector. *Note
- Self-Evaluating Forms::.
- Here are examples illustrating these principles:
- (setq avector [1 two '(three) "four" [five]])
- => [1 two (quote (three)) "four" [five]]
- (eval avector)
- => [1 two (quote (three)) "four" [five]]
- (eq avector (eval avector))
- => t
- File: elisp, Node: Vector Functions, Next: Char-Tables, Prev: Vectors, Up: Sequences Arrays Vectors
- 6.5 Functions for Vectors
- =========================
- Here are some functions that relate to vectors:
- -- Function: vectorp object
- This function returns `t' if OBJECT is a vector.
- (vectorp [a])
- => t
- (vectorp "asdf")
- => nil
- -- Function: vector &rest objects
- This function creates and returns a vector whose elements are the
- arguments, OBJECTS.
- (vector 'foo 23 [bar baz] "rats")
- => [foo 23 [bar baz] "rats"]
- (vector)
- => []
- -- Function: make-vector length object
- This function returns a new vector consisting of LENGTH elements,
- each initialized to OBJECT.
- (setq sleepy (make-vector 9 'Z))
- => [Z Z Z Z Z Z Z Z Z]
- -- Function: vconcat &rest sequences
- This function returns a new vector containing all the elements of
- SEQUENCES. The arguments SEQUENCES may be true lists, vectors,
- strings or bool-vectors. If no SEQUENCES are given, an empty
- vector is returned.
- The value is a newly constructed vector that is not `eq' to any
- existing vector.
- (setq a (vconcat '(A B C) '(D E F)))
- => [A B C D E F]
- (eq a (vconcat a))
- => nil
- (vconcat)
- => []
- (vconcat [A B C] "aa" '(foo (6 7)))
- => [A B C 97 97 foo (6 7)]
- The `vconcat' function also allows byte-code function objects as
- arguments. This is a special feature to make it easy to access
- the entire contents of a byte-code function object. *Note
- Byte-Code Objects::.
- For other concatenation functions, see `mapconcat' in *note
- Mapping Functions::, `concat' in *note Creating Strings::, and
- `append' in *note Building Lists::.
- The `append' function also provides a way to convert a vector into a
- list with the same elements:
- (setq avector [1 two (quote (three)) "four" [five]])
- => [1 two (quote (three)) "four" [five]]
- (append avector nil)
- => (1 two (quote (three)) "four" [five])
- File: elisp, Node: Char-Tables, Next: Bool-Vectors, Prev: Vector Functions, Up: Sequences Arrays Vectors
- 6.6 Char-Tables
- ===============
- A char-table is much like a vector, except that it is indexed by
- character codes. Any valid character code, without modifiers, can be
- used as an index in a char-table. You can access a char-table's
- elements with `aref' and `aset', as with any array. In addition, a
- char-table can have "extra slots" to hold additional data not
- associated with particular character codes. Like vectors, char-tables
- are constants when evaluated, and can hold elements of any type.
- Each char-table has a "subtype", a symbol, which serves two purposes:
- * The subtype provides an easy way to tell what the char-table is
- for. For instance, display tables are char-tables with
- `display-table' as the subtype, and syntax tables are char-tables
- with `syntax-table' as the subtype. The subtype can be queried
- using the function `char-table-subtype', described below.
- * The subtype controls the number of "extra slots" in the
- char-table. This number is specified by the subtype's
- `char-table-extra-slots' symbol property, which should be an
- integer between 0 and 10. If the subtype has no such symbol
- property, the char-table has no extra slots. *Note Property
- Lists::, for information about symbol properties.
- A char-table can have a "parent", which is another char-table. If
- it does, then whenever the char-table specifies `nil' for a particular
- character C, it inherits the value specified in the parent. In other
- words, `(aref CHAR-TABLE C)' returns the value from the parent of
- CHAR-TABLE if CHAR-TABLE itself specifies `nil'.
- A char-table can also have a "default value". If so, then `(aref
- CHAR-TABLE C)' returns the default value whenever the char-table does
- not specify any other non-`nil' value.
- -- Function: make-char-table subtype &optional init
- Return a newly-created char-table, with subtype SUBTYPE (a
- symbol). Each element is initialized to INIT, which defaults to
- `nil'. You cannot alter the subtype of a char-table after the
- char-table is created.
- There is no argument to specify the length of the char-table,
- because all char-tables have room for any valid character code as
- an index.
- If SUBTYPE has the `char-table-extra-slots' symbol property, that
- specifies the number of extra slots in the char-table. This
- should be an integer between 0 and 10; otherwise,
- `make-char-table' raises an error. If SUBTYPE has no
- `char-table-extra-slots' symbol property (*note Property Lists::),
- the char-table has no extra slots.
- -- Function: char-table-p object
- This function returns `t' if OBJECT is a char-table, and `nil'
- otherwise.
- -- Function: char-table-subtype char-table
- This function returns the subtype symbol of CHAR-TABLE.
- There is no special function to access default values in a
- char-table. To do that, use `char-table-range' (see below).
- -- Function: char-table-parent char-table
- This function returns the parent of CHAR-TABLE. The parent is
- always either `nil' or another char-table.
- -- Function: set-char-table-parent char-table new-parent
- This function sets the parent of CHAR-TABLE to NEW-PARENT.
- -- Function: char-table-extra-slot char-table n
- This function returns the contents of extra slot N of CHAR-TABLE.
- The number of extra slots in a char-table is determined by its
- subtype.
- -- Function: set-char-table-extra-slot char-table n value
- This function stores VALUE in extra slot N of CHAR-TABLE.
- A char-table can specify an element value for a single character
- code; it can also specify a value for an entire character set.
- -- Function: char-table-range char-table range
- This returns the value specified in CHAR-TABLE for a range of
- characters RANGE. Here are the possibilities for RANGE:
- `nil'
- Refers to the default value.
- CHAR
- Refers to the element for character CHAR (supposing CHAR is a
- valid character code).
- `(FROM . TO)'
- A cons cell refers to all the characters in the inclusive
- range `[FROM..TO]'.
- -- Function: set-char-table-range char-table range value
- This function sets the value in CHAR-TABLE for a range of
- characters RANGE. Here are the possibilities for RANGE:
- `nil'
- Refers to the default value.
- `t'
- Refers to the whole range of character codes.
- CHAR
- Refers to the element for character CHAR (supposing CHAR is a
- valid character code).
- `(FROM . TO)'
- A cons cell refers to all the characters in the inclusive
- range `[FROM..TO]'.
- -- Function: map-char-table function char-table
- This function calls its argument FUNCTION for each element of
- CHAR-TABLE that has a non-`nil' value. The call to FUNCTION is
- with two arguments, a key and a value. The key is a possible
- RANGE argument for `char-table-range'--either a valid character or
- a cons cell `(FROM . TO)', specifying a range of characters that
- share the same value. The value is what `(char-table-range
- CHAR-TABLE KEY)' returns.
- Overall, the key-value pairs passed to FUNCTION describe all the
- values stored in CHAR-TABLE.
- The return value is always `nil'; to make calls to
- `map-char-table' useful, FUNCTION should have side effects. For
- example, here is how to examine the elements of the syntax table:
- (let (accumulator)
- (map-char-table
- #'(lambda (key value)
- (setq accumulator
- (cons (list
- (if (consp key)
- (list (car key) (cdr key))
- key)
- value)
- accumulator)))
- (syntax-table))
- accumulator)
- =>
- (((2597602 4194303) (2)) ((2597523 2597601) (3))
- ... (65379 (5 . 65378)) (65378 (4 . 65379)) (65377 (1))
- ... (12 (0)) (11 (3)) (10 (12)) (9 (0)) ((0 8) (3)))
- File: elisp, Node: Bool-Vectors, Next: Rings, Prev: Char-Tables, Up: Sequences Arrays Vectors
- 6.7 Bool-vectors
- ================
- A bool-vector is much like a vector, except that it stores only the
- values `t' and `nil'. If you try to store any non-`nil' value into an
- element of the bool-vector, the effect is to store `t' there. As with
- all arrays, bool-vector indices start from 0, and the length cannot be
- changed once the bool-vector is created. Bool-vectors are constants
- when evaluated.
- There are two special functions for working with bool-vectors; aside
- from that, you manipulate them with same functions used for other kinds
- of arrays.
- -- Function: make-bool-vector length initial
- Return a new bool-vector of LENGTH elements, each one initialized
- to INITIAL.
- -- Function: bool-vector-p object
- This returns `t' if OBJECT is a bool-vector, and `nil' otherwise.
- Here is an example of creating, examining, and updating a
- bool-vector. Note that the printed form represents up to 8 boolean
- values as a single character.
- (setq bv (make-bool-vector 5 t))
- => #&5"^_"
- (aref bv 1)
- => t
- (aset bv 3 nil)
- => nil
- bv
- => #&5"^W"
- These results make sense because the binary codes for control-_ and
- control-W are 11111 and 10111, respectively.
- File: elisp, Node: Rings, Prev: Bool-Vectors, Up: Sequences Arrays Vectors
- 6.8 Managing a Fixed-Size Ring of Objects
- =========================================
- A "ring" is a fixed-size data structure that supports insertion,
- deletion, rotation, and modulo-indexed reference and traversal. An
- efficient ring data structure is implemented by the `ring' package. It
- provides the functions listed in this section.
- Note that several "rings" in Emacs, like the kill ring and the mark
- ring, are actually implemented as simple lists, _not_ using the `ring'
- package; thus the following functions won't work on them.
- -- Function: make-ring size
- This returns a new ring capable of holding SIZE objects. SIZE
- should be an integer.
- -- Function: ring-p object
- This returns `t' if OBJECT is a ring, `nil' otherwise.
- -- Function: ring-size ring
- This returns the maximum capacity of the RING.
- -- Function: ring-length ring
- This returns the number of objects that RING currently contains.
- The value will never exceed that returned by `ring-size'.
- -- Function: ring-elements ring
- This returns a list of the objects in RING, in order, newest first.
- -- Function: ring-copy ring
- This returns a new ring which is a copy of RING. The new ring
- contains the same (`eq') objects as RING.
- -- Function: ring-empty-p ring
- This returns `t' if RING is empty, `nil' otherwise.
- The newest element in the ring always has index 0. Higher indices
- correspond to older elements. Indices are computed modulo the ring
- length. Index -1 corresponds to the oldest element, -2 to the
- next-oldest, and so forth.
- -- Function: ring-ref ring index
- This returns the object in RING found at index INDEX. INDEX may
- be negative or greater than the ring length. If RING is empty,
- `ring-ref' signals an error.
- -- Function: ring-insert ring object
- This inserts OBJECT into RING, making it the newest element, and
- returns OBJECT.
- If the ring is full, insertion removes the oldest element to make
- room for the new element.
- -- Function: ring-remove ring &optional index
- Remove an object from RING, and return that object. The argument
- INDEX specifies which item to remove; if it is `nil', that means
- to remove the oldest item. If RING is empty, `ring-remove'
- signals an error.
- -- Function: ring-insert-at-beginning ring object
- This inserts OBJECT into RING, treating it as the oldest element.
- The return value is not significant.
- If the ring is full, this function removes the newest element to
- make room for the inserted element.
- If you are careful not to exceed the ring size, you can use the ring
- as a first-in-first-out queue. For example:
- (let ((fifo (make-ring 5)))
- (mapc (lambda (obj) (ring-insert fifo obj))
- '(0 one "two"))
- (list (ring-remove fifo) t
- (ring-remove fifo) t
- (ring-remove fifo)))
- => (0 t one t "two")
- File: elisp, Node: Hash Tables, Next: Symbols, Prev: Sequences Arrays Vectors, Up: Top
- 7 Hash Tables
- *************
- A hash table is a very fast kind of lookup table, somewhat like an
- alist (*note Association Lists::) in that it maps keys to corresponding
- values. It differs from an alist in these ways:
- * Lookup in a hash table is extremely fast for large tables--in
- fact, the time required is essentially _independent_ of how many
- elements are stored in the table. For smaller tables (a few tens
- of elements) alists may still be faster because hash tables have a
- more-or-less constant overhead.
- * The correspondences in a hash table are in no particular order.
- * There is no way to share structure between two hash tables, the
- way two alists can share a common tail.
- Emacs Lisp provides a general-purpose hash table data type, along
- with a series of functions for operating on them. Hash tables have a
- special printed representation, which consists of `#s' followed by a
- list specifying the hash table properties and contents. *Note Creating
- Hash::. (Note that the term "hash notation", which refers to the
- initial `#' character used in the printed representations of objects
- with no read representation, has nothing to do with the term "hash
- table". *Note Printed Representation::.)
- Obarrays are also a kind of hash table, but they are a different type
- of object and are used only for recording interned symbols (*note
- Creating Symbols::).
- * Menu:
- * Creating Hash:: Functions to create hash tables.
- * Hash Access:: Reading and writing the hash table contents.
- * Defining Hash:: Defining new comparison methods.
- * Other Hash:: Miscellaneous.
- File: elisp, Node: Creating Hash, Next: Hash Access, Up: Hash Tables
- 7.1 Creating Hash Tables
- ========================
- The principal function for creating a hash table is `make-hash-table'.
- -- Function: make-hash-table &rest keyword-args
- This function creates a new hash table according to the specified
- arguments. The arguments should consist of alternating keywords
- (particular symbols recognized specially) and values corresponding
- to them.
- Several keywords make sense in `make-hash-table', but the only two
- that you really need to know about are `:test' and `:weakness'.
- `:test TEST'
- This specifies the method of key lookup for this hash table.
- The default is `eql'; `eq' and `equal' are other alternatives:
- `eql'
- Keys which are numbers are "the same" if they are
- `equal', that is, if they are equal in value and either
- both are integers or both are floating point numbers;
- otherwise, two distinct objects are never "the same".
- `eq'
- Any two distinct Lisp objects are "different" as keys.
- `equal'
- Two Lisp objects are "the same", as keys, if they are
- equal according to `equal'.
- You can use `define-hash-table-test' (*note Defining Hash::)
- to define additional possibilities for TEST.
- `:weakness WEAK'
- The weakness of a hash table specifies whether the presence
- of a key or value in the hash table preserves it from garbage
- collection.
- The value, WEAK, must be one of `nil', `key', `value',
- `key-or-value', `key-and-value', or `t' which is an alias for
- `key-and-value'. If WEAK is `key' then the hash table does
- not prevent its keys from being collected as garbage (if they
- are not referenced anywhere else); if a particular key does
- get collected, the corresponding association is removed from
- the hash table.
- If WEAK is `value', then the hash table does not prevent
- values from being collected as garbage (if they are not
- referenced anywhere else); if a particular value does get
- collected, the corresponding association is removed from the
- hash table.
- If WEAK is `key-and-value' or `t', both the key and the value
- must be live in order to preserve the association. Thus, the
- hash table does not protect either keys or values from garbage
- collection; if either one is collected as garbage, that
- removes the association.
- If WEAK is `key-or-value', either the key or the value can
- preserve the association. Thus, associations are removed
- from the hash table when both their key and value would be
- collected as garbage (if not for references from weak hash
- tables).
- The default for WEAK is `nil', so that all keys and values
- referenced in the hash table are preserved from garbage
- collection.
- `:size SIZE'
- This specifies a hint for how many associations you plan to
- store in the hash table. If you know the approximate number,
- you can make things a little more efficient by specifying it
- this way. If you specify too small a size, the hash table
- will grow automatically when necessary, but doing that takes
- some extra time.
- The default size is 65.
- `:rehash-size REHASH-SIZE'
- When you add an association to a hash table and the table is
- "full", it grows automatically. This value specifies how to
- make the hash table larger, at that time.
- If REHASH-SIZE is an integer, it should be positive, and the
- hash table grows by adding that much to the nominal size. If
- REHASH-SIZE is a floating point number, it had better be
- greater than 1, and the hash table grows by multiplying the
- old size by that number.
- The default value is 1.5.
- `:rehash-threshold THRESHOLD'
- This specifies the criterion for when the hash table is
- "full" (so it should be made larger). The value, THRESHOLD,
- should be a positive floating point number, no greater than
- 1. The hash table is "full" whenever the actual number of
- entries exceeds this fraction of the nominal size. The
- default for THRESHOLD is 0.8.
- -- Function: makehash &optional test
- This is equivalent to `make-hash-table', but with a different style
- argument list. The argument TEST specifies the method of key
- lookup.
- This function is obsolete. Use `make-hash-table' instead.
- You can also create a new hash table using the printed representation
- for hash tables. The Lisp reader can read this printed representation,
- provided each element in the specified hash table has a valid read
- syntax (*note Printed Representation::). For instance, the following
- specifies a new hash table containing the keys `key1' and `key2' (both
- symbols) associated with `val1' (a symbol) and `300' (a number)
- respectively.
- #s(hash-table size 30 data (key1 val1 key2 300))
- The printed representation for a hash table consists of `#s' followed
- by a list beginning with `hash-table'. The rest of the list should
- consist of zero or more property-value pairs specifying the hash
- table's properties and initial contents. The properties and values are
- read literally. Valid property names are `size', `test', `weakness',
- `rehash-size', `rehash-threshold', and `data'. The `data' property
- should be a list of key-value pairs for the initial contents; the other
- properties have the same meanings as the matching `make-hash-table'
- keywords (`:size', `:test', etc.), described above.
- Note that you cannot specify a hash table whose initial contents
- include objects that have no read syntax, such as buffers and frames.
- Such objects may be added to the hash table after it is created.
- File: elisp, Node: Hash Access, Next: Defining Hash, Prev: Creating Hash, Up: Hash Tables
- 7.2 Hash Table Access
- =====================
- This section describes the functions for accessing and storing
- associations in a hash table. In general, any Lisp object can be used
- as a hash key, unless the comparison method imposes limits. Any Lisp
- object can also be used as the value.
- -- Function: gethash key table &optional default
- This function looks up KEY in TABLE, and returns its associated
- VALUE--or DEFAULT, if KEY has no association in TABLE.
- -- Function: puthash key value table
- This function enters an association for KEY in TABLE, with value
- VALUE. If KEY already has an association in TABLE, VALUE replaces
- the old associated value.
- -- Function: remhash key table
- This function removes the association for KEY from TABLE, if there
- is one. If KEY has no association, `remhash' does nothing.
- Common Lisp note: In Common Lisp, `remhash' returns non-`nil' if
- it actually removed an association and `nil' otherwise. In Emacs
- Lisp, `remhash' always returns `nil'.
- -- Function: clrhash table
- This function removes all the associations from hash table TABLE,
- so that it becomes empty. This is also called "clearing" the hash
- table.
- Common Lisp note: In Common Lisp, `clrhash' returns the empty
- TABLE. In Emacs Lisp, it returns `nil'.
- -- Function: maphash function table
- This function calls FUNCTION once for each of the associations in
- TABLE. The function FUNCTION should accept two arguments--a KEY
- listed in TABLE, and its associated VALUE. `maphash' returns
- `nil'.
- File: elisp, Node: Defining Hash, Next: Other Hash, Prev: Hash Access, Up: Hash Tables
- 7.3 Defining Hash Comparisons
- =============================
- You can define new methods of key lookup by means of
- `define-hash-table-test'. In order to use this feature, you need to
- understand how hash tables work, and what a "hash code" means.
- You can think of a hash table conceptually as a large array of many
- slots, each capable of holding one association. To look up a key,
- `gethash' first computes an integer, the hash code, from the key. It
- reduces this integer modulo the length of the array, to produce an
- index in the array. Then it looks in that slot, and if necessary in
- other nearby slots, to see if it has found the key being sought.
- Thus, to define a new method of key lookup, you need to specify both
- a function to compute the hash code from a key, and a function to
- compare two keys directly.
- -- Function: define-hash-table-test name test-fn hash-fn
- This function defines a new hash table test, named NAME.
- After defining NAME in this way, you can use it as the TEST
- argument in `make-hash-table'. When you do that, the hash table
- will use TEST-FN to compare key values, and HASH-FN to compute a
- "hash code" from a key value.
- The function TEST-FN should accept two arguments, two keys, and
- return non-`nil' if they are considered "the same".
- The function HASH-FN should accept one argument, a key, and return
- an integer that is the "hash code" of that key. For good results,
- the function should use the whole range of integer values for hash
- codes, including negative integers.
- The specified functions are stored in the property list of NAME
- under the property `hash-table-test'; the property value's form is
- `(TEST-FN HASH-FN)'.
- -- Function: sxhash obj
- This function returns a hash code for Lisp object OBJ. This is an
- integer which reflects the contents of OBJ and the other Lisp
- objects it points to.
- If two objects OBJ1 and OBJ2 are equal, then `(sxhash OBJ1)' and
- `(sxhash OBJ2)' are the same integer.
- If the two objects are not equal, the values returned by `sxhash'
- are usually different, but not always; once in a rare while, by
- luck, you will encounter two distinct-looking objects that give
- the same result from `sxhash'.
- This example creates a hash table whose keys are strings that are
- compared case-insensitively.
- (defun case-fold-string= (a b)
- (compare-strings a nil nil b nil nil t))
- (defun case-fold-string-hash (a)
- (sxhash (upcase a)))
- (define-hash-table-test 'case-fold
- 'case-fold-string= 'case-fold-string-hash)
- (make-hash-table :test 'case-fold)
- Here is how you could define a hash table test equivalent to the
- predefined test value `equal'. The keys can be any Lisp object, and
- equal-looking objects are considered the same key.
- (define-hash-table-test 'contents-hash 'equal 'sxhash)
- (make-hash-table :test 'contents-hash)
- File: elisp, Node: Other Hash, Prev: Defining Hash, Up: Hash Tables
- 7.4 Other Hash Table Functions
- ==============================
- Here are some other functions for working with hash tables.
- -- Function: hash-table-p table
- This returns non-`nil' if TABLE is a hash table object.
- -- Function: copy-hash-table table
- This function creates and returns a copy of TABLE. Only the table
- itself is copied--the keys and values are shared.
- -- Function: hash-table-count table
- This function returns the actual number of entries in TABLE.
- -- Function: hash-table-test table
- This returns the TEST value that was given when TABLE was created,
- to specify how to hash and compare keys. See `make-hash-table'
- (*note Creating Hash::).
- -- Function: hash-table-weakness table
- This function returns the WEAK value that was specified for hash
- table TABLE.
- -- Function: hash-table-rehash-size table
- This returns the rehash size of TABLE.
- -- Function: hash-table-rehash-threshold table
- This returns the rehash threshold of TABLE.
- -- Function: hash-table-size table
- This returns the current nominal size of TABLE.
- File: elisp, Node: Symbols, Next: Evaluation, Prev: Hash Tables, Up: Top
- 8 Symbols
- *********
- A "symbol" is an object with a unique name. This chapter describes
- symbols, their components, their property lists, and how they are
- created and interned. Separate chapters describe the use of symbols as
- variables and as function names; see *note Variables::, and *note
- Functions::. For the precise read syntax for symbols, see *note Symbol
- Type::.
- You can test whether an arbitrary Lisp object is a symbol with
- `symbolp':
- -- Function: symbolp object
- This function returns `t' if OBJECT is a symbol, `nil' otherwise.
- * Menu:
- * Symbol Components:: Symbols have names, values, function definitions
- and property lists.
- * Definitions:: A definition says how a symbol will be used.
- * Creating Symbols:: How symbols are kept unique.
- * Property Lists:: Each symbol has a property list
- for recording miscellaneous information.
- File: elisp, Node: Symbol Components, Next: Definitions, Prev: Symbols, Up: Symbols
- 8.1 Symbol Components
- =====================
- Each symbol has four components (or "cells"), each of which references
- another object:
- Print name
- The symbol's name.
- Value
- The symbol's current value as a variable.
- Function
- The symbol's function definition. It can also hold a symbol, a
- keymap, or a keyboard macro.
- Property list
- The symbol's property list.
- The print name cell always holds a string, and cannot be changed. Each
- of the other three cells can be set to any Lisp object.
- The print name cell holds the string that is the name of a symbol.
- Since symbols are represented textually by their names, it is important
- not to have two symbols with the same name. The Lisp reader ensures
- this: every time it reads a symbol, it looks for an existing symbol
- with the specified name before it creates a new one. To get a symbol's
- name, use the function `symbol-name' (*note Creating Symbols::).
- The value cell holds a symbol's value as a variable, which is what
- you get if the symbol itself is evaluated as a Lisp expression. *Note
- Variables::, for details about how values are set and retrieved,
- including complications such as "local bindings" and "scoping rules".
- Most symbols can have any Lisp object as a value, but certain special
- symbols have values that cannot be changed; these include `nil' and
- `t', and any symbol whose name starts with `:' (those are called
- "keywords"). *Note Constant Variables::.
- The function cell holds a symbol's function definition. Often, we
- refer to "the function `foo'" when we really mean the function stored
- in the function cell of `foo'; we make the distinction explicit only
- when necessary. Typically, the function cell is used to hold a
- function (*note Functions::) or a macro (*note Macros::). However, it
- can also be used to hold a symbol (*note Function Indirection::),
- keyboard macro (*note Keyboard Macros::), keymap (*note Keymaps::), or
- autoload object (*note Autoloading::). To get the contents of a
- symbol's function cell, use the function `symbol-function' (*note
- Function Cells::).
- The property list cell normally should hold a correctly formatted
- property list. To get a symbol's property list, use the function
- `symbol-plist'. *Note Property Lists::.
- The function cell or the value cell may be "void", which means that
- the cell does not reference any object. (This is not the same thing as
- holding the symbol `void', nor the same as holding the symbol `nil'.)
- Examining a function or value cell that is void results in an error,
- such as `Symbol's value as variable is void'.
- Because each symbol has separate value and function cells, variables
- names and function names do not conflict. For example, the symbol
- `buffer-file-name' has a value (the name of the file being visited in
- the current buffer) as well as a function definition (a primitive
- function that returns the name of the file):
- buffer-file-name
- => "/gnu/elisp/symbols.texi"
- (symbol-function 'buffer-file-name)
- => #<subr buffer-file-name>
- File: elisp, Node: Definitions, Next: Creating Symbols, Prev: Symbol Components, Up: Symbols
- 8.2 Defining Symbols
- ====================
- A "definition" is a special kind of Lisp expression that announces your
- intention to use a symbol in a particular way. It typically specifies
- a value or meaning for the symbol for one kind of use, plus
- documentation for its meaning when used in this way. Thus, when you
- define a symbol as a variable, you can supply an initial value for the
- variable, plus documentation for the variable.
- `defvar' and `defconst' are special forms that define a symbol as a
- "global variable"--a variable that can be accessed at any point in a
- Lisp program. *Note Variables::, for details about variables. To
- define a customizable variable, use the `defcustom' macro, which also
- calls `defvar' as a subroutine (*note Customization::).
- In principle, you can assign a variable value to any symbol with
- `setq', whether not it has first been defined as a variable. However,
- you ought to write a variable definition for each global variable that
- you want to use; otherwise, your Lisp program may not act correctly if
- it is evaluated with lexical scoping enabled (*note Variable Scoping::).
- `defun' defines a symbol as a function, creating a lambda expression
- and storing it in the function cell of the symbol. This lambda
- expression thus becomes the function definition of the symbol. (The
- term "function definition", meaning the contents of the function cell,
- is derived from the idea that `defun' gives the symbol its definition
- as a function.) `defsubst' and `defalias' are two other ways of
- defining a function. *Note Functions::.
- `defmacro' defines a symbol as a macro. It creates a macro object
- and stores it in the function cell of the symbol. Note that a given
- symbol can be a macro or a function, but not both at once, because both
- macro and function definitions are kept in the function cell, and that
- cell can hold only one Lisp object at any given time. *Note Macros::.
- As previously noted, Emacs Lisp allows the same symbol to be defined
- both as a variable (e.g. with `defvar') and as a function or macro
- (e.g. with `defun'). Such definitions do not conflict.
- These definition also act as guides for programming tools. For
- example, the `C-h f' and `C-h v' commands create help buffers
- containing links to the relevant variable, function, or macro
- definitions. *Note Name Help: (emacs)Name Help.
- File: elisp, Node: Creating Symbols, Next: Property Lists, Prev: Definitions, Up: Symbols
- 8.3 Creating and Interning Symbols
- ==================================
- To understand how symbols are created in GNU Emacs Lisp, you must know
- how Lisp reads them. Lisp must ensure that it finds the same symbol
- every time it reads the same set of characters. Failure to do so would
- cause complete confusion.
- When the Lisp reader encounters a symbol, it reads all the characters
- of the name. Then it "hashes" those characters to find an index in a
- table called an "obarray". Hashing is an efficient method of looking
- something up. For example, instead of searching a telephone book cover
- to cover when looking up Jan Jones, you start with the J's and go from
- there. That is a simple version of hashing. Each element of the
- obarray is a "bucket" which holds all the symbols with a given hash
- code; to look for a given name, it is sufficient to look through all
- the symbols in the bucket for that name's hash code. (The same idea is
- used for general Emacs hash tables, but they are a different data type;
- see *note Hash Tables::.)
- If a symbol with the desired name is found, the reader uses that
- symbol. If the obarray does not contain a symbol with that name, the
- reader makes a new symbol and adds it to the obarray. Finding or adding
- a symbol with a certain name is called "interning" it, and the symbol
- is then called an "interned symbol".
- Interning ensures that each obarray has just one symbol with any
- particular name. Other like-named symbols may exist, but not in the
- same obarray. Thus, the reader gets the same symbols for the same
- names, as long as you keep reading with the same obarray.
- Interning usually happens automatically in the reader, but sometimes
- other programs need to do it. For example, after the `M-x' command
- obtains the command name as a string using the minibuffer, it then
- interns the string, to get the interned symbol with that name.
- No obarray contains all symbols; in fact, some symbols are not in any
- obarray. They are called "uninterned symbols". An uninterned symbol
- has the same four cells as other symbols; however, the only way to gain
- access to it is by finding it in some other object or as the value of a
- variable.
- Creating an uninterned symbol is useful in generating Lisp code,
- because an uninterned symbol used as a variable in the code you generate
- cannot clash with any variables used in other Lisp programs.
- In Emacs Lisp, an obarray is actually a vector. Each element of the
- vector is a bucket; its value is either an interned symbol whose name
- hashes to that bucket, or 0 if the bucket is empty. Each interned
- symbol has an internal link (invisible to the user) to the next symbol
- in the bucket. Because these links are invisible, there is no way to
- find all the symbols in an obarray except using `mapatoms' (below).
- The order of symbols in a bucket is not significant.
- In an empty obarray, every element is 0, so you can create an obarray
- with `(make-vector LENGTH 0)'. *This is the only valid way to create
- an obarray.* Prime numbers as lengths tend to result in good hashing;
- lengths one less than a power of two are also good.
- *Do not try to put symbols in an obarray yourself.* This does not
- work--only `intern' can enter a symbol in an obarray properly.
- Common Lisp note: Unlike Common Lisp, Emacs Lisp does not provide
- for interning a single symbol in several obarrays.
- Most of the functions below take a name and sometimes an obarray as
- arguments. A `wrong-type-argument' error is signaled if the name is
- not a string, or if the obarray is not a vector.
- -- Function: symbol-name symbol
- This function returns the string that is SYMBOL's name. For
- example:
- (symbol-name 'foo)
- => "foo"
- *Warning:* Changing the string by substituting characters does
- change the name of the symbol, but fails to update the obarray, so
- don't do it!
- -- Function: make-symbol name
- This function returns a newly-allocated, uninterned symbol whose
- name is NAME (which must be a string). Its value and function
- definition are void, and its property list is `nil'. In the
- example below, the value of `sym' is not `eq' to `foo' because it
- is a distinct uninterned symbol whose name is also `foo'.
- (setq sym (make-symbol "foo"))
- => foo
- (eq sym 'foo)
- => nil
- -- Function: intern name &optional obarray
- This function returns the interned symbol whose name is NAME. If
- there is no such symbol in the obarray OBARRAY, `intern' creates a
- new one, adds it to the obarray, and returns it. If OBARRAY is
- omitted, the value of the global variable `obarray' is used.
- (setq sym (intern "foo"))
- => foo
- (eq sym 'foo)
- => t
- (setq sym1 (intern "foo" other-obarray))
- => foo
- (eq sym1 'foo)
- => nil
- Common Lisp note: In Common Lisp, you can intern an existing symbol
- in an obarray. In Emacs Lisp, you cannot do this, because the
- argument to `intern' must be a string, not a symbol.
- -- Function: intern-soft name &optional obarray
- This function returns the symbol in OBARRAY whose name is NAME, or
- `nil' if OBARRAY has no symbol with that name. Therefore, you can
- use `intern-soft' to test whether a symbol with a given name is
- already interned. If OBARRAY is omitted, the value of the global
- variable `obarray' is used.
- The argument NAME may also be a symbol; in that case, the function
- returns NAME if NAME is interned in the specified obarray, and
- otherwise `nil'.
- (intern-soft "frazzle") ; No such symbol exists.
- => nil
- (make-symbol "frazzle") ; Create an uninterned one.
- => frazzle
- (intern-soft "frazzle") ; That one cannot be found.
- => nil
- (setq sym (intern "frazzle")) ; Create an interned one.
- => frazzle
- (intern-soft "frazzle") ; That one can be found!
- => frazzle
- (eq sym 'frazzle) ; And it is the same one.
- => t
- -- Variable: obarray
- This variable is the standard obarray for use by `intern' and
- `read'.
- -- Function: mapatoms function &optional obarray
- This function calls FUNCTION once with each symbol in the obarray
- OBARRAY. Then it returns `nil'. If OBARRAY is omitted, it
- defaults to the value of `obarray', the standard obarray for
- ordinary symbols.
- (setq count 0)
- => 0
- (defun count-syms (s)
- (setq count (1+ count)))
- => count-syms
- (mapatoms 'count-syms)
- => nil
- count
- => 1871
- See `documentation' in *note Accessing Documentation::, for another
- example using `mapatoms'.
- -- Function: unintern symbol obarray
- This function deletes SYMBOL from the obarray OBARRAY. If
- `symbol' is not actually in the obarray, `unintern' does nothing.
- If OBARRAY is `nil', the current obarray is used.
- If you provide a string instead of a symbol as SYMBOL, it stands
- for a symbol name. Then `unintern' deletes the symbol (if any) in
- the obarray which has that name. If there is no such symbol,
- `unintern' does nothing.
- If `unintern' does delete a symbol, it returns `t'. Otherwise it
- returns `nil'.
- File: elisp, Node: Property Lists, Prev: Creating Symbols, Up: Symbols
- 8.4 Property Lists
- ==================
- A "property list" ("plist" for short) is a list of paired elements.
- Each of the pairs associates a property name (usually a symbol) with a
- property or value.
- Every symbol has a cell that stores a property list (*note Symbol
- Components::). This property list is used to record information about
- the symbol, such as its variable documentation and the name of the file
- where it was defined.
- Property lists can also be used in other contexts. For instance,
- you can assign property lists to character positions in a string or
- buffer. *Note Text Properties::.
- The property names and values in a property list can be any Lisp
- objects, but the names are usually symbols. Property list functions
- compare the property names using `eq'. Here is an example of a
- property list, found on the symbol `progn' when the compiler is loaded:
- (lisp-indent-function 0 byte-compile byte-compile-progn)
- Here `lisp-indent-function' and `byte-compile' are property names, and
- the other two elements are the corresponding values.
- * Menu:
- * Plists and Alists:: Comparison of the advantages of property
- lists and association lists.
- * Symbol Plists:: Functions to access symbols' property lists.
- * Other Plists:: Accessing property lists stored elsewhere.
- File: elisp, Node: Plists and Alists, Next: Symbol Plists, Up: Property Lists
- 8.4.1 Property Lists and Association Lists
- ------------------------------------------
- Association lists (*note Association Lists::) are very similar to
- property lists. In contrast to association lists, the order of the
- pairs in the property list is not significant since the property names
- must be distinct.
- Property lists are better than association lists for attaching
- information to various Lisp function names or variables. If your
- program keeps all such information in one association list, it will
- typically need to search that entire list each time it checks for an
- association for a particular Lisp function name or variable, which
- could be slow. By contrast, if you keep the same information in the
- property lists of the function names or variables themselves, each
- search will scan only the length of one property list, which is usually
- short. This is why the documentation for a variable is recorded in a
- property named `variable-documentation'. The byte compiler likewise
- uses properties to record those functions needing special treatment.
- However, association lists have their own advantages. Depending on
- your application, it may be faster to add an association to the front of
- an association list than to update a property. All properties for a
- symbol are stored in the same property list, so there is a possibility
- of a conflict between different uses of a property name. (For this
- reason, it is a good idea to choose property names that are probably
- unique, such as by beginning the property name with the program's usual
- name-prefix for variables and functions.) An association list may be
- used like a stack where associations are pushed on the front of the list
- and later discarded; this is not possible with a property list.
- File: elisp, Node: Symbol Plists, Next: Other Plists, Prev: Plists and Alists, Up: Property Lists
- 8.4.2 Property List Functions for Symbols
- -----------------------------------------
- -- Function: symbol-plist symbol
- This function returns the property list of SYMBOL.
- -- Function: setplist symbol plist
- This function sets SYMBOL's property list to PLIST. Normally,
- PLIST should be a well-formed property list, but this is not
- enforced. The return value is PLIST.
- (setplist 'foo '(a 1 b (2 3) c nil))
- => (a 1 b (2 3) c nil)
- (symbol-plist 'foo)
- => (a 1 b (2 3) c nil)
- For symbols in special obarrays, which are not used for ordinary
- purposes, it may make sense to use the property list cell in a
- nonstandard fashion; in fact, the abbrev mechanism does so (*note
- Abbrevs::).
- -- Function: get symbol property
- This function finds the value of the property named PROPERTY in
- SYMBOL's property list. If there is no such property, `nil' is
- returned. Thus, there is no distinction between a value of `nil'
- and the absence of the property.
- The name PROPERTY is compared with the existing property names
- using `eq', so any object is a legitimate property.
- See `put' for an example.
- -- Function: put symbol property value
- This function puts VALUE onto SYMBOL's property list under the
- property name PROPERTY, replacing any previous property value.
- The `put' function returns VALUE.
- (put 'fly 'verb 'transitive)
- =>'transitive
- (put 'fly 'noun '(a buzzing little bug))
- => (a buzzing little bug)
- (get 'fly 'verb)
- => transitive
- (symbol-plist 'fly)
- => (verb transitive noun (a buzzing little bug))
- File: elisp, Node: Other Plists, Prev: Symbol Plists, Up: Property Lists
- 8.4.3 Property Lists Outside Symbols
- ------------------------------------
- These functions are useful for manipulating property lists not stored
- in symbols:
- -- Function: plist-get plist property
- This returns the value of the PROPERTY property stored in the
- property list PLIST. It accepts a malformed PLIST argument. If
- PROPERTY is not found in the PLIST, it returns `nil'. For example,
- (plist-get '(foo 4) 'foo)
- => 4
- (plist-get '(foo 4 bad) 'foo)
- => 4
- (plist-get '(foo 4 bad) 'bad)
- => nil
- (plist-get '(foo 4 bad) 'bar)
- => nil
- -- Function: plist-put plist property value
- This stores VALUE as the value of the PROPERTY property in the
- property list PLIST. It may modify PLIST destructively, or it may
- construct a new list structure without altering the old. The
- function returns the modified property list, so you can store that
- back in the place where you got PLIST. For example,
- (setq my-plist '(bar t foo 4))
- => (bar t foo 4)
- (setq my-plist (plist-put my-plist 'foo 69))
- => (bar t foo 69)
- (setq my-plist (plist-put my-plist 'quux '(a)))
- => (bar t foo 69 quux (a))
- You could define `put' in terms of `plist-put' as follows:
- (defun put (symbol prop value)
- (setplist symbol
- (plist-put (symbol-plist symbol) prop value)))
- -- Function: lax-plist-get plist property
- Like `plist-get' except that it compares properties using `equal'
- instead of `eq'.
- -- Function: lax-plist-put plist property value
- Like `plist-put' except that it compares properties using `equal'
- instead of `eq'.
- -- Function: plist-member plist property
- This returns non-`nil' if PLIST contains the given PROPERTY.
- Unlike `plist-get', this allows you to distinguish between a
- missing property and a property with the value `nil'. The value
- is actually the tail of PLIST whose `car' is PROPERTY.
- File: elisp, Node: Evaluation, Next: Control Structures, Prev: Symbols, Up: Top
- 9 Evaluation
- ************
- The "evaluation" of expressions in Emacs Lisp is performed by the "Lisp
- interpreter"--a program that receives a Lisp object as input and
- computes its "value as an expression". How it does this depends on the
- data type of the object, according to rules described in this chapter.
- The interpreter runs automatically to evaluate portions of your
- program, but can also be called explicitly via the Lisp primitive
- function `eval'.
- * Menu:
- * Intro Eval:: Evaluation in the scheme of things.
- * Forms:: How various sorts of objects are evaluated.
- * Quoting:: Avoiding evaluation (to put constants in the program).
- * Backquote:: Easier construction of list structure.
- * Eval:: How to invoke the Lisp interpreter explicitly.
- File: elisp, Node: Intro Eval, Next: Forms, Up: Evaluation
- 9.1 Introduction to Evaluation
- ==============================
- The Lisp interpreter, or evaluator, is the part of Emacs that computes
- the value of an expression that is given to it. When a function
- written in Lisp is called, the evaluator computes the value of the
- function by evaluating the expressions in the function body. Thus,
- running any Lisp program really means running the Lisp interpreter.
- A Lisp object that is intended for evaluation is called a "form" or
- "expression"(1). The fact that forms are data objects and not merely
- text is one of the fundamental differences between Lisp-like languages
- and typical programming languages. Any object can be evaluated, but in
- practice only numbers, symbols, lists and strings are evaluated very
- often.
- In subsequent sections, we will describe the details of what
- evaluation means for each kind of form.
- It is very common to read a Lisp form and then evaluate the form,
- but reading and evaluation are separate activities, and either can be
- performed alone. Reading per se does not evaluate anything; it
- converts the printed representation of a Lisp object to the object
- itself. It is up to the caller of `read' to specify whether this
- object is a form to be evaluated, or serves some entirely different
- purpose. *Note Input Functions::.
- Evaluation is a recursive process, and evaluating a form often
- involves evaluating parts within that form. For instance, when you
- evaluate a "function call" form such as `(car x)', Emacs first
- evaluates the argument (the subform `x'). After evaluating the
- argument, Emacs "executes" the function (`car'), and if the function is
- written in Lisp, execution works by evaluating the "body" of the
- function (in this example, however, `car' is not a Lisp function; it is
- a primitive function implemented in C). *Note Functions::, for more
- information about functions and function calls.
- Evaluation takes place in a context called the "environment", which
- consists of the current values and bindings of all Lisp variables
- (*note Variables::).(2) Whenever a form refers to a variable without
- creating a new binding for it, the variable evaluates to the value
- given by the current environment. Evaluating a form may also
- temporarily alter the environment by binding variables (*note Local
- Variables::).
- Evaluating a form may also make changes that persist; these changes
- are called "side effects". An example of a form that produces a side
- effect is `(setq foo 1)'.
- Do not confuse evaluation with command key interpretation. The
- editor command loop translates keyboard input into a command (an
- interactively callable function) using the active keymaps, and then
- uses `call-interactively' to execute that command. Executing the
- command usually involves evaluation, if the command is written in Lisp;
- however, this step is not considered a part of command key
- interpretation. *Note Command Loop::.
- ---------- Footnotes ----------
- (1) It is sometimes also referred to as an "S-expression" or "sexp",
- but we generally do not use this terminology in this manual.
- (2) This definition of "environment" is specifically not intended to
- include all the data that can affect the result of a program.
- File: elisp, Node: Forms, Next: Quoting, Prev: Intro Eval, Up: Evaluation
- 9.2 Kinds of Forms
- ==================
- A Lisp object that is intended to be evaluated is called a "form" (or
- an "expression"). How Emacs evaluates a form depends on its data type.
- Emacs has three different kinds of form that are evaluated differently:
- symbols, lists, and "all other types". This section describes all
- three kinds, one by one, starting with the "all other types" which are
- self-evaluating forms.
- * Menu:
- * Self-Evaluating Forms:: Forms that evaluate to themselves.
- * Symbol Forms:: Symbols evaluate as variables.
- * Classifying Lists:: How to distinguish various sorts of list forms.
- * Function Indirection:: When a symbol appears as the car of a list,
- we find the real function via the symbol.
- * Function Forms:: Forms that call functions.
- * Macro Forms:: Forms that call macros.
- * Special Forms:: "Special forms" are idiosyncratic primitives,
- most of them extremely important.
- * Autoloading:: Functions set up to load files
- containing their real definitions.
- File: elisp, Node: Self-Evaluating Forms, Next: Symbol Forms, Up: Forms
- 9.2.1 Self-Evaluating Forms
- ---------------------------
- A "self-evaluating form" is any form that is not a list or symbol.
- Self-evaluating forms evaluate to themselves: the result of evaluation
- is the same object that was evaluated. Thus, the number 25 evaluates
- to 25, and the string `"foo"' evaluates to the string `"foo"'.
- Likewise, evaluating a vector does not cause evaluation of the elements
- of the vector--it returns the same vector with its contents unchanged.
- '123 ; A number, shown without evaluation.
- => 123
- 123 ; Evaluated as usual--result is the same.
- => 123
- (eval '123) ; Evaluated "by hand"--result is the same.
- => 123
- (eval (eval '123)) ; Evaluating twice changes nothing.
- => 123
- It is common to write numbers, characters, strings, and even vectors
- in Lisp code, taking advantage of the fact that they self-evaluate.
- However, it is quite unusual to do this for types that lack a read
- syntax, because there's no way to write them textually. It is possible
- to construct Lisp expressions containing these types by means of a Lisp
- program. Here is an example:
- ;; Build an expression containing a buffer object.
- (setq print-exp (list 'print (current-buffer)))
- => (print #<buffer eval.texi>)
- ;; Evaluate it.
- (eval print-exp)
- -| #<buffer eval.texi>
- => #<buffer eval.texi>
- File: elisp, Node: Symbol Forms, Next: Classifying Lists, Prev: Self-Evaluating Forms, Up: Forms
- 9.2.2 Symbol Forms
- ------------------
- When a symbol is evaluated, it is treated as a variable. The result is
- the variable's value, if it has one. If the symbol has no value as a
- variable, the Lisp interpreter signals an error. For more information
- on the use of variables, see *note Variables::.
- In the following example, we set the value of a symbol with `setq'.
- Then we evaluate the symbol, and get back the value that `setq' stored.
- (setq a 123)
- => 123
- (eval 'a)
- => 123
- a
- => 123
- The symbols `nil' and `t' are treated specially, so that the value
- of `nil' is always `nil', and the value of `t' is always `t'; you
- cannot set or bind them to any other values. Thus, these two symbols
- act like self-evaluating forms, even though `eval' treats them like any
- other symbol. A symbol whose name starts with `:' also self-evaluates
- in the same way; likewise, its value ordinarily cannot be changed.
- *Note Constant Variables::.
- File: elisp, Node: Classifying Lists, Next: Function Indirection, Prev: Symbol Forms, Up: Forms
- 9.2.3 Classification of List Forms
- ----------------------------------
- A form that is a nonempty list is either a function call, a macro call,
- or a special form, according to its first element. These three kinds
- of forms are evaluated in different ways, described below. The
- remaining list elements constitute the "arguments" for the function,
- macro, or special form.
- The first step in evaluating a nonempty list is to examine its first
- element. This element alone determines what kind of form the list is
- and how the rest of the list is to be processed. The first element is
- _not_ evaluated, as it would be in some Lisp dialects such as Scheme.
- File: elisp, Node: Function Indirection, Next: Function Forms, Prev: Classifying Lists, Up: Forms
- 9.2.4 Symbol Function Indirection
- ---------------------------------
- If the first element of the list is a symbol then evaluation examines
- the symbol's function cell, and uses its contents instead of the
- original symbol. If the contents are another symbol, this process,
- called "symbol function indirection", is repeated until it obtains a
- non-symbol. *Note Function Names::, for more information about symbol
- function indirection.
- One possible consequence of this process is an infinite loop, in the
- event that a symbol's function cell refers to the same symbol. Or a
- symbol may have a void function cell, in which case the subroutine
- `symbol-function' signals a `void-function' error. But if neither of
- these things happens, we eventually obtain a non-symbol, which ought to
- be a function or other suitable object.
- More precisely, we should now have a Lisp function (a lambda
- expression), a byte-code function, a primitive function, a Lisp macro,
- a special form, or an autoload object. Each of these types is a case
- described in one of the following sections. If the object is not one
- of these types, Emacs signals an `invalid-function' error.
- The following example illustrates the symbol indirection process. We
- use `fset' to set the function cell of a symbol and `symbol-function'
- to get the function cell contents (*note Function Cells::).
- Specifically, we store the symbol `car' into the function cell of
- `first', and the symbol `first' into the function cell of `erste'.
- ;; Build this function cell linkage:
- ;; ------------- ----- ------- -------
- ;; | #<subr car> | <-- | car | <-- | first | <-- | erste |
- ;; ------------- ----- ------- -------
- (symbol-function 'car)
- => #<subr car>
- (fset 'first 'car)
- => car
- (fset 'erste 'first)
- => first
- (erste '(1 2 3)) ; Call the function referenced by `erste'.
- => 1
- By contrast, the following example calls a function without any
- symbol function indirection, because the first element is an anonymous
- Lisp function, not a symbol.
- ((lambda (arg) (erste arg))
- '(1 2 3))
- => 1
- Executing the function itself evaluates its body; this does involve
- symbol function indirection when calling `erste'.
- This form is rarely used and is now deprecated. Instead, you should
- write it as:
- (funcall (lambda (arg) (erste arg))
- '(1 2 3))
- or just
- (let ((arg '(1 2 3))) (erste arg))
- The built-in function `indirect-function' provides an easy way to
- perform symbol function indirection explicitly.
- -- Function: indirect-function function &optional noerror
- This function returns the meaning of FUNCTION as a function. If
- FUNCTION is a symbol, then it finds FUNCTION's function definition
- and starts over with that value. If FUNCTION is not a symbol,
- then it returns FUNCTION itself.
- This function signals a `void-function' error if the final symbol
- is unbound and optional argument NOERROR is `nil' or omitted.
- Otherwise, if NOERROR is non-`nil', it returns `nil' if the final
- symbol is unbound.
- It signals a `cyclic-function-indirection' error if there is a
- loop in the chain of symbols.
- Here is how you could define `indirect-function' in Lisp:
- (defun indirect-function (function)
- (if (symbolp function)
- (indirect-function (symbol-function function))
- function))
- File: elisp, Node: Function Forms, Next: Macro Forms, Prev: Function Indirection, Up: Forms
- 9.2.5 Evaluation of Function Forms
- ----------------------------------
- If the first element of a list being evaluated is a Lisp function
- object, byte-code object or primitive function object, then that list is
- a "function call". For example, here is a call to the function `+':
- (+ 1 x)
- The first step in evaluating a function call is to evaluate the
- remaining elements of the list from left to right. The results are the
- actual argument values, one value for each list element. The next step
- is to call the function with this list of arguments, effectively using
- the function `apply' (*note Calling Functions::). If the function is
- written in Lisp, the arguments are used to bind the argument variables
- of the function (*note Lambda Expressions::); then the forms in the
- function body are evaluated in order, and the value of the last body
- form becomes the value of the function call.
- File: elisp, Node: Macro Forms, Next: Special Forms, Prev: Function Forms, Up: Forms
- 9.2.6 Lisp Macro Evaluation
- ---------------------------
- If the first element of a list being evaluated is a macro object, then
- the list is a "macro call". When a macro call is evaluated, the
- elements of the rest of the list are _not_ initially evaluated.
- Instead, these elements themselves are used as the arguments of the
- macro. The macro definition computes a replacement form, called the
- "expansion" of the macro, to be evaluated in place of the original
- form. The expansion may be any sort of form: a self-evaluating
- constant, a symbol, or a list. If the expansion is itself a macro call,
- this process of expansion repeats until some other sort of form results.
- Ordinary evaluation of a macro call finishes by evaluating the
- expansion. However, the macro expansion is not necessarily evaluated
- right away, or at all, because other programs also expand macro calls,
- and they may or may not evaluate the expansions.
- Normally, the argument expressions are not evaluated as part of
- computing the macro expansion, but instead appear as part of the
- expansion, so they are computed when the expansion is evaluated.
- For example, given a macro defined as follows:
- (defmacro cadr (x)
- (list 'car (list 'cdr x)))
- an expression such as `(cadr (assq 'handler list))' is a macro call,
- and its expansion is:
- (car (cdr (assq 'handler list)))
- Note that the argument `(assq 'handler list)' appears in the expansion.
- *Note Macros::, for a complete description of Emacs Lisp macros.
- File: elisp, Node: Special Forms, Next: Autoloading, Prev: Macro Forms, Up: Forms
- 9.2.7 Special Forms
- -------------------
- A "special form" is a primitive function specially marked so that its
- arguments are not all evaluated. Most special forms define control
- structures or perform variable bindings--things which functions cannot
- do.
- Each special form has its own rules for which arguments are evaluated
- and which are used without evaluation. Whether a particular argument is
- evaluated may depend on the results of evaluating other arguments.
- Here is a list, in alphabetical order, of all of the special forms in
- Emacs Lisp with a reference to where each is described.
- `and'
- *note Combining Conditions::
- `catch'
- *note Catch and Throw::
- `cond'
- *note Conditionals::
- `condition-case'
- *note Handling Errors::
- `defconst'
- *note Defining Variables::
- `defmacro'
- *note Defining Macros::
- `defun'
- *note Defining Functions::
- `defvar'
- *note Defining Variables::
- `function'
- *note Anonymous Functions::
- `if'
- *note Conditionals::
- `interactive'
- *note Interactive Call::
- `let'
- `let*'
- *note Local Variables::
- `or'
- *note Combining Conditions::
- `prog1'
- `prog2'
- `progn'
- *note Sequencing::
- `quote'
- *note Quoting::
- `save-current-buffer'
- *note Current Buffer::
- `save-excursion'
- *note Excursions::
- `save-restriction'
- *note Narrowing::
- `save-window-excursion'
- *note Window Configurations::
- `setq'
- *note Setting Variables::
- `setq-default'
- *note Creating Buffer-Local::
- `track-mouse'
- *note Mouse Tracking::
- `unwind-protect'
- *note Nonlocal Exits::
- `while'
- *note Iteration::
- `with-output-to-temp-buffer'
- *note Temporary Displays::
- Common Lisp note: Here are some comparisons of special forms in
- GNU Emacs Lisp and Common Lisp. `setq', `if', and `catch' are
- special forms in both Emacs Lisp and Common Lisp. `defun' is a
- special form in Emacs Lisp, but a macro in Common Lisp.
- `save-excursion' is a special form in Emacs Lisp, but doesn't
- exist in Common Lisp. `throw' is a special form in Common Lisp
- (because it must be able to throw multiple values), but it is a
- function in Emacs Lisp (which doesn't have multiple values).
- File: elisp, Node: Autoloading, Prev: Special Forms, Up: Forms
- 9.2.8 Autoloading
- -----------------
- The "autoload" feature allows you to call a function or macro whose
- function definition has not yet been loaded into Emacs. It specifies
- which file contains the definition. When an autoload object appears as
- a symbol's function definition, calling that symbol as a function
- automatically loads the specified file; then it calls the real
- definition loaded from that file. The way to arrange for an autoload
- object to appear as a symbol's function definition is described in
- *note Autoload::.
- File: elisp, Node: Quoting, Next: Backquote, Prev: Forms, Up: Evaluation
- 9.3 Quoting
- ===========
- The special form `quote' returns its single argument, as written,
- without evaluating it. This provides a way to include constant symbols
- and lists, which are not self-evaluating objects, in a program. (It is
- not necessary to quote self-evaluating objects such as numbers, strings,
- and vectors.)
- -- Special Form: quote object
- This special form returns OBJECT, without evaluating it.
- Because `quote' is used so often in programs, Lisp provides a
- convenient read syntax for it. An apostrophe character (`'') followed
- by a Lisp object (in read syntax) expands to a list whose first element
- is `quote', and whose second element is the object. Thus, the read
- syntax `'x' is an abbreviation for `(quote x)'.
- Here are some examples of expressions that use `quote':
- (quote (+ 1 2))
- => (+ 1 2)
- (quote foo)
- => foo
- 'foo
- => foo
- ''foo
- => (quote foo)
- '(quote foo)
- => (quote foo)
- ['foo]
- => [(quote foo)]
- Other quoting constructs include `function' (*note Anonymous
- Functions::), which causes an anonymous lambda expression written in
- Lisp to be compiled, and ``' (*note Backquote::), which is used to quote
- only part of a list, while computing and substituting other parts.
- File: elisp, Node: Backquote, Next: Eval, Prev: Quoting, Up: Evaluation
- 9.4 Backquote
- =============
- "Backquote constructs" allow you to quote a list, but selectively
- evaluate elements of that list. In the simplest case, it is identical
- to the special form `quote' (described in the previous section; *note
- Quoting::). For example, these two forms yield identical results:
- `(a list of (+ 2 3) elements)
- => (a list of (+ 2 3) elements)
- '(a list of (+ 2 3) elements)
- => (a list of (+ 2 3) elements)
- The special marker `,' inside of the argument to backquote indicates
- a value that isn't constant. The Emacs Lisp evaluator evaluates the
- argument of `,', and puts the value in the list structure:
- `(a list of ,(+ 2 3) elements)
- => (a list of 5 elements)
- Substitution with `,' is allowed at deeper levels of the list structure
- also. For example:
- `(1 2 (3 ,(+ 4 5)))
- => (1 2 (3 9))
- You can also "splice" an evaluated value into the resulting list,
- using the special marker `,@'. The elements of the spliced list become
- elements at the same level as the other elements of the resulting list.
- The equivalent code without using ``' is often unreadable. Here are
- some examples:
- (setq some-list '(2 3))
- => (2 3)
- (cons 1 (append some-list '(4) some-list))
- => (1 2 3 4 2 3)
- `(1 ,@some-list 4 ,@some-list)
- => (1 2 3 4 2 3)
- (setq list '(hack foo bar))
- => (hack foo bar)
- (cons 'use
- (cons 'the
- (cons 'words (append (cdr list) '(as elements)))))
- => (use the words foo bar as elements)
- `(use the words ,@(cdr list) as elements)
- => (use the words foo bar as elements)
- File: elisp, Node: Eval, Prev: Backquote, Up: Evaluation
- 9.5 Eval
- ========
- Most often, forms are evaluated automatically, by virtue of their
- occurrence in a program being run. On rare occasions, you may need to
- write code that evaluates a form that is computed at run time, such as
- after reading a form from text being edited or getting one from a
- property list. On these occasions, use the `eval' function. Often
- `eval' is not needed and something else should be used instead. For
- example, to get the value of a variable, while `eval' works,
- `symbol-value' is preferable; or rather than store expressions in a
- property list that then need to go through `eval', it is better to
- store functions instead that are then passed to `funcall'.
- The functions and variables described in this section evaluate forms,
- specify limits to the evaluation process, or record recently returned
- values. Loading a file also does evaluation (*note Loading::).
- It is generally cleaner and more flexible to store a function in a
- data structure, and call it with `funcall' or `apply', than to store an
- expression in the data structure and evaluate it. Using functions
- provides the ability to pass information to them as arguments.
- -- Function: eval form &optional lexical
- This is the basic function for evaluating an expression. It
- evaluates FORM in the current environment and returns the result.
- How the evaluation proceeds depends on the type of the object
- (*note Forms::).
- The argument LEXICAL, if non-`nil', means to evaluate FORM using
- lexical scoping rules for variables, instead of the default
- dynamic scoping rules. *Note Lexical Binding::.
- Since `eval' is a function, the argument expression that appears
- in a call to `eval' is evaluated twice: once as preparation before
- `eval' is called, and again by the `eval' function itself. Here
- is an example:
- (setq foo 'bar)
- => bar
- (setq bar 'baz)
- => baz
- ;; Here `eval' receives argument `foo'
- (eval 'foo)
- => bar
- ;; Here `eval' receives argument `bar', which is the value of `foo'
- (eval foo)
- => baz
- The number of currently active calls to `eval' is limited to
- `max-lisp-eval-depth' (see below).
- -- Command: eval-region start end &optional stream read-function
- This function evaluates the forms in the current buffer in the
- region defined by the positions START and END. It reads forms from
- the region and calls `eval' on them until the end of the region is
- reached, or until an error is signaled and not handled.
- By default, `eval-region' does not produce any output. However,
- if STREAM is non-`nil', any output produced by output functions
- (*note Output Functions::), as well as the values that result from
- evaluating the expressions in the region are printed using STREAM.
- *Note Output Streams::.
- If READ-FUNCTION is non-`nil', it should be a function, which is
- used instead of `read' to read expressions one by one. This
- function is called with one argument, the stream for reading
- input. You can also use the variable `load-read-function' (*note
- How Programs Do Loading: Definition of load-read-function.) to
- specify this function, but it is more robust to use the
- READ-FUNCTION argument.
- `eval-region' does not move point. It always returns `nil'.
- -- Command: eval-buffer &optional buffer-or-name stream filename
- unibyte print
- This is similar to `eval-region', but the arguments provide
- different optional features. `eval-buffer' operates on the entire
- accessible portion of buffer BUFFER-OR-NAME. BUFFER-OR-NAME can
- be a buffer, a buffer name (a string), or `nil' (or omitted),
- which means to use the current buffer. STREAM is used as in
- `eval-region', unless STREAM is `nil' and PRINT non-`nil'. In
- that case, values that result from evaluating the expressions are
- still discarded, but the output of the output functions is printed
- in the echo area. FILENAME is the file name to use for
- `load-history' (*note Unloading::), and defaults to
- `buffer-file-name' (*note Buffer File Name::). If UNIBYTE is
- non-`nil', `read' converts strings to unibyte whenever possible.
- `eval-current-buffer' is an alias for this command.
- -- User Option: max-lisp-eval-depth
- This variable defines the maximum depth allowed in calls to `eval',
- `apply', and `funcall' before an error is signaled (with error
- message `"Lisp nesting exceeds max-lisp-eval-depth"').
- This limit, with the associated error when it is exceeded, is one
- way Emacs Lisp avoids infinite recursion on an ill-defined
- function. If you increase the value of `max-lisp-eval-depth' too
- much, such code can cause stack overflow instead.
- The depth limit counts internal uses of `eval', `apply', and
- `funcall', such as for calling the functions mentioned in Lisp
- expressions, and recursive evaluation of function call arguments
- and function body forms, as well as explicit calls in Lisp code.
- The default value of this variable is 400. If you set it to a
- value less than 100, Lisp will reset it to 100 if the given value
- is reached. Entry to the Lisp debugger increases the value, if
- there is little room left, to make sure the debugger itself has
- room to execute.
- `max-specpdl-size' provides another limit on nesting. *Note Local
- Variables: Definition of max-specpdl-size.
- -- Variable: values
- The value of this variable is a list of the values returned by all
- the expressions that were read, evaluated, and printed from buffers
- (including the minibuffer) by the standard Emacs commands which do
- this. (Note that this does _not_ include evaluation in `*ielm*'
- buffers, nor evaluation using `C-j' in `lisp-interaction-mode'.)
- The elements are ordered most recent first.
- (setq x 1)
- => 1
- (list 'A (1+ 2) auto-save-default)
- => (A 3 t)
- values
- => ((A 3 t) 1 ...)
- This variable is useful for referring back to values of forms
- recently evaluated. It is generally a bad idea to print the value
- of `values' itself, since this may be very long. Instead, examine
- particular elements, like this:
- ;; Refer to the most recent evaluation result.
- (nth 0 values)
- => (A 3 t)
- ;; That put a new element on,
- ;; so all elements move back one.
- (nth 1 values)
- => (A 3 t)
- ;; This gets the element that was next-to-most-recent
- ;; before this example.
- (nth 3 values)
- => 1
- File: elisp, Node: Control Structures, Next: Variables, Prev: Evaluation, Up: Top
- 10 Control Structures
- *********************
- A Lisp program consists of a set of "expressions", or "forms" (*note
- Forms::). We control the order of execution of these forms by
- enclosing them in "control structures". Control structures are special
- forms which control when, whether, or how many times to execute the
- forms they contain.
- The simplest order of execution is sequential execution: first form
- A, then form B, and so on. This is what happens when you write several
- forms in succession in the body of a function, or at top level in a
- file of Lisp code--the forms are executed in the order written. We
- call this "textual order". For example, if a function body consists of
- two forms A and B, evaluation of the function evaluates first A and
- then B. The result of evaluating B becomes the value of the function.
- Explicit control structures make possible an order of execution other
- than sequential.
- Emacs Lisp provides several kinds of control structure, including
- other varieties of sequencing, conditionals, iteration, and (controlled)
- jumps--all discussed below. The built-in control structures are
- special forms since their subforms are not necessarily evaluated or not
- evaluated sequentially. You can use macros to define your own control
- structure constructs (*note Macros::).
- * Menu:
- * Sequencing:: Evaluation in textual order.
- * Conditionals:: `if', `cond', `when', `unless'.
- * Combining Conditions:: `and', `or', `not'.
- * Iteration:: `while' loops.
- * Nonlocal Exits:: Jumping out of a sequence.
- File: elisp, Node: Sequencing, Next: Conditionals, Up: Control Structures
- 10.1 Sequencing
- ===============
- Evaluating forms in the order they appear is the most common way
- control passes from one form to another. In some contexts, such as in a
- function body, this happens automatically. Elsewhere you must use a
- control structure construct to do this: `progn', the simplest control
- construct of Lisp.
- A `progn' special form looks like this:
- (progn A B C ...)
- and it says to execute the forms A, B, C, and so on, in that order.
- These forms are called the "body" of the `progn' form. The value of
- the last form in the body becomes the value of the entire `progn'.
- `(progn)' returns `nil'.
- In the early days of Lisp, `progn' was the only way to execute two
- or more forms in succession and use the value of the last of them. But
- programmers found they often needed to use a `progn' in the body of a
- function, where (at that time) only one form was allowed. So the body
- of a function was made into an "implicit `progn'": several forms are
- allowed just as in the body of an actual `progn'. Many other control
- structures likewise contain an implicit `progn'. As a result, `progn'
- is not used as much as it was many years ago. It is needed now most
- often inside an `unwind-protect', `and', `or', or in the THEN-part of
- an `if'.
- -- Special Form: progn forms...
- This special form evaluates all of the FORMS, in textual order,
- returning the result of the final form.
- (progn (print "The first form")
- (print "The second form")
- (print "The third form"))
- -| "The first form"
- -| "The second form"
- -| "The third form"
- => "The third form"
- Two other constructs likewise evaluate a series of forms but return
- different values:
- -- Special Form: prog1 form1 forms...
- This special form evaluates FORM1 and all of the FORMS, in textual
- order, returning the result of FORM1.
- (prog1 (print "The first form")
- (print "The second form")
- (print "The third form"))
- -| "The first form"
- -| "The second form"
- -| "The third form"
- => "The first form"
- Here is a way to remove the first element from a list in the
- variable `x', then return the value of that former element:
- (prog1 (car x) (setq x (cdr x)))
- -- Special Form: prog2 form1 form2 forms...
- This special form evaluates FORM1, FORM2, and all of the following
- FORMS, in textual order, returning the result of FORM2.
- (prog2 (print "The first form")
- (print "The second form")
- (print "The third form"))
- -| "The first form"
- -| "The second form"
- -| "The third form"
- => "The second form"
- File: elisp, Node: Conditionals, Next: Combining Conditions, Prev: Sequencing, Up: Control Structures
- 10.2 Conditionals
- =================
- Conditional control structures choose among alternatives. Emacs Lisp
- has four conditional forms: `if', which is much the same as in other
- languages; `when' and `unless', which are variants of `if'; and `cond',
- which is a generalized case statement.
- -- Special Form: if condition then-form else-forms...
- `if' chooses between the THEN-FORM and the ELSE-FORMS based on the
- value of CONDITION. If the evaluated CONDITION is non-`nil',
- THEN-FORM is evaluated and the result returned. Otherwise, the
- ELSE-FORMS are evaluated in textual order, and the value of the
- last one is returned. (The ELSE part of `if' is an example of an
- implicit `progn'. *Note Sequencing::.)
- If CONDITION has the value `nil', and no ELSE-FORMS are given,
- `if' returns `nil'.
- `if' is a special form because the branch that is not selected is
- never evaluated--it is ignored. Thus, in this example, `true' is
- not printed because `print' is never called:
- (if nil
- (print 'true)
- 'very-false)
- => very-false
- -- Macro: when condition then-forms...
- This is a variant of `if' where there are no ELSE-FORMS, and
- possibly several THEN-FORMS. In particular,
- (when CONDITION A B C)
- is entirely equivalent to
- (if CONDITION (progn A B C) nil)
- -- Macro: unless condition forms...
- This is a variant of `if' where there is no THEN-FORM:
- (unless CONDITION A B C)
- is entirely equivalent to
- (if CONDITION nil
- A B C)
- -- Special Form: cond clause...
- `cond' chooses among an arbitrary number of alternatives. Each
- CLAUSE in the `cond' must be a list. The CAR of this list is the
- CONDITION; the remaining elements, if any, the BODY-FORMS. Thus,
- a clause looks like this:
- (CONDITION BODY-FORMS...)
- `cond' tries the clauses in textual order, by evaluating the
- CONDITION of each clause. If the value of CONDITION is non-`nil',
- the clause "succeeds"; then `cond' evaluates its BODY-FORMS, and
- the value of the last of BODY-FORMS becomes the value of the
- `cond'. The remaining clauses are ignored.
- If the value of CONDITION is `nil', the clause "fails", so the
- `cond' moves on to the following clause, trying its CONDITION.
- If every CONDITION evaluates to `nil', so that every clause fails,
- `cond' returns `nil'.
- A clause may also look like this:
- (CONDITION)
- Then, if CONDITION is non-`nil' when tested, the value of
- CONDITION becomes the value of the `cond' form.
- The following example has four clauses, which test for the cases
- where the value of `x' is a number, string, buffer and symbol,
- respectively:
- (cond ((numberp x) x)
- ((stringp x) x)
- ((bufferp x)
- (setq temporary-hack x) ; multiple body-forms
- (buffer-name x)) ; in one clause
- ((symbolp x) (symbol-value x)))
- Often we want to execute the last clause whenever none of the
- previous clauses was successful. To do this, we use `t' as the
- CONDITION of the last clause, like this: `(t BODY-FORMS)'. The
- form `t' evaluates to `t', which is never `nil', so this clause
- never fails, provided the `cond' gets to it at all. For example:
- (setq a 5)
- (cond ((eq a 'hack) 'foo)
- (t "default"))
- => "default"
- This `cond' expression returns `foo' if the value of `a' is
- `hack', and returns the string `"default"' otherwise.
- Any conditional construct can be expressed with `cond' or with `if'.
- Therefore, the choice between them is a matter of style. For example:
- (if A B C)
- ==
- (cond (A B) (t C))
- File: elisp, Node: Combining Conditions, Next: Iteration, Prev: Conditionals, Up: Control Structures
- 10.3 Constructs for Combining Conditions
- ========================================
- This section describes three constructs that are often used together
- with `if' and `cond' to express complicated conditions. The constructs
- `and' and `or' can also be used individually as kinds of multiple
- conditional constructs.
- -- Function: not condition
- This function tests for the falsehood of CONDITION. It returns
- `t' if CONDITION is `nil', and `nil' otherwise. The function
- `not' is identical to `null', and we recommend using the name
- `null' if you are testing for an empty list.
- -- Special Form: and conditions...
- The `and' special form tests whether all the CONDITIONS are true.
- It works by evaluating the CONDITIONS one by one in the order
- written.
- If any of the CONDITIONS evaluates to `nil', then the result of
- the `and' must be `nil' regardless of the remaining CONDITIONS; so
- `and' returns `nil' right away, ignoring the remaining CONDITIONS.
- If all the CONDITIONS turn out non-`nil', then the value of the
- last of them becomes the value of the `and' form. Just `(and)',
- with no CONDITIONS, returns `t', appropriate because all the
- CONDITIONS turned out non-`nil'. (Think about it; which one did
- not?)
- Here is an example. The first condition returns the integer 1,
- which is not `nil'. Similarly, the second condition returns the
- integer 2, which is not `nil'. The third condition is `nil', so
- the remaining condition is never evaluated.
- (and (print 1) (print 2) nil (print 3))
- -| 1
- -| 2
- => nil
- Here is a more realistic example of using `and':
- (if (and (consp foo) (eq (car foo) 'x))
- (message "foo is a list starting with x"))
- Note that `(car foo)' is not executed if `(consp foo)' returns
- `nil', thus avoiding an error.
- `and' expressions can also be written using either `if' or `cond'.
- Here's how:
- (and ARG1 ARG2 ARG3)
- ==
- (if ARG1 (if ARG2 ARG3))
- ==
- (cond (ARG1 (cond (ARG2 ARG3))))
- -- Special Form: or conditions...
- The `or' special form tests whether at least one of the CONDITIONS
- is true. It works by evaluating all the CONDITIONS one by one in
- the order written.
- If any of the CONDITIONS evaluates to a non-`nil' value, then the
- result of the `or' must be non-`nil'; so `or' returns right away,
- ignoring the remaining CONDITIONS. The value it returns is the
- non-`nil' value of the condition just evaluated.
- If all the CONDITIONS turn out `nil', then the `or' expression
- returns `nil'. Just `(or)', with no CONDITIONS, returns `nil',
- appropriate because all the CONDITIONS turned out `nil'. (Think
- about it; which one did not?)
- For example, this expression tests whether `x' is either `nil' or
- the integer zero:
- (or (eq x nil) (eq x 0))
- Like the `and' construct, `or' can be written in terms of `cond'.
- For example:
- (or ARG1 ARG2 ARG3)
- ==
- (cond (ARG1)
- (ARG2)
- (ARG3))
- You could almost write `or' in terms of `if', but not quite:
- (if ARG1 ARG1
- (if ARG2 ARG2
- ARG3))
- This is not completely equivalent because it can evaluate ARG1 or
- ARG2 twice. By contrast, `(or ARG1 ARG2 ARG3)' never evaluates
- any argument more than once.
- File: elisp, Node: Iteration, Next: Nonlocal Exits, Prev: Combining Conditions, Up: Control Structures
- 10.4 Iteration
- ==============
- Iteration means executing part of a program repetitively. For example,
- you might want to repeat some computation once for each element of a
- list, or once for each integer from 0 to N. You can do this in Emacs
- Lisp with the special form `while':
- -- Special Form: while condition forms...
- `while' first evaluates CONDITION. If the result is non-`nil', it
- evaluates FORMS in textual order. Then it reevaluates CONDITION,
- and if the result is non-`nil', it evaluates FORMS again. This
- process repeats until CONDITION evaluates to `nil'.
- There is no limit on the number of iterations that may occur. The
- loop will continue until either CONDITION evaluates to `nil' or
- until an error or `throw' jumps out of it (*note Nonlocal Exits::).
- The value of a `while' form is always `nil'.
- (setq num 0)
- => 0
- (while (< num 4)
- (princ (format "Iteration %d." num))
- (setq num (1+ num)))
- -| Iteration 0.
- -| Iteration 1.
- -| Iteration 2.
- -| Iteration 3.
- => nil
- To write a "repeat...until" loop, which will execute something on
- each iteration and then do the end-test, put the body followed by
- the end-test in a `progn' as the first argument of `while', as
- shown here:
- (while (progn
- (forward-line 1)
- (not (looking-at "^$"))))
- This moves forward one line and continues moving by lines until it
- reaches an empty line. It is peculiar in that the `while' has no
- body, just the end test (which also does the real work of moving
- point).
- The `dolist' and `dotimes' macros provide convenient ways to write
- two common kinds of loops.
- -- Macro: dolist (var list [result]) body...
- This construct executes BODY once for each element of LIST,
- binding the variable VAR locally to hold the current element.
- Then it returns the value of evaluating RESULT, or `nil' if RESULT
- is omitted. For example, here is how you could use `dolist' to
- define the `reverse' function:
- (defun reverse (list)
- (let (value)
- (dolist (elt list value)
- (setq value (cons elt value)))))
- -- Macro: dotimes (var count [result]) body...
- This construct executes BODY once for each integer from 0
- (inclusive) to COUNT (exclusive), binding the variable VAR to the
- integer for the current iteration. Then it returns the value of
- evaluating RESULT, or `nil' if RESULT is omitted. Here is an
- example of using `dotimes' to do something 100 times:
- (dotimes (i 100)
- (insert "I will not obey absurd orders\n"))
- File: elisp, Node: Nonlocal Exits, Prev: Iteration, Up: Control Structures
- 10.5 Nonlocal Exits
- ===================
- A "nonlocal exit" is a transfer of control from one point in a program
- to another remote point. Nonlocal exits can occur in Emacs Lisp as a
- result of errors; you can also use them under explicit control.
- Nonlocal exits unbind all variable bindings made by the constructs being
- exited.
- * Menu:
- * Catch and Throw:: Nonlocal exits for the program's own purposes.
- * Examples of Catch:: Showing how such nonlocal exits can be written.
- * Errors:: How errors are signaled and handled.
- * Cleanups:: Arranging to run a cleanup form if an error happens.
- File: elisp, Node: Catch and Throw, Next: Examples of Catch, Up: Nonlocal Exits
- 10.5.1 Explicit Nonlocal Exits: `catch' and `throw'
- ---------------------------------------------------
- Most control constructs affect only the flow of control within the
- construct itself. The function `throw' is the exception to this rule
- of normal program execution: it performs a nonlocal exit on request.
- (There are other exceptions, but they are for error handling only.)
- `throw' is used inside a `catch', and jumps back to that `catch'. For
- example:
- (defun foo-outer ()
- (catch 'foo
- (foo-inner)))
- (defun foo-inner ()
- ...
- (if x
- (throw 'foo t))
- ...)
- The `throw' form, if executed, transfers control straight back to the
- corresponding `catch', which returns immediately. The code following
- the `throw' is not executed. The second argument of `throw' is used as
- the return value of the `catch'.
- The function `throw' finds the matching `catch' based on the first
- argument: it searches for a `catch' whose first argument is `eq' to the
- one specified in the `throw'. If there is more than one applicable
- `catch', the innermost one takes precedence. Thus, in the above
- example, the `throw' specifies `foo', and the `catch' in `foo-outer'
- specifies the same symbol, so that `catch' is the applicable one
- (assuming there is no other matching `catch' in between).
- Executing `throw' exits all Lisp constructs up to the matching
- `catch', including function calls. When binding constructs such as
- `let' or function calls are exited in this way, the bindings are
- unbound, just as they are when these constructs exit normally (*note
- Local Variables::). Likewise, `throw' restores the buffer and position
- saved by `save-excursion' (*note Excursions::), and the narrowing
- status saved by `save-restriction' and the window selection saved by
- `save-window-excursion' (*note Window Configurations::). It also runs
- any cleanups established with the `unwind-protect' special form when it
- exits that form (*note Cleanups::).
- The `throw' need not appear lexically within the `catch' that it
- jumps to. It can equally well be called from another function called
- within the `catch'. As long as the `throw' takes place chronologically
- after entry to the `catch', and chronologically before exit from it, it
- has access to that `catch'. This is why `throw' can be used in
- commands such as `exit-recursive-edit' that throw back to the editor
- command loop (*note Recursive Editing::).
- Common Lisp note: Most other versions of Lisp, including Common
- Lisp, have several ways of transferring control nonsequentially:
- `return', `return-from', and `go', for example. Emacs Lisp has
- only `throw'.
- -- Special Form: catch tag body...
- `catch' establishes a return point for the `throw' function. The
- return point is distinguished from other such return points by
- TAG, which may be any Lisp object except `nil'. The argument TAG
- is evaluated normally before the return point is established.
- With the return point in effect, `catch' evaluates the forms of the
- BODY in textual order. If the forms execute normally (without
- error or nonlocal exit) the value of the last body form is
- returned from the `catch'.
- If a `throw' is executed during the execution of BODY, specifying
- the same value TAG, the `catch' form exits immediately; the value
- it returns is whatever was specified as the second argument of
- `throw'.
- -- Function: throw tag value
- The purpose of `throw' is to return from a return point previously
- established with `catch'. The argument TAG is used to choose
- among the various existing return points; it must be `eq' to the
- value specified in the `catch'. If multiple return points match
- TAG, the innermost one is used.
- The argument VALUE is used as the value to return from that
- `catch'.
- If no return point is in effect with tag TAG, then a `no-catch'
- error is signaled with data `(TAG VALUE)'.
- File: elisp, Node: Examples of Catch, Next: Errors, Prev: Catch and Throw, Up: Nonlocal Exits
- 10.5.2 Examples of `catch' and `throw'
- --------------------------------------
- One way to use `catch' and `throw' is to exit from a doubly nested
- loop. (In most languages, this would be done with a "goto".) Here we
- compute `(foo I J)' for I and J varying from 0 to 9:
- (defun search-foo ()
- (catch 'loop
- (let ((i 0))
- (while (< i 10)
- (let ((j 0))
- (while (< j 10)
- (if (foo i j)
- (throw 'loop (list i j)))
- (setq j (1+ j))))
- (setq i (1+ i))))))
- If `foo' ever returns non-`nil', we stop immediately and return a list
- of I and J. If `foo' always returns `nil', the `catch' returns
- normally, and the value is `nil', since that is the result of the
- `while'.
- Here are two tricky examples, slightly different, showing two return
- points at once. First, two return points with the same tag, `hack':
- (defun catch2 (tag)
- (catch tag
- (throw 'hack 'yes)))
- => catch2
- (catch 'hack
- (print (catch2 'hack))
- 'no)
- -| yes
- => no
- Since both return points have tags that match the `throw', it goes to
- the inner one, the one established in `catch2'. Therefore, `catch2'
- returns normally with value `yes', and this value is printed. Finally
- the second body form in the outer `catch', which is `'no', is evaluated
- and returned from the outer `catch'.
- Now let's change the argument given to `catch2':
- (catch 'hack
- (print (catch2 'quux))
- 'no)
- => yes
- We still have two return points, but this time only the outer one has
- the tag `hack'; the inner one has the tag `quux' instead. Therefore,
- `throw' makes the outer `catch' return the value `yes'. The function
- `print' is never called, and the body-form `'no' is never evaluated.
- File: elisp, Node: Errors, Next: Cleanups, Prev: Examples of Catch, Up: Nonlocal Exits
- 10.5.3 Errors
- -------------
- When Emacs Lisp attempts to evaluate a form that, for some reason,
- cannot be evaluated, it "signals" an "error".
- When an error is signaled, Emacs's default reaction is to print an
- error message and terminate execution of the current command. This is
- the right thing to do in most cases, such as if you type `C-f' at the
- end of the buffer.
- In complicated programs, simple termination may not be what you want.
- For example, the program may have made temporary changes in data
- structures, or created temporary buffers that should be deleted before
- the program is finished. In such cases, you would use `unwind-protect'
- to establish "cleanup expressions" to be evaluated in case of error.
- (*Note Cleanups::.) Occasionally, you may wish the program to continue
- execution despite an error in a subroutine. In these cases, you would
- use `condition-case' to establish "error handlers" to recover control
- in case of error.
- Resist the temptation to use error handling to transfer control from
- one part of the program to another; use `catch' and `throw' instead.
- *Note Catch and Throw::.
- * Menu:
- * Signaling Errors:: How to report an error.
- * Processing of Errors:: What Emacs does when you report an error.
- * Handling Errors:: How you can trap errors and continue execution.
- * Error Symbols:: How errors are classified for trapping them.
- File: elisp, Node: Signaling Errors, Next: Processing of Errors, Up: Errors
- 10.5.3.1 How to Signal an Error
- ...............................
- "Signaling" an error means beginning error processing. Error
- processing normally aborts all or part of the running program and
- returns to a point that is set up to handle the error (*note Processing
- of Errors::). Here we describe how to signal an error.
- Most errors are signaled "automatically" within Lisp primitives
- which you call for other purposes, such as if you try to take the CAR
- of an integer or move forward a character at the end of the buffer.
- You can also signal errors explicitly with the functions `error' and
- `signal'.
- Quitting, which happens when the user types `C-g', is not considered
- an error, but it is handled almost like an error. *Note Quitting::.
- Every error specifies an error message, one way or another. The
- message should state what is wrong ("File does not exist"), not how
- things ought to be ("File must exist"). The convention in Emacs Lisp
- is that error messages should start with a capital letter, but should
- not end with any sort of punctuation.
- -- Function: error format-string &rest args
- This function signals an error with an error message constructed by
- applying `format' (*note Formatting Strings::) to FORMAT-STRING
- and ARGS.
- These examples show typical uses of `error':
- (error "That is an error -- try something else")
- error--> That is an error -- try something else
- (error "You have committed %d errors" 10)
- error--> You have committed 10 errors
- `error' works by calling `signal' with two arguments: the error
- symbol `error', and a list containing the string returned by
- `format'.
- *Warning:* If you want to use your own string as an error message
- verbatim, don't just write `(error STRING)'. If STRING contains
- `%', it will be interpreted as a format specifier, with
- undesirable results. Instead, use `(error "%s" STRING)'.
- -- Function: signal error-symbol data
- This function signals an error named by ERROR-SYMBOL. The
- argument DATA is a list of additional Lisp objects relevant to the
- circumstances of the error.
- The argument ERROR-SYMBOL must be an "error symbol"--a symbol
- bearing a property `error-conditions' whose value is a list of
- condition names. This is how Emacs Lisp classifies different
- sorts of errors. *Note Error Symbols::, for a description of error
- symbols, error conditions and condition names.
- If the error is not handled, the two arguments are used in printing
- the error message. Normally, this error message is provided by the
- `error-message' property of ERROR-SYMBOL. If DATA is non-`nil',
- this is followed by a colon and a comma separated list of the
- unevaluated elements of DATA. For `error', the error message is
- the CAR of DATA (that must be a string). Subcategories of
- `file-error' are handled specially.
- The number and significance of the objects in DATA depends on
- ERROR-SYMBOL. For example, with a `wrong-type-argument' error,
- there should be two objects in the list: a predicate that
- describes the type that was expected, and the object that failed
- to fit that type.
- Both ERROR-SYMBOL and DATA are available to any error handlers
- that handle the error: `condition-case' binds a local variable to
- a list of the form `(ERROR-SYMBOL . DATA)' (*note Handling
- Errors::).
- The function `signal' never returns.
- (signal 'wrong-number-of-arguments '(x y))
- error--> Wrong number of arguments: x, y
- (signal 'no-such-error '("My unknown error condition"))
- error--> peculiar error: "My unknown error condition"
- Common Lisp note: Emacs Lisp has nothing like the Common Lisp
- concept of continuable errors.
- File: elisp, Node: Processing of Errors, Next: Handling Errors, Prev: Signaling Errors, Up: Errors
- 10.5.3.2 How Emacs Processes Errors
- ...................................
- When an error is signaled, `signal' searches for an active "handler"
- for the error. A handler is a sequence of Lisp expressions designated
- to be executed if an error happens in part of the Lisp program. If the
- error has an applicable handler, the handler is executed, and control
- resumes following the handler. The handler executes in the environment
- of the `condition-case' that established it; all functions called
- within that `condition-case' have already been exited, and the handler
- cannot return to them.
- If there is no applicable handler for the error, it terminates the
- current command and returns control to the editor command loop. (The
- command loop has an implicit handler for all kinds of errors.) The
- command loop's handler uses the error symbol and associated data to
- print an error message. You can use the variable
- `command-error-function' to control how this is done:
- -- Variable: command-error-function
- This variable, if non-`nil', specifies a function to use to handle
- errors that return control to the Emacs command loop. The
- function should take three arguments: DATA, a list of the same
- form that `condition-case' would bind to its variable; CONTEXT, a
- string describing the situation in which the error occurred, or
- (more often) `nil'; and CALLER, the Lisp function which called the
- primitive that signaled the error.
- An error that has no explicit handler may call the Lisp debugger.
- The debugger is enabled if the variable `debug-on-error' (*note Error
- Debugging::) is non-`nil'. Unlike error handlers, the debugger runs in
- the environment of the error, so that you can examine values of
- variables precisely as they were at the time of the error.
- File: elisp, Node: Handling Errors, Next: Error Symbols, Prev: Processing of Errors, Up: Errors
- 10.5.3.3 Writing Code to Handle Errors
- ......................................
- The usual effect of signaling an error is to terminate the command that
- is running and return immediately to the Emacs editor command loop.
- You can arrange to trap errors occurring in a part of your program by
- establishing an error handler, with the special form `condition-case'.
- A simple example looks like this:
- (condition-case nil
- (delete-file filename)
- (error nil))
- This deletes the file named FILENAME, catching any error and returning
- `nil' if an error occurs. (You can use the macro `ignore-errors' for a
- simple case like this; see below.)
- The `condition-case' construct is often used to trap errors that are
- predictable, such as failure to open a file in a call to
- `insert-file-contents'. It is also used to trap errors that are
- totally unpredictable, such as when the program evaluates an expression
- read from the user.
- The second argument of `condition-case' is called the "protected
- form". (In the example above, the protected form is a call to
- `delete-file'.) The error handlers go into effect when this form
- begins execution and are deactivated when this form returns. They
- remain in effect for all the intervening time. In particular, they are
- in effect during the execution of functions called by this form, in
- their subroutines, and so on. This is a good thing, since, strictly
- speaking, errors can be signaled only by Lisp primitives (including
- `signal' and `error') called by the protected form, not by the
- protected form itself.
- The arguments after the protected form are handlers. Each handler
- lists one or more "condition names" (which are symbols) to specify
- which errors it will handle. The error symbol specified when an error
- is signaled also defines a list of condition names. A handler applies
- to an error if they have any condition names in common. In the example
- above, there is one handler, and it specifies one condition name,
- `error', which covers all errors.
- The search for an applicable handler checks all the established
- handlers starting with the most recently established one. Thus, if two
- nested `condition-case' forms offer to handle the same error, the inner
- of the two gets to handle it.
- If an error is handled by some `condition-case' form, this
- ordinarily prevents the debugger from being run, even if
- `debug-on-error' says this error should invoke the debugger.
- If you want to be able to debug errors that are caught by a
- `condition-case', set the variable `debug-on-signal' to a non-`nil'
- value. You can also specify that a particular handler should let the
- debugger run first, by writing `debug' among the conditions, like this:
- (condition-case nil
- (delete-file filename)
- ((debug error) nil))
- The effect of `debug' here is only to prevent `condition-case' from
- suppressing the call to the debugger. Any given error will invoke the
- debugger only if `debug-on-error' and the other usual filtering
- mechanisms say it should. *Note Error Debugging::.
- -- Macro: condition-case-unless-debug var protected-form handlers...
- The macro `condition-case-unless-debug' provides another way to
- handle debugging of such forms. It behaves exactly like
- `condition-case', unless the variable `debug-on-error' is
- non-`nil', in which case it does not handle any errors at all.
- Once Emacs decides that a certain handler handles the error, it
- returns control to that handler. To do so, Emacs unbinds all variable
- bindings made by binding constructs that are being exited, and executes
- the cleanups of all `unwind-protect' forms that are being exited. Once
- control arrives at the handler, the body of the handler executes
- normally.
- After execution of the handler body, execution returns from the
- `condition-case' form. Because the protected form is exited completely
- before execution of the handler, the handler cannot resume execution at
- the point of the error, nor can it examine variable bindings that were
- made within the protected form. All it can do is clean up and proceed.
- Error signaling and handling have some resemblance to `throw' and
- `catch' (*note Catch and Throw::), but they are entirely separate
- facilities. An error cannot be caught by a `catch', and a `throw'
- cannot be handled by an error handler (though using `throw' when there
- is no suitable `catch' signals an error that can be handled).
- -- Special Form: condition-case var protected-form handlers...
- This special form establishes the error handlers HANDLERS around
- the execution of PROTECTED-FORM. If PROTECTED-FORM executes
- without error, the value it returns becomes the value of the
- `condition-case' form; in this case, the `condition-case' has no
- effect. The `condition-case' form makes a difference when an
- error occurs during PROTECTED-FORM.
- Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'.
- Here CONDITIONS is an error condition name to be handled, or a
- list of condition names (which can include `debug' to allow the
- debugger to run before the handler); BODY is one or more Lisp
- expressions to be executed when this handler handles an error.
- Here are examples of handlers:
- (error nil)
- (arith-error (message "Division by zero"))
- ((arith-error file-error)
- (message
- "Either division by zero or failure to open a file"))
- Each error that occurs has an "error symbol" that describes what
- kind of error it is. The `error-conditions' property of this
- symbol is a list of condition names (*note Error Symbols::). Emacs
- searches all the active `condition-case' forms for a handler that
- specifies one or more of these condition names; the innermost
- matching `condition-case' handles the error. Within this
- `condition-case', the first applicable handler handles the error.
- After executing the body of the handler, the `condition-case'
- returns normally, using the value of the last form in the handler
- body as the overall value.
- The argument VAR is a variable. `condition-case' does not bind
- this variable when executing the PROTECTED-FORM, only when it
- handles an error. At that time, it binds VAR locally to an "error
- description", which is a list giving the particulars of the error.
- The error description has the form `(ERROR-SYMBOL . DATA)'. The
- handler can refer to this list to decide what to do. For example,
- if the error is for failure opening a file, the file name is the
- second element of DATA--the third element of the error description.
- If VAR is `nil', that means no variable is bound. Then the error
- symbol and associated data are not available to the handler.
- Sometimes it is necessary to re-throw a signal caught by
- `condition-case', for some outer-level handler to catch. Here's
- how to do that:
- (signal (car err) (cdr err))
- where `err' is the error description variable, the first argument
- to `condition-case' whose error condition you want to re-throw.
- *Note Definition of signal::.
- -- Function: error-message-string error-descriptor
- This function returns the error message string for a given error
- descriptor. It is useful if you want to handle an error by
- printing the usual error message for that error. *Note Definition
- of signal::.
- Here is an example of using `condition-case' to handle the error
- that results from dividing by zero. The handler displays the error
- message (but without a beep), then returns a very large number.
- (defun safe-divide (dividend divisor)
- (condition-case err
- ;; Protected form.
- (/ dividend divisor)
- ;; The handler.
- (arith-error ; Condition.
- ;; Display the usual message for this error.
- (message "%s" (error-message-string err))
- 1000000)))
- => safe-divide
- (safe-divide 5 0)
- -| Arithmetic error: (arith-error)
- => 1000000
- The handler specifies condition name `arith-error' so that it will
- handle only division-by-zero errors. Other kinds of errors will not be
- handled (by this `condition-case'). Thus:
- (safe-divide nil 3)
- error--> Wrong type argument: number-or-marker-p, nil
- Here is a `condition-case' that catches all kinds of errors,
- including those from `error':
- (setq baz 34)
- => 34
- (condition-case err
- (if (eq baz 35)
- t
- ;; This is a call to the function `error'.
- (error "Rats! The variable %s was %s, not 35" 'baz baz))
- ;; This is the handler; it is not a form.
- (error (princ (format "The error was: %s" err))
- 2))
- -| The error was: (error "Rats! The variable baz was 34, not 35")
- => 2
- -- Macro: ignore-errors body...
- This construct executes BODY, ignoring any errors that occur
- during its execution. If the execution is without error,
- `ignore-errors' returns the value of the last form in BODY;
- otherwise, it returns `nil'.
- Here's the example at the beginning of this subsection rewritten
- using `ignore-errors':
- (ignore-errors
- (delete-file filename))
- -- Macro: with-demoted-errors body...
- This macro is like a milder version of `ignore-errors'. Rather
- than suppressing errors altogether, it converts them into messages.
- Use this form around code that is not expected to signal errors,
- but should be robust if one does occur. Note that this macro uses
- `condition-case-unless-debug' rather than `condition-case'.
- File: elisp, Node: Error Symbols, Prev: Handling Errors, Up: Errors
- 10.5.3.4 Error Symbols and Condition Names
- ..........................................
- When you signal an error, you specify an "error symbol" to specify the
- kind of error you have in mind. Each error has one and only one error
- symbol to categorize it. This is the finest classification of errors
- defined by the Emacs Lisp language.
- These narrow classifications are grouped into a hierarchy of wider
- classes called "error conditions", identified by "condition names".
- The narrowest such classes belong to the error symbols themselves: each
- error symbol is also a condition name. There are also condition names
- for more extensive classes, up to the condition name `error' which
- takes in all kinds of errors (but not `quit'). Thus, each error has
- one or more condition names: `error', the error symbol if that is
- distinct from `error', and perhaps some intermediate classifications.
- In order for a symbol to be an error symbol, it must have an
- `error-conditions' property which gives a list of condition names.
- This list defines the conditions that this kind of error belongs to.
- (The error symbol itself, and the symbol `error', should always be
- members of this list.) Thus, the hierarchy of condition names is
- defined by the `error-conditions' properties of the error symbols.
- Because quitting is not considered an error, the value of the
- `error-conditions' property of `quit' is just `(quit)'.
- In addition to the `error-conditions' list, the error symbol should
- have an `error-message' property whose value is a string to be printed
- when that error is signaled but not handled. If the error symbol has
- no `error-message' property or if the `error-message' property exists,
- but is not a string, the error message `peculiar error' is used. *Note
- Definition of signal::.
- Here is how we define a new error symbol, `new-error':
- (put 'new-error
- 'error-conditions
- '(error my-own-errors new-error))
- => (error my-own-errors new-error)
- (put 'new-error 'error-message "A new error")
- => "A new error"
- This error has three condition names: `new-error', the narrowest
- classification; `my-own-errors', which we imagine is a wider
- classification; and `error', which is the widest of all.
- The error string should start with a capital letter but it should
- not end with a period. This is for consistency with the rest of Emacs.
- Naturally, Emacs will never signal `new-error' on its own; only an
- explicit call to `signal' (*note Definition of signal::) in your code
- can do this:
- (signal 'new-error '(x y))
- error--> A new error: x, y
- This error can be handled through any of the three condition names.
- This example handles `new-error' and any other errors in the class
- `my-own-errors':
- (condition-case foo
- (bar nil t)
- (my-own-errors nil))
- The significant way that errors are classified is by their condition
- names--the names used to match errors with handlers. An error symbol
- serves only as a convenient way to specify the intended error message
- and list of condition names. It would be cumbersome to give `signal' a
- list of condition names rather than one error symbol.
- By contrast, using only error symbols without condition names would
- seriously decrease the power of `condition-case'. Condition names make
- it possible to categorize errors at various levels of generality when
- you write an error handler. Using error symbols alone would eliminate
- all but the narrowest level of classification.
- *Note Standard Errors::, for a list of the main error symbols and
- their conditions.
- File: elisp, Node: Cleanups, Prev: Errors, Up: Nonlocal Exits
- 10.5.4 Cleaning Up from Nonlocal Exits
- --------------------------------------
- The `unwind-protect' construct is essential whenever you temporarily
- put a data structure in an inconsistent state; it permits you to make
- the data consistent again in the event of an error or throw. (Another
- more specific cleanup construct that is used only for changes in buffer
- contents is the atomic change group; *note Atomic Changes::.)
- -- Special Form: unwind-protect body-form cleanup-forms...
- `unwind-protect' executes BODY-FORM with a guarantee that the
- CLEANUP-FORMS will be evaluated if control leaves BODY-FORM, no
- matter how that happens. BODY-FORM may complete normally, or
- execute a `throw' out of the `unwind-protect', or cause an error;
- in all cases, the CLEANUP-FORMS will be evaluated.
- If BODY-FORM finishes normally, `unwind-protect' returns the value
- of BODY-FORM, after it evaluates the CLEANUP-FORMS. If BODY-FORM
- does not finish, `unwind-protect' does not return any value in the
- normal sense.
- Only BODY-FORM is protected by the `unwind-protect'. If any of
- the CLEANUP-FORMS themselves exits nonlocally (via a `throw' or an
- error), `unwind-protect' is _not_ guaranteed to evaluate the rest
- of them. If the failure of one of the CLEANUP-FORMS has the
- potential to cause trouble, then protect it with another
- `unwind-protect' around that form.
- The number of currently active `unwind-protect' forms counts,
- together with the number of local variable bindings, against the
- limit `max-specpdl-size' (*note Local Variables: Definition of
- max-specpdl-size.).
- For example, here we make an invisible buffer for temporary use, and
- make sure to kill it before finishing:
- (let ((buffer (get-buffer-create " *temp*")))
- (with-current-buffer buffer
- (unwind-protect
- BODY-FORM
- (kill-buffer buffer))))
- You might think that we could just as well write `(kill-buffer
- (current-buffer))' and dispense with the variable `buffer'. However,
- the way shown above is safer, if BODY-FORM happens to get an error
- after switching to a different buffer! (Alternatively, you could write
- a `save-current-buffer' around BODY-FORM, to ensure that the temporary
- buffer becomes current again in time to kill it.)
- Emacs includes a standard macro called `with-temp-buffer' which
- expands into more or less the code shown above (*note Current Buffer:
- Definition of with-temp-buffer.). Several of the macros defined in
- this manual use `unwind-protect' in this way.
- Here is an actual example derived from an FTP package. It creates a
- process (*note Processes::) to try to establish a connection to a remote
- machine. As the function `ftp-login' is highly susceptible to numerous
- problems that the writer of the function cannot anticipate, it is
- protected with a form that guarantees deletion of the process in the
- event of failure. Otherwise, Emacs might fill up with useless
- subprocesses.
- (let ((win nil))
- (unwind-protect
- (progn
- (setq process (ftp-setup-buffer host file))
- (if (setq win (ftp-login process host user password))
- (message "Logged in")
- (error "Ftp login failed")))
- (or win (and process (delete-process process)))))
- This example has a small bug: if the user types `C-g' to quit, and
- the quit happens immediately after the function `ftp-setup-buffer'
- returns but before the variable `process' is set, the process will not
- be killed. There is no easy way to fix this bug, but at least it is
- very unlikely.
- File: elisp, Node: Variables, Next: Functions, Prev: Control Structures, Up: Top
- 11 Variables
- ************
- A "variable" is a name used in a program to stand for a value. In
- Lisp, each variable is represented by a Lisp symbol (*note Symbols::).
- The variable name is simply the symbol's name, and the variable's value
- is stored in the symbol's value cell(1). *Note Symbol Components::.
- In Emacs Lisp, the use of a symbol as a variable is independent of its
- use as a function name.
- As previously noted in this manual, a Lisp program is represented
- primarily by Lisp objects, and only secondarily as text. The textual
- form of a Lisp program is given by the read syntax of the Lisp objects
- that constitute the program. Hence, the textual form of a variable in
- a Lisp program is written using the read syntax for the symbol
- representing the variable.
- * Menu:
- * Global Variables:: Variable values that exist permanently, everywhere.
- * Constant Variables:: Certain "variables" have values that never change.
- * Local Variables:: Variable values that exist only temporarily.
- * Void Variables:: Symbols that lack values.
- * Defining Variables:: A definition says a symbol is used as a variable.
- * Tips for Defining:: Things you should think about when you
- define a variable.
- * Accessing Variables:: Examining values of variables whose names
- are known only at run time.
- * Setting Variables:: Storing new values in variables.
- * Variable Scoping:: How Lisp chooses among local and global values.
- * Buffer-Local Variables:: Variable values in effect only in one buffer.
- * File Local Variables:: Handling local variable lists in files.
- * Directory Local Variables:: Local variables common to all files in a directory.
- * Variable Aliases:: Variables that are aliases for other variables.
- * Variables with Restricted Values:: Non-constant variables whose value can
- _not_ be an arbitrary Lisp object.
- ---------- Footnotes ----------
- (1) To be precise, under the default "dynamic binding" rules the
- value cell always holds the variable's current value, but this is not
- the case under "lexical binding" rules. *Note Variable Scoping::, for
- details.
- File: elisp, Node: Global Variables, Next: Constant Variables, Up: Variables
- 11.1 Global Variables
- =====================
- The simplest way to use a variable is "globally". This means that the
- variable has just one value at a time, and this value is in effect (at
- least for the moment) throughout the Lisp system. The value remains in
- effect until you specify a new one. When a new value replaces the old
- one, no trace of the old value remains in the variable.
- You specify a value for a symbol with `setq'. For example,
- (setq x '(a b))
- gives the variable `x' the value `(a b)'. Note that `setq' is a
- special form (*note Special Forms::); it does not evaluate its first
- argument, the name of the variable, but it does evaluate the second
- argument, the new value.
- Once the variable has a value, you can refer to it by using the
- symbol itself as an expression. Thus,
- x => (a b)
- assuming the `setq' form shown above has already been executed.
- If you do set the same variable again, the new value replaces the old
- one:
- x
- => (a b)
- (setq x 4)
- => 4
- x
- => 4
- File: elisp, Node: Constant Variables, Next: Local Variables, Prev: Global Variables, Up: Variables
- 11.2 Variables that Never Change
- ================================
- In Emacs Lisp, certain symbols normally evaluate to themselves. These
- include `nil' and `t', as well as any symbol whose name starts with `:'
- (these are called "keywords"). These symbols cannot be rebound, nor
- can their values be changed. Any attempt to set or bind `nil' or `t'
- signals a `setting-constant' error. The same is true for a keyword (a
- symbol whose name starts with `:'), if it is interned in the standard
- obarray, except that setting such a symbol to itself is not an error.
- nil == 'nil
- => nil
- (setq nil 500)
- error--> Attempt to set constant symbol: nil
- -- Function: keywordp object
- function returns `t' if OBJECT is a symbol whose name starts with
- `:', interned in the standard obarray, and returns `nil' otherwise.
- These constants are fundamentally different from the "constants"
- defined using the `defconst' special form (*note Defining Variables::).
- A `defconst' form serves to inform human readers that you do not intend
- to change the value of a variable, but Emacs does not raise an error if
- you actually change it.
- File: elisp, Node: Local Variables, Next: Void Variables, Prev: Constant Variables, Up: Variables
- 11.3 Local Variables
- ====================
- Global variables have values that last until explicitly superseded with
- new values. Sometimes it is useful to give a variable a "local
- value"--a value that takes effect only within a certain part of a Lisp
- program. When a variable has a local value, we say that it is "locally
- bound" to that value, and that it is a "local variable".
- For example, when a function is called, its argument variables
- receive local values, which are the actual arguments supplied to the
- function call; these local bindings take effect within the body of the
- function. To take another example, the `let' special form explicitly
- establishes local bindings for specific variables, which take effect
- within the body of the `let' form.
- We also speak of the "global binding", which is where (conceptually)
- the global value is kept.
- Establishing a local binding saves away the variable's previous
- value (or lack of one). We say that the previous value is "shadowed".
- Both global and local values may be shadowed. If a local binding is in
- effect, using `setq' on the local variable stores the specified value
- in the local binding. When that local binding is no longer in effect,
- the previously shadowed value (or lack of one) comes back.
- A variable can have more than one local binding at a time (e.g. if
- there are nested `let' forms that bind the variable). The "current
- binding" is the local binding that is actually in effect. It
- determines the value returned by evaluating the variable symbol, and it
- is the binding acted on by `setq'.
- For most purposes, you can think of the current binding as the
- "innermost" local binding, or the global binding if there is no local
- binding. To be more precise, a rule called the "scoping rule"
- determines where in a program a local binding takes effect. The
- default scoping rule in Emacs Lisp is called "dynamic scoping", which
- simply states that the current binding at any given point in the
- execution of a program is the most recently-created binding for that
- variable that still exists. For details about dynamic scoping, and an
- alternative scoping rule called "lexical scoping", *Note Variable
- Scoping::.
- The special forms `let' and `let*' exist to create local bindings:
- -- Special Form: let (bindings...) forms...
- This special form sets up local bindings for a certain set of
- variables, as specified by BINDINGS, and then evaluates all of the
- FORMS in textual order. Its return value is the value of the last
- form in FORMS.
- Each of the BINDINGS is either (i) a symbol, in which case that
- symbol is locally bound to `nil'; or (ii) a list of the form
- `(SYMBOL VALUE-FORM)', in which case SYMBOL is locally bound to
- the result of evaluating VALUE-FORM. If VALUE-FORM is omitted,
- `nil' is used.
- All of the VALUE-FORMs in BINDINGS are evaluated in the order they
- appear and _before_ binding any of the symbols to them. Here is
- an example of this: `z' is bound to the old value of `y', which is
- 2, not the new value of `y', which is 1.
- (setq y 2)
- => 2
- (let ((y 1)
- (z y))
- (list y z))
- => (1 2)
- -- Special Form: let* (bindings...) forms...
- This special form is like `let', but it binds each variable right
- after computing its local value, before computing the local value
- for the next variable. Therefore, an expression in BINDINGS can
- refer to the preceding symbols bound in this `let*' form. Compare
- the following example with the example above for `let'.
- (setq y 2)
- => 2
- (let* ((y 1)
- (z y)) ; Use the just-established value of `y'.
- (list y z))
- => (1 1)
- Here is a complete list of the other facilities that create local
- bindings:
- * Function calls (*note Functions::).
- * Macro calls (*note Macros::).
- * `condition-case' (*note Errors::).
- Variables can also have buffer-local bindings (*note Buffer-Local
- Variables::); a few variables have terminal-local bindings (*note
- Multiple Terminals::). These kinds of bindings work somewhat like
- ordinary local bindings, but they are localized depending on "where"
- you are in Emacs.
- -- User Option: max-specpdl-size
- This variable defines the limit on the total number of local
- variable bindings and `unwind-protect' cleanups (see *note
- Cleaning Up from Nonlocal Exits: Cleanups.) that are allowed
- before Emacs signals an error (with data `"Variable binding depth
- exceeds max-specpdl-size"').
- This limit, with the associated error when it is exceeded, is one
- way that Lisp avoids infinite recursion on an ill-defined function.
- `max-lisp-eval-depth' provides another limit on depth of nesting.
- *Note Eval: Definition of max-lisp-eval-depth.
- The default value is 1300. Entry to the Lisp debugger increases
- the value, if there is little room left, to make sure the debugger
- itself has room to execute.
- File: elisp, Node: Void Variables, Next: Defining Variables, Prev: Local Variables, Up: Variables
- 11.4 When a Variable is "Void"
- ==============================
- We say that a variable is void if its symbol has an unassigned value
- cell (*note Symbol Components::). Under Emacs Lisp's default dynamic
- binding rules (*note Variable Scoping::), the value cell stores the
- variable's current (local or global) value. Note that an unassigned
- value cell is _not_ the same as having `nil' in the value cell. The
- symbol `nil' is a Lisp object and can be the value of a variable, just
- as any other object can be; but it is still a value. If a variable is
- void, trying to evaluate the variable signals a `void-variable' error
- rather than a value.
- Under lexical binding rules, the value cell only holds the
- variable's global value, i.e. the value outside of any lexical binding
- construct. When a variable is lexically bound, the local value is
- determined by the lexical environment; the variable may have a local
- value if its symbol's value cell is unassigned.
- -- Function: makunbound symbol
- This function empties out the value cell of SYMBOL, making the
- variable void. It returns SYMBOL.
- If SYMBOL has a dynamic local binding, `makunbound' voids the
- current binding, and this voidness lasts only as long as the local
- binding is in effect. Afterwards, the previously shadowed local or
- global binding is reexposed; then the variable will no longer be
- void, unless the reexposed binding is void too.
- Here are some examples (assuming dynamic binding is in effect):
- (setq x 1) ; Put a value in the global binding.
- => 1
- (let ((x 2)) ; Locally bind it.
- (makunbound 'x) ; Void the local binding.
- x)
- error--> Symbol's value as variable is void: x
- x ; The global binding is unchanged.
- => 1
- (let ((x 2)) ; Locally bind it.
- (let ((x 3)) ; And again.
- (makunbound 'x) ; Void the innermost-local binding.
- x)) ; And refer: it's void.
- error--> Symbol's value as variable is void: x
- (let ((x 2))
- (let ((x 3))
- (makunbound 'x)) ; Void inner binding, then remove it.
- x) ; Now outer `let' binding is visible.
- => 2
- -- Function: boundp variable
- This function returns `t' if VARIABLE (a symbol) is not void, and
- `nil' if it is void.
- Here are some examples (assuming dynamic binding is in effect):
- (boundp 'abracadabra) ; Starts out void.
- => nil
- (let ((abracadabra 5)) ; Locally bind it.
- (boundp 'abracadabra))
- => t
- (boundp 'abracadabra) ; Still globally void.
- => nil
- (setq abracadabra 5) ; Make it globally nonvoid.
- => 5
- (boundp 'abracadabra)
- => t
- File: elisp, Node: Defining Variables, Next: Tips for Defining, Prev: Void Variables, Up: Variables
- 11.5 Defining Global Variables
- ==============================
- A "variable definition" is a construct that announces your intention to
- use a symbol as a global variable. It uses the special forms `defvar'
- or `defconst', which are documented below.
- A variable definition serves three purposes. First, it informs
- people who read the code that the symbol is _intended_ to be used a
- certain way (as a variable). Second, it informs the Lisp system of
- this, optionally supplying an initial value and a documentation string.
- Third, it provides information to programming tools such as `etags',
- allowing them to find where the variable was defined.
- The difference between `defconst' and `defvar' is mainly a matter of
- intent, serving to inform human readers of whether the value should
- ever change. Emacs Lisp does not actually prevent you from changing
- the value of a variable defined with `defconst'. One notable
- difference between the two forms is that `defconst' unconditionally
- initializes the variable, whereas `defvar' initializes it only if it is
- originally void.
- To define a customizable variable, you should use `defcustom' (which
- calls `defvar' as a subroutine). *Note Customization::.
- -- Special Form: defvar symbol [value [doc-string]]
- This special form defines SYMBOL as a variable. Note that SYMBOL
- is not evaluated; the symbol to be defined should appear
- explicitly in the `defvar' form. The variable is marked as
- "special", meaning that it should always be dynamically bound
- (*note Variable Scoping::).
- If SYMBOL is void and VALUE is specified, `defvar' evaluates VALUE
- and sets SYMBOL to the result. But if SYMBOL already has a value
- (i.e. it is not void), VALUE is not even evaluated, and SYMBOL's
- value remains unchanged. If VALUE is omitted, the value of SYMBOL
- is not changed in any case.
- If SYMBOL has a buffer-local binding in the current buffer,
- `defvar' operates on the default value, which is
- buffer-independent, not the current (buffer-local) binding. It
- sets the default value if the default value is void. *Note
- Buffer-Local Variables::.
- When you evaluate a top-level `defvar' form with `C-M-x' in Emacs
- Lisp mode (`eval-defun'), a special feature of `eval-defun'
- arranges to set the variable unconditionally, without testing
- whether its value is void.
- If the DOC-STRING argument is supplied, it specifies the
- documentation string for the variable (stored in the symbol's
- `variable-documentation' property). *Note Documentation::.
- Here are some examples. This form defines `foo' but does not
- initialize it:
- (defvar foo)
- => foo
- This example initializes the value of `bar' to `23', and gives it
- a documentation string:
- (defvar bar 23
- "The normal weight of a bar.")
- => bar
- The `defvar' form returns SYMBOL, but it is normally used at top
- level in a file where its value does not matter.
- -- Special Form: defconst symbol value [doc-string]
- This special form defines SYMBOL as a value and initializes it.
- It informs a person reading your code that SYMBOL has a standard
- global value, established here, that should not be changed by the
- user or by other programs. Note that SYMBOL is not evaluated; the
- symbol to be defined must appear explicitly in the `defconst'.
- The `defconst' form, like `defvar', marks the variable as
- "special", meaning that it should always be dynamically bound
- (*note Variable Scoping::). In addition, it marks the variable as
- risky (*note File Local Variables::).
- `defconst' always evaluates VALUE, and sets the value of SYMBOL to
- the result. If SYMBOL does have a buffer-local binding in the
- current buffer, `defconst' sets the default value, not the
- buffer-local value. (But you should not be making buffer-local
- bindings for a symbol that is defined with `defconst'.)
- An example of the use of `defconst' is Emacs's definition of
- `float-pi'--the mathematical constant pi, which ought not to be
- changed by anyone (attempts by the Indiana State Legislature
- notwithstanding). As the second form illustrates, however,
- `defconst' is only advisory.
- (defconst float-pi 3.141592653589793 "The value of Pi.")
- => float-pi
- (setq float-pi 3)
- => float-pi
- float-pi
- => 3
- *Warning:* If you use a `defconst' or `defvar' special form while
- the variable has a local binding (made with `let', or a function
- argument), it sets the local binding rather than the global binding.
- This is not what you usually want. To prevent this, use these special
- forms at top level in a file, where normally no local binding is in
- effect, and make sure to load the file before making a local binding
- for the variable.
- File: elisp, Node: Tips for Defining, Next: Accessing Variables, Prev: Defining Variables, Up: Variables
- 11.6 Tips for Defining Variables Robustly
- =========================================
- When you define a variable whose value is a function, or a list of
- functions, use a name that ends in `-function' or `-functions',
- respectively.
- There are several other variable name conventions; here is a
- complete list:
- `...-hook'
- The variable is a normal hook (*note Hooks::).
- `...-function'
- The value is a function.
- `...-functions'
- The value is a list of functions.
- `...-form'
- The value is a form (an expression).
- `...-forms'
- The value is a list of forms (expressions).
- `...-predicate'
- The value is a predicate--a function of one argument that returns
- non-`nil' for "good" arguments and `nil' for "bad" arguments.
- `...-flag'
- The value is significant only as to whether it is `nil' or not.
- Since such variables often end up acquiring more values over time,
- this convention is not strongly recommended.
- `...-program'
- The value is a program name.
- `...-command'
- The value is a whole shell command.
- `...-switches'
- The value specifies options for a command.
- When you define a variable, always consider whether you should mark
- it as "safe" or "risky"; see *note File Local Variables::.
- When defining and initializing a variable that holds a complicated
- value (such as a keymap with bindings in it), it's best to put the
- entire computation of the value into the `defvar', like this:
- (defvar my-mode-map
- (let ((map (make-sparse-keymap)))
- (define-key map "\C-c\C-a" 'my-command)
- ...
- map)
- DOCSTRING)
- This method has several benefits. First, if the user quits while
- loading the file, the variable is either still uninitialized or
- initialized properly, never in-between. If it is still uninitialized,
- reloading the file will initialize it properly. Second, reloading the
- file once the variable is initialized will not alter it; that is
- important if the user has run hooks to alter part of the contents (such
- as, to rebind keys). Third, evaluating the `defvar' form with `C-M-x'
- will reinitialize the map completely.
- Putting so much code in the `defvar' form has one disadvantage: it
- puts the documentation string far away from the line which names the
- variable. Here's a safe way to avoid that:
- (defvar my-mode-map nil
- DOCSTRING)
- (unless my-mode-map
- (let ((map (make-sparse-keymap)))
- (define-key map "\C-c\C-a" 'my-command)
- ...
- (setq my-mode-map map)))
- This has all the same advantages as putting the initialization inside
- the `defvar', except that you must type `C-M-x' twice, once on each
- form, if you do want to reinitialize the variable.
- File: elisp, Node: Accessing Variables, Next: Setting Variables, Prev: Tips for Defining, Up: Variables
- 11.7 Accessing Variable Values
- ==============================
- The usual way to reference a variable is to write the symbol which
- names it. *Note Symbol Forms::.
- Occasionally, you may want to reference a variable which is only
- determined at run time. In that case, you cannot specify the variable
- name in the text of the program. You can use the `symbol-value'
- function to extract the value.
- -- Function: symbol-value symbol
- This function returns the value stored in SYMBOL's value cell.
- This is where the variable's current (dynamic) value is stored. If
- the variable has no local binding, this is simply its global value.
- If the variable is void, a `void-variable' error is signaled.
- If the variable is lexically bound, the value reported by
- `symbol-value' is not necessarily the same as the variable's
- lexical value, which is determined by the lexical environment
- rather than the symbol's value cell. *Note Variable Scoping::.
- (setq abracadabra 5)
- => 5
- (setq foo 9)
- => 9
- ;; Here the symbol `abracadabra'
- ;; is the symbol whose value is examined.
- (let ((abracadabra 'foo))
- (symbol-value 'abracadabra))
- => foo
- ;; Here, the value of `abracadabra',
- ;; which is `foo',
- ;; is the symbol whose value is examined.
- (let ((abracadabra 'foo))
- (symbol-value abracadabra))
- => 9
- (symbol-value 'abracadabra)
- => 5
- File: elisp, Node: Setting Variables, Next: Variable Scoping, Prev: Accessing Variables, Up: Variables
- 11.8 Setting Variable Values
- ============================
- The usual way to change the value of a variable is with the special
- form `setq'. When you need to compute the choice of variable at run
- time, use the function `set'.
- -- Special Form: setq [symbol form]...
- This special form is the most common method of changing a
- variable's value. Each SYMBOL is given a new value, which is the
- result of evaluating the corresponding FORM. The current binding
- of the symbol is changed.
- `setq' does not evaluate SYMBOL; it sets the symbol that you
- write. We say that this argument is "automatically quoted". The
- `q' in `setq' stands for "quoted".
- The value of the `setq' form is the value of the last FORM.
- (setq x (1+ 2))
- => 3
- x ; `x' now has a global value.
- => 3
- (let ((x 5))
- (setq x 6) ; The local binding of `x' is set.
- x)
- => 6
- x ; The global value is unchanged.
- => 3
- Note that the first FORM is evaluated, then the first SYMBOL is
- set, then the second FORM is evaluated, then the second SYMBOL is
- set, and so on:
- (setq x 10 ; Notice that `x' is set before
- y (1+ x)) ; the value of `y' is computed.
- => 11
- -- Function: set symbol value
- This function puts VALUE in the value cell of SYMBOL. Since it is
- a function rather than a special form, the expression written for
- SYMBOL is evaluated to obtain the symbol to set. The return value
- is VALUE.
- When dynamic variable binding is in effect (the default), `set'
- has the same effect as `setq', apart from the fact that `set'
- evaluates its SYMBOL argument whereas `setq' does not. But when a
- variable is lexically bound, `set' affects its _dynamic_ value,
- whereas `setq' affects its current (lexical) value. *Note
- Variable Scoping::.
- (set one 1)
- error--> Symbol's value as variable is void: one
- (set 'one 1)
- => 1
- (set 'two 'one)
- => one
- (set two 2) ; `two' evaluates to symbol `one'.
- => 2
- one ; So it is `one' that was set.
- => 2
- (let ((one 1)) ; This binding of `one' is set,
- (set 'one 3) ; not the global value.
- one)
- => 3
- one
- => 2
- If SYMBOL is not actually a symbol, a `wrong-type-argument' error
- is signaled.
- (set '(x y) 'z)
- error--> Wrong type argument: symbolp, (x y)
- File: elisp, Node: Variable Scoping, Next: Buffer-Local Variables, Prev: Setting Variables, Up: Variables
- 11.9 Scoping Rules for Variable Bindings
- ========================================
- When you create a local binding for a variable, that binding takes
- effect only within a limited portion of the program (*note Local
- Variables::). This section describes exactly what this means.
- Each local binding has a certain "scope" and "extent". "Scope"
- refers to _where_ in the textual source code the binding can be
- accessed. "Extent" refers to _when_, as the program is executing, the
- binding exists.
- By default, the local bindings that Emacs creates are "dynamic
- bindings". Such a binding has "indefinite scope", meaning that any
- part of the program can potentially access the variable binding. It
- also has "dynamic extent", meaning that the binding lasts only while
- the binding construct (such as the body of a `let' form) is being
- executed.
- Emacs can optionally create "lexical bindings". A lexical binding
- has "lexical scope", meaning that any reference to the variable must be
- located textually within the binding construct. It also has
- "indefinite extent", meaning that under some circumstances the binding
- can live on even after the binding construct has finished executing, by
- means of special objects called "closures".
- The following subsections describe dynamic binding and lexical
- binding in greater detail, and how to enable lexical binding in Emacs
- Lisp programs.
- * Menu:
- * Dynamic Binding:: The default for binding local variables in Emacs.
- * Dynamic Binding Tips:: Avoiding problems with dynamic binding.
- * Lexical Binding:: A different type of local variable binding.
- * Using Lexical Binding:: How to enable lexical binding.
- File: elisp, Node: Dynamic Binding, Next: Dynamic Binding Tips, Up: Variable Scoping
- 11.9.1 Dynamic Binding
- ----------------------
- By default, the local variable bindings made by Emacs are dynamic
- bindings. When a variable is dynamically bound, its current binding at
- any point in the execution of the Lisp program is simply the most
- recently-created dynamic local binding for that symbol, or the global
- binding if there is no such local binding.
- Dynamic bindings have indefinite scope and dynamic extent, as shown
- by the following example:
- (defvar x -99) ; `x' receives an initial value of -99.
- (defun getx ()
- x) ; `x' is used "free" in this function.
- (let ((x 1)) ; `x' is dynamically bound.
- (getx))
- => 1
- ;; After the `let' form finishes, `x' reverts to its
- ;; previous value, which is -99.
- (getx)
- => -99
- The function `getx' refers to `x'. This is a "free" reference, in the
- sense that there is no binding for `x' within that `defun' construct
- itself. When we call `getx' from within a `let' form in which `x' is
- (dynamically) bound, it retrieves the local value of `x' (i.e. 1). But
- when we call `getx' outside the `let' form, it retrieves the global
- value of `x' (i.e. -99).
- Here is another example, which illustrates setting a dynamically
- bound variable using `setq':
- (defvar x -99) ; `x' receives an initial value of -99.
- (defun addx ()
- (setq x (1+ x))) ; Add 1 to `x' and return its new value.
- (let ((x 1))
- (addx)
- (addx))
- => 3 ; The two `addx' calls add to `x' twice.
- ;; After the `let' form finishes, `x' reverts to its
- ;; previous value, which is -99.
- (addx)
- => -98
- Dynamic binding is implemented in Emacs Lisp in a simple way. Each
- symbol has a value cell, which specifies its current dynamic value (or
- absence of value). *Note Symbol Components::. When a symbol is given
- a dynamic local binding, Emacs records the contents of the value cell
- (or absence thereof) in a stack, and stores the new local value in the
- value cell. When the binding construct finishes executing, Emacs pops
- the old value off the stack, and puts it in the value cell.
- File: elisp, Node: Dynamic Binding Tips, Next: Lexical Binding, Prev: Dynamic Binding, Up: Variable Scoping
- 11.9.2 Proper Use of Dynamic Binding
- ------------------------------------
- Dynamic binding is a powerful feature, as it allows programs to refer
- to variables that are not defined within their local textual scope.
- However, if used without restraint, this can also make programs hard to
- understand. There are two clean ways to use this technique:
- * If a variable has no global definition, use it as a local variable
- only within a binding construct, e.g. the body of the `let' form
- where the variable was bound, or the body of the function for an
- argument variable. If this convention is followed consistently
- throughout a program, the value of the variable will not affect,
- nor be affected by, any uses of the same variable symbol elsewhere
- in the program.
- * Otherwise, define the variable with `defvar', `defconst', or
- `defcustom'. *Note Defining Variables::. Usually, the definition
- should be at top-level in an Emacs Lisp file. As far as possible,
- it should include a documentation string which explains the
- meaning and purpose of the variable. You should also choose the
- variable's name to avoid name conflicts (*note Coding
- Conventions::).
- Then you can bind the variable anywhere in a program, knowing
- reliably what the effect will be. Wherever you encounter the
- variable, it will be easy to refer back to the definition, e.g.
- via the `C-h v' command (provided the variable definition has been
- loaded into Emacs). *Note Name Help: (emacs)Name Help.
- For example, it is common to use local bindings for customizable
- variables like `case-fold-search':
- (defun search-for-abc ()
- "Search for the string \"abc\", ignoring case differences."
- (let ((case-fold-search nil))
- (re-search-forward "abc")))
- File: elisp, Node: Lexical Binding, Next: Using Lexical Binding, Prev: Dynamic Binding Tips, Up: Variable Scoping
- 11.9.3 Lexical Binding
- ----------------------
- Optionally, you can create lexical bindings in Emacs Lisp. A lexically
- bound variable has "lexical scope", meaning that any reference to the
- variable must be located textually within the binding construct.
- Here is an example (*note Using Lexical Binding::, for how to
- actually enable lexical binding):
- (let ((x 1)) ; `x' is lexically bound.
- (+ x 3))
- => 4
- (defun getx ()
- x) ; `x' is used "free" in this function.
- (let ((x 1)) ; `x' is lexically bound.
- (getx))
- error--> Symbol's value as variable is void: x
- Here, the variable `x' has no global value. When it is lexically bound
- within a `let' form, it can be used in the textual confines of that
- `let' form. But it can _not_ be used from within a `getx' function
- called from the `let' form, since the function definition of `getx'
- occurs outside the `let' form itself.
- Here is how lexical binding works. Each binding construct defines a
- "lexical environment", specifying the symbols that are bound within the
- construct and their local values. When the Lisp evaluator wants the
- current value of a variable, it looks first in the lexical environment;
- if the variable is not specified in there, it looks in the symbol's
- value cell, where the dynamic value is stored.
- Lexical bindings have indefinite extent. Even after a binding
- construct has finished executing, its lexical environment can be "kept
- around" in Lisp objects called "closures". A closure is created when
- you define a named or anonymous function with lexical binding enabled.
- *Note Closures::, for details.
- When a closure is called as a function, any lexical variable
- references within its definition use the retained lexical environment.
- Here is an example:
- (defvar my-ticker nil) ; We will use this dynamically bound
- ; variable to store a closure.
- (let ((x 0)) ; `x' is lexically bound.
- (setq my-ticker (lambda ()
- (setq x (1+ x)))))
- => (closure ((x . 0) t) ()
- (1+ x))
- (funcall my-ticker)
- => 1
- (funcall my-ticker)
- => 2
- (funcall my-ticker)
- => 3
- x ; Note that `x' has no global value.
- error--> Symbol's value as variable is void: x
- The `let' binding defines a lexical environment in which the variable
- `x' is locally bound to 0. Within this binding construct, we define a
- lambda expression which increments `x' by one and returns the
- incremented value. This lambda expression is automatically turned into
- a closure, in which the lexical environment lives on even after the
- `let' binding construct has exited. Each time we evaluate the closure,
- it increments `x', using the binding of `x' in that lexical environment.
- Note that functions like `symbol-value', `boundp', and `set' only
- retrieve or modify a variable's dynamic binding (i.e. the contents of
- its symbol's value cell). Also, the code in the body of a `defun' or
- `defmacro' cannot refer to surrounding lexical variables.
- Currently, lexical binding is not much used within the Emacs
- sources. However, we expect its importance to increase in the future.
- Lexical binding opens up a lot more opportunities for optimization, so
- Emacs Lisp code that makes use of lexical binding is likely to run
- faster in future Emacs versions. Such code is also much more friendly
- to concurrency, which we want to add to Emacs in the near future.
- File: elisp, Node: Using Lexical Binding, Prev: Lexical Binding, Up: Variable Scoping
- 11.9.4 Using Lexical Binding
- ----------------------------
- When loading an Emacs Lisp file or evaluating a Lisp buffer, lexical
- binding is enabled if the buffer-local variable `lexical-binding' is
- non-`nil':
- -- Variable: lexical-binding
- If this buffer-local variable is non-`nil', Emacs Lisp files and
- buffers are evaluated using lexical binding instead of dynamic
- binding. (However, special variables are still dynamically bound;
- see below.) If `nil', dynamic binding is used for all local
- variables. This variable is typically set for a whole Emacs Lisp
- file, as a file local variable (*note File Local Variables::).
- Note that unlike other such variables, this one must be set in the
- first line of a file.
- When evaluating Emacs Lisp code directly using an `eval' call, lexical
- binding is enabled if the LEXICAL argument to `eval' is non-`nil'.
- *Note Eval::.
- Even when lexical binding is enabled, certain variables will
- continue to be dynamically bound. These are called "special
- variables". Every variable that has been defined with `defvar',
- `defcustom' or `defconst' is a special variable (*note Defining
- Variables::). All other variables are subject to lexical binding.
- -- Function: special-variable-p SYMBOL
- This function returns non-`nil' if SYMBOL is a special variable
- (i.e. it has a `defvar', `defcustom', or `defconst' variable
- definition). Otherwise, the return value is `nil'.
- The use of a special variable as a formal argument in a function is
- discouraged. Doing so gives rise to unspecified behavior when lexical
- binding mode is enabled (it may use lexical binding sometimes, and
- dynamic binding other times).
- Converting an Emacs Lisp program to lexical binding is pretty easy.
- First, add a file-local variable setting of `lexical-binding' to `t' in
- the Emacs Lisp source file. Second, check that every variable in the
- program which needs to be dynamically bound has a variable definition,
- so that it is not inadvertently bound lexically.
- A simple way to find out which variables need a variable definition
- is to byte-compile the source file. *Note Byte Compilation::. If a
- non-special variable is used outside of a `let' form, the byte-compiler
- will warn about reference or assignment to a "free variable". If a
- non-special variable is bound but not used within a `let' form, the
- byte-compiler will warn about an "unused lexical variable". The
- byte-compiler will also issue a warning if you use a special variable
- as a function argument.
- (To silence byte-compiler warnings about unused variables, just use
- a variable name that start with an underscore. The byte-compiler
- interprets this as an indication that this is a variable known not to
- be used.)
- File: elisp, Node: Buffer-Local Variables, Next: File Local Variables, Prev: Variable Scoping, Up: Variables
- 11.10 Buffer-Local Variables
- ============================
- Global and local variable bindings are found in most programming
- languages in one form or another. Emacs, however, also supports
- additional, unusual kinds of variable binding, such as "buffer-local"
- bindings, which apply only in one buffer. Having different values for
- a variable in different buffers is an important customization method.
- (Variables can also have bindings that are local to each terminal.
- *Note Multiple Terminals::.)
- * Menu:
- * Intro to Buffer-Local:: Introduction and concepts.
- * Creating Buffer-Local:: Creating and destroying buffer-local bindings.
- * Default Value:: The default value is seen in buffers
- that don't have their own buffer-local values.
- File: elisp, Node: Intro to Buffer-Local, Next: Creating Buffer-Local, Up: Buffer-Local Variables
- 11.10.1 Introduction to Buffer-Local Variables
- ----------------------------------------------
- A buffer-local variable has a buffer-local binding associated with a
- particular buffer. The binding is in effect when that buffer is
- current; otherwise, it is not in effect. If you set the variable while
- a buffer-local binding is in effect, the new value goes in that binding,
- so its other bindings are unchanged. This means that the change is
- visible only in the buffer where you made it.
- The variable's ordinary binding, which is not associated with any
- specific buffer, is called the "default binding". In most cases, this
- is the global binding.
- A variable can have buffer-local bindings in some buffers but not in
- other buffers. The default binding is shared by all the buffers that
- don't have their own bindings for the variable. (This includes all
- newly-created buffers.) If you set the variable in a buffer that does
- not have a buffer-local binding for it, this sets the default binding,
- so the new value is visible in all the buffers that see the default
- binding.
- The most common use of buffer-local bindings is for major modes to
- change variables that control the behavior of commands. For example, C
- mode and Lisp mode both set the variable `paragraph-start' to specify
- that only blank lines separate paragraphs. They do this by making the
- variable buffer-local in the buffer that is being put into C mode or
- Lisp mode, and then setting it to the new value for that mode. *Note
- Major Modes::.
- The usual way to make a buffer-local binding is with
- `make-local-variable', which is what major mode commands typically use.
- This affects just the current buffer; all other buffers (including
- those yet to be created) will continue to share the default value unless
- they are explicitly given their own buffer-local bindings.
- A more powerful operation is to mark the variable as "automatically
- buffer-local" by calling `make-variable-buffer-local'. You can think
- of this as making the variable local in all buffers, even those yet to
- be created. More precisely, the effect is that setting the variable
- automatically makes the variable local to the current buffer if it is
- not already so. All buffers start out by sharing the default value of
- the variable as usual, but setting the variable creates a buffer-local
- binding for the current buffer. The new value is stored in the
- buffer-local binding, leaving the default binding untouched. This
- means that the default value cannot be changed with `setq' in any
- buffer; the only way to change it is with `setq-default'.
- *Warning:* When a variable has buffer-local bindings in one or more
- buffers, `let' rebinds the binding that's currently in effect. For
- instance, if the current buffer has a buffer-local value, `let'
- temporarily rebinds that. If no buffer-local bindings are in effect,
- `let' rebinds the default value. If inside the `let' you then change
- to a different current buffer in which a different binding is in effect,
- you won't see the `let' binding any more. And if you exit the `let'
- while still in the other buffer, you won't see the unbinding occur
- (though it will occur properly). Here is an example to illustrate:
- (setq foo 'g)
- (set-buffer "a")
- (make-local-variable 'foo)
- (setq foo 'a)
- (let ((foo 'temp))
- ;; foo => 'temp ; let binding in buffer `a'
- (set-buffer "b")
- ;; foo => 'g ; the global value since foo is not local in `b'
- BODY...)
- foo => 'g ; exiting restored the local value in buffer `a',
- ; but we don't see that in buffer `b'
- (set-buffer "a") ; verify the local value was restored
- foo => 'a
- Note that references to `foo' in BODY access the buffer-local binding
- of buffer `b'.
- When a file specifies local variable values, these become
- buffer-local values when you visit the file. *Note File Variables:
- (emacs)File Variables.
- A buffer-local variable cannot be made terminal-local (*note
- Multiple Terminals::).
- File: elisp, Node: Creating Buffer-Local, Next: Default Value, Prev: Intro to Buffer-Local, Up: Buffer-Local Variables
- 11.10.2 Creating and Deleting Buffer-Local Bindings
- ---------------------------------------------------
- -- Command: make-local-variable variable
- This function creates a buffer-local binding in the current buffer
- for VARIABLE (a symbol). Other buffers are not affected. The
- value returned is VARIABLE.
- The buffer-local value of VARIABLE starts out as the same value
- VARIABLE previously had. If VARIABLE was void, it remains void.
- ;; In buffer `b1':
- (setq foo 5) ; Affects all buffers.
- => 5
- (make-local-variable 'foo) ; Now it is local in `b1'.
- => foo
- foo ; That did not change
- => 5 ; the value.
- (setq foo 6) ; Change the value
- => 6 ; in `b1'.
- foo
- => 6
- ;; In buffer `b2', the value hasn't changed.
- (with-current-buffer "b2"
- foo)
- => 5
- Making a variable buffer-local within a `let'-binding for that
- variable does not work reliably, unless the buffer in which you do
- this is not current either on entry to or exit from the `let'.
- This is because `let' does not distinguish between different kinds
- of bindings; it knows only which variable the binding was made for.
- If the variable is terminal-local (*note Multiple Terminals::),
- this function signals an error. Such variables cannot have
- buffer-local bindings as well.
- *Warning:* do not use `make-local-variable' for a hook variable.
- The hook variables are automatically made buffer-local as needed
- if you use the LOCAL argument to `add-hook' or `remove-hook'.
- -- Command: make-variable-buffer-local variable
- This function marks VARIABLE (a symbol) automatically
- buffer-local, so that any subsequent attempt to set it will make it
- local to the current buffer at the time. Unlike
- `make-local-variable', with which it is often confused, this
- cannot be undone, and affects the behavior of the variable in all
- buffers.
- A peculiar wrinkle of this feature is that binding the variable
- (with `let' or other binding constructs) does not create a
- buffer-local binding for it. Only setting the variable (with
- `set' or `setq'), while the variable does not have a `let'-style
- binding that was made in the current buffer, does so.
- If VARIABLE does not have a default value, then calling this
- command will give it a default value of `nil'. If VARIABLE
- already has a default value, that value remains unchanged.
- Subsequently calling `makunbound' on VARIABLE will result in a
- void buffer-local value and leave the default value unaffected.
- The value returned is VARIABLE.
- *Warning:* Don't assume that you should use
- `make-variable-buffer-local' for user-option variables, simply
- because users _might_ want to customize them differently in
- different buffers. Users can make any variable local, when they
- wish to. It is better to leave the choice to them.
- The time to use `make-variable-buffer-local' is when it is crucial
- that no two buffers ever share the same binding. For example,
- when a variable is used for internal purposes in a Lisp program
- which depends on having separate values in separate buffers, then
- using `make-variable-buffer-local' can be the best solution.
- -- Function: local-variable-p variable &optional buffer
- This returns `t' if VARIABLE is buffer-local in buffer BUFFER
- (which defaults to the current buffer); otherwise, `nil'.
- -- Function: local-variable-if-set-p variable &optional buffer
- This returns `t' if VARIABLE will become buffer-local in buffer
- BUFFER (which defaults to the current buffer) if it is set there.
- -- Function: buffer-local-value variable buffer
- This function returns the buffer-local binding of VARIABLE (a
- symbol) in buffer BUFFER. If VARIABLE does not have a
- buffer-local binding in buffer BUFFER, it returns the default
- value (*note Default Value::) of VARIABLE instead.
- -- Function: buffer-local-variables &optional buffer
- This function returns a list describing the buffer-local variables
- in buffer BUFFER. (If BUFFER is omitted, the current buffer is
- used.) Normally, each list element has the form `(SYM . VAL)',
- where SYM is a buffer-local variable (a symbol) and VAL is its
- buffer-local value. But when a variable's buffer-local binding in
- BUFFER is void, its list element is just SYM.
- (make-local-variable 'foobar)
- (makunbound 'foobar)
- (make-local-variable 'bind-me)
- (setq bind-me 69)
- (setq lcl (buffer-local-variables))
- ;; First, built-in variables local in all buffers:
- => ((mark-active . nil)
- (buffer-undo-list . nil)
- (mode-name . "Fundamental")
- ...
- ;; Next, non-built-in buffer-local variables.
- ;; This one is buffer-local and void:
- foobar
- ;; This one is buffer-local and nonvoid:
- (bind-me . 69))
- Note that storing new values into the CDRs of cons cells in this
- list does _not_ change the buffer-local values of the variables.
- -- Command: kill-local-variable variable
- This function deletes the buffer-local binding (if any) for
- VARIABLE (a symbol) in the current buffer. As a result, the
- default binding of VARIABLE becomes visible in this buffer. This
- typically results in a change in the value of VARIABLE, since the
- default value is usually different from the buffer-local value just
- eliminated.
- If you kill the buffer-local binding of a variable that
- automatically becomes buffer-local when set, this makes the
- default value visible in the current buffer. However, if you set
- the variable again, that will once again create a buffer-local
- binding for it.
- `kill-local-variable' returns VARIABLE.
- This function is a command because it is sometimes useful to kill
- one buffer-local variable interactively, just as it is useful to
- create buffer-local variables interactively.
- -- Function: kill-all-local-variables
- This function eliminates all the buffer-local variable bindings of
- the current buffer except for variables marked as "permanent" and
- local hook functions that have a non-`nil' `permanent-local-hook'
- property (*note Setting Hooks::). As a result, the buffer will see
- the default values of most variables.
- This function also resets certain other information pertaining to
- the buffer: it sets the local keymap to `nil', the syntax table to
- the value of `(standard-syntax-table)', the case table to
- `(standard-case-table)', and the abbrev table to the value of
- `fundamental-mode-abbrev-table'.
- The very first thing this function does is run the normal hook
- `change-major-mode-hook' (see below).
- Every major mode command begins by calling this function, which
- has the effect of switching to Fundamental mode and erasing most
- of the effects of the previous major mode. To ensure that this
- does its job, the variables that major modes set should not be
- marked permanent.
- `kill-all-local-variables' returns `nil'.
- -- Variable: change-major-mode-hook
- The function `kill-all-local-variables' runs this normal hook
- before it does anything else. This gives major modes a way to
- arrange for something special to be done if the user switches to a
- different major mode. It is also useful for buffer-specific minor
- modes that should be forgotten if the user changes the major mode.
- For best results, make this variable buffer-local, so that it will
- disappear after doing its job and will not interfere with the
- subsequent major mode. *Note Hooks::.
- A buffer-local variable is "permanent" if the variable name (a
- symbol) has a `permanent-local' property that is non-`nil'. Such
- variables are unaffected by `kill-all-local-variables', and their local
- bindings are therefore not cleared by changing major modes. Permanent
- locals are appropriate for data pertaining to where the file came from
- or how to save it, rather than with how to edit the contents.
- File: elisp, Node: Default Value, Prev: Creating Buffer-Local, Up: Buffer-Local Variables
- 11.10.3 The Default Value of a Buffer-Local Variable
- ----------------------------------------------------
- The global value of a variable with buffer-local bindings is also
- called the "default" value, because it is the value that is in effect
- whenever neither the current buffer nor the selected frame has its own
- binding for the variable.
- The functions `default-value' and `setq-default' access and change a
- variable's default value regardless of whether the current buffer has a
- buffer-local binding. For example, you could use `setq-default' to
- change the default setting of `paragraph-start' for most buffers; and
- this would work even when you are in a C or Lisp mode buffer that has a
- buffer-local value for this variable.
- The special forms `defvar' and `defconst' also set the default value
- (if they set the variable at all), rather than any buffer-local value.
- -- Function: default-value symbol
- This function returns SYMBOL's default value. This is the value
- that is seen in buffers and frames that do not have their own
- values for this variable. If SYMBOL is not buffer-local, this is
- equivalent to `symbol-value' (*note Accessing Variables::).
- -- Function: default-boundp symbol
- The function `default-boundp' tells you whether SYMBOL's default
- value is nonvoid. If `(default-boundp 'foo)' returns `nil', then
- `(default-value 'foo)' would get an error.
- `default-boundp' is to `default-value' as `boundp' is to
- `symbol-value'.
- -- Special Form: setq-default [symbol form]...
- This special form gives each SYMBOL a new default value, which is
- the result of evaluating the corresponding FORM. It does not
- evaluate SYMBOL, but does evaluate FORM. The value of the
- `setq-default' form is the value of the last FORM.
- If a SYMBOL is not buffer-local for the current buffer, and is not
- marked automatically buffer-local, `setq-default' has the same
- effect as `setq'. If SYMBOL is buffer-local for the current
- buffer, then this changes the value that other buffers will see
- (as long as they don't have a buffer-local value), but not the
- value that the current buffer sees.
- ;; In buffer `foo':
- (make-local-variable 'buffer-local)
- => buffer-local
- (setq buffer-local 'value-in-foo)
- => value-in-foo
- (setq-default buffer-local 'new-default)
- => new-default
- buffer-local
- => value-in-foo
- (default-value 'buffer-local)
- => new-default
- ;; In (the new) buffer `bar':
- buffer-local
- => new-default
- (default-value 'buffer-local)
- => new-default
- (setq buffer-local 'another-default)
- => another-default
- (default-value 'buffer-local)
- => another-default
- ;; Back in buffer `foo':
- buffer-local
- => value-in-foo
- (default-value 'buffer-local)
- => another-default
- -- Function: set-default symbol value
- This function is like `setq-default', except that SYMBOL is an
- ordinary evaluated argument.
- (set-default (car '(a b c)) 23)
- => 23
- (default-value 'a)
- => 23
- File: elisp, Node: File Local Variables, Next: Directory Local Variables, Prev: Buffer-Local Variables, Up: Variables
- 11.11 File Local Variables
- ==========================
- A file can specify local variable values; Emacs uses these to create
- buffer-local bindings for those variables in the buffer visiting that
- file. *Note Local Variables in Files: (emacs)File variables, for basic
- information about file-local variables. This section describes the
- functions and variables that affect how file-local variables are
- processed.
- If a file-local variable could specify an arbitrary function or Lisp
- expression that would be called later, visiting a file could take over
- your Emacs. Emacs protects against this by automatically setting only
- those file-local variables whose specified values are known to be safe.
- Other file-local variables are set only if the user agrees.
- For additional safety, `read-circle' is temporarily bound to `nil'
- when Emacs reads file-local variables (*note Input Functions::). This
- prevents the Lisp reader from recognizing circular and shared Lisp
- structures (*note Circular Objects::).
- -- User Option: enable-local-variables
- This variable controls whether to process file-local variables.
- The possible values are:
- `t' (the default)
- Set the safe variables, and query (once) about any unsafe
- variables.
- `:safe'
- Set only the safe variables and do not query.
- `:all'
- Set all the variables and do not query.
- `nil'
- Don't set any variables.
- anything else
- Query (once) about all the variables.
- -- Variable: inhibit-local-variables-regexps
- This is a list of regular expressions. If a file has a name
- matching an element of this list, then it is not scanned for any
- form of file-local variable. For examples of why you might want
- to use this, *note Auto Major Mode::.
- -- Function: hack-local-variables &optional mode-only
- This function parses, and binds or evaluates as appropriate, any
- local variables specified by the contents of the current buffer.
- The variable `enable-local-variables' has its effect here.
- However, this function does not look for the `mode:' local
- variable in the `-*-' line. `set-auto-mode' does that, also taking
- `enable-local-variables' into account (*note Auto Major Mode::).
- This function works by walking the alist stored in
- `file-local-variables-alist' and applying each local variable in
- turn. It calls `before-hack-local-variables-hook' and
- `hack-local-variables-hook' before and after applying the
- variables, respectively. It only calls the before-hook if the
- alist is non-`nil'; it always calls the other hook. This function
- ignores a `mode' element if it specifies the same major mode as
- the buffer already has.
- If the optional argument MODE-ONLY is non-`nil', then all this
- function does is return a symbol specifying the major mode, if the
- `-*-' line or the local variables list specifies one, and `nil'
- otherwise. It does not set the mode nor any other file-local
- variable.
- -- Variable: file-local-variables-alist
- This buffer-local variable holds the alist of file-local variable
- settings. Each element of the alist is of the form
- `(VAR . VALUE)', where VAR is a symbol of the local variable and
- VALUE is its value. When Emacs visits a file, it first collects
- all the file-local variables into this alist, and then the
- `hack-local-variables' function applies them one by one.
- -- Variable: before-hack-local-variables-hook
- Emacs calls this hook immediately before applying file-local
- variables stored in `file-local-variables-alist'.
- -- Variable: hack-local-variables-hook
- Emacs calls this hook immediately after it finishes applying
- file-local variables stored in `file-local-variables-alist'.
- You can specify safe values for a variable with a
- `safe-local-variable' property. The property has to be a function of
- one argument; any value is safe if the function returns non-`nil' given
- that value. Many commonly-encountered file variables have
- `safe-local-variable' properties; these include `fill-column',
- `fill-prefix', and `indent-tabs-mode'. For boolean-valued variables
- that are safe, use `booleanp' as the property value. Lambda
- expressions should be quoted so that `describe-variable' can display
- the predicate.
- When defining a user option using `defcustom', you can set its
- `safe-local-variable' property by adding the arguments `:safe FUNCTION'
- to `defcustom' (*note Variable Definitions::).
- -- User Option: safe-local-variable-values
- This variable provides another way to mark some variable values as
- safe. It is a list of cons cells `(VAR . VAL)', where VAR is a
- variable name and VAL is a value which is safe for that variable.
- When Emacs asks the user whether or not to obey a set of file-local
- variable specifications, the user can choose to mark them as safe.
- Doing so adds those variable/value pairs to
- `safe-local-variable-values', and saves it to the user's custom
- file.
- -- Function: safe-local-variable-p sym val
- This function returns non-`nil' if it is safe to give SYM the
- value VAL, based on the above criteria.
- Some variables are considered "risky". If a variable is risky, it
- is never entered automatically into `safe-local-variable-values'; Emacs
- always queries before setting a risky variable, unless the user
- explicitly allows a value by customizing `safe-local-variable-values'
- directly.
- Any variable whose name has a non-`nil' `risky-local-variable'
- property is considered risky. When you define a user option using
- `defcustom', you can set its `risky-local-variable' property by adding
- the arguments `:risky VALUE' to `defcustom' (*note Variable
- Definitions::). In addition, any variable whose name ends in any of
- `-command', `-frame-alist', `-function', `-functions', `-hook',
- `-hooks', `-form', `-forms', `-map', `-map-alist', `-mode-alist',
- `-program', or `-predicate' is automatically considered risky. The
- variables `font-lock-keywords', `font-lock-keywords' followed by a
- digit, and `font-lock-syntactic-keywords' are also considered risky.
- -- Function: risky-local-variable-p sym
- This function returns non-`nil' if SYM is a risky variable, based
- on the above criteria.
- -- Variable: ignored-local-variables
- This variable holds a list of variables that should not be given
- local values by files. Any value specified for one of these
- variables is completely ignored.
- The `Eval:' "variable" is also a potential loophole, so Emacs
- normally asks for confirmation before handling it.
- -- User Option: enable-local-eval
- This variable controls processing of `Eval:' in `-*-' lines or
- local variables lists in files being visited. A value of `t'
- means process them unconditionally; `nil' means ignore them;
- anything else means ask the user what to do for each file. The
- default value is `maybe'.
- -- User Option: safe-local-eval-forms
- This variable holds a list of expressions that are safe to
- evaluate when found in the `Eval:' "variable" in a file local
- variables list.
- If the expression is a function call and the function has a
- `safe-local-eval-function' property, the property value determines
- whether the expression is safe to evaluate. The property value can be
- a predicate to call to test the expression, a list of such predicates
- (it's safe if any predicate succeeds), or `t' (always safe provided the
- arguments are constant).
- Text properties are also potential loopholes, since their values
- could include functions to call. So Emacs discards all text properties
- from string values specified for file-local variables.
- File: elisp, Node: Directory Local Variables, Next: Variable Aliases, Prev: File Local Variables, Up: Variables
- 11.12 Directory Local Variables
- ===============================
- A directory can specify local variable values common to all files in
- that directory; Emacs uses these to create buffer-local bindings for
- those variables in buffers visiting any file in that directory. This
- is useful when the files in the directory belong to some "project" and
- therefore share the same local variables.
- There are two different methods for specifying directory local
- variables: by putting them in a special file, or by defining a "project
- class" for that directory.
- -- Constant: dir-locals-file
- This constant is the name of the file where Emacs expects to find
- the directory-local variables. The name of the file is
- `.dir-locals.el'(1). A file by that name in a directory causes
- Emacs to apply its settings to any file in that directory or any
- of its subdirectories (optionally, you can exclude subdirectories;
- see below). If some of the subdirectories have their own
- `.dir-locals.el' files, Emacs uses the settings from the deepest
- file it finds starting from the file's directory and moving up the
- directory tree. The file specifies local variables as a specially
- formatted list; see *note Per-directory Local Variables:
- (emacs)Directory Variables, for more details.
- -- Function: hack-dir-local-variables
- This function reads the `.dir-locals.el' file and stores the
- directory-local variables in `file-local-variables-alist' that is
- local to the buffer visiting any file in the directory, without
- applying them. It also stores the directory-local settings in
- `dir-locals-class-alist', where it defines a special class for the
- directory in which `.dir-locals.el' file was found. This function
- works by calling `dir-locals-set-class-variables' and
- `dir-locals-set-directory-class', described below.
- -- Function: hack-dir-local-variables-non-file-buffer
- This function looks for directory-local variables, and immediately
- applies them in the current buffer. It is intended to be called in
- the mode commands for non-file buffers, such as Dired buffers, to
- let them obey directory-local variable settings. For non-file
- buffers, Emacs looks for directory-local variables in
- `default-directory' and its parent directories.
- -- Function: dir-locals-set-class-variables class variables
- This function defines a set of variable settings for the named
- CLASS, which is a symbol. You can later assign the class to one
- or more directories, and Emacs will apply those variable settings
- to all files in those directories. The list in VARIABLES can be of
- one of the two forms: `(MAJOR-MODE . ALIST)' or `(DIRECTORY .
- LIST)'. With the first form, if the file's buffer turns on a mode
- that is derived from MAJOR-MODE, then the all the variables in the
- associated ALIST are applied; ALIST should be of the form `(NAME .
- VALUE)'. A special value `nil' for MAJOR-MODE means the settings
- are applicable to any mode. In ALIST, you can use a special NAME:
- `subdirs'. If the associated value is `nil', the alist is only
- applied to files in the relevant directory, not to those in any
- subdirectories.
- With the second form of VARIABLES, if DIRECTORY is the initial
- substring of the file's directory, then LIST is applied
- recursively by following the above rules; LIST should be of one of
- the two forms accepted by this function in VARIABLES.
- -- Function: dir-locals-set-directory-class directory class &optional
- mtime
- This function assigns CLASS to all the files in `directory' and
- its subdirectories. Thereafter, all the variable settings
- specified for CLASS will be applied to any visited file in
- DIRECTORY and its children. CLASS must have been already defined
- by `dir-locals-set-class-variables'.
- Emacs uses this function internally when it loads directory
- variables from a `.dir-locals.el' file. In that case, the optional
- argument MTIME holds the file modification time (as returned by
- `file-attributes'). Emacs uses this time to check stored local
- variables are still valid. If you are assigning a class directly,
- not via a file, this argument should be `nil'.
- -- Variable: dir-locals-class-alist
- This alist holds the class symbols and the associated variable
- settings. It is updated by `dir-locals-set-class-variables'.
- -- Variable: dir-locals-directory-cache
- This alist holds directory names, their assigned class names, and
- modification times of the associated directory local variables file
- (if there is one). The function `dir-locals-set-directory-class'
- updates this list.
- ---------- Footnotes ----------
- (1) The MS-DOS version of Emacs uses `_dir-locals.el' instead, due to
- limitations of the DOS filesystems.
- File: elisp, Node: Variable Aliases, Next: Variables with Restricted Values, Prev: Directory Local Variables, Up: Variables
- 11.13 Variable Aliases
- ======================
- It is sometimes useful to make two variables synonyms, so that both
- variables always have the same value, and changing either one also
- changes the other. Whenever you change the name of a variable--either
- because you realize its old name was not well chosen, or because its
- meaning has partly changed--it can be useful to keep the old name as an
- _alias_ of the new one for compatibility. You can do this with
- `defvaralias'.
- -- Function: defvaralias new-alias base-variable &optional docstring
- This function defines the symbol NEW-ALIAS as a variable alias for
- symbol BASE-VARIABLE. This means that retrieving the value of
- NEW-ALIAS returns the value of BASE-VARIABLE, and changing the
- value of NEW-ALIAS changes the value of BASE-VARIABLE. The two
- aliased variable names always share the same value and the same
- bindings.
- If the DOCSTRING argument is non-`nil', it specifies the
- documentation for NEW-ALIAS; otherwise, the alias gets the same
- documentation as BASE-VARIABLE has, if any, unless BASE-VARIABLE
- is itself an alias, in which case NEW-ALIAS gets the documentation
- of the variable at the end of the chain of aliases.
- This function returns BASE-VARIABLE.
- Variable aliases are convenient for replacing an old name for a
- variable with a new name. `make-obsolete-variable' declares that the
- old name is obsolete and therefore that it may be removed at some stage
- in the future.
- -- Function: make-obsolete-variable obsolete-name current-name when
- &optional access-type
- This function makes the byte compiler warn that the variable
- OBSOLETE-NAME is obsolete. If CURRENT-NAME is a symbol, it is the
- variable's new name; then the warning message says to use
- CURRENT-NAME instead of OBSOLETE-NAME. If CURRENT-NAME is a
- string, this is the message and there is no replacement variable.
- WHEN should be a string indicating when the variable was first
- made obsolete (usually a version number string).
- The optional argument ACCESS-TYPE, if non-`nil', should should
- specify the kind of access that will trigger obsolescence
- warnings; it can be either `get' or `set'.
- You can make two variables synonyms and declare one obsolete at the
- same time using the macro `define-obsolete-variable-alias'.
- -- Macro: define-obsolete-variable-alias obsolete-name current-name
- &optional when docstring
- This macro marks the variable OBSOLETE-NAME as obsolete and also
- makes it an alias for the variable CURRENT-NAME. It is equivalent
- to the following:
- (defvaralias OBSOLETE-NAME CURRENT-NAME DOCSTRING)
- (make-obsolete-variable OBSOLETE-NAME CURRENT-NAME WHEN)
- -- Function: indirect-variable variable
- This function returns the variable at the end of the chain of
- aliases of VARIABLE. If VARIABLE is not a symbol, or if VARIABLE
- is not defined as an alias, the function returns VARIABLE.
- This function signals a `cyclic-variable-indirection' error if
- there is a loop in the chain of symbols.
- (defvaralias 'foo 'bar)
- (indirect-variable 'foo)
- => bar
- (indirect-variable 'bar)
- => bar
- (setq bar 2)
- bar
- => 2
- foo
- => 2
- (setq foo 0)
- bar
- => 0
- foo
- => 0
- File: elisp, Node: Variables with Restricted Values, Prev: Variable Aliases, Up: Variables
- 11.14 Variables with Restricted Values
- ======================================
- Ordinary Lisp variables can be assigned any value that is a valid Lisp
- object. However, certain Lisp variables are not defined in Lisp, but
- in C. Most of these variables are defined in the C code using
- `DEFVAR_LISP'. Like variables defined in Lisp, these can take on any
- value. However, some variables are defined using `DEFVAR_INT' or
- `DEFVAR_BOOL'. *Note Writing Emacs Primitives: Defining Lisp variables
- in C, in particular the description of functions of the type
- `syms_of_FILENAME', for a brief discussion of the C implementation.
- Variables of type `DEFVAR_BOOL' can only take on the values `nil' or
- `t'. Attempting to assign them any other value will set them to `t':
- (let ((display-hourglass 5))
- display-hourglass)
- => t
- -- Variable: byte-boolean-vars
- This variable holds a list of all variables of type `DEFVAR_BOOL'.
- Variables of type `DEFVAR_INT' can only take on integer values.
- Attempting to assign them any other value will result in an error:
- (setq undo-limit 1000.0)
- error--> Wrong type argument: integerp, 1000.0
- File: elisp, Node: Functions, Next: Macros, Prev: Variables, Up: Top
- 12 Functions
- ************
- A Lisp program is composed mainly of Lisp functions. This chapter
- explains what functions are, how they accept arguments, and how to
- define them.
- * Menu:
- * What Is a Function:: Lisp functions vs. primitives; terminology.
- * Lambda Expressions:: How functions are expressed as Lisp objects.
- * Function Names:: A symbol can serve as the name of a function.
- * Defining Functions:: Lisp expressions for defining functions.
- * Calling Functions:: How to use an existing function.
- * Mapping Functions:: Applying a function to each element of a list, etc.
- * Anonymous Functions:: Lambda expressions are functions with no names.
- * Function Cells:: Accessing or setting the function definition
- of a symbol.
- * Closures:: Functions that enclose a lexical environment.
- * Obsolete Functions:: Declaring functions obsolete.
- * Inline Functions:: Functions that the compiler will expand inline.
- * Declaring Functions:: Telling the compiler that a function is defined.
- * Function Safety:: Determining whether a function is safe to call.
- * Related Topics:: Cross-references to specific Lisp primitives
- that have a special bearing on how functions work.
- File: elisp, Node: What Is a Function, Next: Lambda Expressions, Up: Functions
- 12.1 What Is a Function?
- ========================
- In a general sense, a function is a rule for carrying out a computation
- given input values called "arguments". The result of the computation
- is called the "value" or "return value" of the function. The
- computation can also have side effects, such as lasting changes in the
- values of variables or the contents of data structures.
- In most computer languages, every function has a name. But in Lisp,
- a function in the strictest sense has no name: it is an object which
- can _optionally_ be associated with a symbol (e.g. `car') that serves
- as the function name. *Note Function Names::. When a function has
- been given a name, we usually also refer to that symbol as a "function"
- (e.g. we refer to "the function `car'"). In this manual, the
- distinction between a function name and the function object itself is
- usually unimportant, but we will take note wherever it is relevant.
- Certain function-like objects, called "special forms" and "macros",
- also accept arguments to carry out computations. However, as explained
- below, these are not considered functions in Emacs Lisp.
- Here are important terms for functions and function-like objects:
- "lambda expression"
- A function (in the strict sense, i.e. a function object) which is
- written in Lisp. These are described in the following section.
- *Note Lambda Expressions::.
- "primitive"
- A function which is callable from Lisp but is actually written in
- C. Primitives are also called "built-in functions", or "subrs".
- Examples include functions like `car' and `append'. In addition,
- all special forms (see below) are also considered primitives.
- Usually, a function is implemented as a primitive because it is a
- fundamental part of Lisp (e.g. `car'), or because it provides a
- low-level interface to operating system services, or because it
- needs to run fast. Unlike functions defined in Lisp, primitives
- can be modified or added only by changing the C sources and
- recompiling Emacs. See *note Writing Emacs Primitives::.
- "special form"
- A primitive that is like a function but does not evaluate all of
- its arguments in the usual way. It may evaluate only some of the
- arguments, or may evaluate them in an unusual order, or several
- times. Examples include `if', `and', and `while'. *Note Special
- Forms::.
- "macro"
- A construct defined in Lisp, which differs from a function in that
- it translates a Lisp expression into another expression which is
- to be evaluated instead of the original expression. Macros enable
- Lisp programmers to do the sorts of things that special forms can
- do. *Note Macros::.
- "command"
- An object which can be invoked via the `command-execute'
- primitive, usually due to the user typing in a key sequence
- "bound" to that command. *Note Interactive Call::. A command is
- usually a function; if the function is written in Lisp, it is made
- into a command by an `interactive' form in the function definition
- (*note Defining Commands::). Commands that are functions can also
- be called from Lisp expressions, just like other functions.
- Keyboard macros (strings and vectors) are commands also, even
- though they are not functions. *Note Keyboard Macros::. We say
- that a symbol is a command if its function cell contains a command
- (*note Symbol Components::); such a "named command" can be invoked
- with `M-x'.
- "closure"
- A function object that is much like a lambda expression, except
- that it also encloses an "environment" of lexical variable
- bindings. *Note Closures::.
- "byte-code function"
- A function that has been compiled by the byte compiler. *Note
- Byte-Code Type::.
- "autoload object"
- A place-holder for a real function. If the autoload object is
- called, Emacs loads the file containing the definition of the real
- function, and then calls the real function. *Note Autoload::.
- You can use the function `functionp' to test if an object is a
- function:
- -- Function: functionp object
- This function returns `t' if OBJECT is any kind of function, i.e.
- can be passed to `funcall'. Note that `functionp' returns `t' for
- symbols that are function names, and returns `nil' for special
- forms.
- Unlike `functionp', the next three functions do _not_ treat a symbol as
- its function definition.
- -- Function: subrp object
- This function returns `t' if OBJECT is a built-in function (i.e.,
- a Lisp primitive).
- (subrp 'message) ; `message' is a symbol,
- => nil ; not a subr object.
- (subrp (symbol-function 'message))
- => t
- -- Function: byte-code-function-p object
- This function returns `t' if OBJECT is a byte-code function. For
- example:
- (byte-code-function-p (symbol-function 'next-line))
- => t
- -- Function: subr-arity subr
- This function provides information about the argument list of a
- primitive, SUBR. The returned value is a pair `(MIN . MAX)'. MIN
- is the minimum number of args. MAX is the maximum number or the
- symbol `many', for a function with `&rest' arguments, or the
- symbol `unevalled' if SUBR is a special form.
- File: elisp, Node: Lambda Expressions, Next: Function Names, Prev: What Is a Function, Up: Functions
- 12.2 Lambda Expressions
- =======================
- A lambda expression is a function object written in Lisp. Here is an
- example:
- (lambda (x)
- "Return the hyperbolic cosine of X."
- (* 0.5 (+ (exp x) (exp (- x)))))
- In Emacs Lisp, such a list is valid as an expression--it evaluates to
- itself. But its main use is not to be evaluated as an expression, but
- to be called as a function.
- A lambda expression, by itself, has no name; it is an "anonymous
- function". Although lambda expressions can be used this way (*note
- Anonymous Functions::), they are more commonly associated with symbols
- to make "named functions" (*note Function Names::). Before going into
- these details, the following subsections describe the components of a
- lambda expression and what they do.
- * Menu:
- * Lambda Components:: The parts of a lambda expression.
- * Simple Lambda:: A simple example.
- * Argument List:: Details and special features of argument lists.
- * Function Documentation:: How to put documentation in a function.
- File: elisp, Node: Lambda Components, Next: Simple Lambda, Up: Lambda Expressions
- 12.2.1 Components of a Lambda Expression
- ----------------------------------------
- A lambda expression is a list that looks like this:
- (lambda (ARG-VARIABLES...)
- [DOCUMENTATION-STRING]
- [INTERACTIVE-DECLARATION]
- BODY-FORMS...)
- The first element of a lambda expression is always the symbol
- `lambda'. This indicates that the list represents a function. The
- reason functions are defined to start with `lambda' is so that other
- lists, intended for other uses, will not accidentally be valid as
- functions.
- The second element is a list of symbols--the argument variable names.
- This is called the "lambda list". When a Lisp function is called, the
- argument values are matched up against the variables in the lambda
- list, which are given local bindings with the values provided. *Note
- Local Variables::.
- The documentation string is a Lisp string object placed within the
- function definition to describe the function for the Emacs help
- facilities. *Note Function Documentation::.
- The interactive declaration is a list of the form `(interactive
- CODE-STRING)'. This declares how to provide arguments if the function
- is used interactively. Functions with this declaration are called
- "commands"; they can be called using `M-x' or bound to a key.
- Functions not intended to be called in this way should not have
- interactive declarations. *Note Defining Commands::, for how to write
- an interactive declaration.
- The rest of the elements are the "body" of the function: the Lisp
- code to do the work of the function (or, as a Lisp programmer would say,
- "a list of Lisp forms to evaluate"). The value returned by the
- function is the value returned by the last element of the body.
- File: elisp, Node: Simple Lambda, Next: Argument List, Prev: Lambda Components, Up: Lambda Expressions
- 12.2.2 A Simple Lambda Expression Example
- -----------------------------------------
- Consider the following example:
- (lambda (a b c) (+ a b c))
- We can call this function by passing it to `funcall', like this:
- (funcall (lambda (a b c) (+ a b c))
- 1 2 3)
- This call evaluates the body of the lambda expression with the variable
- `a' bound to 1, `b' bound to 2, and `c' bound to 3. Evaluation of the
- body adds these three numbers, producing the result 6; therefore, this
- call to the function returns the value 6.
- Note that the arguments can be the results of other function calls,
- as in this example:
- (funcall (lambda (a b c) (+ a b c))
- 1 (* 2 3) (- 5 4))
- This evaluates the arguments `1', `(* 2 3)', and `(- 5 4)' from left to
- right. Then it applies the lambda expression to the argument values 1,
- 6 and 1 to produce the value 8.
- As these examples show, you can use a form with a lambda expression
- as its CAR to make local variables and give them values. In the old
- days of Lisp, this technique was the only way to bind and initialize
- local variables. But nowadays, it is clearer to use the special form
- `let' for this purpose (*note Local Variables::). Lambda expressions
- are mainly used as anonymous functions for passing as arguments to
- other functions (*note Anonymous Functions::), or stored as symbol
- function definitions to produce named functions (*note Function
- Names::).
- File: elisp, Node: Argument List, Next: Function Documentation, Prev: Simple Lambda, Up: Lambda Expressions
- 12.2.3 Other Features of Argument Lists
- ---------------------------------------
- Our simple sample function, `(lambda (a b c) (+ a b c))', specifies
- three argument variables, so it must be called with three arguments: if
- you try to call it with only two arguments or four arguments, you get a
- `wrong-number-of-arguments' error.
- It is often convenient to write a function that allows certain
- arguments to be omitted. For example, the function `substring' accepts
- three arguments--a string, the start index and the end index--but the
- third argument defaults to the LENGTH of the string if you omit it. It
- is also convenient for certain functions to accept an indefinite number
- of arguments, as the functions `list' and `+' do.
- To specify optional arguments that may be omitted when a function is
- called, simply include the keyword `&optional' before the optional
- arguments. To specify a list of zero or more extra arguments, include
- the keyword `&rest' before one final argument.
- Thus, the complete syntax for an argument list is as follows:
- (REQUIRED-VARS...
- [&optional OPTIONAL-VARS...]
- [&rest REST-VAR])
- The square brackets indicate that the `&optional' and `&rest' clauses,
- and the variables that follow them, are optional.
- A call to the function requires one actual argument for each of the
- REQUIRED-VARS. There may be actual arguments for zero or more of the
- OPTIONAL-VARS, and there cannot be any actual arguments beyond that
- unless the lambda list uses `&rest'. In that case, there may be any
- number of extra actual arguments.
- If actual arguments for the optional and rest variables are omitted,
- then they always default to `nil'. There is no way for the function to
- distinguish between an explicit argument of `nil' and an omitted
- argument. However, the body of the function is free to consider `nil'
- an abbreviation for some other meaningful value. This is what
- `substring' does; `nil' as the third argument to `substring' means to
- use the length of the string supplied.
- Common Lisp note: Common Lisp allows the function to specify what
- default value to use when an optional argument is omitted; Emacs
- Lisp always uses `nil'. Emacs Lisp does not support "supplied-p"
- variables that tell you whether an argument was explicitly passed.
- For example, an argument list that looks like this:
- (a b &optional c d &rest e)
- binds `a' and `b' to the first two actual arguments, which are
- required. If one or two more arguments are provided, `c' and `d' are
- bound to them respectively; any arguments after the first four are
- collected into a list and `e' is bound to that list. If there are only
- two arguments, `c' is `nil'; if two or three arguments, `d' is `nil';
- if four arguments or fewer, `e' is `nil'.
- There is no way to have required arguments following optional
- ones--it would not make sense. To see why this must be so, suppose
- that `c' in the example were optional and `d' were required. Suppose
- three actual arguments are given; which variable would the third
- argument be for? Would it be used for the C, or for D? One can argue
- for both possibilities. Similarly, it makes no sense to have any more
- arguments (either required or optional) after a `&rest' argument.
- Here are some examples of argument lists and proper calls:
- (funcall (lambda (n) (1+ n)) ; One required:
- 1) ; requires exactly one argument.
- => 2
- (funcall (lambda (n &optional n1) ; One required and one optional:
- (if n1 (+ n n1) (1+ n))) ; 1 or 2 arguments.
- 1 2)
- => 3
- (funcall (lambda (n &rest ns) ; One required and one rest:
- (+ n (apply '+ ns))) ; 1 or more arguments.
- 1 2 3 4 5)
- => 15
- File: elisp, Node: Function Documentation, Prev: Argument List, Up: Lambda Expressions
- 12.2.4 Documentation Strings of Functions
- -----------------------------------------
- A lambda expression may optionally have a "documentation string" just
- after the lambda list. This string does not affect execution of the
- function; it is a kind of comment, but a systematized comment which
- actually appears inside the Lisp world and can be used by the Emacs
- help facilities. *Note Documentation::, for how the documentation
- string is accessed.
- It is a good idea to provide documentation strings for all the
- functions in your program, even those that are called only from within
- your program. Documentation strings are like comments, except that they
- are easier to access.
- The first line of the documentation string should stand on its own,
- because `apropos' displays just this first line. It should consist of
- one or two complete sentences that summarize the function's purpose.
- The start of the documentation string is usually indented in the
- source file, but since these spaces come before the starting
- double-quote, they are not part of the string. Some people make a
- practice of indenting any additional lines of the string so that the
- text lines up in the program source. _That is a mistake._ The
- indentation of the following lines is inside the string; what looks
- nice in the source code will look ugly when displayed by the help
- commands.
- You may wonder how the documentation string could be optional, since
- there are required components of the function that follow it (the body).
- Since evaluation of a string returns that string, without any side
- effects, it has no effect if it is not the last form in the body.
- Thus, in practice, there is no confusion between the first form of the
- body and the documentation string; if the only body form is a string
- then it serves both as the return value and as the documentation.
- The last line of the documentation string can specify calling
- conventions different from the actual function arguments. Write text
- like this:
- \(fn ARGLIST)
- following a blank line, at the beginning of the line, with no newline
- following it inside the documentation string. (The `\' is used to
- avoid confusing the Emacs motion commands.) The calling convention
- specified in this way appears in help messages in place of the one
- derived from the actual arguments of the function.
- This feature is particularly useful for macro definitions, since the
- arguments written in a macro definition often do not correspond to the
- way users think of the parts of the macro call.
- File: elisp, Node: Function Names, Next: Defining Functions, Prev: Lambda Expressions, Up: Functions
- 12.3 Naming a Function
- ======================
- A symbol can serve as the name of a function. This happens when the
- symbol's "function cell" (*note Symbol Components::) contains a
- function object (e.g. a lambda expression). Then the symbol itself
- becomes a valid, callable function, equivalent to the function object
- in its function cell.
- The contents of the function cell are also called the symbol's
- "function definition". The procedure of using a symbol's function
- definition in place of the symbol is called "symbol function
- indirection"; see *note Function Indirection::. If you have not given a
- symbol a function definition, its function cell is said to be "void",
- and it cannot be used as a function.
- In practice, nearly all functions have names, and are referred to by
- their names. You can create a named Lisp function by defining a lambda
- expression and putting it in a function cell (*note Function Cells::).
- However, it is more common to use the `defun' special form, described
- in the next section. *Note Defining Functions::.
- We give functions names because it is convenient to refer to them by
- their names in Lisp expressions. Also, a named Lisp function can
- easily refer to itself--it can be recursive. Furthermore, primitives
- can only be referred to textually by their names, since primitive
- function objects (*note Primitive Function Type::) have no read syntax.
- A function need not have a unique name. A given function object
- _usually_ appears in the function cell of only one symbol, but this is
- just a convention. It is easy to store it in several symbols using
- `fset'; then each of the symbols is a valid name for the same function.
- Note that a symbol used as a function name may also be used as a
- variable; these two uses of a symbol are independent and do not
- conflict. (This is not the case in some dialects of Lisp, like Scheme.)
- File: elisp, Node: Defining Functions, Next: Calling Functions, Prev: Function Names, Up: Functions
- 12.4 Defining Functions
- =======================
- We usually give a name to a function when it is first created. This is
- called "defining a function", and it is done with the `defun' special
- form.
- -- Special Form: defun name argument-list body-forms...
- `defun' is the usual way to define new Lisp functions. It defines
- the symbol NAME as a function that looks like this:
- (lambda ARGUMENT-LIST . BODY-FORMS)
- `defun' stores this lambda expression in the function cell of
- NAME. It returns the value NAME, but usually we ignore this value.
- As described previously, ARGUMENT-LIST is a list of argument names
- and may include the keywords `&optional' and `&rest'. Also, the
- first two of the BODY-FORMS may be a documentation string and an
- interactive declaration. *Note Lambda Components::.
- Here are some examples:
- (defun foo () 5)
- => foo
- (foo)
- => 5
- (defun bar (a &optional b &rest c)
- (list a b c))
- => bar
- (bar 1 2 3 4 5)
- => (1 2 (3 4 5))
- (bar 1)
- => (1 nil nil)
- (bar)
- error--> Wrong number of arguments.
- (defun capitalize-backwards ()
- "Upcase the last letter of the word at point."
- (interactive)
- (backward-word 1)
- (forward-word 1)
- (backward-char 1)
- (capitalize-word 1))
- => capitalize-backwards
- Be careful not to redefine existing functions unintentionally.
- `defun' redefines even primitive functions such as `car' without
- any hesitation or notification. Emacs does not prevent you from
- doing this, because redefining a function is sometimes done
- deliberately, and there is no way to distinguish deliberate
- redefinition from unintentional redefinition.
- -- Function: defalias name definition &optional docstring
- This special form defines the symbol NAME as a function, with
- definition DEFINITION (which can be any valid Lisp function). It
- returns DEFINITION.
- If DOCSTRING is non-`nil', it becomes the function documentation
- of NAME. Otherwise, any documentation provided by DEFINITION is
- used.
- The proper place to use `defalias' is where a specific function
- name is being defined--especially where that name appears
- explicitly in the source file being loaded. This is because
- `defalias' records which file defined the function, just like
- `defun' (*note Unloading::).
- By contrast, in programs that manipulate function definitions for
- other purposes, it is better to use `fset', which does not keep
- such records. *Note Function Cells::.
- You cannot create a new primitive function with `defun' or
- `defalias', but you can use them to change the function definition of
- any symbol, even one such as `car' or `x-popup-menu' whose normal
- definition is a primitive. However, this is risky: for instance, it is
- next to impossible to redefine `car' without breaking Lisp completely.
- Redefining an obscure function such as `x-popup-menu' is less
- dangerous, but it still may not work as you expect. If there are calls
- to the primitive from C code, they call the primitive's C definition
- directly, so changing the symbol's definition will have no effect on
- them.
- See also `defsubst', which defines a function like `defun' and tells
- the Lisp compiler to perform inline expansion on it. *Note Inline
- Functions::.
- File: elisp, Node: Calling Functions, Next: Mapping Functions, Prev: Defining Functions, Up: Functions
- 12.5 Calling Functions
- ======================
- Defining functions is only half the battle. Functions don't do
- anything until you "call" them, i.e., tell them to run. Calling a
- function is also known as "invocation".
- The most common way of invoking a function is by evaluating a list.
- For example, evaluating the list `(concat "a" "b")' calls the function
- `concat' with arguments `"a"' and `"b"'. *Note Evaluation::, for a
- description of evaluation.
- When you write a list as an expression in your program, you specify
- which function to call, and how many arguments to give it, in the text
- of the program. Usually that's just what you want. Occasionally you
- need to compute at run time which function to call. To do that, use
- the function `funcall'. When you also need to determine at run time
- how many arguments to pass, use `apply'.
- -- Function: funcall function &rest arguments
- `funcall' calls FUNCTION with ARGUMENTS, and returns whatever
- FUNCTION returns.
- Since `funcall' is a function, all of its arguments, including
- FUNCTION, are evaluated before `funcall' is called. This means
- that you can use any expression to obtain the function to be
- called. It also means that `funcall' does not see the expressions
- you write for the ARGUMENTS, only their values. These values are
- _not_ evaluated a second time in the act of calling FUNCTION; the
- operation of `funcall' is like the normal procedure for calling a
- function, once its arguments have already been evaluated.
- The argument FUNCTION must be either a Lisp function or a
- primitive function. Special forms and macros are not allowed,
- because they make sense only when given the "unevaluated" argument
- expressions. `funcall' cannot provide these because, as we saw
- above, it never knows them in the first place.
- (setq f 'list)
- => list
- (funcall f 'x 'y 'z)
- => (x y z)
- (funcall f 'x 'y '(z))
- => (x y (z))
- (funcall 'and t nil)
- error--> Invalid function: #<subr and>
- Compare these examples with the examples of `apply'.
- -- Function: apply function &rest arguments
- `apply' calls FUNCTION with ARGUMENTS, just like `funcall' but
- with one difference: the last of ARGUMENTS is a list of objects,
- which are passed to FUNCTION as separate arguments, rather than a
- single list. We say that `apply' "spreads" this list so that each
- individual element becomes an argument.
- `apply' returns the result of calling FUNCTION. As with
- `funcall', FUNCTION must either be a Lisp function or a primitive
- function; special forms and macros do not make sense in `apply'.
- (setq f 'list)
- => list
- (apply f 'x 'y 'z)
- error--> Wrong type argument: listp, z
- (apply '+ 1 2 '(3 4))
- => 10
- (apply '+ '(1 2 3 4))
- => 10
- (apply 'append '((a b c) nil (x y z) nil))
- => (a b c x y z)
- For an interesting example of using `apply', see *note Definition
- of mapcar::.
- Sometimes it is useful to fix some of the function's arguments at
- certain values, and leave the rest of arguments for when the function
- is actually called. The act of fixing some of the function's arguments
- is called "partial application" of the function(1). The result is a
- new function that accepts the rest of arguments and calls the original
- function with all the arguments combined.
- Here's how to do partial application in Emacs Lisp:
- -- Function: apply-partially func &rest args
- This function returns a new function which, when called, will call
- FUNC with the list of arguments composed from ARGS and additional
- arguments specified at the time of the call. If FUNC accepts N
- arguments, then a call to `apply-partially' with `M < N' arguments
- will produce a new function of `N - M' arguments.
- Here's how we could define the built-in function `1+', if it
- didn't exist, using `apply-partially' and `+', another built-in
- function:
- (defalias '1+ (apply-partially '+ 1)
- "Increment argument by one.")
- (1+ 10)
- => 11
- It is common for Lisp functions to accept functions as arguments or
- find them in data structures (especially in hook variables and property
- lists) and call them using `funcall' or `apply'. Functions that accept
- function arguments are often called "functionals".
- Sometimes, when you call a functional, it is useful to supply a no-op
- function as the argument. Here are two different kinds of no-op
- function:
- -- Function: identity arg
- This function returns ARG and has no side effects.
- -- Function: ignore &rest args
- This function ignores any arguments and returns `nil'.
- Some functions are user-visible "commands", which can be called
- interactively (usually by a key sequence). It is possible to invoke
- such a command exactly as though it was called interactively, by using
- the `call-interactively' function. *Note Interactive Call::.
- ---------- Footnotes ----------
- (1) This is related to, but different from "currying", which
- transforms a function that takes multiple arguments in such a way that
- it can be called as a chain of functions, each one with a single
- argument.
- File: elisp, Node: Mapping Functions, Next: Anonymous Functions, Prev: Calling Functions, Up: Functions
- 12.6 Mapping Functions
- ======================
- A "mapping function" applies a given function (_not_ a special form or
- macro) to each element of a list or other collection. Emacs Lisp has
- several such functions; this section describes `mapcar', `mapc', and
- `mapconcat', which map over a list. *Note Definition of mapatoms::,
- for the function `mapatoms' which maps over the symbols in an obarray.
- *Note Definition of maphash::, for the function `maphash' which maps
- over key/value associations in a hash table.
- These mapping functions do not allow char-tables because a char-table
- is a sparse array whose nominal range of indices is very large. To map
- over a char-table in a way that deals properly with its sparse nature,
- use the function `map-char-table' (*note Char-Tables::).
- -- Function: mapcar function sequence
- `mapcar' applies FUNCTION to each element of SEQUENCE in turn, and
- returns a list of the results.
- The argument SEQUENCE can be any kind of sequence except a
- char-table; that is, a list, a vector, a bool-vector, or a string.
- The result is always a list. The length of the result is the same
- as the length of SEQUENCE. For example:
- (mapcar 'car '((a b) (c d) (e f)))
- => (a c e)
- (mapcar '1+ [1 2 3])
- => (2 3 4)
- (mapcar 'string "abc")
- => ("a" "b" "c")
- ;; Call each function in `my-hooks'.
- (mapcar 'funcall my-hooks)
- (defun mapcar* (function &rest args)
- "Apply FUNCTION to successive cars of all ARGS.
- Return the list of results."
- ;; If no list is exhausted,
- (if (not (memq nil args))
- ;; apply function to CARs.
- (cons (apply function (mapcar 'car args))
- (apply 'mapcar* function
- ;; Recurse for rest of elements.
- (mapcar 'cdr args)))))
- (mapcar* 'cons '(a b c) '(1 2 3 4))
- => ((a . 1) (b . 2) (c . 3))
- -- Function: mapc function sequence
- `mapc' is like `mapcar' except that FUNCTION is used for
- side-effects only--the values it returns are ignored, not collected
- into a list. `mapc' always returns SEQUENCE.
- -- Function: mapconcat function sequence separator
- `mapconcat' applies FUNCTION to each element of SEQUENCE: the
- results, which must be strings, are concatenated. Between each
- pair of result strings, `mapconcat' inserts the string SEPARATOR.
- Usually SEPARATOR contains a space or comma or other suitable
- punctuation.
- The argument FUNCTION must be a function that can take one
- argument and return a string. The argument SEQUENCE can be any
- kind of sequence except a char-table; that is, a list, a vector, a
- bool-vector, or a string.
- (mapconcat 'symbol-name
- '(The cat in the hat)
- " ")
- => "The cat in the hat"
- (mapconcat (function (lambda (x) (format "%c" (1+ x))))
- "HAL-8000"
- "")
- => "IBM.9111"
- File: elisp, Node: Anonymous Functions, Next: Function Cells, Prev: Mapping Functions, Up: Functions
- 12.7 Anonymous Functions
- ========================
- Although functions are usually defined with `defun' and given names at
- the same time, it is sometimes convenient to use an explicit lambda
- expression--an "anonymous function". Anonymous functions are valid
- wherever function names are. They are often assigned as variable
- values, or as arguments to functions; for instance, you might pass one
- as the FUNCTION argument to `mapcar', which applies that function to
- each element of a list (*note Mapping Functions::). *Note
- describe-symbols example::, for a realistic example of this.
- When defining a lambda expression that is to be used as an anonymous
- function, you can in principle use any method to construct the list.
- But typically you should use the `lambda' macro, or the `function'
- special form, or the `#'' read syntax:
- -- Macro: lambda args body...
- This macro returns an anonymous function with argument list ARGS
- and body forms given by BODY. In effect, this macro makes
- `lambda' forms "self-quoting": evaluating a form whose CAR is
- `lambda' yields the form itself:
- (lambda (x) (* x x))
- => (lambda (x) (* x x))
- The `lambda' form has one other effect: it tells the Emacs
- evaluator and byte-compiler that its argument is a function, by
- using `function' as a subroutine (see below).
- -- Special Form: function function-object
- This special form returns FUNCTION-OBJECT without evaluating it.
- In this, it is similar to `quote' (*note Quoting::). But unlike
- `quote', it also serves as a note to the Emacs evaluator and
- byte-compiler that FUNCTION-OBJECT is intended to be used as a
- function. Assuming FUNCTION-OBJECT is a valid lambda expression,
- this has two effects:
- * When the code is byte-compiled, FUNCTION-OBJECT is compiled
- into a byte-code function object (*note Byte Compilation::).
- * When lexical binding is enabled, FUNCTION-OBJECT is converted
- into a closure. *Note Closures::.
- The read syntax `#'' is a short-hand for using `function'. The
- following forms are all equivalent:
- (lambda (x) (* x x))
- (function (lambda (x) (* x x)))
- #'(lambda (x) (* x x))
- In the following example, we define a `change-property' function
- that takes a function as its third argument, followed by a
- `double-property' function that makes use of `change-property' by
- passing it an anonymous function:
- (defun change-property (symbol prop function)
- (let ((value (get symbol prop)))
- (put symbol prop (funcall function value))))
- (defun double-property (symbol prop)
- (change-property symbol prop (lambda (x) (* 2 x))))
- Note that we do not quote the `lambda' form.
- If you compile the above code, the anonymous function is also
- compiled. This would not happen if, say, you had constructed the
- anonymous function by quoting it as a list:
- (defun double-property (symbol prop)
- (change-property symbol prop '(lambda (x) (* 2 x))))
- In that case, the anonymous function is kept as a lambda expression in
- the compiled code. The byte-compiler cannot assume this list is a
- function, even though it looks like one, since it does not know that
- `change-property' intends to use it as a function.
- File: elisp, Node: Function Cells, Next: Closures, Prev: Anonymous Functions, Up: Functions
- 12.8 Accessing Function Cell Contents
- =====================================
- The "function definition" of a symbol is the object stored in the
- function cell of the symbol. The functions described here access, test,
- and set the function cell of symbols.
- See also the function `indirect-function'. *Note Definition of
- indirect-function::.
- -- Function: symbol-function symbol
- This returns the object in the function cell of SYMBOL. If the
- symbol's function cell is void, a `void-function' error is
- signaled.
- This function does not check that the returned object is a
- legitimate function.
- (defun bar (n) (+ n 2))
- => bar
- (symbol-function 'bar)
- => (lambda (n) (+ n 2))
- (fset 'baz 'bar)
- => bar
- (symbol-function 'baz)
- => bar
- If you have never given a symbol any function definition, we say that
- that symbol's function cell is "void". In other words, the function
- cell does not have any Lisp object in it. If you try to call such a
- symbol as a function, it signals a `void-function' error.
- Note that void is not the same as `nil' or the symbol `void'. The
- symbols `nil' and `void' are Lisp objects, and can be stored into a
- function cell just as any other object can be (and they can be valid
- functions if you define them in turn with `defun'). A void function
- cell contains no object whatsoever.
- You can test the voidness of a symbol's function definition with
- `fboundp'. After you have given a symbol a function definition, you
- can make it void once more using `fmakunbound'.
- -- Function: fboundp symbol
- This function returns `t' if the symbol has an object in its
- function cell, `nil' otherwise. It does not check that the object
- is a legitimate function.
- -- Function: fmakunbound symbol
- This function makes SYMBOL's function cell void, so that a
- subsequent attempt to access this cell will cause a
- `void-function' error. It returns SYMBOL. (See also
- `makunbound', in *note Void Variables::.)
- (defun foo (x) x)
- => foo
- (foo 1)
- =>1
- (fmakunbound 'foo)
- => foo
- (foo 1)
- error--> Symbol's function definition is void: foo
- -- Function: fset symbol definition
- This function stores DEFINITION in the function cell of SYMBOL.
- The result is DEFINITION. Normally DEFINITION should be a
- function or the name of a function, but this is not checked. The
- argument SYMBOL is an ordinary evaluated argument.
- The primary use of this function is as a subroutine by constructs
- that define or alter functions, like `defadvice' (*note Advising
- Functions::). (If `defun' were not a primitive, it could be
- written as a Lisp macro using `fset'.) You can also use it to
- give a symbol a function definition that is not a list, e.g. a
- keyboard macro (*note Keyboard Macros::):
- ;; Define a named keyboard macro.
- (fset 'kill-two-lines "\^u2\^k")
- => "\^u2\^k"
- It you wish to use `fset' to make an alternate name for a
- function, consider using `defalias' instead. *Note Definition of
- defalias::.
- File: elisp, Node: Closures, Next: Obsolete Functions, Prev: Function Cells, Up: Functions
- 12.9 Closures
- =============
- As explained in *note Variable Scoping::, Emacs can optionally enable
- lexical binding of variables. When lexical binding is enabled, any
- named function that you create (e.g. with `defun'), as well as any
- anonymous function that you create using the `lambda' macro or the
- `function' special form or the `#'' syntax (*note Anonymous
- Functions::), is automatically converted into a "closure".
- A closure is a function that also carries a record of the lexical
- environment that existed when the function was defined. When it is
- invoked, any lexical variable references within its definition use the
- retained lexical environment. In all other respects, closures behave
- much like ordinary functions; in particular, they can be called in the
- same way as ordinary functions.
- *Note Lexical Binding::, for an example of using a closure.
- Currently, an Emacs Lisp closure object is represented by a list
- with the symbol `closure' as the first element, a list representing the
- lexical environment as the second element, and the argument list and
- body forms as the remaining elements:
- ;; lexical binding is enabled.
- (lambda (x) (* x x))
- => (closure (t) (x) (* x x))
- However, the fact that the internal structure of a closure is "exposed"
- to the rest of the Lisp world is considered an internal implementation
- detail. For this reason, we recommend against directly examining or
- altering the structure of closure objects.
- File: elisp, Node: Obsolete Functions, Next: Inline Functions, Prev: Closures, Up: Functions
- 12.10 Declaring Functions Obsolete
- ==================================
- You can use `make-obsolete' to declare a function obsolete. This
- indicates that the function may be removed at some stage in the future.
- -- Function: make-obsolete obsolete-name current-name &optional when
- This function makes the byte compiler warn that the function
- OBSOLETE-NAME is obsolete. If CURRENT-NAME is a symbol, the
- warning message says to use CURRENT-NAME instead of OBSOLETE-NAME.
- CURRENT-NAME does not need to be an alias for OBSOLETE-NAME; it
- can be a different function with similar functionality. If
- CURRENT-NAME is a string, it is the warning message.
- If provided, WHEN should be a string indicating when the function
- was first made obsolete--for example, a date or a release number.
- You can define a function as an alias and declare it obsolete at the
- same time using the macro `define-obsolete-function-alias':
- -- Macro: define-obsolete-function-alias obsolete-name current-name
- &optional when docstring
- This macro marks the function OBSOLETE-NAME obsolete and also
- defines it as an alias for the function CURRENT-NAME. It is
- equivalent to the following:
- (defalias OBSOLETE-NAME CURRENT-NAME DOCSTRING)
- (make-obsolete OBSOLETE-NAME CURRENT-NAME WHEN)
- In addition, you can mark a certain a particular calling convention
- for a function as obsolete:
- -- Function: set-advertised-calling-convention function signature when
- This function specifies the argument list SIGNATURE as the correct
- way to call FUNCTION. This causes the Emacs byte compiler to
- issue a warning whenever it comes across an Emacs Lisp program
- that calls FUNCTION any other way (however, it will still allow
- the code to be byte compiled). WHEN should be a string indicating
- when the variable was first made obsolete (usually a version
- number string).
- For instance, in old versions of Emacs the `sit-for' function
- accepted three arguments, like this
- (sit-for seconds milliseconds nodisp)
- However, calling `sit-for' this way is considered obsolete (*note
- Waiting::). The old calling convention is deprecated like this:
- (set-advertised-calling-convention
- 'sit-for '(seconds &optional nodisp) "22.1")
- File: elisp, Node: Inline Functions, Next: Declaring Functions, Prev: Obsolete Functions, Up: Functions
- 12.11 Inline Functions
- ======================
- -- Macro: defsubst name argument-list body-forms...
- Define an inline function. The syntax is exactly the same as
- `defun' (*note Defining Functions::).
- You can define an "inline function" by using `defsubst' instead of
- `defun'. An inline function works just like an ordinary function
- except for one thing: when you byte-compile a call to the function
- (*note Byte Compilation::), the function's definition is expanded into
- the caller.
- Making a function inline often makes its function calls run faster.
- But it also has disadvantages. For one thing, it reduces flexibility;
- if you change the definition of the function, calls already inlined
- still use the old definition until you recompile them.
- Another disadvantage is that making a large function inline can
- increase the size of compiled code both in files and in memory. Since
- the speed advantage of inline functions is greatest for small
- functions, you generally should not make large functions inline.
- Also, inline functions do not behave well with respect to debugging,
- tracing, and advising (*note Advising Functions::). Since ease of
- debugging and the flexibility of redefining functions are important
- features of Emacs, you should not make a function inline, even if it's
- small, unless its speed is really crucial, and you've timed the code to
- verify that using `defun' actually has performance problems.
- It's possible to define a macro to expand into the same code that an
- inline function would execute (*note Macros::). But the macro would be
- limited to direct use in expressions--a macro cannot be called with
- `apply', `mapcar' and so on. Also, it takes some work to convert an
- ordinary function into a macro. To convert it into an inline function
- is easy; just replace `defun' with `defsubst'. Since each argument of
- an inline function is evaluated exactly once, you needn't worry about
- how many times the body uses the arguments, as you do for macros.
- After an inline function is defined, its inline expansion can be
- performed later on in the same file, just like macros.
- File: elisp, Node: Declaring Functions, Next: Function Safety, Prev: Inline Functions, Up: Functions
- 12.12 Telling the Compiler that a Function is Defined
- =====================================================
- Byte-compiling a file often produces warnings about functions that the
- compiler doesn't know about (*note Compiler Errors::). Sometimes this
- indicates a real problem, but usually the functions in question are
- defined in other files which would be loaded if that code is run. For
- example, byte-compiling `fortran.el' used to warn:
- In end of data:
- fortran.el:2152:1:Warning: the function `gud-find-c-expr' is not
- known to be defined.
- In fact, `gud-find-c-expr' is only used in the function that Fortran
- mode uses for the local value of `gud-find-expr-function', which is a
- callback from GUD; if it is called, the GUD functions will be loaded.
- When you know that such a warning does not indicate a real problem, it
- is good to suppress the warning. That makes new warnings which might
- mean real problems more visible. You do that with `declare-function'.
- All you need to do is add a `declare-function' statement before the
- first use of the function in question:
- (declare-function gud-find-c-expr "gud.el" nil)
- This says that `gud-find-c-expr' is defined in `gud.el' (the `.el'
- can be omitted). The compiler takes for granted that that file really
- defines the function, and does not check.
- The optional third argument specifies the argument list of
- `gud-find-c-expr'. In this case, it takes no arguments (`nil' is
- different from not specifying a value). In other cases, this might be
- something like `(file &optional overwrite)'. You don't have to specify
- the argument list, but if you do the byte compiler can check that the
- calls match the declaration.
- -- Macro: declare-function function file &optional arglist fileonly
- Tell the byte compiler to assume that FUNCTION is defined, with
- arguments ARGLIST, and that the definition should come from the
- file FILE. FILEONLY non-`nil' means only check that FILE exists,
- not that it actually defines FUNCTION.
- To verify that these functions really are declared where
- `declare-function' says they are, use `check-declare-file' to check all
- `declare-function' calls in one source file, or use
- `check-declare-directory' check all the files in and under a certain
- directory.
- These commands find the file that ought to contain a function's
- definition using `locate-library'; if that finds no file, they expand
- the definition file name relative to the directory of the file that
- contains the `declare-function' call.
- You can also say that a function is a primitive by specifying a file
- name ending in `.c' or `.m'. This is useful only when you call a
- primitive that is defined only on certain systems. Most primitives are
- always defined, so they will never give you a warning.
- Sometimes a file will optionally use functions from an external
- package. If you prefix the filename in the `declare-function'
- statement with `ext:', then it will be checked if it is found,
- otherwise skipped without error.
- There are some function definitions that `check-declare' does not
- understand (e.g. `defstruct' and some other macros). In such cases,
- you can pass a non-`nil' FILEONLY argument to `declare-function',
- meaning to only check that the file exists, not that it actually
- defines the function. Note that to do this without having to specify
- an argument list, you should set the ARGLIST argument to `t' (because
- `nil' means an empty argument list, as opposed to an unspecified one).
- File: elisp, Node: Function Safety, Next: Related Topics, Prev: Declaring Functions, Up: Functions
- 12.13 Determining whether a Function is Safe to Call
- ====================================================
- Some major modes such as SES call functions that are stored in user
- files. (*note (ses)Top::, for more information on SES.) User files
- sometimes have poor pedigrees--you can get a spreadsheet from someone
- you've just met, or you can get one through email from someone you've
- never met. So it is risky to call a function whose source code is
- stored in a user file until you have determined that it is safe.
- -- Function: unsafep form &optional unsafep-vars
- Returns `nil' if FORM is a "safe" Lisp expression, or returns a
- list that describes why it might be unsafe. The argument
- UNSAFEP-VARS is a list of symbols known to have temporary bindings
- at this point; it is mainly used for internal recursive calls.
- The current buffer is an implicit argument, which provides a list
- of buffer-local bindings.
- Being quick and simple, `unsafep' does a very light analysis and
- rejects many Lisp expressions that are actually safe. There are no
- known cases where `unsafep' returns `nil' for an unsafe expression.
- However, a "safe" Lisp expression can return a string with a `display'
- property, containing an associated Lisp expression to be executed after
- the string is inserted into a buffer. This associated expression can
- be a virus. In order to be safe, you must delete properties from all
- strings calculated by user code before inserting them into buffers.
- File: elisp, Node: Related Topics, Prev: Function Safety, Up: Functions
- 12.14 Other Topics Related to Functions
- =======================================
- Here is a table of several functions that do things related to function
- calling and function definitions. They are documented elsewhere, but
- we provide cross references here.
- `apply'
- See *note Calling Functions::.
- `autoload'
- See *note Autoload::.
- `call-interactively'
- See *note Interactive Call::.
- `called-interactively-p'
- See *note Distinguish Interactive::.
- `commandp'
- See *note Interactive Call::.
- `documentation'
- See *note Accessing Documentation::.
- `eval'
- See *note Eval::.
- `funcall'
- See *note Calling Functions::.
- `function'
- See *note Anonymous Functions::.
- `ignore'
- See *note Calling Functions::.
- `indirect-function'
- See *note Function Indirection::.
- `interactive'
- See *note Using Interactive::.
- `interactive-p'
- See *note Distinguish Interactive::.
- `mapatoms'
- See *note Creating Symbols::.
- `mapcar'
- See *note Mapping Functions::.
- `map-char-table'
- See *note Char-Tables::.
- `mapconcat'
- See *note Mapping Functions::.
- `undefined'
- See *note Functions for Key Lookup::.
- File: elisp, Node: Macros, Next: Customization, Prev: Functions, Up: Top
- 13 Macros
- *********
- "Macros" enable you to define new control constructs and other language
- features. A macro is defined much like a function, but instead of
- telling how to compute a value, it tells how to compute another Lisp
- expression which will in turn compute the value. We call this
- expression the "expansion" of the macro.
- Macros can do this because they operate on the unevaluated
- expressions for the arguments, not on the argument values as functions
- do. They can therefore construct an expansion containing these
- argument expressions or parts of them.
- If you are using a macro to do something an ordinary function could
- do, just for the sake of speed, consider using an inline function
- instead. *Note Inline Functions::.
- * Menu:
- * Simple Macro:: A basic example.
- * Expansion:: How, when and why macros are expanded.
- * Compiling Macros:: How macros are expanded by the compiler.
- * Defining Macros:: How to write a macro definition.
- * Problems with Macros:: Don't evaluate the macro arguments too many times.
- Don't hide the user's variables.
- * Indenting Macros:: Specifying how to indent macro calls.
- File: elisp, Node: Simple Macro, Next: Expansion, Up: Macros
- 13.1 A Simple Example of a Macro
- ================================
- Suppose we would like to define a Lisp construct to increment a
- variable value, much like the `++' operator in C. We would like to
- write `(inc x)' and have the effect of `(setq x (1+ x))'. Here's a
- macro definition that does the job:
- (defmacro inc (var)
- (list 'setq var (list '1+ var)))
- When this is called with `(inc x)', the argument VAR is the symbol
- `x'--_not_ the _value_ of `x', as it would be in a function. The body
- of the macro uses this to construct the expansion, which is `(setq x
- (1+ x))'. Once the macro definition returns this expansion, Lisp
- proceeds to evaluate it, thus incrementing `x'.
- File: elisp, Node: Expansion, Next: Compiling Macros, Prev: Simple Macro, Up: Macros
- 13.2 Expansion of a Macro Call
- ==============================
- A macro call looks just like a function call in that it is a list which
- starts with the name of the macro. The rest of the elements of the list
- are the arguments of the macro.
- Evaluation of the macro call begins like evaluation of a function
- call except for one crucial difference: the macro arguments are the
- actual expressions appearing in the macro call. They are not evaluated
- before they are given to the macro definition. By contrast, the
- arguments of a function are results of evaluating the elements of the
- function call list.
- Having obtained the arguments, Lisp invokes the macro definition just
- as a function is invoked. The argument variables of the macro are bound
- to the argument values from the macro call, or to a list of them in the
- case of a `&rest' argument. And the macro body executes and returns
- its value just as a function body does.
- The second crucial difference between macros and functions is that
- the value returned by the macro body is an alternate Lisp expression,
- also known as the "expansion" of the macro. The Lisp interpreter
- proceeds to evaluate the expansion as soon as it comes back from the
- macro.
- Since the expansion is evaluated in the normal manner, it may contain
- calls to other macros. It may even be a call to the same macro, though
- this is unusual.
- You can see the expansion of a given macro call by calling
- `macroexpand'.
- -- Function: macroexpand form &optional environment
- This function expands FORM, if it is a macro call. If the result
- is another macro call, it is expanded in turn, until something
- which is not a macro call results. That is the value returned by
- `macroexpand'. If FORM is not a macro call to begin with, it is
- returned as given.
- Note that `macroexpand' does not look at the subexpressions of
- FORM (although some macro definitions may do so). Even if they
- are macro calls themselves, `macroexpand' does not expand them.
- The function `macroexpand' does not expand calls to inline
- functions. Normally there is no need for that, since a call to an
- inline function is no harder to understand than a call to an
- ordinary function.
- If ENVIRONMENT is provided, it specifies an alist of macro
- definitions that shadow the currently defined macros. Byte
- compilation uses this feature.
- (defmacro inc (var)
- (list 'setq var (list '1+ var)))
- => inc
- (macroexpand '(inc r))
- => (setq r (1+ r))
- (defmacro inc2 (var1 var2)
- (list 'progn (list 'inc var1) (list 'inc var2)))
- => inc2
- (macroexpand '(inc2 r s))
- => (progn (inc r) (inc s)) ; `inc' not expanded here.
- -- Function: macroexpand-all form &optional environment
- `macroexpand-all' expands macros like `macroexpand', but will look
- for and expand all macros in FORM, not just at the top-level. If
- no macros are expanded, the return value is `eq' to FORM.
- Repeating the example used for `macroexpand' above with
- `macroexpand-all', we see that `macroexpand-all' _does_ expand the
- embedded calls to `inc':
- (macroexpand-all '(inc2 r s))
- => (progn (setq r (1+ r)) (setq s (1+ s)))
- File: elisp, Node: Compiling Macros, Next: Defining Macros, Prev: Expansion, Up: Macros
- 13.3 Macros and Byte Compilation
- ================================
- You might ask why we take the trouble to compute an expansion for a
- macro and then evaluate the expansion. Why not have the macro body
- produce the desired results directly? The reason has to do with
- compilation.
- When a macro call appears in a Lisp program being compiled, the Lisp
- compiler calls the macro definition just as the interpreter would, and
- receives an expansion. But instead of evaluating this expansion, it
- compiles the expansion as if it had appeared directly in the program.
- As a result, the compiled code produces the value and side effects
- intended for the macro, but executes at full compiled speed. This would
- not work if the macro body computed the value and side effects
- itself--they would be computed at compile time, which is not useful.
- In order for compilation of macro calls to work, the macros must
- already be defined in Lisp when the calls to them are compiled. The
- compiler has a special feature to help you do this: if a file being
- compiled contains a `defmacro' form, the macro is defined temporarily
- for the rest of the compilation of that file.
- Byte-compiling a file also executes any `require' calls at top-level
- in the file, so you can ensure that necessary macro definitions are
- available during compilation by requiring the files that define them
- (*note Named Features::). To avoid loading the macro definition files
- when someone _runs_ the compiled program, write `eval-when-compile'
- around the `require' calls (*note Eval During Compile::).
- File: elisp, Node: Defining Macros, Next: Problems with Macros, Prev: Compiling Macros, Up: Macros
- 13.4 Defining Macros
- ====================
- A Lisp macro is a list whose CAR is `macro'. Its CDR should be a
- function; expansion of the macro works by applying the function (with
- `apply') to the list of unevaluated argument-expressions from the macro
- call.
- It is possible to use an anonymous Lisp macro just like an anonymous
- function, but this is never done, because it does not make sense to pass
- an anonymous macro to functionals such as `mapcar'. In practice, all
- Lisp macros have names, and they are usually defined with the special
- form `defmacro'.
- -- Special Form: defmacro name argument-list body-forms...
- `defmacro' defines the symbol NAME as a macro that looks like this:
- (macro lambda ARGUMENT-LIST . BODY-FORMS)
- (Note that the CDR of this list is a function--a lambda
- expression.) This macro object is stored in the function cell of
- NAME. The value returned by evaluating the `defmacro' form is
- NAME, but usually we ignore this value.
- The shape and meaning of ARGUMENT-LIST is the same as in a
- function, and the keywords `&rest' and `&optional' may be used
- (*note Argument List::). Macros may have a documentation string,
- but any `interactive' declaration is ignored since macros cannot be
- called interactively.
- Macros often need to construct large list structures from a mixture
- of constants and nonconstant parts. To make this easier, use the ``'
- syntax (*note Backquote::). For example:
- (defmacro t-becomes-nil (variable)
- `(if (eq ,variable t)
- (setq ,variable nil)))
- (t-becomes-nil foo)
- == (if (eq foo t) (setq foo nil))
- The body of a macro definition can include a `declare' form, which
- can specify how <TAB> should indent macro calls, and how to step
- through them for Edebug.
- -- Macro: declare SPECS...
- A `declare' form is used in a macro definition to specify various
- additional information about it. The following specifications are
- currently supported:
- `(debug EDEBUG-FORM-SPEC)'
- Specify how to step through macro calls for Edebug. *Note
- Instrumenting Macro Calls::.
- `(indent INDENT-SPEC)'
- Specify how to indent calls to this macro. *Note Indenting
- Macros::, for more details.
- `(doc-string NUMBER)'
- Specify which element of the macro is the documentation
- string, if any.
- A `declare' form only has its special effect in the body of a
- `defmacro' form if it immediately follows the documentation
- string, if present, or the argument list otherwise. (Strictly
- speaking, _several_ `declare' forms can follow the documentation
- string or argument list, but since a `declare' form can have
- several SPECS, they can always be combined into a single form.)
- When used at other places in a `defmacro' form, or outside a
- `defmacro' form, `declare' just returns `nil' without evaluating
- any SPECS.
- No macro absolutely needs a `declare' form, because that form has no
- effect on how the macro expands, on what the macro means in the
- program. It only affects the secondary features listed above.
- File: elisp, Node: Problems with Macros, Next: Indenting Macros, Prev: Defining Macros, Up: Macros
- 13.5 Common Problems Using Macros
- =================================
- Macro expansion can have counterintuitive consequences. This section
- describes some important consequences that can lead to trouble, and
- rules to follow to avoid trouble.
- * Menu:
- * Wrong Time:: Do the work in the expansion, not in the macro.
- * Argument Evaluation:: The expansion should evaluate each macro arg once.
- * Surprising Local Vars:: Local variable bindings in the expansion
- require special care.
- * Eval During Expansion:: Don't evaluate them; put them in the expansion.
- * Repeated Expansion:: Avoid depending on how many times expansion is done.
- File: elisp, Node: Wrong Time, Next: Argument Evaluation, Up: Problems with Macros
- 13.5.1 Wrong Time
- -----------------
- The most common problem in writing macros is doing some of the real
- work prematurely--while expanding the macro, rather than in the
- expansion itself. For instance, one real package had this macro
- definition:
- (defmacro my-set-buffer-multibyte (arg)
- (if (fboundp 'set-buffer-multibyte)
- (set-buffer-multibyte arg)))
- With this erroneous macro definition, the program worked fine when
- interpreted but failed when compiled. This macro definition called
- `set-buffer-multibyte' during compilation, which was wrong, and then
- did nothing when the compiled package was run. The definition that the
- programmer really wanted was this:
- (defmacro my-set-buffer-multibyte (arg)
- (if (fboundp 'set-buffer-multibyte)
- `(set-buffer-multibyte ,arg)))
- This macro expands, if appropriate, into a call to
- `set-buffer-multibyte' that will be executed when the compiled program
- is actually run.
- File: elisp, Node: Argument Evaluation, Next: Surprising Local Vars, Prev: Wrong Time, Up: Problems with Macros
- 13.5.2 Evaluating Macro Arguments Repeatedly
- --------------------------------------------
- When defining a macro you must pay attention to the number of times the
- arguments will be evaluated when the expansion is executed. The
- following macro (used to facilitate iteration) illustrates the problem.
- This macro allows us to write a "for" loop construct.
- (defmacro for (var from init to final do &rest body)
- "Execute a simple \"for\" loop.
- For example, (for i from 1 to 10 do (print i))."
- (list 'let (list (list var init))
- (cons 'while
- (cons (list '<= var final)
- (append body (list (list 'inc var)))))))
- => for
- (for i from 1 to 3 do
- (setq square (* i i))
- (princ (format "\n%d %d" i square)))
- ==>
- (let ((i 1))
- (while (<= i 3)
- (setq square (* i i))
- (princ (format "\n%d %d" i square))
- (inc i)))
- -|1 1
- -|2 4
- -|3 9
- => nil
- The arguments `from', `to', and `do' in this macro are "syntactic
- sugar"; they are entirely ignored. The idea is that you will write
- noise words (such as `from', `to', and `do') in those positions in the
- macro call.
- Here's an equivalent definition simplified through use of backquote:
- (defmacro for (var from init to final do &rest body)
- "Execute a simple \"for\" loop.
- For example, (for i from 1 to 10 do (print i))."
- `(let ((,var ,init))
- (while (<= ,var ,final)
- ,@body
- (inc ,var))))
- Both forms of this definition (with backquote and without) suffer
- from the defect that FINAL is evaluated on every iteration. If FINAL
- is a constant, this is not a problem. If it is a more complex form,
- say `(long-complex-calculation x)', this can slow down the execution
- significantly. If FINAL has side effects, executing it more than once
- is probably incorrect.
- A well-designed macro definition takes steps to avoid this problem by
- producing an expansion that evaluates the argument expressions exactly
- once unless repeated evaluation is part of the intended purpose of the
- macro. Here is a correct expansion for the `for' macro:
- (let ((i 1)
- (max 3))
- (while (<= i max)
- (setq square (* i i))
- (princ (format "%d %d" i square))
- (inc i)))
- Here is a macro definition that creates this expansion:
- (defmacro for (var from init to final do &rest body)
- "Execute a simple for loop: (for i from 1 to 10 do (print i))."
- `(let ((,var ,init)
- (max ,final))
- (while (<= ,var max)
- ,@body
- (inc ,var))))
- Unfortunately, this fix introduces another problem, described in the
- following section.
- File: elisp, Node: Surprising Local Vars, Next: Eval During Expansion, Prev: Argument Evaluation, Up: Problems with Macros
- 13.5.3 Local Variables in Macro Expansions
- ------------------------------------------
- In the previous section, the definition of `for' was fixed as follows
- to make the expansion evaluate the macro arguments the proper number of
- times:
- (defmacro for (var from init to final do &rest body)
- "Execute a simple for loop: (for i from 1 to 10 do (print i))."
- `(let ((,var ,init)
- (max ,final))
- (while (<= ,var max)
- ,@body
- (inc ,var))))
- The new definition of `for' has a new problem: it introduces a local
- variable named `max' which the user does not expect. This causes
- trouble in examples such as the following:
- (let ((max 0))
- (for x from 0 to 10 do
- (let ((this (frob x)))
- (if (< max this)
- (setq max this)))))
- The references to `max' inside the body of the `for', which are
- supposed to refer to the user's binding of `max', really access the
- binding made by `for'.
- The way to correct this is to use an uninterned symbol instead of
- `max' (*note Creating Symbols::). The uninterned symbol can be bound
- and referred to just like any other symbol, but since it is created by
- `for', we know that it cannot already appear in the user's program.
- Since it is not interned, there is no way the user can put it into the
- program later. It will never appear anywhere except where put by
- `for'. Here is a definition of `for' that works this way:
- (defmacro for (var from init to final do &rest body)
- "Execute a simple for loop: (for i from 1 to 10 do (print i))."
- (let ((tempvar (make-symbol "max")))
- `(let ((,var ,init)
- (,tempvar ,final))
- (while (<= ,var ,tempvar)
- ,@body
- (inc ,var)))))
- This creates an uninterned symbol named `max' and puts it in the
- expansion instead of the usual interned symbol `max' that appears in
- expressions ordinarily.
- File: elisp, Node: Eval During Expansion, Next: Repeated Expansion, Prev: Surprising Local Vars, Up: Problems with Macros
- 13.5.4 Evaluating Macro Arguments in Expansion
- ----------------------------------------------
- Another problem can happen if the macro definition itself evaluates any
- of the macro argument expressions, such as by calling `eval' (*note
- Eval::). If the argument is supposed to refer to the user's variables,
- you may have trouble if the user happens to use a variable with the
- same name as one of the macro arguments. Inside the macro body, the
- macro argument binding is the most local binding of this variable, so
- any references inside the form being evaluated do refer to it. Here is
- an example:
- (defmacro foo (a)
- (list 'setq (eval a) t))
- => foo
- (setq x 'b)
- (foo x) ==> (setq b t)
- => t ; and `b' has been set.
- ;; but
- (setq a 'c)
- (foo a) ==> (setq a t)
- => t ; but this set `a', not `c'.
- It makes a difference whether the user's variable is named `a' or
- `x', because `a' conflicts with the macro argument variable `a'.
- Another problem with calling `eval' in a macro definition is that it
- probably won't do what you intend in a compiled program. The byte
- compiler runs macro definitions while compiling the program, when the
- program's own computations (which you might have wished to access with
- `eval') don't occur and its local variable bindings don't exist.
- To avoid these problems, *don't evaluate an argument expression
- while computing the macro expansion*. Instead, substitute the
- expression into the macro expansion, so that its value will be computed
- as part of executing the expansion. This is how the other examples in
- this chapter work.
- File: elisp, Node: Repeated Expansion, Prev: Eval During Expansion, Up: Problems with Macros
- 13.5.5 How Many Times is the Macro Expanded?
- --------------------------------------------
- Occasionally problems result from the fact that a macro call is
- expanded each time it is evaluated in an interpreted function, but is
- expanded only once (during compilation) for a compiled function. If the
- macro definition has side effects, they will work differently depending
- on how many times the macro is expanded.
- Therefore, you should avoid side effects in computation of the macro
- expansion, unless you really know what you are doing.
- One special kind of side effect can't be avoided: constructing Lisp
- objects. Almost all macro expansions include constructed lists; that is
- the whole point of most macros. This is usually safe; there is just one
- case where you must be careful: when the object you construct is part
- of a quoted constant in the macro expansion.
- If the macro is expanded just once, in compilation, then the object
- is constructed just once, during compilation. But in interpreted
- execution, the macro is expanded each time the macro call runs, and this
- means a new object is constructed each time.
- In most clean Lisp code, this difference won't matter. It can matter
- only if you perform side-effects on the objects constructed by the macro
- definition. Thus, to avoid trouble, *avoid side effects on objects
- constructed by macro definitions*. Here is an example of how such side
- effects can get you into trouble:
- (defmacro empty-object ()
- (list 'quote (cons nil nil)))
- (defun initialize (condition)
- (let ((object (empty-object)))
- (if condition
- (setcar object condition))
- object))
- If `initialize' is interpreted, a new list `(nil)' is constructed each
- time `initialize' is called. Thus, no side effect survives between
- calls. If `initialize' is compiled, then the macro `empty-object' is
- expanded during compilation, producing a single "constant" `(nil)' that
- is reused and altered each time `initialize' is called.
- One way to avoid pathological cases like this is to think of
- `empty-object' as a funny kind of constant, not as a memory allocation
- construct. You wouldn't use `setcar' on a constant such as `'(nil)',
- so naturally you won't use it on `(empty-object)' either.
- File: elisp, Node: Indenting Macros, Prev: Problems with Macros, Up: Macros
- 13.6 Indenting Macros
- =====================
- Within a macro definition, you can use the `declare' form (*note
- Defining Macros::) to specify how <TAB> should indent calls to the
- macro. An indentation specification is written like this:
- (declare (indent INDENT-SPEC))
- Here are the possibilities for INDENT-SPEC:
- `nil'
- This is the same as no property--use the standard indentation
- pattern.
- `defun'
- Handle this function like a `def' construct: treat the second line
- as the start of a "body".
- an integer, NUMBER
- The first NUMBER arguments of the function are "distinguished"
- arguments; the rest are considered the body of the expression. A
- line in the expression is indented according to whether the first
- argument on it is distinguished or not. If the argument is part
- of the body, the line is indented `lisp-body-indent' more columns
- than the open-parenthesis starting the containing expression. If
- the argument is distinguished and is either the first or second
- argument, it is indented _twice_ that many extra columns. If the
- argument is distinguished and not the first or second argument,
- the line uses the standard pattern.
- a symbol, SYMBOL
- SYMBOL should be a function name; that function is called to
- calculate the indentation of a line within this expression. The
- function receives two arguments:
- STATE
- The value returned by `parse-partial-sexp' (a Lisp primitive
- for indentation and nesting computation) when it parses up to
- the beginning of this line.
- POS
- The position at which the line being indented begins.
- It should return either a number, which is the number of columns of
- indentation for that line, or a list whose car is such a number.
- The difference between returning a number and returning a list is
- that a number says that all following lines at the same nesting
- level should be indented just like this one; a list says that
- following lines might call for different indentations. This makes
- a difference when the indentation is being computed by `C-M-q'; if
- the value is a number, `C-M-q' need not recalculate indentation
- for the following lines until the end of the list.
- File: elisp, Node: Customization, Next: Loading, Prev: Macros, Up: Top
- 14 Customization Settings
- *************************
- This chapter describes how to declare customizable variables and
- customization groups for classifying them. We use the term
- "customization item" to include customizable variables, customization
- groups, as well as faces.
- *Note Defining Faces::, for the `defface' macro, which is used for
- declaring customizable faces.
- * Menu:
- * Common Keywords:: Common keyword arguments for all kinds of
- customization declarations.
- * Group Definitions:: Writing customization group definitions.
- * Variable Definitions:: Declaring user options.
- * Customization Types:: Specifying the type of a user option.
- * Applying Customizations:: Functions to apply customization settings.
- * Custom Themes:: Writing Custom themes.
- File: elisp, Node: Common Keywords, Next: Group Definitions, Up: Customization
- 14.1 Common Item Keywords
- =========================
- The customization declarations that we will describe in the next few
- sections (`defcustom', `defgroup', etc.) all accept keyword arguments
- for specifying various information. This section describes keywords
- that apply to all types of customization declarations.
- All of these keywords, except `:tag', can be used more than once in
- a given item. Each use of the keyword has an independent effect. The
- keyword `:tag' is an exception because any given item can only display
- one name.
- `:tag LABEL'
- Use LABEL, a string, instead of the item's name, to label the item
- in customization menus and buffers. *Don't use a tag which is
- substantially different from the item's real name; that would
- cause confusion.*
- `:group GROUP'
- Put this customization item in group GROUP. When you use `:group'
- in a `defgroup', it makes the new group a subgroup of GROUP.
- If you use this keyword more than once, you can put a single item
- into more than one group. Displaying any of those groups will
- show this item. Please don't overdo this, since the result would
- be annoying.
- `:link LINK-DATA'
- Include an external link after the documentation string for this
- item. This is a sentence containing an active field which
- references some other documentation.
- There are several alternatives you can use for LINK-DATA:
- `(custom-manual INFO-NODE)'
- Link to an Info node; INFO-NODE is a string which specifies
- the node name, as in `"(emacs)Top"'. The link appears as
- `[Manual]' in the customization buffer and enters the built-in
- Info reader on INFO-NODE.
- `(info-link INFO-NODE)'
- Like `custom-manual' except that the link appears in the
- customization buffer with the Info node name.
- `(url-link URL)'
- Link to a web page; URL is a string which specifies the URL.
- The link appears in the customization buffer as URL and
- invokes the WWW browser specified by
- `browse-url-browser-function'.
- `(emacs-commentary-link LIBRARY)'
- Link to the commentary section of a library; LIBRARY is a
- string which specifies the library name.
- `(emacs-library-link LIBRARY)'
- Link to an Emacs Lisp library file; LIBRARY is a string which
- specifies the library name.
- `(file-link FILE)'
- Link to a file; FILE is a string which specifies the name of
- the file to visit with `find-file' when the user invokes this
- link.
- `(function-link FUNCTION)'
- Link to the documentation of a function; FUNCTION is a string
- which specifies the name of the function to describe with
- `describe-function' when the user invokes this link.
- `(variable-link VARIABLE)'
- Link to the documentation of a variable; VARIABLE is a string
- which specifies the name of the variable to describe with
- `describe-variable' when the user invokes this link.
- `(custom-group-link GROUP)'
- Link to another customization group. Invoking it creates a
- new customization buffer for GROUP.
- You can specify the text to use in the customization buffer by
- adding `:tag NAME' after the first element of the LINK-DATA; for
- example, `(info-link :tag "foo" "(emacs)Top")' makes a link to the
- Emacs manual which appears in the buffer as `foo'.
- You can use this keyword more than once, to add multiple links.
- `:load FILE'
- Load file FILE (a string) before displaying this customization
- item (*note Loading::). Loading is done with `load', and only if
- the file is not already loaded.
- `:require FEATURE'
- Execute `(require 'FEATURE)' when your saved customizations set
- the value of this item. FEATURE should be a symbol.
- The most common reason to use `:require' is when a variable enables
- a feature such as a minor mode, and just setting the variable
- won't have any effect unless the code which implements the mode is
- loaded.
- `:version VERSION'
- This keyword specifies that the item was first introduced in Emacs
- version VERSION, or that its default value was changed in that
- version. The value VERSION must be a string.
- `:package-version '(PACKAGE . VERSION)'
- This keyword specifies that the item was first introduced in
- PACKAGE version VERSION, or that its meaning or default value was
- changed in that version. This keyword takes priority over
- `:version'.
- PACKAGE should be the official name of the package, as a symbol
- (e.g. `MH-E'). VERSION should be a string. If the package
- PACKAGE is released as part of Emacs, PACKAGE and VERSION should
- appear in the value of `customize-package-emacs-version-alist'.
- Packages distributed as part of Emacs that use the
- `:package-version' keyword must also update the
- `customize-package-emacs-version-alist' variable.
- -- Variable: customize-package-emacs-version-alist
- This alist provides a mapping for the versions of Emacs that are
- associated with versions of a package listed in the
- `:package-version' keyword. Its elements are:
- (PACKAGE (PVERSION . EVERSION)...)
- For each PACKAGE, which is a symbol, there are one or more
- elements that contain a package version PVERSION with an
- associated Emacs version EVERSION. These versions are strings.
- For example, the MH-E package updates this alist with the
- following:
- (add-to-list 'customize-package-emacs-version-alist
- '(MH-E ("6.0" . "22.1") ("6.1" . "22.1") ("7.0" . "22.1")
- ("7.1" . "22.1") ("7.2" . "22.1") ("7.3" . "22.1")
- ("7.4" . "22.1") ("8.0" . "22.1")))
- The value of PACKAGE needs to be unique and it needs to match the
- PACKAGE value appearing in the `:package-version' keyword. Since
- the user might see the value in an error message, a good choice is
- the official name of the package, such as MH-E or Gnus.
- File: elisp, Node: Group Definitions, Next: Variable Definitions, Prev: Common Keywords, Up: Customization
- 14.2 Defining Customization Groups
- ==================================
- Each Emacs Lisp package should have one main customization group which
- contains all the options, faces and other groups in the package. If the
- package has a small number of options and faces, use just one group and
- put everything in it. When there are more than twelve or so options and
- faces, then you should structure them into subgroups, and put the
- subgroups under the package's main customization group. It is OK to
- put some of the options and faces in the package's main group alongside
- the subgroups.
- The package's main or only group should be a member of one or more of
- the standard customization groups. (To display the full list of them,
- use `M-x customize'.) Choose one or more of them (but not too many),
- and add your group to each of them using the `:group' keyword.
- The way to declare new customization groups is with `defgroup'.
- -- Macro: defgroup group members doc [keyword value]...
- Declare GROUP as a customization group containing MEMBERS. Do not
- quote the symbol GROUP. The argument DOC specifies the
- documentation string for the group.
- The argument MEMBERS is a list specifying an initial set of
- customization items to be members of the group. However, most
- often MEMBERS is `nil', and you specify the group's members by
- using the `:group' keyword when defining those members.
- If you want to specify group members through MEMBERS, each element
- should have the form `(NAME WIDGET)'. Here NAME is a symbol, and
- WIDGET is a widget type for editing that symbol. Useful widgets
- are `custom-variable' for a variable, `custom-face' for a face,
- and `custom-group' for a group.
- When you introduce a new group into Emacs, use the `:version'
- keyword in the `defgroup'; then you need not use it for the
- individual members of the group.
- In addition to the common keywords (*note Common Keywords::), you
- can also use this keyword in `defgroup':
- `:prefix PREFIX'
- If the name of an item in the group starts with PREFIX, and
- the customizable variable `custom-unlispify-remove-prefixes'
- is non-`nil', the item's tag will omit PREFIX. A group can
- have any number of prefixes.
- -- User Option: custom-unlispify-remove-prefixes
- If this variable is non-`nil', the prefixes specified by a group's
- `:prefix' keyword are omitted from tag names, whenever the user
- customizes the group.
- The default value is `nil', i.e. the prefix-discarding feature is
- disabled. This is because discarding prefixes often leads to
- confusing names for options and faces.
- File: elisp, Node: Variable Definitions, Next: Customization Types, Prev: Group Definitions, Up: Customization
- 14.3 Defining Customization Variables
- =====================================
- -- Macro: defcustom option standard doc [keyword value]...
- This macro declares OPTION as a user option (i.e. a customizable
- variable). You should not quote OPTION.
- The argument STANDARD is an expression that specifies the standard
- value for OPTION. Evaluating the `defcustom' form evaluates
- STANDARD, but does not necessarily install the standard value. If
- OPTION already has a default value, `defcustom' does not change
- it. If the user has saved a customization for OPTION, `defcustom'
- installs the user's customized value as OPTION's default value.
- If neither of those cases applies, `defcustom' installs the result
- of evaluating STANDARD as the default value.
- The expression STANDARD can be evaluated at various other times,
- too--whenever the customization facility needs to know OPTION's
- standard value. So be sure to use an expression which is harmless
- to evaluate at any time.
- The argument DOC specifies the documentation string for the
- variable.
- Every `defcustom' should specify `:group' at least once.
- When you evaluate a `defcustom' form with `C-M-x' in Emacs Lisp
- mode (`eval-defun'), a special feature of `eval-defun' arranges to
- set the variable unconditionally, without testing whether its
- value is void. (The same feature applies to `defvar'.) *Note
- Defining Variables::.
- If you put a `defcustom' in a pre-loaded Emacs Lisp file (*note
- Building Emacs::), the standard value installed at dump time might
- be incorrect, e.g. because another variable that it depends on has
- not been assigned the right value yet. In that case, use
- `custom-reevaluate-setting', described below, to re-evaluate the
- standard value after Emacs starts up.
- `defcustom' accepts the following additional keywords:
- `:type TYPE'
- Use TYPE as the data type for this option. It specifies which
- values are legitimate, and how to display the value. *Note
- Customization Types::, for more information.
- `:options VALUE-LIST'
- Specify the list of reasonable values for use in this option. The
- user is not restricted to using only these values, but they are
- offered as convenient alternatives.
- This is meaningful only for certain types, currently including
- `hook', `plist' and `alist'. See the definition of the individual
- types for a description of how to use `:options'.
- `:set SETFUNCTION'
- Specify SETFUNCTION as the way to change the value of this option
- when using the Customize interface. The function SETFUNCTION
- should take two arguments, a symbol (the option name) and the new
- value, and should do whatever is necessary to update the value
- properly for this option (which may not mean simply setting the
- option as a Lisp variable). The default for SETFUNCTION is
- `set-default'.
- If you specify this keyword, the variable's documentation string
- should describe how to do the same job in hand-written Lisp code.
- `:get GETFUNCTION'
- Specify GETFUNCTION as the way to extract the value of this
- option. The function GETFUNCTION should take one argument, a
- symbol, and should return whatever customize should use as the
- "current value" for that symbol (which need not be the symbol's
- Lisp value). The default is `default-value'.
- You have to really understand the workings of Custom to use `:get'
- correctly. It is meant for values that are treated in Custom as
- variables but are not actually stored in Lisp variables. It is
- almost surely a mistake to specify GETFUNCTION for a value that
- really is stored in a Lisp variable.
- `:initialize FUNCTION'
- FUNCTION should be a function used to initialize the variable when
- the `defcustom' is evaluated. It should take two arguments, the
- option name (a symbol) and the value. Here are some predefined
- functions meant for use in this way:
- `custom-initialize-set'
- Use the variable's `:set' function to initialize the
- variable, but do not reinitialize it if it is already
- non-void.
- `custom-initialize-default'
- Like `custom-initialize-set', but use the function
- `set-default' to set the variable, instead of the variable's
- `:set' function. This is the usual choice for a variable
- whose `:set' function enables or disables a minor mode; with
- this choice, defining the variable will not call the minor
- mode function, but customizing the variable will do so.
- `custom-initialize-reset'
- Always use the `:set' function to initialize the variable. If
- the variable is already non-void, reset it by calling the
- `:set' function using the current value (returned by the
- `:get' method). This is the default `:initialize' function.
- `custom-initialize-changed'
- Use the `:set' function to initialize the variable, if it is
- already set or has been customized; otherwise, just use
- `set-default'.
- `custom-initialize-safe-set'
- `custom-initialize-safe-default'
- These functions behave like `custom-initialize-set'
- (`custom-initialize-default', respectively), but catch errors.
- If an error occurs during initialization, they set the
- variable to `nil' using `set-default', and signal no error.
- These functions are meant for options defined in pre-loaded
- files, where the STANDARD expression may signal an error
- because some required variable or function is not yet
- defined. The value normally gets updated in `startup.el',
- ignoring the value computed by `defcustom'. After startup,
- if one unsets the value and reevaluates the `defcustom', the
- STANDARD expression can be evaluated without error.
- `:risky VALUE'
- Set the variable's `risky-local-variable' property to VALUE (*note
- File Local Variables::).
- `:safe FUNCTION'
- Set the variable's `safe-local-variable' property to FUNCTION
- (*note File Local Variables::).
- `:set-after VARIABLES'
- When setting variables according to saved customizations, make
- sure to set the variables VARIABLES before this one; i.e., delay
- setting this variable until after those others have been handled.
- Use `:set-after' if setting this variable won't work properly
- unless those other variables already have their intended values.
- It is useful to specify the `:require' keyword for an option that
- "turns on" a certain feature. This causes Emacs to load the feature,
- if it is not already loaded, whenever the option is set. *Note Common
- Keywords::. Here is an example, from the library `saveplace.el':
- (defcustom save-place nil
- "Non-nil means automatically save place in each file..."
- :type 'boolean
- :require 'saveplace
- :group 'save-place)
- If a customization item has a type such as `hook' or `alist', which
- supports `:options', you can add additional values to the list from
- outside the `defcustom' declaration by calling
- `custom-add-frequent-value'. For example, if you define a function
- `my-lisp-mode-initialization' intended to be called from
- `emacs-lisp-mode-hook', you might want to add that to the list of
- reasonable values for `emacs-lisp-mode-hook', but not by editing its
- definition. You can do it thus:
- (custom-add-frequent-value 'emacs-lisp-mode-hook
- 'my-lisp-mode-initialization)
- -- Function: custom-add-frequent-value symbol value
- For the customization option SYMBOL, add VALUE to the list of
- reasonable values.
- The precise effect of adding a value depends on the customization
- type of SYMBOL.
- Internally, `defcustom' uses the symbol property `standard-value' to
- record the expression for the standard value, `saved-value' to record
- the value saved by the user with the customization buffer, and
- `customized-value' to record the value set by the user with the
- customization buffer, but not saved. *Note Property Lists::. These
- properties are lists, the car of which is an expression that evaluates
- to the value.
- -- Function: custom-reevaluate-setting symbol
- This function re-evaluates the standard value of SYMBOL, which
- should be a user option declared via `defcustom'. If the variable
- was customized, this function re-evaluates the saved value
- instead. Then it sets the user option to that value (using the
- option's `:set' property if that is defined).
- This is useful for customizable options that are defined before
- their value could be computed correctly. For example, during
- startup Emacs calls this function for some user options that were
- defined in pre-loaded Emacs Lisp files, but whose initial values
- depend on information available only at run-time.
- -- Function: custom-variable-p arg
- This function returns non-`nil' if ARG is a customizable variable.
- A customizable variable is either a variable that has a
- `standard-value' or `custom-autoload' property (usually meaning it
- was declared with `defcustom'), or an alias for another
- customizable variable.
- -- Function: user-variable-p arg
- This function is like `custom-variable-p', except it also returns
- `t' if the first character of the variable's documentation string
- is the character `*'. That is an obsolete way of indicating a
- user option, so for most purposes you may consider
- `user-variable-p' as equivalent to `custom-variable-p'.
- File: elisp, Node: Customization Types, Next: Applying Customizations, Prev: Variable Definitions, Up: Customization
- 14.4 Customization Types
- ========================
- When you define a user option with `defcustom', you must specify its
- "customization type". That is a Lisp object which describes (1) which
- values are legitimate and (2) how to display the value in the
- customization buffer for editing.
- You specify the customization type in `defcustom' with the `:type'
- keyword. The argument of `:type' is evaluated, but only once when the
- `defcustom' is executed, so it isn't useful for the value to vary.
- Normally we use a quoted constant. For example:
- (defcustom diff-command "diff"
- "The command to use to run diff."
- :type '(string)
- :group 'diff)
- In general, a customization type is a list whose first element is a
- symbol, one of the customization type names defined in the following
- sections. After this symbol come a number of arguments, depending on
- the symbol. Between the type symbol and its arguments, you can
- optionally write keyword-value pairs (*note Type Keywords::).
- Some type symbols do not use any arguments; those are called "simple
- types". For a simple type, if you do not use any keyword-value pairs,
- you can omit the parentheses around the type symbol. For example just
- `string' as a customization type is equivalent to `(string)'.
- All customization types are implemented as widgets; see *note
- Introduction: (widget)Top, for details.
- * Menu:
- * Simple Types:: Simple customization types: sexp, integer, etc.
- * Composite Types:: Build new types from other types or data.
- * Splicing into Lists:: Splice elements into list with `:inline'.
- * Type Keywords:: Keyword-argument pairs in a customization type.
- * Defining New Types:: Give your type a name.
- Local Variables:
- coding: iso-8859-1
- End:
|