ox.el 260 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729
  1. ;;; ox.el --- Export Framework for Org Mode -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2012-2016 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;;
  18. ;; This library implements a generic export engine for Org, built on
  19. ;; its syntactical parser: Org Elements.
  20. ;;
  21. ;; Besides that parser, the generic exporter is made of three distinct
  22. ;; parts:
  23. ;;
  24. ;; - The communication channel consists of a property list, which is
  25. ;; created and updated during the process. Its use is to offer
  26. ;; every piece of information, would it be about initial environment
  27. ;; or contextual data, all in a single place.
  28. ;;
  29. ;; - The transcoder walks the parse tree, ignores or treat as plain
  30. ;; text elements and objects according to export options, and
  31. ;; eventually calls back-end specific functions to do the real
  32. ;; transcoding, concatenating their return value along the way.
  33. ;;
  34. ;; - The filter system is activated at the very beginning and the very
  35. ;; end of the export process, and each time an element or an object
  36. ;; has been converted. It is the entry point to fine-tune standard
  37. ;; output from back-end transcoders. See "The Filter System"
  38. ;; section for more information.
  39. ;;
  40. ;; The core functions is `org-export-as'. It returns the transcoded
  41. ;; buffer as a string. Its derivatives are `org-export-to-buffer' and
  42. ;; `org-export-to-file'.
  43. ;;
  44. ;; An export back-end is defined with `org-export-define-backend'.
  45. ;; This function can also support specific buffer keywords, OPTION
  46. ;; keyword's items and filters. Refer to function's documentation for
  47. ;; more information.
  48. ;;
  49. ;; If the new back-end shares most properties with another one,
  50. ;; `org-export-define-derived-backend' can be used to simplify the
  51. ;; process.
  52. ;;
  53. ;; Any back-end can define its own variables. Among them, those
  54. ;; customizable should belong to the `org-export-BACKEND' group.
  55. ;;
  56. ;; Tools for common tasks across back-ends are implemented in the
  57. ;; following part of the file.
  58. ;;
  59. ;; Eventually, a dispatcher (`org-export-dispatch') is provided in the
  60. ;; last one.
  61. ;;
  62. ;; See <http://orgmode.org/worg/dev/org-export-reference.html> for
  63. ;; more information.
  64. ;;; Code:
  65. (require 'cl-lib)
  66. (require 'ob-exp)
  67. (require 'org-element)
  68. (require 'org-macro)
  69. (require 'tabulated-list)
  70. (declare-function org-publish "ox-publish" (project &optional force async))
  71. (declare-function org-publish-all "ox-publish" (&optional force async))
  72. (declare-function org-publish-current-file "ox-publish" (&optional force async))
  73. (declare-function org-publish-current-project "ox-publish" (&optional force async))
  74. (declare-function org-src-coderef-format "org-src" (&optional element))
  75. (declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
  76. (defvar org-publish-project-alist)
  77. (defvar org-table-number-fraction)
  78. (defvar org-table-number-regexp)
  79. ;;; Internal Variables
  80. ;;
  81. ;; Among internal variables, the most important is
  82. ;; `org-export-options-alist'. This variable define the global export
  83. ;; options, shared between every exporter, and how they are acquired.
  84. (defconst org-export-max-depth 19
  85. "Maximum nesting depth for headlines, counting from 0.")
  86. (defconst org-export-options-alist
  87. '((:title "TITLE" nil nil parse)
  88. (:date "DATE" nil nil parse)
  89. (:author "AUTHOR" nil user-full-name parse)
  90. (:email "EMAIL" nil user-mail-address t)
  91. (:language "LANGUAGE" nil org-export-default-language t)
  92. (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
  93. (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
  94. (:creator "CREATOR" nil org-export-creator-string)
  95. (:headline-levels nil "H" org-export-headline-levels)
  96. (:preserve-breaks nil "\\n" org-export-preserve-breaks)
  97. (:section-numbers nil "num" org-export-with-section-numbers)
  98. (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
  99. (:with-archived-trees nil "arch" org-export-with-archived-trees)
  100. (:with-author nil "author" org-export-with-author)
  101. (:with-broken-links nil "broken-links" org-export-with-broken-links)
  102. (:with-clocks nil "c" org-export-with-clocks)
  103. (:with-creator nil "creator" org-export-with-creator)
  104. (:with-date nil "date" org-export-with-date)
  105. (:with-drawers nil "d" org-export-with-drawers)
  106. (:with-email nil "email" org-export-with-email)
  107. (:with-emphasize nil "*" org-export-with-emphasize)
  108. (:with-entities nil "e" org-export-with-entities)
  109. (:with-fixed-width nil ":" org-export-with-fixed-width)
  110. (:with-footnotes nil "f" org-export-with-footnotes)
  111. (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
  112. (:with-latex nil "tex" org-export-with-latex)
  113. (:with-planning nil "p" org-export-with-planning)
  114. (:with-priority nil "pri" org-export-with-priority)
  115. (:with-properties nil "prop" org-export-with-properties)
  116. (:with-smart-quotes nil "'" org-export-with-smart-quotes)
  117. (:with-special-strings nil "-" org-export-with-special-strings)
  118. (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
  119. (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
  120. (:with-toc nil "toc" org-export-with-toc)
  121. (:with-tables nil "|" org-export-with-tables)
  122. (:with-tags nil "tags" org-export-with-tags)
  123. (:with-tasks nil "tasks" org-export-with-tasks)
  124. (:with-timestamps nil "<" org-export-with-timestamps)
  125. (:with-title nil "title" org-export-with-title)
  126. (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
  127. "Alist between export properties and ways to set them.
  128. The key of the alist is the property name, and the value is a list
  129. like (KEYWORD OPTION DEFAULT BEHAVIOR) where:
  130. KEYWORD is a string representing a buffer keyword, or nil. Each
  131. property defined this way can also be set, during subtree
  132. export, through a headline property named after the keyword
  133. with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
  134. property).
  135. OPTION is a string that could be found in an #+OPTIONS: line.
  136. DEFAULT is the default value for the property.
  137. BEHAVIOR determines how Org should handle multiple keywords for
  138. the same property. It is a symbol among:
  139. nil Keep old value and discard the new one.
  140. t Replace old value with the new one.
  141. `space' Concatenate the values, separating them with a space.
  142. `newline' Concatenate the values, separating them with
  143. a newline.
  144. `split' Split values at white spaces, and cons them to the
  145. previous list.
  146. `parse' Parse value as a list of strings and Org objects,
  147. which can then be transcoded with, e.g.,
  148. `org-export-data'. It implies `space' behavior.
  149. Values set through KEYWORD and OPTION have precedence over
  150. DEFAULT.
  151. All these properties should be back-end agnostic. Back-end
  152. specific properties are set through `org-export-define-backend'.
  153. Properties redefined there have precedence over these.")
  154. (defconst org-export-special-keywords '("FILETAGS" "SETUPFILE" "OPTIONS")
  155. "List of in-buffer keywords that require special treatment.
  156. These keywords are not directly associated to a property. The
  157. way they are handled must be hard-coded into
  158. `org-export--get-inbuffer-options' function.")
  159. (defconst org-export-filters-alist
  160. '((:filter-body . org-export-filter-body-functions)
  161. (:filter-bold . org-export-filter-bold-functions)
  162. (:filter-babel-call . org-export-filter-babel-call-functions)
  163. (:filter-center-block . org-export-filter-center-block-functions)
  164. (:filter-clock . org-export-filter-clock-functions)
  165. (:filter-code . org-export-filter-code-functions)
  166. (:filter-diary-sexp . org-export-filter-diary-sexp-functions)
  167. (:filter-drawer . org-export-filter-drawer-functions)
  168. (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
  169. (:filter-entity . org-export-filter-entity-functions)
  170. (:filter-example-block . org-export-filter-example-block-functions)
  171. (:filter-export-block . org-export-filter-export-block-functions)
  172. (:filter-export-snippet . org-export-filter-export-snippet-functions)
  173. (:filter-final-output . org-export-filter-final-output-functions)
  174. (:filter-fixed-width . org-export-filter-fixed-width-functions)
  175. (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
  176. (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
  177. (:filter-headline . org-export-filter-headline-functions)
  178. (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
  179. (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
  180. (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
  181. (:filter-inlinetask . org-export-filter-inlinetask-functions)
  182. (:filter-italic . org-export-filter-italic-functions)
  183. (:filter-item . org-export-filter-item-functions)
  184. (:filter-keyword . org-export-filter-keyword-functions)
  185. (:filter-latex-environment . org-export-filter-latex-environment-functions)
  186. (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
  187. (:filter-line-break . org-export-filter-line-break-functions)
  188. (:filter-link . org-export-filter-link-functions)
  189. (:filter-node-property . org-export-filter-node-property-functions)
  190. (:filter-options . org-export-filter-options-functions)
  191. (:filter-paragraph . org-export-filter-paragraph-functions)
  192. (:filter-parse-tree . org-export-filter-parse-tree-functions)
  193. (:filter-plain-list . org-export-filter-plain-list-functions)
  194. (:filter-plain-text . org-export-filter-plain-text-functions)
  195. (:filter-planning . org-export-filter-planning-functions)
  196. (:filter-property-drawer . org-export-filter-property-drawer-functions)
  197. (:filter-quote-block . org-export-filter-quote-block-functions)
  198. (:filter-radio-target . org-export-filter-radio-target-functions)
  199. (:filter-section . org-export-filter-section-functions)
  200. (:filter-special-block . org-export-filter-special-block-functions)
  201. (:filter-src-block . org-export-filter-src-block-functions)
  202. (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
  203. (:filter-strike-through . org-export-filter-strike-through-functions)
  204. (:filter-subscript . org-export-filter-subscript-functions)
  205. (:filter-superscript . org-export-filter-superscript-functions)
  206. (:filter-table . org-export-filter-table-functions)
  207. (:filter-table-cell . org-export-filter-table-cell-functions)
  208. (:filter-table-row . org-export-filter-table-row-functions)
  209. (:filter-target . org-export-filter-target-functions)
  210. (:filter-timestamp . org-export-filter-timestamp-functions)
  211. (:filter-underline . org-export-filter-underline-functions)
  212. (:filter-verbatim . org-export-filter-verbatim-functions)
  213. (:filter-verse-block . org-export-filter-verse-block-functions))
  214. "Alist between filters properties and initial values.
  215. The key of each association is a property name accessible through
  216. the communication channel. Its value is a configurable global
  217. variable defining initial filters.
  218. This list is meant to install user specified filters. Back-end
  219. developers may install their own filters using
  220. `org-export-define-backend'. Filters defined there will always
  221. be prepended to the current list, so they always get applied
  222. first.")
  223. (defconst org-export-default-inline-image-rule
  224. `(("file" .
  225. ,(format "\\.%s\\'"
  226. (regexp-opt
  227. '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
  228. "xpm" "pbm" "pgm" "ppm") t))))
  229. "Default rule for link matching an inline image.
  230. This rule applies to links with no description. By default, it
  231. will be considered as an inline image if it targets a local file
  232. whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
  233. \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
  234. See `org-export-inline-image-p' for more information about
  235. rules.")
  236. (defconst org-export-ignored-local-variables
  237. '(org-font-lock-keywords
  238. org-element--cache org-element--cache-objects org-element--cache-sync-keys
  239. org-element--cache-sync-requests org-element--cache-sync-timer)
  240. "List of variables not copied through upon buffer duplication.
  241. Export process takes place on a copy of the original buffer.
  242. When this copy is created, all Org related local variables not in
  243. this list are copied to the new buffer. Variables with an
  244. unreadable value are also ignored.")
  245. (defvar org-export-async-debug nil
  246. "Non-nil means asynchronous export process should leave data behind.
  247. This data is found in the appropriate \"*Org Export Process*\"
  248. buffer, and in files prefixed with \"org-export-process\" and
  249. located in `temporary-file-directory'.
  250. When non-nil, it will also set `debug-on-error' to a non-nil
  251. value in the external process.")
  252. (defvar org-export-stack-contents nil
  253. "Record asynchronously generated export results and processes.
  254. This is an alist: its CAR is the source of the
  255. result (destination file or buffer for a finished process,
  256. original buffer for a running one) and its CDR is a list
  257. containing the back-end used, as a symbol, and either a process
  258. or the time at which it finished. It is used to build the menu
  259. from `org-export-stack'.")
  260. (defvar org-export-registered-backends nil
  261. "List of backends currently available in the exporter.
  262. This variable is set with `org-export-define-backend' and
  263. `org-export-define-derived-backend' functions.")
  264. (defvar org-export-dispatch-last-action nil
  265. "Last command called from the dispatcher.
  266. The value should be a list. Its CAR is the action, as a symbol,
  267. and its CDR is a list of export options.")
  268. (defvar org-export-dispatch-last-position (make-marker)
  269. "The position where the last export command was created using the dispatcher.
  270. This marker will be used with `C-u C-c C-e' to make sure export repetition
  271. uses the same subtree if the previous command was restricted to a subtree.")
  272. ;; For compatibility with Org < 8
  273. (defvar org-export-current-backend nil
  274. "Name, if any, of the back-end used during an export process.
  275. Its value is a symbol such as `html', `latex', `ascii', or nil if
  276. the back-end is anonymous (see `org-export-create-backend') or if
  277. there is no export process in progress.
  278. It can be used to teach Babel blocks how to act differently
  279. according to the back-end used.")
  280. ;;; User-configurable Variables
  281. ;;
  282. ;; Configuration for the masses.
  283. ;;
  284. ;; They should never be accessed directly, as their value is to be
  285. ;; stored in a property list (cf. `org-export-options-alist').
  286. ;; Back-ends will read their value from there instead.
  287. (defgroup org-export nil
  288. "Options for exporting Org mode files."
  289. :tag "Org Export"
  290. :group 'org)
  291. (defgroup org-export-general nil
  292. "General options for export engine."
  293. :tag "Org Export General"
  294. :group 'org-export)
  295. (defcustom org-export-with-archived-trees 'headline
  296. "Whether sub-trees with the ARCHIVE tag should be exported.
  297. This can have three different values:
  298. nil Do not export, pretend this tree is not present.
  299. t Do export the entire tree.
  300. `headline' Only export the headline, but skip the tree below it.
  301. This option can also be set with the OPTIONS keyword,
  302. e.g. \"arch:nil\"."
  303. :group 'org-export-general
  304. :type '(choice
  305. (const :tag "Not at all" nil)
  306. (const :tag "Headline only" headline)
  307. (const :tag "Entirely" t))
  308. :safe (lambda (x) (memq x '(t nil headline))))
  309. (defcustom org-export-with-author t
  310. "Non-nil means insert author name into the exported file.
  311. This option can also be set with the OPTIONS keyword,
  312. e.g. \"author:nil\"."
  313. :group 'org-export-general
  314. :type 'boolean
  315. :safe #'booleanp)
  316. (defcustom org-export-with-clocks nil
  317. "Non-nil means export CLOCK keywords.
  318. This option can also be set with the OPTIONS keyword,
  319. e.g. \"c:t\"."
  320. :group 'org-export-general
  321. :type 'boolean
  322. :safe #'booleanp)
  323. (defcustom org-export-with-creator nil
  324. "Non-nil means the postamble should contain a creator sentence.
  325. The sentence can be set in `org-export-creator-string', which
  326. see.
  327. This option can also be set with the OPTIONS keyword, e.g.,
  328. \"creator:t\"."
  329. :group 'org-export-general
  330. :version "25.2"
  331. :package-version '(Org . "8.3")
  332. :type 'boolean
  333. :safe #'booleanp)
  334. (defcustom org-export-with-date t
  335. "Non-nil means insert date in the exported document.
  336. This option can also be set with the OPTIONS keyword,
  337. e.g. \"date:nil\"."
  338. :group 'org-export-general
  339. :type 'boolean
  340. :safe #'booleanp)
  341. (defcustom org-export-date-timestamp-format nil
  342. "Time-stamp format string to use for DATE keyword.
  343. The format string, when specified, only applies if date consists
  344. in a single time-stamp. Otherwise its value will be ignored.
  345. See `format-time-string' for details on how to build this
  346. string."
  347. :group 'org-export-general
  348. :type '(choice
  349. (string :tag "Time-stamp format string")
  350. (const :tag "No format string" nil))
  351. :safe (lambda (x) (or (null x) (stringp x))))
  352. (defcustom org-export-creator-string
  353. (format "Emacs %s (Org mode %s)"
  354. emacs-version
  355. (if (fboundp 'org-version) (org-version) "unknown version"))
  356. "Information about the creator of the document.
  357. This option can also be set on with the CREATOR keyword."
  358. :group 'org-export-general
  359. :type '(string :tag "Creator string")
  360. :safe #'stringp)
  361. (defcustom org-export-with-drawers '(not "LOGBOOK")
  362. "Non-nil means export contents of standard drawers.
  363. When t, all drawers are exported. This may also be a list of
  364. drawer names to export, as strings. If that list starts with
  365. `not', only drawers with such names will be ignored.
  366. This variable doesn't apply to properties drawers. See
  367. `org-export-with-properties' instead.
  368. This option can also be set with the OPTIONS keyword,
  369. e.g. \"d:nil\"."
  370. :group 'org-export-general
  371. :version "24.4"
  372. :package-version '(Org . "8.0")
  373. :type '(choice
  374. (const :tag "All drawers" t)
  375. (const :tag "None" nil)
  376. (repeat :tag "Selected drawers"
  377. (string :tag "Drawer name"))
  378. (list :tag "Ignored drawers"
  379. (const :format "" not)
  380. (repeat :tag "Specify names of drawers to ignore during export"
  381. :inline t
  382. (string :tag "Drawer name"))))
  383. :safe (lambda (x) (or (booleanp x)
  384. (and (listp x)
  385. (or (cl-every #'stringp x)
  386. (and (eq (nth 0 x) 'not)
  387. (cl-every #'stringp (cdr x))))))))
  388. (defcustom org-export-with-email nil
  389. "Non-nil means insert author email into the exported file.
  390. This option can also be set with the OPTIONS keyword,
  391. e.g. \"email:t\"."
  392. :group 'org-export-general
  393. :type 'boolean
  394. :safe #'booleanp)
  395. (defcustom org-export-with-emphasize t
  396. "Non-nil means interpret *word*, /word/, _word_ and +word+.
  397. If the export target supports emphasizing text, the word will be
  398. typeset in bold, italic, with an underline or strike-through,
  399. respectively.
  400. This option can also be set with the OPTIONS keyword,
  401. e.g. \"*:nil\"."
  402. :group 'org-export-general
  403. :type 'boolean
  404. :safe #'booleanp)
  405. (defcustom org-export-exclude-tags '("noexport")
  406. "Tags that exclude a tree from export.
  407. All trees carrying any of these tags will be excluded from
  408. export. This is without condition, so even subtrees inside that
  409. carry one of the `org-export-select-tags' will be removed.
  410. This option can also be set with the EXCLUDE_TAGS keyword."
  411. :group 'org-export-general
  412. :type '(repeat (string :tag "Tag"))
  413. :safe (lambda (x) (and (listp x) (cl-every #'stringp x))))
  414. (defcustom org-export-with-fixed-width t
  415. "Non-nil means export lines starting with \":\".
  416. This option can also be set with the OPTIONS keyword,
  417. e.g. \"::nil\"."
  418. :group 'org-export-general
  419. :version "24.4"
  420. :package-version '(Org . "8.0")
  421. :type 'boolean
  422. :safe #'booleanp)
  423. (defcustom org-export-with-footnotes t
  424. "Non-nil means Org footnotes should be exported.
  425. This option can also be set with the OPTIONS keyword,
  426. e.g. \"f:nil\"."
  427. :group 'org-export-general
  428. :type 'boolean
  429. :safe #'booleanp)
  430. (defcustom org-export-with-latex t
  431. "Non-nil means process LaTeX environments and fragments.
  432. This option can also be set with the OPTIONS line,
  433. e.g. \"tex:verbatim\". Allowed values are:
  434. nil Ignore math snippets.
  435. `verbatim' Keep everything in verbatim.
  436. t Allow export of math snippets."
  437. :group 'org-export-general
  438. :version "24.4"
  439. :package-version '(Org . "8.0")
  440. :type '(choice
  441. (const :tag "Do not process math in any way" nil)
  442. (const :tag "Interpret math snippets" t)
  443. (const :tag "Leave math verbatim" verbatim))
  444. :safe (lambda (x) (memq x '(t nil verbatim))))
  445. (defcustom org-export-headline-levels 3
  446. "The last level which is still exported as a headline.
  447. Inferior levels will usually produce itemize or enumerate lists
  448. when exported, but back-end behavior may differ.
  449. This option can also be set with the OPTIONS keyword,
  450. e.g. \"H:2\"."
  451. :group 'org-export-general
  452. :type 'integer
  453. :safe #'integerp)
  454. (defcustom org-export-default-language "en"
  455. "The default language for export and clocktable translations, as a string.
  456. This may have an association in
  457. `org-clock-clocktable-language-setup',
  458. `org-export-smart-quotes-alist' and `org-export-dictionary'.
  459. This option can also be set with the LANGUAGE keyword."
  460. :group 'org-export-general
  461. :type '(string :tag "Language")
  462. :safe #'stringp)
  463. (defcustom org-export-preserve-breaks nil
  464. "Non-nil means preserve all line breaks when exporting.
  465. This option can also be set with the OPTIONS keyword,
  466. e.g. \"\\n:t\"."
  467. :group 'org-export-general
  468. :type 'boolean
  469. :safe #'booleanp)
  470. (defcustom org-export-with-entities t
  471. "Non-nil means interpret entities when exporting.
  472. For example, HTML export converts \\alpha to &alpha; and \\AA to
  473. &Aring;.
  474. For a list of supported names, see the constant `org-entities'
  475. and the user option `org-entities-user'.
  476. This option can also be set with the OPTIONS keyword,
  477. e.g. \"e:nil\"."
  478. :group 'org-export-general
  479. :type 'boolean
  480. :safe #'booleanp)
  481. (defcustom org-export-with-inlinetasks t
  482. "Non-nil means inlinetasks should be exported.
  483. This option can also be set with the OPTIONS keyword,
  484. e.g. \"inline:nil\"."
  485. :group 'org-export-general
  486. :version "24.4"
  487. :package-version '(Org . "8.0")
  488. :type 'boolean
  489. :safe #'booleanp)
  490. (defcustom org-export-with-planning nil
  491. "Non-nil means include planning info in export.
  492. Planning info is the line containing either SCHEDULED:,
  493. DEADLINE:, CLOSED: time-stamps, or a combination of them.
  494. This option can also be set with the OPTIONS keyword,
  495. e.g. \"p:t\"."
  496. :group 'org-export-general
  497. :version "24.4"
  498. :package-version '(Org . "8.0")
  499. :type 'boolean
  500. :safe #'booleanp)
  501. (defcustom org-export-with-priority nil
  502. "Non-nil means include priority cookies in export.
  503. This option can also be set with the OPTIONS keyword,
  504. e.g. \"pri:t\"."
  505. :group 'org-export-general
  506. :type 'boolean
  507. :safe #'booleanp)
  508. (defcustom org-export-with-properties nil
  509. "Non-nil means export contents of properties drawers.
  510. When t, all properties are exported. This may also be a list of
  511. properties to export, as strings.
  512. This option can also be set with the OPTIONS keyword,
  513. e.g. \"prop:t\"."
  514. :group 'org-export-general
  515. :version "24.4"
  516. :package-version '(Org . "8.3")
  517. :type '(choice
  518. (const :tag "All properties" t)
  519. (const :tag "None" nil)
  520. (repeat :tag "Selected properties"
  521. (string :tag "Property name")))
  522. :safe (lambda (x) (or (booleanp x)
  523. (and (listp x) (cl-every #'stringp x)))))
  524. (defcustom org-export-with-section-numbers t
  525. "Non-nil means add section numbers to headlines when exporting.
  526. When set to an integer n, numbering will only happen for
  527. headlines whose relative level is higher or equal to n.
  528. This option can also be set with the OPTIONS keyword,
  529. e.g. \"num:t\"."
  530. :group 'org-export-general
  531. :type 'boolean
  532. :safe #'booleanp)
  533. (defcustom org-export-select-tags '("export")
  534. "Tags that select a tree for export.
  535. If any such tag is found in a buffer, all trees that do not carry
  536. one of these tags will be ignored during export. Inside trees
  537. that are selected like this, you can still deselect a subtree by
  538. tagging it with one of the `org-export-exclude-tags'.
  539. This option can also be set with the SELECT_TAGS keyword."
  540. :group 'org-export-general
  541. :type '(repeat (string :tag "Tag"))
  542. :safe (lambda (x) (and (listp x) (cl-every #'stringp x))))
  543. (defcustom org-export-with-smart-quotes nil
  544. "Non-nil means activate smart quotes during export.
  545. This option can also be set with the OPTIONS keyword,
  546. e.g., \"':t\".
  547. When setting this to non-nil, you need to take care of
  548. using the correct Babel package when exporting to LaTeX.
  549. E.g., you can load Babel for french like this:
  550. #+LATEX_HEADER: \\usepackage[french]{babel}"
  551. :group 'org-export-general
  552. :version "24.4"
  553. :package-version '(Org . "8.0")
  554. :type 'boolean
  555. :safe #'booleanp)
  556. (defcustom org-export-with-special-strings t
  557. "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
  558. When this option is turned on, these strings will be exported as:
  559. Org HTML LaTeX UTF-8
  560. -----+----------+--------+-------
  561. \\- &shy; \\-
  562. -- &ndash; -- –
  563. --- &mdash; --- —
  564. ... &hellip; \\ldots …
  565. This option can also be set with the OPTIONS keyword,
  566. e.g. \"-:nil\"."
  567. :group 'org-export-general
  568. :type 'boolean
  569. :safe #'booleanp)
  570. (defcustom org-export-with-statistics-cookies t
  571. "Non-nil means include statistics cookies in export.
  572. This option can also be set with the OPTIONS keyword,
  573. e.g. \"stat:nil\""
  574. :group 'org-export-general
  575. :version "24.4"
  576. :package-version '(Org . "8.0")
  577. :type 'boolean
  578. :safe #'booleanp)
  579. (defcustom org-export-with-sub-superscripts t
  580. "Non-nil means interpret \"_\" and \"^\" for export.
  581. If you want to control how Org displays those characters, see
  582. `org-use-sub-superscripts'. `org-export-with-sub-superscripts'
  583. used to be an alias for `org-use-sub-superscripts' in Org <8.0,
  584. it is not anymore.
  585. When this option is turned on, you can use TeX-like syntax for
  586. sub- and superscripts and see them exported correctly.
  587. You can also set the option with #+OPTIONS: ^:t
  588. Several characters after \"_\" or \"^\" will be considered as a
  589. single item - so grouping with {} is normally not needed. For
  590. example, the following things will be parsed as single sub- or
  591. superscripts:
  592. 10^24 or 10^tau several digits will be considered 1 item.
  593. 10^-12 or 10^-tau a leading sign with digits or a word
  594. x^2-y^3 will be read as x^2 - y^3, because items are
  595. terminated by almost any nonword/nondigit char.
  596. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  597. Still, ambiguity is possible. So when in doubt, use {} to enclose
  598. the sub/superscript. If you set this variable to the symbol `{}',
  599. the braces are *required* in order to trigger interpretations as
  600. sub/superscript. This can be helpful in documents that need \"_\"
  601. frequently in plain text."
  602. :group 'org-export-general
  603. :version "24.4"
  604. :package-version '(Org . "8.0")
  605. :type '(choice
  606. (const :tag "Interpret them" t)
  607. (const :tag "Curly brackets only" {})
  608. (const :tag "Do not interpret them" nil))
  609. :safe (lambda (x) (memq x '(t nil {}))))
  610. (defcustom org-export-with-toc t
  611. "Non-nil means create a table of contents in exported files.
  612. The TOC contains headlines with levels up
  613. to`org-export-headline-levels'. When an integer, include levels
  614. up to N in the toc, this may then be different from
  615. `org-export-headline-levels', but it will not be allowed to be
  616. larger than the number of headline levels. When nil, no table of
  617. contents is made.
  618. This option can also be set with the OPTIONS keyword,
  619. e.g. \"toc:nil\" or \"toc:3\"."
  620. :group 'org-export-general
  621. :type '(choice
  622. (const :tag "No Table of Contents" nil)
  623. (const :tag "Full Table of Contents" t)
  624. (integer :tag "TOC to level"))
  625. :safe (lambda (x) (or (booleanp x)
  626. (integerp x))))
  627. (defcustom org-export-with-tables t
  628. "Non-nil means export tables.
  629. This option can also be set with the OPTIONS keyword,
  630. e.g. \"|:nil\"."
  631. :group 'org-export-general
  632. :version "24.4"
  633. :package-version '(Org . "8.0")
  634. :type 'boolean
  635. :safe #'booleanp)
  636. (defcustom org-export-with-tags t
  637. "If nil, do not export tags, just remove them from headlines.
  638. If this is the symbol `not-in-toc', tags will be removed from
  639. table of contents entries, but still be shown in the headlines of
  640. the document.
  641. This option can also be set with the OPTIONS keyword,
  642. e.g. \"tags:nil\"."
  643. :group 'org-export-general
  644. :type '(choice
  645. (const :tag "Off" nil)
  646. (const :tag "Not in TOC" not-in-toc)
  647. (const :tag "On" t))
  648. :safe (lambda (x) (memq x '(t nil not-in-toc))))
  649. (defcustom org-export-with-tasks t
  650. "Non-nil means include TODO items for export.
  651. This may have the following values:
  652. t include tasks independent of state.
  653. `todo' include only tasks that are not yet done.
  654. `done' include only tasks that are already done.
  655. nil ignore all tasks.
  656. list of keywords include tasks with these keywords.
  657. This option can also be set with the OPTIONS keyword,
  658. e.g. \"tasks:nil\"."
  659. :group 'org-export-general
  660. :type '(choice
  661. (const :tag "All tasks" t)
  662. (const :tag "No tasks" nil)
  663. (const :tag "Not-done tasks" todo)
  664. (const :tag "Only done tasks" done)
  665. (repeat :tag "Specific TODO keywords"
  666. (string :tag "Keyword")))
  667. :safe (lambda (x) (or (memq x '(nil t todo done))
  668. (and (listp x)
  669. (cl-every #'stringp x)))))
  670. (defcustom org-export-with-title t
  671. "Non-nil means print title into the exported file.
  672. This option can also be set with the OPTIONS keyword,
  673. e.g. \"title:nil\"."
  674. :group 'org-export-general
  675. :version "25.2"
  676. :package-version '(Org . "8.3")
  677. :type 'boolean
  678. :safe #'booleanp)
  679. (defcustom org-export-time-stamp-file t
  680. "Non-nil means insert a time stamp into the exported file.
  681. The time stamp shows when the file was created. This option can
  682. also be set with the OPTIONS keyword, e.g. \"timestamp:nil\"."
  683. :group 'org-export-general
  684. :type 'boolean
  685. :safe #'booleanp)
  686. (defcustom org-export-with-timestamps t
  687. "Non nil means allow timestamps in export.
  688. It can be set to any of the following values:
  689. t export all timestamps.
  690. `active' export active timestamps only.
  691. `inactive' export inactive timestamps only.
  692. nil do not export timestamps
  693. This only applies to timestamps isolated in a paragraph
  694. containing only timestamps. Other timestamps are always
  695. exported.
  696. This option can also be set with the OPTIONS keyword, e.g.
  697. \"<:nil\"."
  698. :group 'org-export-general
  699. :type '(choice
  700. (const :tag "All timestamps" t)
  701. (const :tag "Only active timestamps" active)
  702. (const :tag "Only inactive timestamps" inactive)
  703. (const :tag "No timestamp" nil))
  704. :safe (lambda (x) (memq x '(t nil active inactive))))
  705. (defcustom org-export-with-todo-keywords t
  706. "Non-nil means include TODO keywords in export.
  707. When nil, remove all these keywords from the export. This option
  708. can also be set with the OPTIONS keyword, e.g. \"todo:nil\"."
  709. :group 'org-export-general
  710. :type 'boolean)
  711. (defcustom org-export-allow-bind-keywords nil
  712. "Non-nil means BIND keywords can define local variable values.
  713. This is a potential security risk, which is why the default value
  714. is nil. You can also allow them through local buffer variables."
  715. :group 'org-export-general
  716. :version "24.4"
  717. :package-version '(Org . "8.0")
  718. :type 'boolean)
  719. (defcustom org-export-with-broken-links nil
  720. "Non-nil means do not raise an error on broken links.
  721. When this variable is non-nil, broken links are ignored, without
  722. stopping the export process. If it is set to `mark', broken
  723. links are marked as such in the output, with a string like
  724. [BROKEN LINK: path]
  725. where PATH is the un-resolvable reference.
  726. This option can also be set with the OPTIONS keyword, e.g.,
  727. \"broken-links:mark\"."
  728. :group 'org-export-general
  729. :version "25.2"
  730. :package-version '(Org . "9.0")
  731. :type '(choice
  732. (const :tag "Ignore broken links" t)
  733. (const :tag "Mark broken links in output" mark)
  734. (const :tag "Raise an error" nil)))
  735. (defcustom org-export-snippet-translation-alist nil
  736. "Alist between export snippets back-ends and exporter back-ends.
  737. This variable allows providing shortcuts for export snippets.
  738. For example, with a value of \\='((\"h\" . \"html\")), the
  739. HTML back-end will recognize the contents of \"@@h:<b>@@\" as
  740. HTML code while every other back-end will ignore it."
  741. :group 'org-export-general
  742. :version "24.4"
  743. :package-version '(Org . "8.0")
  744. :type '(repeat
  745. (cons (string :tag "Shortcut")
  746. (string :tag "Back-end")))
  747. :safe (lambda (x)
  748. (and (listp x)
  749. (cl-every #'consp x)
  750. (cl-every #'stringp (mapcar #'car x))
  751. (cl-every #'stringp (mapcar #'cdr x)))))
  752. (defcustom org-export-global-macros nil
  753. "Alist between macro names and expansion templates.
  754. This variable defines macro expansion templates available
  755. globally. Associations follow the pattern
  756. (NAME . TEMPLATE)
  757. where NAME is a string beginning with a letter and consisting of
  758. alphanumeric characters only.
  759. TEMPLATE is the string to which the macro is going to be
  760. expanded. Inside, \"$1\", \"$2\"... are place-holders for
  761. macro's arguments. Moreover, if the template starts with
  762. \"(eval\", it will be parsed as an Elisp expression and evaluated
  763. accordingly."
  764. :group 'org-export-general
  765. :version "25.2"
  766. :package-version '(Org . "9.1")
  767. :type '(repeat
  768. (cons (string :tag "Name")
  769. (string :tag "Template"))))
  770. (defcustom org-export-coding-system nil
  771. "Coding system for the exported file."
  772. :group 'org-export-general
  773. :version "24.4"
  774. :package-version '(Org . "8.0")
  775. :type 'coding-system)
  776. (defcustom org-export-copy-to-kill-ring nil
  777. "Non-nil means pushing export output to the kill ring.
  778. This variable is ignored during asynchronous export."
  779. :group 'org-export-general
  780. :version "25.2"
  781. :package-version '(Org . "8.3")
  782. :type '(choice
  783. (const :tag "Always" t)
  784. (const :tag "When export is done interactively" if-interactive)
  785. (const :tag "Never" nil)))
  786. (defcustom org-export-initial-scope 'buffer
  787. "The initial scope when exporting with `org-export-dispatch'.
  788. This variable can be either set to `buffer' or `subtree'."
  789. :group 'org-export-general
  790. :type '(choice
  791. (const :tag "Export current buffer" buffer)
  792. (const :tag "Export current subtree" subtree)))
  793. (defcustom org-export-show-temporary-export-buffer t
  794. "Non-nil means show buffer after exporting to temp buffer.
  795. When Org exports to a file, the buffer visiting that file is never
  796. shown, but remains buried. However, when exporting to
  797. a temporary buffer, that buffer is popped up in a second window.
  798. When this variable is nil, the buffer remains buried also in
  799. these cases."
  800. :group 'org-export-general
  801. :type 'boolean)
  802. (defcustom org-export-in-background nil
  803. "Non-nil means export and publishing commands will run in background.
  804. Results from an asynchronous export are never displayed
  805. automatically. But you can retrieve them with `\\[org-export-stack]'."
  806. :group 'org-export-general
  807. :version "24.4"
  808. :package-version '(Org . "8.0")
  809. :type 'boolean)
  810. (defcustom org-export-async-init-file nil
  811. "File used to initialize external export process.
  812. Value must be either nil or an absolute file name. When nil, the
  813. external process is launched like a regular Emacs session,
  814. loading user's initialization file and any site specific
  815. configuration. If a file is provided, it, and only it, is loaded
  816. at start-up.
  817. Therefore, using a specific configuration makes the process to
  818. load faster and the export more portable."
  819. :group 'org-export-general
  820. :version "24.4"
  821. :package-version '(Org . "8.0")
  822. :type '(choice
  823. (const :tag "Regular startup" nil)
  824. (file :tag "Specific start-up file" :must-match t)))
  825. (defcustom org-export-dispatch-use-expert-ui nil
  826. "Non-nil means using a non-intrusive `org-export-dispatch'.
  827. In that case, no help buffer is displayed. Though, an indicator
  828. for current export scope is added to the prompt (\"b\" when
  829. output is restricted to body only, \"s\" when it is restricted to
  830. the current subtree, \"v\" when only visible elements are
  831. considered for export, \"f\" when publishing functions should be
  832. passed the FORCE argument and \"a\" when the export should be
  833. asynchronous). Also, [?] allows switching back to standard
  834. mode."
  835. :group 'org-export-general
  836. :version "24.4"
  837. :package-version '(Org . "8.0")
  838. :type 'boolean)
  839. ;;; Defining Back-ends
  840. ;;
  841. ;; An export back-end is a structure with `org-export-backend' type
  842. ;; and `name', `parent', `transcoders', `options', `filters', `blocks'
  843. ;; and `menu' slots.
  844. ;;
  845. ;; At the lowest level, a back-end is created with
  846. ;; `org-export-create-backend' function.
  847. ;;
  848. ;; A named back-end can be registered with
  849. ;; `org-export-register-backend' function. A registered back-end can
  850. ;; later be referred to by its name, with `org-export-get-backend'
  851. ;; function. Also, such a back-end can become the parent of a derived
  852. ;; back-end from which slot values will be inherited by default.
  853. ;; `org-export-derived-backend-p' can check if a given back-end is
  854. ;; derived from a list of back-end names.
  855. ;;
  856. ;; `org-export-get-all-transcoders', `org-export-get-all-options' and
  857. ;; `org-export-get-all-filters' return the full alist of transcoders,
  858. ;; options and filters, including those inherited from ancestors.
  859. ;;
  860. ;; At a higher level, `org-export-define-backend' is the standard way
  861. ;; to define an export back-end. If the new back-end is similar to
  862. ;; a registered back-end, `org-export-define-derived-backend' may be
  863. ;; used instead.
  864. ;;
  865. ;; Eventually `org-export-barf-if-invalid-backend' returns an error
  866. ;; when a given back-end hasn't been registered yet.
  867. (cl-defstruct (org-export-backend (:constructor org-export-create-backend)
  868. (:copier nil))
  869. name parent transcoders options filters blocks menu)
  870. (defun org-export-get-backend (name)
  871. "Return export back-end named after NAME.
  872. NAME is a symbol. Return nil if no such back-end is found."
  873. (catch 'found
  874. (dolist (b org-export-registered-backends)
  875. (when (eq (org-export-backend-name b) name)
  876. (throw 'found b)))))
  877. (defun org-export-register-backend (backend)
  878. "Register BACKEND as a known export back-end.
  879. BACKEND is a structure with `org-export-backend' type."
  880. ;; Refuse to register an unnamed back-end.
  881. (unless (org-export-backend-name backend)
  882. (error "Cannot register a unnamed export back-end"))
  883. ;; Refuse to register a back-end with an unknown parent.
  884. (let ((parent (org-export-backend-parent backend)))
  885. (when (and parent (not (org-export-get-backend parent)))
  886. (error "Cannot use unknown \"%s\" back-end as a parent" parent)))
  887. ;; If a back-end with the same name as BACKEND is already
  888. ;; registered, replace it with BACKEND. Otherwise, simply add
  889. ;; BACKEND to the list of registered back-ends.
  890. (let ((old (org-export-get-backend (org-export-backend-name backend))))
  891. (if old (setcar (memq old org-export-registered-backends) backend)
  892. (push backend org-export-registered-backends))))
  893. (defun org-export-barf-if-invalid-backend (backend)
  894. "Signal an error if BACKEND isn't defined."
  895. (unless (org-export-backend-p backend)
  896. (error "Unknown \"%s\" back-end: Aborting export" backend)))
  897. (defun org-export-derived-backend-p (backend &rest backends)
  898. "Non-nil if BACKEND is derived from one of BACKENDS.
  899. BACKEND is an export back-end, as returned by, e.g.,
  900. `org-export-create-backend', or a symbol referring to
  901. a registered back-end. BACKENDS is constituted of symbols."
  902. (when (symbolp backend) (setq backend (org-export-get-backend backend)))
  903. (when backend
  904. (catch 'exit
  905. (while (org-export-backend-parent backend)
  906. (when (memq (org-export-backend-name backend) backends)
  907. (throw 'exit t))
  908. (setq backend
  909. (org-export-get-backend (org-export-backend-parent backend))))
  910. (memq (org-export-backend-name backend) backends))))
  911. (defun org-export-get-all-transcoders (backend)
  912. "Return full translation table for BACKEND.
  913. BACKEND is an export back-end, as return by, e.g,,
  914. `org-export-create-backend'. Return value is an alist where
  915. keys are element or object types, as symbols, and values are
  916. transcoders.
  917. Unlike to `org-export-backend-transcoders', this function
  918. also returns transcoders inherited from parent back-ends,
  919. if any."
  920. (when (symbolp backend) (setq backend (org-export-get-backend backend)))
  921. (when backend
  922. (let ((transcoders (org-export-backend-transcoders backend))
  923. parent)
  924. (while (setq parent (org-export-backend-parent backend))
  925. (setq backend (org-export-get-backend parent))
  926. (setq transcoders
  927. (append transcoders (org-export-backend-transcoders backend))))
  928. transcoders)))
  929. (defun org-export-get-all-options (backend)
  930. "Return export options for BACKEND.
  931. BACKEND is an export back-end, as return by, e.g,,
  932. `org-export-create-backend'. See `org-export-options-alist'
  933. for the shape of the return value.
  934. Unlike to `org-export-backend-options', this function also
  935. returns options inherited from parent back-ends, if any."
  936. (when (symbolp backend) (setq backend (org-export-get-backend backend)))
  937. (when backend
  938. (let ((options (org-export-backend-options backend))
  939. parent)
  940. (while (setq parent (org-export-backend-parent backend))
  941. (setq backend (org-export-get-backend parent))
  942. (setq options (append options (org-export-backend-options backend))))
  943. options)))
  944. (defun org-export-get-all-filters (backend)
  945. "Return complete list of filters for BACKEND.
  946. BACKEND is an export back-end, as return by, e.g,,
  947. `org-export-create-backend'. Return value is an alist where
  948. keys are symbols and values lists of functions.
  949. Unlike to `org-export-backend-filters', this function also
  950. returns filters inherited from parent back-ends, if any."
  951. (when (symbolp backend) (setq backend (org-export-get-backend backend)))
  952. (when backend
  953. (let ((filters (org-export-backend-filters backend))
  954. parent)
  955. (while (setq parent (org-export-backend-parent backend))
  956. (setq backend (org-export-get-backend parent))
  957. (setq filters (append filters (org-export-backend-filters backend))))
  958. filters)))
  959. (defun org-export-define-backend (backend transcoders &rest body)
  960. "Define a new back-end BACKEND.
  961. TRANSCODERS is an alist between object or element types and
  962. functions handling them.
  963. These functions should return a string without any trailing
  964. space, or nil. They must accept three arguments: the object or
  965. element itself, its contents or nil when it isn't recursive and
  966. the property list used as a communication channel.
  967. Contents, when not nil, are stripped from any global indentation
  968. \(although the relative one is preserved). They also always end
  969. with a single newline character.
  970. If, for a given type, no function is found, that element or
  971. object type will simply be ignored, along with any blank line or
  972. white space at its end. The same will happen if the function
  973. returns the nil value. If that function returns the empty
  974. string, the type will be ignored, but the blank lines or white
  975. spaces will be kept.
  976. In addition to element and object types, one function can be
  977. associated to the `template' (or `inner-template') symbol and
  978. another one to the `plain-text' symbol.
  979. The former returns the final transcoded string, and can be used
  980. to add a preamble and a postamble to document's body. It must
  981. accept two arguments: the transcoded string and the property list
  982. containing export options. A function associated to `template'
  983. will not be applied if export has option \"body-only\".
  984. A function associated to `inner-template' is always applied.
  985. The latter, when defined, is to be called on every text not
  986. recognized as an element or an object. It must accept two
  987. arguments: the text string and the information channel. It is an
  988. appropriate place to protect special chars relative to the
  989. back-end.
  990. BODY can start with pre-defined keyword arguments. The following
  991. keywords are understood:
  992. :filters-alist
  993. Alist between filters and function, or list of functions,
  994. specific to the back-end. See `org-export-filters-alist' for
  995. a list of all allowed filters. Filters defined here
  996. shouldn't make a back-end test, as it may prevent back-ends
  997. derived from this one to behave properly.
  998. :menu-entry
  999. Menu entry for the export dispatcher. It should be a list
  1000. like:
  1001. \\='(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
  1002. where :
  1003. KEY is a free character selecting the back-end.
  1004. DESCRIPTION-OR-ORDINAL is either a string or a number.
  1005. If it is a string, is will be used to name the back-end in
  1006. its menu entry. If it is a number, the following menu will
  1007. be displayed as a sub-menu of the back-end with the same
  1008. KEY. Also, the number will be used to determine in which
  1009. order such sub-menus will appear (lowest first).
  1010. ACTION-OR-MENU is either a function or an alist.
  1011. If it is an action, it will be called with four
  1012. arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
  1013. BODY-ONLY. See `org-export-as' for further explanations on
  1014. some of them.
  1015. If it is an alist, associations should follow the
  1016. pattern:
  1017. \\='(KEY DESCRIPTION ACTION)
  1018. where KEY, DESCRIPTION and ACTION are described above.
  1019. Valid values include:
  1020. \\='(?m \"My Special Back-end\" my-special-export-function)
  1021. or
  1022. \\='(?l \"Export to LaTeX\"
  1023. (?p \"As PDF file\" org-latex-export-to-pdf)
  1024. (?o \"As PDF file and open\"
  1025. (lambda (a s v b)
  1026. (if a (org-latex-export-to-pdf t s v b)
  1027. (org-open-file
  1028. (org-latex-export-to-pdf nil s v b)))))))
  1029. or the following, which will be added to the previous
  1030. sub-menu,
  1031. \\='(?l 1
  1032. ((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
  1033. (?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
  1034. :options-alist
  1035. Alist between back-end specific properties introduced in
  1036. communication channel and how their value are acquired. See
  1037. `org-export-options-alist' for more information about
  1038. structure of the values."
  1039. (declare (indent 1))
  1040. (let (filters menu-entry options)
  1041. (while (keywordp (car body))
  1042. (let ((keyword (pop body)))
  1043. (pcase keyword
  1044. (:filters-alist (setq filters (pop body)))
  1045. (:menu-entry (setq menu-entry (pop body)))
  1046. (:options-alist (setq options (pop body)))
  1047. (_ (error "Unknown keyword: %s" keyword)))))
  1048. (org-export-register-backend
  1049. (org-export-create-backend :name backend
  1050. :transcoders transcoders
  1051. :options options
  1052. :filters filters
  1053. :menu menu-entry))))
  1054. (defun org-export-define-derived-backend (child parent &rest body)
  1055. "Create a new back-end as a variant of an existing one.
  1056. CHILD is the name of the derived back-end. PARENT is the name of
  1057. the parent back-end.
  1058. BODY can start with pre-defined keyword arguments. The following
  1059. keywords are understood:
  1060. :filters-alist
  1061. Alist of filters that will overwrite or complete filters
  1062. defined in PARENT back-end. See `org-export-filters-alist'
  1063. for a list of allowed filters.
  1064. :menu-entry
  1065. Menu entry for the export dispatcher. See
  1066. `org-export-define-backend' for more information about the
  1067. expected value.
  1068. :options-alist
  1069. Alist of back-end specific properties that will overwrite or
  1070. complete those defined in PARENT back-end. Refer to
  1071. `org-export-options-alist' for more information about
  1072. structure of the values.
  1073. :translate-alist
  1074. Alist of element and object types and transcoders that will
  1075. overwrite or complete transcode table from PARENT back-end.
  1076. Refer to `org-export-define-backend' for detailed information
  1077. about transcoders.
  1078. As an example, here is how one could define \"my-latex\" back-end
  1079. as a variant of `latex' back-end with a custom template function:
  1080. (org-export-define-derived-backend \\='my-latex \\='latex
  1081. :translate-alist \\='((template . my-latex-template-fun)))
  1082. The back-end could then be called with, for example:
  1083. (org-export-to-buffer \\='my-latex \"*Test my-latex*\")"
  1084. (declare (indent 2))
  1085. (let (filters menu-entry options transcoders)
  1086. (while (keywordp (car body))
  1087. (let ((keyword (pop body)))
  1088. (pcase keyword
  1089. (:filters-alist (setq filters (pop body)))
  1090. (:menu-entry (setq menu-entry (pop body)))
  1091. (:options-alist (setq options (pop body)))
  1092. (:translate-alist (setq transcoders (pop body)))
  1093. (_ (error "Unknown keyword: %s" keyword)))))
  1094. (org-export-register-backend
  1095. (org-export-create-backend :name child
  1096. :parent parent
  1097. :transcoders transcoders
  1098. :options options
  1099. :filters filters
  1100. :menu menu-entry))))
  1101. ;;; The Communication Channel
  1102. ;;
  1103. ;; During export process, every function has access to a number of
  1104. ;; properties. They are of two types:
  1105. ;;
  1106. ;; 1. Environment options are collected once at the very beginning of
  1107. ;; the process, out of the original buffer and configuration.
  1108. ;; Collecting them is handled by `org-export-get-environment'
  1109. ;; function.
  1110. ;;
  1111. ;; Most environment options are defined through the
  1112. ;; `org-export-options-alist' variable.
  1113. ;;
  1114. ;; 2. Tree properties are extracted directly from the parsed tree,
  1115. ;; just before export, by `org-export--collect-tree-properties'.
  1116. ;;;; Environment Options
  1117. ;;
  1118. ;; Environment options encompass all parameters defined outside the
  1119. ;; scope of the parsed data. They come from five sources, in
  1120. ;; increasing precedence order:
  1121. ;;
  1122. ;; - Global variables,
  1123. ;; - Buffer's attributes,
  1124. ;; - Options keyword symbols,
  1125. ;; - Buffer keywords,
  1126. ;; - Subtree properties.
  1127. ;;
  1128. ;; The central internal function with regards to environment options
  1129. ;; is `org-export-get-environment'. It updates global variables with
  1130. ;; "#+BIND:" keywords, then retrieve and prioritize properties from
  1131. ;; the different sources.
  1132. ;;
  1133. ;; The internal functions doing the retrieval are:
  1134. ;; `org-export--get-global-options',
  1135. ;; `org-export--get-buffer-attributes',
  1136. ;; `org-export--parse-option-keyword',
  1137. ;; `org-export--get-subtree-options' and
  1138. ;; `org-export--get-inbuffer-options'
  1139. ;;
  1140. ;; Also, `org-export--list-bound-variables' collects bound variables
  1141. ;; along with their value in order to set them as buffer local
  1142. ;; variables later in the process.
  1143. (defun org-export-get-environment (&optional backend subtreep ext-plist)
  1144. "Collect export options from the current buffer.
  1145. Optional argument BACKEND is an export back-end, as returned by
  1146. `org-export-create-backend'.
  1147. When optional argument SUBTREEP is non-nil, assume the export is
  1148. done against the current sub-tree.
  1149. Third optional argument EXT-PLIST is a property list with
  1150. external parameters overriding Org default settings, but still
  1151. inferior to file-local settings."
  1152. ;; First install #+BIND variables since these must be set before
  1153. ;; global options are read.
  1154. (dolist (pair (org-export--list-bound-variables))
  1155. (set (make-local-variable (car pair)) (nth 1 pair)))
  1156. ;; Get and prioritize export options...
  1157. (org-combine-plists
  1158. ;; ... from global variables...
  1159. (org-export--get-global-options backend)
  1160. ;; ... from an external property list...
  1161. ext-plist
  1162. ;; ... from in-buffer settings...
  1163. (org-export--get-inbuffer-options backend)
  1164. ;; ... and from subtree, when appropriate.
  1165. (and subtreep (org-export--get-subtree-options backend))))
  1166. (defun org-export--parse-option-keyword (options &optional backend)
  1167. "Parse an OPTIONS line and return values as a plist.
  1168. Optional argument BACKEND is an export back-end, as returned by,
  1169. e.g., `org-export-create-backend'. It specifies which back-end
  1170. specific items to read, if any."
  1171. (let ((line
  1172. (let ((s 0) alist)
  1173. (while (string-match "\\(.+?\\):\\((.*?)\\|\\S-*\\)[ \t]*" options s)
  1174. (setq s (match-end 0))
  1175. (push (cons (match-string 1 options)
  1176. (read (match-string 2 options)))
  1177. alist))
  1178. alist))
  1179. ;; Priority is given to back-end specific options.
  1180. (all (append (and backend (org-export-get-all-options backend))
  1181. org-export-options-alist))
  1182. (plist))
  1183. (when line
  1184. (dolist (entry all plist)
  1185. (let ((item (nth 2 entry)))
  1186. (when item
  1187. (let ((v (assoc-string item line t)))
  1188. (when v (setq plist (plist-put plist (car entry) (cdr v)))))))))))
  1189. (defun org-export--get-subtree-options (&optional backend)
  1190. "Get export options in subtree at point.
  1191. Optional argument BACKEND is an export back-end, as returned by,
  1192. e.g., `org-export-create-backend'. It specifies back-end used
  1193. for export. Return options as a plist."
  1194. ;; For each buffer keyword, create a headline property setting the
  1195. ;; same property in communication channel. The name for the
  1196. ;; property is the keyword with "EXPORT_" appended to it.
  1197. (org-with-wide-buffer
  1198. ;; Make sure point is at a heading.
  1199. (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
  1200. (let ((plist
  1201. ;; EXPORT_OPTIONS are parsed in a non-standard way. Take
  1202. ;; care of them right from the start.
  1203. (let ((o (org-entry-get (point) "EXPORT_OPTIONS" 'selective)))
  1204. (and o (org-export--parse-option-keyword o backend))))
  1205. ;; Take care of EXPORT_TITLE. If it isn't defined, use
  1206. ;; headline's title (with no todo keyword, priority cookie or
  1207. ;; tag) as its fallback value.
  1208. (cache (list
  1209. (cons "TITLE"
  1210. (or (org-entry-get (point) "EXPORT_TITLE" 'selective)
  1211. (let ((case-fold-search nil))
  1212. (looking-at org-complex-heading-regexp)
  1213. (match-string-no-properties 4))))))
  1214. ;; Look for both general keywords and back-end specific
  1215. ;; options, with priority given to the latter.
  1216. (options (append (and backend (org-export-get-all-options backend))
  1217. org-export-options-alist)))
  1218. ;; Handle other keywords. Then return PLIST.
  1219. (dolist (option options plist)
  1220. (let ((property (car option))
  1221. (keyword (nth 1 option)))
  1222. (when keyword
  1223. (let ((value
  1224. (or (cdr (assoc keyword cache))
  1225. (let ((v (org-entry-get (point)
  1226. (concat "EXPORT_" keyword)
  1227. 'selective)))
  1228. (push (cons keyword v) cache) v))))
  1229. (when value
  1230. (setq plist
  1231. (plist-put plist
  1232. property
  1233. (cl-case (nth 4 option)
  1234. (parse
  1235. (org-element-parse-secondary-string
  1236. value (org-element-restriction 'keyword)))
  1237. (split (org-split-string value))
  1238. (t value))))))))))))
  1239. (defun org-export--get-inbuffer-options (&optional backend)
  1240. "Return current buffer export options, as a plist.
  1241. Optional argument BACKEND, when non-nil, is an export back-end,
  1242. as returned by, e.g., `org-export-create-backend'. It specifies
  1243. which back-end specific options should also be read in the
  1244. process.
  1245. Assume buffer is in Org mode. Narrowing, if any, is ignored."
  1246. (let* ((case-fold-search t)
  1247. (options (append
  1248. ;; Priority is given to back-end specific options.
  1249. (and backend (org-export-get-all-options backend))
  1250. org-export-options-alist))
  1251. (regexp (format "^[ \t]*#\\+%s:"
  1252. (regexp-opt (nconc (delq nil (mapcar #'cadr options))
  1253. org-export-special-keywords))))
  1254. plist to-parse)
  1255. (letrec ((find-properties
  1256. (lambda (keyword)
  1257. ;; Return all properties associated to KEYWORD.
  1258. (let (properties)
  1259. (dolist (option options properties)
  1260. (when (equal (nth 1 option) keyword)
  1261. (cl-pushnew (car option) properties))))))
  1262. (get-options
  1263. (lambda (&optional files)
  1264. ;; Recursively read keywords in buffer. FILES is
  1265. ;; a list of files read so far. PLIST is the current
  1266. ;; property list obtained.
  1267. (org-with-wide-buffer
  1268. (goto-char (point-min))
  1269. (while (re-search-forward regexp nil t)
  1270. (let ((element (org-element-at-point)))
  1271. (when (eq (org-element-type element) 'keyword)
  1272. (let ((key (org-element-property :key element))
  1273. (val (org-element-property :value element)))
  1274. (cond
  1275. ;; Options in `org-export-special-keywords'.
  1276. ((equal key "SETUPFILE")
  1277. (let ((file
  1278. (expand-file-name
  1279. (org-unbracket-string "\"" "\"" (org-trim val)))))
  1280. ;; Avoid circular dependencies.
  1281. (unless (member file files)
  1282. (with-temp-buffer
  1283. (setq default-directory
  1284. (file-name-directory file))
  1285. (insert (org-file-contents file 'noerror))
  1286. (let ((org-inhibit-startup t)) (org-mode))
  1287. (funcall get-options (cons file files))))))
  1288. ((equal key "OPTIONS")
  1289. (setq plist
  1290. (org-combine-plists
  1291. plist
  1292. (org-export--parse-option-keyword
  1293. val backend))))
  1294. ((equal key "FILETAGS")
  1295. (setq plist
  1296. (org-combine-plists
  1297. plist
  1298. (list :filetags
  1299. (org-uniquify
  1300. (append
  1301. (org-split-string val ":")
  1302. (plist-get plist :filetags)))))))
  1303. (t
  1304. ;; Options in `org-export-options-alist'.
  1305. (dolist (property (funcall find-properties key))
  1306. (setq
  1307. plist
  1308. (plist-put
  1309. plist property
  1310. ;; Handle value depending on specified
  1311. ;; BEHAVIOR.
  1312. (cl-case (nth 4 (assq property options))
  1313. (parse
  1314. (unless (memq property to-parse)
  1315. (push property to-parse))
  1316. ;; Even if `parse' implies `space'
  1317. ;; behavior, we separate line with
  1318. ;; "\n" so as to preserve
  1319. ;; line-breaks. However, empty
  1320. ;; lines are forbidden since `parse'
  1321. ;; doesn't allow more than one
  1322. ;; paragraph.
  1323. (let ((old (plist-get plist property)))
  1324. (cond ((not (org-string-nw-p val)) old)
  1325. (old (concat old "\n" val))
  1326. (t val))))
  1327. (space
  1328. (if (not (plist-get plist property))
  1329. (org-trim val)
  1330. (concat (plist-get plist property)
  1331. " "
  1332. (org-trim val))))
  1333. (newline
  1334. (org-trim
  1335. (concat (plist-get plist property)
  1336. "\n"
  1337. (org-trim val))))
  1338. (split `(,@(plist-get plist property)
  1339. ,@(org-split-string val)))
  1340. ((t) val)
  1341. (otherwise
  1342. (if (not (plist-member plist property)) val
  1343. (plist-get plist property)))))))))))))))))
  1344. ;; Read options in the current buffer and return value.
  1345. (funcall get-options (and buffer-file-name (list buffer-file-name)))
  1346. ;; Parse properties in TO-PARSE. Remove newline characters not
  1347. ;; involved in line breaks to simulate `space' behavior.
  1348. ;; Finally return options.
  1349. (dolist (p to-parse plist)
  1350. (let ((value (org-element-parse-secondary-string
  1351. (plist-get plist p)
  1352. (org-element-restriction 'keyword))))
  1353. (org-element-map value 'plain-text
  1354. (lambda (s)
  1355. (org-element-set-element
  1356. s (replace-regexp-in-string "\n" " " s))))
  1357. (setq plist (plist-put plist p value)))))))
  1358. (defun org-export--get-export-attributes
  1359. (&optional backend subtreep visible-only body-only)
  1360. "Return properties related to export process, as a plist.
  1361. Optional arguments BACKEND, SUBTREEP, VISIBLE-ONLY and BODY-ONLY
  1362. are like the arguments with the same names of function
  1363. `org-export-as'."
  1364. (list :export-options (delq nil
  1365. (list (and subtreep 'subtree)
  1366. (and visible-only 'visible-only)
  1367. (and body-only 'body-only)))
  1368. :back-end backend
  1369. :translate-alist (org-export-get-all-transcoders backend)
  1370. :exported-data (make-hash-table :test #'eq :size 4001)))
  1371. (defun org-export--get-buffer-attributes ()
  1372. "Return properties related to buffer attributes, as a plist."
  1373. (list :input-buffer (buffer-name (buffer-base-buffer))
  1374. :input-file (buffer-file-name (buffer-base-buffer))))
  1375. (defun org-export--get-global-options (&optional backend)
  1376. "Return global export options as a plist.
  1377. Optional argument BACKEND, if non-nil, is an export back-end, as
  1378. returned by, e.g., `org-export-create-backend'. It specifies
  1379. which back-end specific export options should also be read in the
  1380. process."
  1381. (let (plist
  1382. ;; Priority is given to back-end specific options.
  1383. (all (append (and backend (org-export-get-all-options backend))
  1384. org-export-options-alist)))
  1385. (dolist (cell all plist)
  1386. (let ((prop (car cell)))
  1387. (unless (plist-member plist prop)
  1388. (setq plist
  1389. (plist-put
  1390. plist
  1391. prop
  1392. ;; Evaluate default value provided.
  1393. (let ((value (eval (nth 3 cell))))
  1394. (if (eq (nth 4 cell) 'parse)
  1395. (org-element-parse-secondary-string
  1396. value (org-element-restriction 'keyword))
  1397. value)))))))))
  1398. (defun org-export--list-bound-variables ()
  1399. "Return variables bound from BIND keywords in current buffer.
  1400. Also look for BIND keywords in setup files. The return value is
  1401. an alist where associations are (VARIABLE-NAME VALUE)."
  1402. (when org-export-allow-bind-keywords
  1403. (letrec ((collect-bind
  1404. (lambda (files alist)
  1405. ;; Return an alist between variable names and their
  1406. ;; value. FILES is a list of setup files names read
  1407. ;; so far, used to avoid circular dependencies. ALIST
  1408. ;; is the alist collected so far.
  1409. (let ((case-fold-search t))
  1410. (org-with-wide-buffer
  1411. (goto-char (point-min))
  1412. (while (re-search-forward
  1413. "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
  1414. (let ((element (org-element-at-point)))
  1415. (when (eq (org-element-type element) 'keyword)
  1416. (let ((val (org-element-property :value element)))
  1417. (if (equal (org-element-property :key element)
  1418. "BIND")
  1419. (push (read (format "(%s)" val)) alist)
  1420. ;; Enter setup file.
  1421. (let ((file (expand-file-name
  1422. (org-unbracket-string "\"" "\"" val))))
  1423. (unless (member file files)
  1424. (with-temp-buffer
  1425. (setq default-directory
  1426. (file-name-directory file))
  1427. (let ((org-inhibit-startup t)) (org-mode))
  1428. (insert (org-file-contents file 'noerror))
  1429. (setq alist
  1430. (funcall collect-bind
  1431. (cons file files)
  1432. alist))))))))))
  1433. alist)))))
  1434. ;; Return value in appropriate order of appearance.
  1435. (nreverse (funcall collect-bind nil nil)))))
  1436. ;; defsubst org-export-get-parent must be defined before first use,
  1437. ;; was originally defined in the topology section
  1438. (defsubst org-export-get-parent (blob)
  1439. "Return BLOB parent or nil.
  1440. BLOB is the element or object considered."
  1441. (org-element-property :parent blob))
  1442. ;;;; Tree Properties
  1443. ;;
  1444. ;; Tree properties are information extracted from parse tree. They
  1445. ;; are initialized at the beginning of the transcoding process by
  1446. ;; `org-export--collect-tree-properties'.
  1447. ;;
  1448. ;; Dedicated functions focus on computing the value of specific tree
  1449. ;; properties during initialization. Thus,
  1450. ;; `org-export--populate-ignore-list' lists elements and objects that
  1451. ;; should be skipped during export, `org-export--get-min-level' gets
  1452. ;; the minimal exportable level, used as a basis to compute relative
  1453. ;; level for headlines. Eventually
  1454. ;; `org-export--collect-headline-numbering' builds an alist between
  1455. ;; headlines and their numbering.
  1456. (defun org-export--collect-tree-properties (data info)
  1457. "Extract tree properties from parse tree.
  1458. DATA is the parse tree from which information is retrieved. INFO
  1459. is a list holding export options.
  1460. Following tree properties are set or updated:
  1461. `:headline-offset' Offset between true level of headlines and
  1462. local level. An offset of -1 means a headline
  1463. of level 2 should be considered as a level
  1464. 1 headline in the context.
  1465. `:headline-numbering' Alist of all headlines as key and the
  1466. associated numbering as value.
  1467. `:id-alist' Alist of all ID references as key and associated file
  1468. as value.
  1469. Return updated plist."
  1470. ;; Install the parse tree in the communication channel.
  1471. (setq info (plist-put info :parse-tree data))
  1472. ;; Compute `:headline-offset' in order to be able to use
  1473. ;; `org-export-get-relative-level'.
  1474. (setq info
  1475. (plist-put info
  1476. :headline-offset
  1477. (- 1 (org-export--get-min-level data info))))
  1478. ;; From now on, properties order doesn't matter: get the rest of the
  1479. ;; tree properties.
  1480. (org-combine-plists
  1481. info
  1482. (list :headline-numbering (org-export--collect-headline-numbering data info)
  1483. :id-alist
  1484. (org-element-map data 'link
  1485. (lambda (l)
  1486. (and (string= (org-element-property :type l) "id")
  1487. (let* ((id (org-element-property :path l))
  1488. (file (car (org-id-find id))))
  1489. (and file (cons id (file-relative-name file))))))))))
  1490. (defun org-export--get-min-level (data options)
  1491. "Return minimum exportable headline's level in DATA.
  1492. DATA is parsed tree as returned by `org-element-parse-buffer'.
  1493. OPTIONS is a plist holding export options."
  1494. (catch 'exit
  1495. (let ((min-level 10000))
  1496. (dolist (datum (org-element-contents data))
  1497. (when (and (eq (org-element-type datum) 'headline)
  1498. (not (org-element-property :footnote-section-p datum))
  1499. (not (memq datum (plist-get options :ignore-list))))
  1500. (setq min-level (min (org-element-property :level datum) min-level))
  1501. (when (= min-level 1) (throw 'exit 1))))
  1502. ;; If no headline was found, for the sake of consistency, set
  1503. ;; minimum level to 1 nonetheless.
  1504. (if (= min-level 10000) 1 min-level))))
  1505. (defun org-export--collect-headline-numbering (data options)
  1506. "Return numbering of all exportable, numbered headlines in a parse tree.
  1507. DATA is the parse tree. OPTIONS is the plist holding export
  1508. options.
  1509. Return an alist whose key is a headline and value is its
  1510. associated numbering \(in the shape of a list of numbers) or nil
  1511. for a footnotes section."
  1512. (let ((numbering (make-vector org-export-max-depth 0)))
  1513. (org-element-map data 'headline
  1514. (lambda (headline)
  1515. (when (and (org-export-numbered-headline-p headline options)
  1516. (not (org-element-property :footnote-section-p headline)))
  1517. (let ((relative-level
  1518. (1- (org-export-get-relative-level headline options))))
  1519. (cons
  1520. headline
  1521. (cl-loop
  1522. for n across numbering
  1523. for idx from 0 to org-export-max-depth
  1524. when (< idx relative-level) collect n
  1525. when (= idx relative-level) collect (aset numbering idx (1+ n))
  1526. when (> idx relative-level) do (aset numbering idx 0))))))
  1527. options)))
  1528. (defun org-export--selected-trees (data info)
  1529. "List headlines and inlinetasks with a select tag in their tree.
  1530. DATA is parsed data as returned by `org-element-parse-buffer'.
  1531. INFO is a plist holding export options."
  1532. (let ((select (plist-get info :select-tags)))
  1533. (if (cl-some (lambda (tag) (member tag select)) (plist-get info :filetags))
  1534. ;; If FILETAGS contains a select tag, every headline or
  1535. ;; inlinetask is returned.
  1536. (org-element-map data '(headline inlinetask) #'identity)
  1537. (letrec ((selected-trees nil)
  1538. (walk-data
  1539. (lambda (data genealogy)
  1540. (let ((type (org-element-type data)))
  1541. (cond
  1542. ((memq type '(headline inlinetask))
  1543. (let ((tags (org-element-property :tags data)))
  1544. (if (cl-some (lambda (tag) (member tag select)) tags)
  1545. ;; When a select tag is found, mark full
  1546. ;; genealogy and every headline within the
  1547. ;; tree as acceptable.
  1548. (setq selected-trees
  1549. (append
  1550. genealogy
  1551. (org-element-map data '(headline inlinetask)
  1552. #'identity)
  1553. selected-trees))
  1554. ;; If at a headline, continue searching in
  1555. ;; tree, recursively.
  1556. (when (eq type 'headline)
  1557. (dolist (el (org-element-contents data))
  1558. (funcall walk-data el (cons data genealogy)))))))
  1559. ((or (eq type 'org-data)
  1560. (memq type org-element-greater-elements))
  1561. (dolist (el (org-element-contents data))
  1562. (funcall walk-data el genealogy))))))))
  1563. (funcall walk-data data nil)
  1564. selected-trees))))
  1565. (defun org-export--skip-p (blob options selected)
  1566. "Non-nil when element or object BLOB should be skipped during export.
  1567. OPTIONS is the plist holding export options. SELECTED, when
  1568. non-nil, is a list of headlines or inlinetasks belonging to
  1569. a tree with a select tag."
  1570. (cl-case (org-element-type blob)
  1571. (clock (not (plist-get options :with-clocks)))
  1572. (drawer
  1573. (let ((with-drawers-p (plist-get options :with-drawers)))
  1574. (or (not with-drawers-p)
  1575. (and (consp with-drawers-p)
  1576. ;; If `:with-drawers' value starts with `not', ignore
  1577. ;; every drawer whose name belong to that list.
  1578. ;; Otherwise, ignore drawers whose name isn't in that
  1579. ;; list.
  1580. (let ((name (org-element-property :drawer-name blob)))
  1581. (if (eq (car with-drawers-p) 'not)
  1582. (member-ignore-case name (cdr with-drawers-p))
  1583. (not (member-ignore-case name with-drawers-p))))))))
  1584. (fixed-width (not (plist-get options :with-fixed-width)))
  1585. ((footnote-definition footnote-reference)
  1586. (not (plist-get options :with-footnotes)))
  1587. ((headline inlinetask)
  1588. (let ((with-tasks (plist-get options :with-tasks))
  1589. (todo (org-element-property :todo-keyword blob))
  1590. (todo-type (org-element-property :todo-type blob))
  1591. (archived (plist-get options :with-archived-trees))
  1592. (tags (org-export-get-tags blob options nil t)))
  1593. (or
  1594. (and (eq (org-element-type blob) 'inlinetask)
  1595. (not (plist-get options :with-inlinetasks)))
  1596. ;; Ignore subtrees with an exclude tag.
  1597. (cl-loop for k in (plist-get options :exclude-tags)
  1598. thereis (member k tags))
  1599. ;; When a select tag is present in the buffer, ignore any tree
  1600. ;; without it.
  1601. (and selected (not (memq blob selected)))
  1602. ;; Ignore commented sub-trees.
  1603. (org-element-property :commentedp blob)
  1604. ;; Ignore archived subtrees if `:with-archived-trees' is nil.
  1605. (and (not archived) (org-element-property :archivedp blob))
  1606. ;; Ignore tasks, if specified by `:with-tasks' property.
  1607. (and todo
  1608. (or (not with-tasks)
  1609. (and (memq with-tasks '(todo done))
  1610. (not (eq todo-type with-tasks)))
  1611. (and (consp with-tasks) (not (member todo with-tasks))))))))
  1612. ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
  1613. (node-property
  1614. (let ((properties-set (plist-get options :with-properties)))
  1615. (cond ((null properties-set) t)
  1616. ((consp properties-set)
  1617. (not (member-ignore-case (org-element-property :key blob)
  1618. properties-set))))))
  1619. (planning (not (plist-get options :with-planning)))
  1620. (property-drawer (not (plist-get options :with-properties)))
  1621. (statistics-cookie (not (plist-get options :with-statistics-cookies)))
  1622. (table (not (plist-get options :with-tables)))
  1623. (table-cell
  1624. (and (org-export-table-has-special-column-p
  1625. (org-export-get-parent-table blob))
  1626. (org-export-first-sibling-p blob options)))
  1627. (table-row (org-export-table-row-is-special-p blob options))
  1628. (timestamp
  1629. ;; `:with-timestamps' only applies to isolated timestamps
  1630. ;; objects, i.e. timestamp objects in a paragraph containing only
  1631. ;; timestamps and whitespaces.
  1632. (when (let ((parent (org-export-get-parent-element blob)))
  1633. (and (memq (org-element-type parent) '(paragraph verse-block))
  1634. (not (org-element-map parent
  1635. (cons 'plain-text
  1636. (remq 'timestamp org-element-all-objects))
  1637. (lambda (obj)
  1638. (or (not (stringp obj)) (org-string-nw-p obj)))
  1639. options t))))
  1640. (cl-case (plist-get options :with-timestamps)
  1641. ((nil) t)
  1642. (active
  1643. (not (memq (org-element-property :type blob) '(active active-range))))
  1644. (inactive
  1645. (not (memq (org-element-property :type blob)
  1646. '(inactive inactive-range)))))))))
  1647. ;;; The Transcoder
  1648. ;;
  1649. ;; `org-export-data' reads a parse tree (obtained with, i.e.
  1650. ;; `org-element-parse-buffer') and transcodes it into a specified
  1651. ;; back-end output. It takes care of filtering out elements or
  1652. ;; objects according to export options and organizing the output blank
  1653. ;; lines and white space are preserved. The function memoizes its
  1654. ;; results, so it is cheap to call it within transcoders.
  1655. ;;
  1656. ;; It is possible to modify locally the back-end used by
  1657. ;; `org-export-data' or even use a temporary back-end by using
  1658. ;; `org-export-data-with-backend'.
  1659. ;;
  1660. ;; `org-export-transcoder' is an accessor returning appropriate
  1661. ;; translator function for a given element or object.
  1662. (defun org-export-transcoder (blob info)
  1663. "Return appropriate transcoder for BLOB.
  1664. INFO is a plist containing export directives."
  1665. (let ((type (org-element-type blob)))
  1666. ;; Return contents only for complete parse trees.
  1667. (if (eq type 'org-data) (lambda (_datum contents _info) contents)
  1668. (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
  1669. (and (functionp transcoder) transcoder)))))
  1670. (defun org-export-data (data info)
  1671. "Convert DATA into current back-end format.
  1672. DATA is a parse tree, an element or an object or a secondary
  1673. string. INFO is a plist holding export options.
  1674. Return a string."
  1675. (or (gethash data (plist-get info :exported-data))
  1676. ;; Handle broken links according to
  1677. ;; `org-export-with-broken-links'.
  1678. (cl-macrolet
  1679. ((broken-link-handler
  1680. (&rest body)
  1681. `(condition-case err
  1682. (progn ,@body)
  1683. (org-link-broken
  1684. (pcase (plist-get info :with-broken-links)
  1685. (`nil (user-error "Unable to resolve link: %S" (nth 1 err)))
  1686. (`mark (org-export-data
  1687. (format "[BROKEN LINK: %s]" (nth 1 err)) info))
  1688. (_ nil))))))
  1689. (let* ((type (org-element-type data))
  1690. (parent (org-export-get-parent data))
  1691. (results
  1692. (cond
  1693. ;; Ignored element/object.
  1694. ((memq data (plist-get info :ignore-list)) nil)
  1695. ;; Plain text.
  1696. ((eq type 'plain-text)
  1697. (org-export-filter-apply-functions
  1698. (plist-get info :filter-plain-text)
  1699. (let ((transcoder (org-export-transcoder data info)))
  1700. (if transcoder (funcall transcoder data info) data))
  1701. info))
  1702. ;; Secondary string.
  1703. ((not type)
  1704. (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
  1705. ;; Element/Object without contents or, as a special
  1706. ;; case, headline with archive tag and archived trees
  1707. ;; restricted to title only.
  1708. ((or (not (org-element-contents data))
  1709. (and (eq type 'headline)
  1710. (eq (plist-get info :with-archived-trees) 'headline)
  1711. (org-element-property :archivedp data)))
  1712. (let ((transcoder (org-export-transcoder data info)))
  1713. (or (and (functionp transcoder)
  1714. (broken-link-handler
  1715. (funcall transcoder data nil info)))
  1716. ;; Export snippets never return a nil value so
  1717. ;; that white spaces following them are never
  1718. ;; ignored.
  1719. (and (eq type 'export-snippet) ""))))
  1720. ;; Element/Object with contents.
  1721. (t
  1722. (let ((transcoder (org-export-transcoder data info)))
  1723. (when transcoder
  1724. (let* ((greaterp (memq type org-element-greater-elements))
  1725. (objectp
  1726. (and (not greaterp)
  1727. (memq type org-element-recursive-objects)))
  1728. (contents
  1729. (mapconcat
  1730. (lambda (element) (org-export-data element info))
  1731. (org-element-contents
  1732. (if (or greaterp objectp) data
  1733. ;; Elements directly containing
  1734. ;; objects must have their indentation
  1735. ;; normalized first.
  1736. (org-element-normalize-contents
  1737. data
  1738. ;; When normalizing contents of the
  1739. ;; first paragraph in an item or
  1740. ;; a footnote definition, ignore
  1741. ;; first line's indentation: there is
  1742. ;; none and it might be misleading.
  1743. (when (eq type 'paragraph)
  1744. (and
  1745. (eq (car (org-element-contents parent))
  1746. data)
  1747. (memq (org-element-type parent)
  1748. '(footnote-definition item)))))))
  1749. "")))
  1750. (broken-link-handler
  1751. (funcall transcoder data
  1752. (if (not greaterp) contents
  1753. (org-element-normalize-string contents))
  1754. info)))))))))
  1755. ;; Final result will be memoized before being returned.
  1756. (puthash
  1757. data
  1758. (cond
  1759. ((not results) "")
  1760. ((memq type '(org-data plain-text nil)) results)
  1761. ;; Append the same white space between elements or objects
  1762. ;; as in the original buffer, and call appropriate filters.
  1763. (t
  1764. (org-export-filter-apply-functions
  1765. (plist-get info (intern (format ":filter-%s" type)))
  1766. (let ((blank (or (org-element-property :post-blank data) 0)))
  1767. (if (eq (org-element-class data parent) 'object)
  1768. (concat results (make-string blank ?\s))
  1769. (concat (org-element-normalize-string results)
  1770. (make-string blank ?\n))))
  1771. info)))
  1772. (plist-get info :exported-data))))))
  1773. (defun org-export-data-with-backend (data backend info)
  1774. "Convert DATA into BACKEND format.
  1775. DATA is an element, an object, a secondary string or a string.
  1776. BACKEND is a symbol. INFO is a plist used as a communication
  1777. channel.
  1778. Unlike to `org-export-with-backend', this function will
  1779. recursively convert DATA using BACKEND translation table."
  1780. (when (symbolp backend) (setq backend (org-export-get-backend backend)))
  1781. ;; Set-up a new communication channel with translations defined in
  1782. ;; BACKEND as the translate table and a new hash table for
  1783. ;; memoization.
  1784. (let ((new-info
  1785. (org-combine-plists
  1786. info
  1787. (list :back-end backend
  1788. :translate-alist (org-export-get-all-transcoders backend)
  1789. ;; Size of the hash table is reduced since this
  1790. ;; function will probably be used on small trees.
  1791. :exported-data (make-hash-table :test 'eq :size 401)))))
  1792. (prog1 (org-export-data data new-info)
  1793. ;; Preserve `:internal-references', as those do not depend on
  1794. ;; the back-end used; we need to make sure that any new
  1795. ;; reference when the temporary back-end was active gets through
  1796. ;; the default one.
  1797. (plist-put info :internal-references
  1798. (plist-get new-info :internal-references)))))
  1799. (defun org-export-expand (blob contents &optional with-affiliated)
  1800. "Expand a parsed element or object to its original state.
  1801. BLOB is either an element or an object. CONTENTS is its
  1802. contents, as a string or nil.
  1803. When optional argument WITH-AFFILIATED is non-nil, add affiliated
  1804. keywords before output."
  1805. (let ((type (org-element-type blob)))
  1806. (concat (and with-affiliated
  1807. (eq (org-element-class blob) 'element)
  1808. (org-element--interpret-affiliated-keywords blob))
  1809. (funcall (intern (format "org-element-%s-interpreter" type))
  1810. blob contents))))
  1811. ;;; The Filter System
  1812. ;;
  1813. ;; Filters allow end-users to tweak easily the transcoded output.
  1814. ;; They are the functional counterpart of hooks, as every filter in
  1815. ;; a set is applied to the return value of the previous one.
  1816. ;;
  1817. ;; Every set is back-end agnostic. Although, a filter is always
  1818. ;; called, in addition to the string it applies to, with the back-end
  1819. ;; used as argument, so it's easy for the end-user to add back-end
  1820. ;; specific filters in the set. The communication channel, as
  1821. ;; a plist, is required as the third argument.
  1822. ;;
  1823. ;; From the developer side, filters sets can be installed in the
  1824. ;; process with the help of `org-export-define-backend', which
  1825. ;; internally stores filters as an alist. Each association has a key
  1826. ;; among the following symbols and a function or a list of functions
  1827. ;; as value.
  1828. ;;
  1829. ;; - `:filter-options' applies to the property list containing export
  1830. ;; options. Unlike to other filters, functions in this list accept
  1831. ;; two arguments instead of three: the property list containing
  1832. ;; export options and the back-end. Users can set its value through
  1833. ;; `org-export-filter-options-functions' variable.
  1834. ;;
  1835. ;; - `:filter-parse-tree' applies directly to the complete parsed
  1836. ;; tree. Users can set it through
  1837. ;; `org-export-filter-parse-tree-functions' variable.
  1838. ;;
  1839. ;; - `:filter-body' applies to the body of the output, before template
  1840. ;; translator chimes in. Users can set it through
  1841. ;; `org-export-filter-body-functions' variable.
  1842. ;;
  1843. ;; - `:filter-final-output' applies to the final transcoded string.
  1844. ;; Users can set it with `org-export-filter-final-output-functions'
  1845. ;; variable.
  1846. ;;
  1847. ;; - `:filter-plain-text' applies to any string not recognized as Org
  1848. ;; syntax. `org-export-filter-plain-text-functions' allows users to
  1849. ;; configure it.
  1850. ;;
  1851. ;; - `:filter-TYPE' applies on the string returned after an element or
  1852. ;; object of type TYPE has been transcoded. A user can modify
  1853. ;; `org-export-filter-TYPE-functions' to install these filters.
  1854. ;;
  1855. ;; All filters sets are applied with
  1856. ;; `org-export-filter-apply-functions' function. Filters in a set are
  1857. ;; applied in a LIFO fashion. It allows developers to be sure that
  1858. ;; their filters will be applied first.
  1859. ;;
  1860. ;; Filters properties are installed in communication channel with
  1861. ;; `org-export-install-filters' function.
  1862. ;;
  1863. ;; Eventually, two hooks (`org-export-before-processing-hook' and
  1864. ;; `org-export-before-parsing-hook') are run at the beginning of the
  1865. ;; export process and just before parsing to allow for heavy structure
  1866. ;; modifications.
  1867. ;;;; Hooks
  1868. (defvar org-export-before-processing-hook nil
  1869. "Hook run at the beginning of the export process.
  1870. This is run before include keywords and macros are expanded and
  1871. Babel code blocks executed, on a copy of the original buffer
  1872. being exported. Visibility and narrowing are preserved. Point
  1873. is at the beginning of the buffer.
  1874. Every function in this hook will be called with one argument: the
  1875. back-end currently used, as a symbol.")
  1876. (defvar org-export-before-parsing-hook nil
  1877. "Hook run before parsing an export buffer.
  1878. This is run after include keywords and macros have been expanded
  1879. and Babel code blocks executed, on a copy of the original buffer
  1880. being exported. Visibility and narrowing are preserved. Point
  1881. is at the beginning of the buffer.
  1882. Every function in this hook will be called with one argument: the
  1883. back-end currently used, as a symbol.")
  1884. ;;;; Special Filters
  1885. (defvar org-export-filter-options-functions nil
  1886. "List of functions applied to the export options.
  1887. Each filter is called with two arguments: the export options, as
  1888. a plist, and the back-end, as a symbol. It must return
  1889. a property list containing export options.")
  1890. (defvar org-export-filter-parse-tree-functions nil
  1891. "List of functions applied to the parsed tree.
  1892. Each filter is called with three arguments: the parse tree, as
  1893. returned by `org-element-parse-buffer', the back-end, as
  1894. a symbol, and the communication channel, as a plist. It must
  1895. return the modified parse tree to transcode.")
  1896. (defvar org-export-filter-plain-text-functions nil
  1897. "List of functions applied to plain text.
  1898. Each filter is called with three arguments: a string which
  1899. contains no Org syntax, the back-end, as a symbol, and the
  1900. communication channel, as a plist. It must return a string or
  1901. nil.")
  1902. (defvar org-export-filter-body-functions nil
  1903. "List of functions applied to transcoded body.
  1904. Each filter is called with three arguments: a string which
  1905. contains no Org syntax, the back-end, as a symbol, and the
  1906. communication channel, as a plist. It must return a string or
  1907. nil.")
  1908. (defvar org-export-filter-final-output-functions nil
  1909. "List of functions applied to the transcoded string.
  1910. Each filter is called with three arguments: the full transcoded
  1911. string, the back-end, as a symbol, and the communication channel,
  1912. as a plist. It must return a string that will be used as the
  1913. final export output.")
  1914. ;;;; Elements Filters
  1915. (defvar org-export-filter-babel-call-functions nil
  1916. "List of functions applied to a transcoded babel-call.
  1917. Each filter is called with three arguments: the transcoded data,
  1918. as a string, the back-end, as a symbol, and the communication
  1919. channel, as a plist. It must return a string or nil.")
  1920. (defvar org-export-filter-center-block-functions nil
  1921. "List of functions applied to a transcoded center block.
  1922. Each filter is called with three arguments: the transcoded data,
  1923. as a string, the back-end, as a symbol, and the communication
  1924. channel, as a plist. It must return a string or nil.")
  1925. (defvar org-export-filter-clock-functions nil
  1926. "List of functions applied to a transcoded clock.
  1927. Each filter is called with three arguments: the transcoded data,
  1928. as a string, the back-end, as a symbol, and the communication
  1929. channel, as a plist. It must return a string or nil.")
  1930. (defvar org-export-filter-diary-sexp-functions nil
  1931. "List of functions applied to a transcoded diary-sexp.
  1932. Each filter is called with three arguments: the transcoded data,
  1933. as a string, the back-end, as a symbol, and the communication
  1934. channel, as a plist. It must return a string or nil.")
  1935. (defvar org-export-filter-drawer-functions nil
  1936. "List of functions applied to a transcoded drawer.
  1937. Each filter is called with three arguments: the transcoded data,
  1938. as a string, the back-end, as a symbol, and the communication
  1939. channel, as a plist. It must return a string or nil.")
  1940. (defvar org-export-filter-dynamic-block-functions nil
  1941. "List of functions applied to a transcoded dynamic-block.
  1942. Each filter is called with three arguments: the transcoded data,
  1943. as a string, the back-end, as a symbol, and the communication
  1944. channel, as a plist. It must return a string or nil.")
  1945. (defvar org-export-filter-example-block-functions nil
  1946. "List of functions applied to a transcoded example-block.
  1947. Each filter is called with three arguments: the transcoded data,
  1948. as a string, the back-end, as a symbol, and the communication
  1949. channel, as a plist. It must return a string or nil.")
  1950. (defvar org-export-filter-export-block-functions nil
  1951. "List of functions applied to a transcoded export-block.
  1952. Each filter is called with three arguments: the transcoded data,
  1953. as a string, the back-end, as a symbol, and the communication
  1954. channel, as a plist. It must return a string or nil.")
  1955. (defvar org-export-filter-fixed-width-functions nil
  1956. "List of functions applied to a transcoded fixed-width.
  1957. Each filter is called with three arguments: the transcoded data,
  1958. as a string, the back-end, as a symbol, and the communication
  1959. channel, as a plist. It must return a string or nil.")
  1960. (defvar org-export-filter-footnote-definition-functions nil
  1961. "List of functions applied to a transcoded footnote-definition.
  1962. Each filter is called with three arguments: the transcoded data,
  1963. as a string, the back-end, as a symbol, and the communication
  1964. channel, as a plist. It must return a string or nil.")
  1965. (defvar org-export-filter-headline-functions nil
  1966. "List of functions applied to a transcoded headline.
  1967. Each filter is called with three arguments: the transcoded data,
  1968. as a string, the back-end, as a symbol, and the communication
  1969. channel, as a plist. It must return a string or nil.")
  1970. (defvar org-export-filter-horizontal-rule-functions nil
  1971. "List of functions applied to a transcoded horizontal-rule.
  1972. Each filter is called with three arguments: the transcoded data,
  1973. as a string, the back-end, as a symbol, and the communication
  1974. channel, as a plist. It must return a string or nil.")
  1975. (defvar org-export-filter-inlinetask-functions nil
  1976. "List of functions applied to a transcoded inlinetask.
  1977. Each filter is called with three arguments: the transcoded data,
  1978. as a string, the back-end, as a symbol, and the communication
  1979. channel, as a plist. It must return a string or nil.")
  1980. (defvar org-export-filter-item-functions nil
  1981. "List of functions applied to a transcoded item.
  1982. Each filter is called with three arguments: the transcoded data,
  1983. as a string, the back-end, as a symbol, and the communication
  1984. channel, as a plist. It must return a string or nil.")
  1985. (defvar org-export-filter-keyword-functions nil
  1986. "List of functions applied to a transcoded keyword.
  1987. Each filter is called with three arguments: the transcoded data,
  1988. as a string, the back-end, as a symbol, and the communication
  1989. channel, as a plist. It must return a string or nil.")
  1990. (defvar org-export-filter-latex-environment-functions nil
  1991. "List of functions applied to a transcoded latex-environment.
  1992. Each filter is called with three arguments: the transcoded data,
  1993. as a string, the back-end, as a symbol, and the communication
  1994. channel, as a plist. It must return a string or nil.")
  1995. (defvar org-export-filter-node-property-functions nil
  1996. "List of functions applied to a transcoded node-property.
  1997. Each filter is called with three arguments: the transcoded data,
  1998. as a string, the back-end, as a symbol, and the communication
  1999. channel, as a plist. It must return a string or nil.")
  2000. (defvar org-export-filter-paragraph-functions nil
  2001. "List of functions applied to a transcoded paragraph.
  2002. Each filter is called with three arguments: the transcoded data,
  2003. as a string, the back-end, as a symbol, and the communication
  2004. channel, as a plist. It must return a string or nil.")
  2005. (defvar org-export-filter-plain-list-functions nil
  2006. "List of functions applied to a transcoded plain-list.
  2007. Each filter is called with three arguments: the transcoded data,
  2008. as a string, the back-end, as a symbol, and the communication
  2009. channel, as a plist. It must return a string or nil.")
  2010. (defvar org-export-filter-planning-functions nil
  2011. "List of functions applied to a transcoded planning.
  2012. Each filter is called with three arguments: the transcoded data,
  2013. as a string, the back-end, as a symbol, and the communication
  2014. channel, as a plist. It must return a string or nil.")
  2015. (defvar org-export-filter-property-drawer-functions nil
  2016. "List of functions applied to a transcoded property-drawer.
  2017. Each filter is called with three arguments: the transcoded data,
  2018. as a string, the back-end, as a symbol, and the communication
  2019. channel, as a plist. It must return a string or nil.")
  2020. (defvar org-export-filter-quote-block-functions nil
  2021. "List of functions applied to a transcoded quote block.
  2022. Each filter is called with three arguments: the transcoded quote
  2023. data, as a string, the back-end, as a symbol, and the
  2024. communication channel, as a plist. It must return a string or
  2025. nil.")
  2026. (defvar org-export-filter-section-functions nil
  2027. "List of functions applied to a transcoded section.
  2028. Each filter is called with three arguments: the transcoded data,
  2029. as a string, the back-end, as a symbol, and the communication
  2030. channel, as a plist. It must return a string or nil.")
  2031. (defvar org-export-filter-special-block-functions nil
  2032. "List of functions applied to a transcoded special block.
  2033. Each filter is called with three arguments: the transcoded data,
  2034. as a string, the back-end, as a symbol, and the communication
  2035. channel, as a plist. It must return a string or nil.")
  2036. (defvar org-export-filter-src-block-functions nil
  2037. "List of functions applied to a transcoded src-block.
  2038. Each filter is called with three arguments: the transcoded data,
  2039. as a string, the back-end, as a symbol, and the communication
  2040. channel, as a plist. It must return a string or nil.")
  2041. (defvar org-export-filter-table-functions nil
  2042. "List of functions applied to a transcoded table.
  2043. Each filter is called with three arguments: the transcoded data,
  2044. as a string, the back-end, as a symbol, and the communication
  2045. channel, as a plist. It must return a string or nil.")
  2046. (defvar org-export-filter-table-cell-functions nil
  2047. "List of functions applied to a transcoded table-cell.
  2048. Each filter is called with three arguments: the transcoded data,
  2049. as a string, the back-end, as a symbol, and the communication
  2050. channel, as a plist. It must return a string or nil.")
  2051. (defvar org-export-filter-table-row-functions nil
  2052. "List of functions applied to a transcoded table-row.
  2053. Each filter is called with three arguments: the transcoded data,
  2054. as a string, the back-end, as a symbol, and the communication
  2055. channel, as a plist. It must return a string or nil.")
  2056. (defvar org-export-filter-verse-block-functions nil
  2057. "List of functions applied to a transcoded verse block.
  2058. Each filter is called with three arguments: the transcoded data,
  2059. as a string, the back-end, as a symbol, and the communication
  2060. channel, as a plist. It must return a string or nil.")
  2061. ;;;; Objects Filters
  2062. (defvar org-export-filter-bold-functions nil
  2063. "List of functions applied to transcoded bold text.
  2064. Each filter is called with three arguments: the transcoded data,
  2065. as a string, the back-end, as a symbol, and the communication
  2066. channel, as a plist. It must return a string or nil.")
  2067. (defvar org-export-filter-code-functions nil
  2068. "List of functions applied to transcoded code text.
  2069. Each filter is called with three arguments: the transcoded data,
  2070. as a string, the back-end, as a symbol, and the communication
  2071. channel, as a plist. It must return a string or nil.")
  2072. (defvar org-export-filter-entity-functions nil
  2073. "List of functions applied to a transcoded entity.
  2074. Each filter is called with three arguments: the transcoded data,
  2075. as a string, the back-end, as a symbol, and the communication
  2076. channel, as a plist. It must return a string or nil.")
  2077. (defvar org-export-filter-export-snippet-functions nil
  2078. "List of functions applied to a transcoded export-snippet.
  2079. Each filter is called with three arguments: the transcoded data,
  2080. as a string, the back-end, as a symbol, and the communication
  2081. channel, as a plist. It must return a string or nil.")
  2082. (defvar org-export-filter-footnote-reference-functions nil
  2083. "List of functions applied to a transcoded footnote-reference.
  2084. Each filter is called with three arguments: the transcoded data,
  2085. as a string, the back-end, as a symbol, and the communication
  2086. channel, as a plist. It must return a string or nil.")
  2087. (defvar org-export-filter-inline-babel-call-functions nil
  2088. "List of functions applied to a transcoded inline-babel-call.
  2089. Each filter is called with three arguments: the transcoded data,
  2090. as a string, the back-end, as a symbol, and the communication
  2091. channel, as a plist. It must return a string or nil.")
  2092. (defvar org-export-filter-inline-src-block-functions nil
  2093. "List of functions applied to a transcoded inline-src-block.
  2094. Each filter is called with three arguments: the transcoded data,
  2095. as a string, the back-end, as a symbol, and the communication
  2096. channel, as a plist. It must return a string or nil.")
  2097. (defvar org-export-filter-italic-functions nil
  2098. "List of functions applied to transcoded italic text.
  2099. Each filter is called with three arguments: the transcoded data,
  2100. as a string, the back-end, as a symbol, and the communication
  2101. channel, as a plist. It must return a string or nil.")
  2102. (defvar org-export-filter-latex-fragment-functions nil
  2103. "List of functions applied to a transcoded latex-fragment.
  2104. Each filter is called with three arguments: the transcoded data,
  2105. as a string, the back-end, as a symbol, and the communication
  2106. channel, as a plist. It must return a string or nil.")
  2107. (defvar org-export-filter-line-break-functions nil
  2108. "List of functions applied to a transcoded line-break.
  2109. Each filter is called with three arguments: the transcoded data,
  2110. as a string, the back-end, as a symbol, and the communication
  2111. channel, as a plist. It must return a string or nil.")
  2112. (defvar org-export-filter-link-functions nil
  2113. "List of functions applied to a transcoded link.
  2114. Each filter is called with three arguments: the transcoded data,
  2115. as a string, the back-end, as a symbol, and the communication
  2116. channel, as a plist. It must return a string or nil.")
  2117. (defvar org-export-filter-radio-target-functions nil
  2118. "List of functions applied to a transcoded radio-target.
  2119. Each filter is called with three arguments: the transcoded data,
  2120. as a string, the back-end, as a symbol, and the communication
  2121. channel, as a plist. It must return a string or nil.")
  2122. (defvar org-export-filter-statistics-cookie-functions nil
  2123. "List of functions applied to a transcoded statistics-cookie.
  2124. Each filter is called with three arguments: the transcoded data,
  2125. as a string, the back-end, as a symbol, and the communication
  2126. channel, as a plist. It must return a string or nil.")
  2127. (defvar org-export-filter-strike-through-functions nil
  2128. "List of functions applied to transcoded strike-through text.
  2129. Each filter is called with three arguments: the transcoded data,
  2130. as a string, the back-end, as a symbol, and the communication
  2131. channel, as a plist. It must return a string or nil.")
  2132. (defvar org-export-filter-subscript-functions nil
  2133. "List of functions applied to a transcoded subscript.
  2134. Each filter is called with three arguments: the transcoded data,
  2135. as a string, the back-end, as a symbol, and the communication
  2136. channel, as a plist. It must return a string or nil.")
  2137. (defvar org-export-filter-superscript-functions nil
  2138. "List of functions applied to a transcoded superscript.
  2139. Each filter is called with three arguments: the transcoded data,
  2140. as a string, the back-end, as a symbol, and the communication
  2141. channel, as a plist. It must return a string or nil.")
  2142. (defvar org-export-filter-target-functions nil
  2143. "List of functions applied to a transcoded target.
  2144. Each filter is called with three arguments: the transcoded data,
  2145. as a string, the back-end, as a symbol, and the communication
  2146. channel, as a plist. It must return a string or nil.")
  2147. (defvar org-export-filter-timestamp-functions nil
  2148. "List of functions applied to a transcoded timestamp.
  2149. Each filter is called with three arguments: the transcoded data,
  2150. as a string, the back-end, as a symbol, and the communication
  2151. channel, as a plist. It must return a string or nil.")
  2152. (defvar org-export-filter-underline-functions nil
  2153. "List of functions applied to transcoded underline text.
  2154. Each filter is called with three arguments: the transcoded data,
  2155. as a string, the back-end, as a symbol, and the communication
  2156. channel, as a plist. It must return a string or nil.")
  2157. (defvar org-export-filter-verbatim-functions nil
  2158. "List of functions applied to transcoded verbatim text.
  2159. Each filter is called with three arguments: the transcoded data,
  2160. as a string, the back-end, as a symbol, and the communication
  2161. channel, as a plist. It must return a string or nil.")
  2162. ;;;; Filters Tools
  2163. ;;
  2164. ;; Internal function `org-export-install-filters' installs filters
  2165. ;; hard-coded in back-ends (developer filters) and filters from global
  2166. ;; variables (user filters) in the communication channel.
  2167. ;;
  2168. ;; Internal function `org-export-filter-apply-functions' takes care
  2169. ;; about applying each filter in order to a given data. It ignores
  2170. ;; filters returning a nil value but stops whenever a filter returns
  2171. ;; an empty string.
  2172. (defun org-export-filter-apply-functions (filters value info)
  2173. "Call every function in FILTERS.
  2174. Functions are called with three arguments: a value, the export
  2175. back-end name and the communication channel. First function in
  2176. FILTERS is called with VALUE as its first argument. Second
  2177. function in FILTERS is called with the previous result as its
  2178. value, etc.
  2179. Functions returning nil are skipped. Any function returning the
  2180. empty string ends the process, which returns the empty string.
  2181. Call is done in a LIFO fashion, to be sure that developer
  2182. specified filters, if any, are called first."
  2183. (catch :exit
  2184. (let* ((backend (plist-get info :back-end))
  2185. (backend-name (and backend (org-export-backend-name backend))))
  2186. (dolist (filter filters value)
  2187. (let ((result (funcall filter value backend-name info)))
  2188. (cond ((not result))
  2189. ((equal result "") (throw :exit ""))
  2190. (t (setq value result))))))))
  2191. (defun org-export-install-filters (info)
  2192. "Install filters properties in communication channel.
  2193. INFO is a plist containing the current communication channel.
  2194. Return the updated communication channel."
  2195. (let (plist)
  2196. ;; Install user-defined filters with `org-export-filters-alist'
  2197. ;; and filters already in INFO (through ext-plist mechanism).
  2198. (dolist (p org-export-filters-alist)
  2199. (let* ((prop (car p))
  2200. (info-value (plist-get info prop))
  2201. (default-value (symbol-value (cdr p))))
  2202. (setq plist
  2203. (plist-put plist prop
  2204. ;; Filters in INFO will be called
  2205. ;; before those user provided.
  2206. (append (if (listp info-value) info-value
  2207. (list info-value))
  2208. default-value)))))
  2209. ;; Prepend back-end specific filters to that list.
  2210. (dolist (p (org-export-get-all-filters (plist-get info :back-end)))
  2211. ;; Single values get consed, lists are appended.
  2212. (let ((key (car p)) (value (cdr p)))
  2213. (when value
  2214. (setq plist
  2215. (plist-put
  2216. plist key
  2217. (if (atom value) (cons value (plist-get plist key))
  2218. (append value (plist-get plist key))))))))
  2219. ;; Return new communication channel.
  2220. (org-combine-plists info plist)))
  2221. ;;; Core functions
  2222. ;;
  2223. ;; This is the room for the main function, `org-export-as', along with
  2224. ;; its derivative, `org-export-string-as'.
  2225. ;; `org-export--copy-to-kill-ring-p' determines if output of these
  2226. ;; function should be added to kill ring.
  2227. ;;
  2228. ;; Note that `org-export-as' doesn't really parse the current buffer,
  2229. ;; but a copy of it (with the same buffer-local variables and
  2230. ;; visibility), where macros and include keywords are expanded and
  2231. ;; Babel blocks are executed, if appropriate.
  2232. ;; `org-export-with-buffer-copy' macro prepares that copy.
  2233. ;;
  2234. ;; File inclusion is taken care of by
  2235. ;; `org-export-expand-include-keyword' and
  2236. ;; `org-export--prepare-file-contents'. Structure wise, including
  2237. ;; a whole Org file in a buffer often makes little sense. For
  2238. ;; example, if the file contains a headline and the include keyword
  2239. ;; was within an item, the item should contain the headline. That's
  2240. ;; why file inclusion should be done before any structure can be
  2241. ;; associated to the file, that is before parsing.
  2242. ;;
  2243. ;; `org-export-insert-default-template' is a command to insert
  2244. ;; a default template (or a back-end specific template) at point or in
  2245. ;; current subtree.
  2246. (defun org-export-copy-buffer ()
  2247. "Return a copy of the current buffer.
  2248. The copy preserves Org buffer-local variables, visibility and
  2249. narrowing."
  2250. (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
  2251. (new-buf (generate-new-buffer (buffer-name))))
  2252. (with-current-buffer new-buf
  2253. (funcall copy-buffer-fun)
  2254. (set-buffer-modified-p nil))
  2255. new-buf))
  2256. (defmacro org-export-with-buffer-copy (&rest body)
  2257. "Apply BODY in a copy of the current buffer.
  2258. The copy preserves local variables, visibility and contents of
  2259. the original buffer. Point is at the beginning of the buffer
  2260. when BODY is applied."
  2261. (declare (debug t))
  2262. (org-with-gensyms (buf-copy)
  2263. `(let ((,buf-copy (org-export-copy-buffer)))
  2264. (unwind-protect
  2265. (with-current-buffer ,buf-copy
  2266. (goto-char (point-min))
  2267. (progn ,@body))
  2268. (and (buffer-live-p ,buf-copy)
  2269. ;; Kill copy without confirmation.
  2270. (progn (with-current-buffer ,buf-copy
  2271. (restore-buffer-modified-p nil))
  2272. (kill-buffer ,buf-copy)))))))
  2273. (defun org-export--generate-copy-script (buffer)
  2274. "Generate a function duplicating BUFFER.
  2275. The copy will preserve local variables, visibility, contents and
  2276. narrowing of the original buffer. If a region was active in
  2277. BUFFER, contents will be narrowed to that region instead.
  2278. The resulting function can be evaluated at a later time, from
  2279. another buffer, effectively cloning the original buffer there.
  2280. The function assumes BUFFER's major mode is `org-mode'."
  2281. (with-current-buffer buffer
  2282. `(lambda ()
  2283. (let ((inhibit-modification-hooks t))
  2284. ;; Set major mode. Ignore `org-mode-hook' as it has been run
  2285. ;; already in BUFFER.
  2286. (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
  2287. ;; Copy specific buffer local variables and variables set
  2288. ;; through BIND keywords.
  2289. ,@(let ((bound-variables (org-export--list-bound-variables))
  2290. vars)
  2291. (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
  2292. (when (consp entry)
  2293. (let ((var (car entry))
  2294. (val (cdr entry)))
  2295. (and (not (memq var org-export-ignored-local-variables))
  2296. (or (memq var
  2297. '(default-directory
  2298. buffer-file-name
  2299. buffer-file-coding-system))
  2300. (assq var bound-variables)
  2301. (string-match "^\\(org-\\|orgtbl-\\)"
  2302. (symbol-name var)))
  2303. ;; Skip unreadable values, as they cannot be
  2304. ;; sent to external process.
  2305. (or (not val) (ignore-errors (read (format "%S" val))))
  2306. (push `(set (make-local-variable (quote ,var))
  2307. (quote ,val))
  2308. vars))))))
  2309. ;; Whole buffer contents.
  2310. (insert
  2311. ,(org-with-wide-buffer
  2312. (buffer-substring-no-properties
  2313. (point-min) (point-max))))
  2314. ;; Narrowing.
  2315. ,(if (org-region-active-p)
  2316. `(narrow-to-region ,(region-beginning) ,(region-end))
  2317. `(narrow-to-region ,(point-min) ,(point-max)))
  2318. ;; Current position of point.
  2319. (goto-char ,(point))
  2320. ;; Overlays with invisible property.
  2321. ,@(let (ov-set)
  2322. (dolist (ov (overlays-in (point-min) (point-max)) ov-set)
  2323. (let ((invis-prop (overlay-get ov 'invisible)))
  2324. (when invis-prop
  2325. (push `(overlay-put
  2326. (make-overlay ,(overlay-start ov)
  2327. ,(overlay-end ov))
  2328. 'invisible (quote ,invis-prop))
  2329. ov-set)))))))))
  2330. (defun org-export--delete-comments ()
  2331. "Delete commented areas in the buffer.
  2332. Commented areas are comments, comment blocks, commented trees and
  2333. inlinetasks. Trailing blank lines after a comment or a comment
  2334. block are removed, as long as it doesn't alter the structure of
  2335. the document. Narrowing, if any, is ignored."
  2336. (org-with-wide-buffer
  2337. (goto-char (point-min))
  2338. (let* ((case-fold-search t)
  2339. (comment-re "^[ \t]*#\\(?: \\|$\\|\\+end_comment\\)")
  2340. (regexp (concat org-outline-regexp-bol ".*" org-comment-string "\\|"
  2341. comment-re)))
  2342. (while (re-search-forward regexp nil t)
  2343. (let ((element (org-element-at-point)))
  2344. (pcase (org-element-type element)
  2345. ((or `headline `inlinetask)
  2346. (when (org-element-property :commentedp element)
  2347. (delete-region (org-element-property :begin element)
  2348. (org-element-property :end element))))
  2349. ((or `comment `comment-block)
  2350. (let* ((parent (org-element-property :parent element))
  2351. (start (org-element-property :begin element))
  2352. (end (org-element-property :end element))
  2353. ;; We remove trailing blank lines. Doing so could
  2354. ;; modify the structure of the document. Therefore
  2355. ;; we ensure that any comment between elements is
  2356. ;; replaced with one empty line, so as to keep them
  2357. ;; separated.
  2358. (add-blank?
  2359. (save-excursion
  2360. (goto-char start)
  2361. (not (or (bobp)
  2362. (eq (org-element-property :contents-begin parent)
  2363. start)
  2364. (eq (org-element-property :contents-end parent)
  2365. end)
  2366. (progn
  2367. (forward-line -1)
  2368. (or (looking-at-p "^[ \t]*$")
  2369. (org-with-limited-levels
  2370. (org-at-heading-p)))))))))
  2371. (delete-region start end)
  2372. (when add-blank? (insert "\n"))))))))))
  2373. (defun org-export--prune-tree (data info)
  2374. "Prune non exportable elements from DATA.
  2375. DATA is the parse tree to traverse. INFO is the plist holding
  2376. export info. Also set `:ignore-list' in INFO to a list of
  2377. objects which should be ignored during export, but not removed
  2378. from tree."
  2379. (letrec ((ignore nil)
  2380. ;; First find trees containing a select tag, if any.
  2381. (selected (org-export--selected-trees data info))
  2382. (walk-data
  2383. (lambda (data)
  2384. ;; Prune non-exportable elements and objects from tree.
  2385. ;; As a special case, special rows and cells from tables
  2386. ;; are stored in IGNORE, as they still need to be
  2387. ;; accessed during export.
  2388. (when data
  2389. (let ((type (org-element-type data)))
  2390. (if (org-export--skip-p data info selected)
  2391. (if (memq type '(table-cell table-row)) (push data ignore)
  2392. (org-element-extract-element data))
  2393. (if (and (eq type 'headline)
  2394. (eq (plist-get info :with-archived-trees)
  2395. 'headline)
  2396. (org-element-property :archivedp data))
  2397. ;; If headline is archived but tree below has
  2398. ;; to be skipped, remove contents.
  2399. (org-element-set-contents data)
  2400. ;; Move into recursive objects/elements.
  2401. (mapc walk-data (org-element-contents data)))
  2402. ;; Move into secondary string, if any.
  2403. (dolist (p (cdr (assq type
  2404. org-element-secondary-value-alist)))
  2405. (mapc walk-data (org-element-property p data))))))))
  2406. (definitions
  2407. ;; Collect definitions before possibly pruning them so as
  2408. ;; to avoid parsing them again if they are required.
  2409. (org-element-map data '(footnote-definition footnote-reference)
  2410. (lambda (f)
  2411. (cond
  2412. ((eq (org-element-type f) 'footnote-definition) f)
  2413. ((eq (org-element-property :type f) 'standard) nil)
  2414. (t (let ((label (org-element-property :label f)))
  2415. (when label ;Skip anonymous references.
  2416. (apply
  2417. #'org-element-create
  2418. 'footnote-definition `(:label ,label :post-blank 1)
  2419. (org-element-contents f))))))))))
  2420. ;; If a select tag is active, also ignore the section before the
  2421. ;; first headline, if any.
  2422. (when selected
  2423. (let ((first-element (car (org-element-contents data))))
  2424. (when (eq (org-element-type first-element) 'section)
  2425. (org-element-extract-element first-element))))
  2426. ;; Prune tree and communication channel.
  2427. (funcall walk-data data)
  2428. (dolist (entry (append
  2429. ;; Priority is given to back-end specific options.
  2430. (org-export-get-all-options (plist-get info :back-end))
  2431. org-export-options-alist))
  2432. (when (eq (nth 4 entry) 'parse)
  2433. (funcall walk-data (plist-get info (car entry)))))
  2434. (let ((missing (org-export--missing-definitions data definitions)))
  2435. (funcall walk-data missing)
  2436. (org-export--install-footnote-definitions missing data))
  2437. ;; Eventually set `:ignore-list'.
  2438. (plist-put info :ignore-list ignore)))
  2439. (defun org-export--missing-definitions (tree definitions)
  2440. "List footnote definitions missing from TREE.
  2441. Missing definitions are searched within DEFINITIONS, which is
  2442. a list of footnote definitions or in the widened buffer."
  2443. (let* ((list-labels
  2444. (lambda (data)
  2445. ;; List all footnote labels encountered in DATA. Inline
  2446. ;; footnote references are ignored.
  2447. (org-element-map data 'footnote-reference
  2448. (lambda (reference)
  2449. (and (eq (org-element-property :type reference) 'standard)
  2450. (org-element-property :label reference))))))
  2451. defined undefined missing-definitions)
  2452. ;; Partition DIRECT-REFERENCES between DEFINED and UNDEFINED
  2453. ;; references.
  2454. (let ((known-definitions
  2455. (org-element-map tree '(footnote-reference footnote-definition)
  2456. (lambda (f)
  2457. (and (or (eq (org-element-type f) 'footnote-definition)
  2458. (eq (org-element-property :type f) 'inline))
  2459. (org-element-property :label f)))))
  2460. seen)
  2461. (dolist (l (funcall list-labels tree))
  2462. (cond ((member l seen))
  2463. ((member l known-definitions) (push l defined))
  2464. (t (push l undefined)))))
  2465. ;; Complete MISSING-DEFINITIONS by finding the definition of every
  2466. ;; undefined label, first by looking into DEFINITIONS, then by
  2467. ;; searching the widened buffer. This is a recursive process
  2468. ;; since definitions found can themselves contain an undefined
  2469. ;; reference.
  2470. (while undefined
  2471. (let* ((label (pop undefined))
  2472. (definition
  2473. (cond
  2474. ((cl-some
  2475. (lambda (d) (and (equal (org-element-property :label d) label)
  2476. d))
  2477. definitions))
  2478. ((pcase (org-footnote-get-definition label)
  2479. (`(,_ ,beg . ,_)
  2480. (org-with-wide-buffer
  2481. (goto-char beg)
  2482. (let ((datum (org-element-context)))
  2483. (if (eq (org-element-type datum) 'footnote-reference)
  2484. datum
  2485. ;; Parse definition with contents.
  2486. (save-restriction
  2487. (narrow-to-region
  2488. (org-element-property :begin datum)
  2489. (org-element-property :end datum))
  2490. (org-element-map (org-element-parse-buffer)
  2491. 'footnote-definition #'identity nil t))))))
  2492. (_ nil)))
  2493. (t (user-error "Definition not found for footnote %s" label)))))
  2494. (push label defined)
  2495. (push definition missing-definitions)
  2496. ;; Look for footnote references within DEFINITION, since
  2497. ;; we may need to also find their definition.
  2498. (dolist (l (funcall list-labels definition))
  2499. (unless (or (member l defined) ;Known label
  2500. (member l undefined)) ;Processed later
  2501. (push l undefined)))))
  2502. ;; MISSING-DEFINITIONS may contain footnote references with inline
  2503. ;; definitions. Make sure those are changed into real footnote
  2504. ;; definitions.
  2505. (mapcar (lambda (d)
  2506. (if (eq (org-element-type d) 'footnote-definition) d
  2507. (let ((label (org-element-property :label d)))
  2508. (apply #'org-element-create
  2509. 'footnote-definition `(:label ,label :post-blank 1)
  2510. (org-element-contents d)))))
  2511. missing-definitions)))
  2512. (defun org-export--install-footnote-definitions (definitions tree)
  2513. "Install footnote definitions in tree.
  2514. DEFINITIONS is the list of footnote definitions to install. TREE
  2515. is the parse tree.
  2516. If there is a footnote section in TREE, definitions found are
  2517. appended to it. If `org-footnote-section' is non-nil, a new
  2518. footnote section containing all definitions is inserted in TREE.
  2519. Otherwise, definitions are appended at the end of the section
  2520. containing their first reference."
  2521. (cond
  2522. ((null definitions))
  2523. ;; If there is a footnote section, insert definitions there.
  2524. ((let ((footnote-section
  2525. (org-element-map tree 'headline
  2526. (lambda (h) (and (org-element-property :footnote-section-p h) h))
  2527. nil t)))
  2528. (and footnote-section
  2529. (apply #'org-element-adopt-elements
  2530. footnote-section
  2531. (nreverse definitions)))))
  2532. ;; If there should be a footnote section, create one containing all
  2533. ;; the definitions at the end of the tree.
  2534. (org-footnote-section
  2535. (org-element-adopt-elements
  2536. tree
  2537. (org-element-create 'headline
  2538. (list :footnote-section-p t
  2539. :level 1
  2540. :title org-footnote-section)
  2541. (apply #'org-element-create
  2542. 'section
  2543. nil
  2544. (nreverse definitions)))))
  2545. ;; Otherwise add each definition at the end of the section where it
  2546. ;; is first referenced.
  2547. (t
  2548. (letrec ((seen nil)
  2549. (insert-definitions
  2550. (lambda (data)
  2551. ;; Insert footnote definitions in the same section as
  2552. ;; their first reference in DATA.
  2553. (org-element-map data 'footnote-reference
  2554. (lambda (reference)
  2555. (when (eq (org-element-property :type reference) 'standard)
  2556. (let ((label (org-element-property :label reference)))
  2557. (unless (member label seen)
  2558. (push label seen)
  2559. (let ((definition
  2560. (cl-some
  2561. (lambda (d)
  2562. (and (equal (org-element-property :label d)
  2563. label)
  2564. d))
  2565. definitions)))
  2566. (org-element-adopt-elements
  2567. (org-element-lineage reference '(section))
  2568. definition)
  2569. ;; Also insert definitions for nested
  2570. ;; references, if any.
  2571. (funcall insert-definitions definition))))))))))
  2572. (funcall insert-definitions tree)))))
  2573. (defun org-export--remove-uninterpreted-data (data info)
  2574. "Change uninterpreted elements back into Org syntax.
  2575. DATA is the parse tree. INFO is a plist containing export
  2576. options. Each uninterpreted element or object is changed back
  2577. into a string. Contents, if any, are not modified. The parse
  2578. tree is modified by side effect."
  2579. (org-export--remove-uninterpreted-data-1 data info)
  2580. (dolist (entry org-export-options-alist)
  2581. (when (eq (nth 4 entry) 'parse)
  2582. (let ((p (car entry)))
  2583. (plist-put info
  2584. p
  2585. (org-export--remove-uninterpreted-data-1
  2586. (plist-get info p)
  2587. info))))))
  2588. (defun org-export--remove-uninterpreted-data-1 (data info)
  2589. "Change uninterpreted elements back into Org syntax.
  2590. DATA is a parse tree or a secondary string. INFO is a plist
  2591. containing export options. It is modified by side effect and
  2592. returned by the function."
  2593. (org-element-map data
  2594. '(entity bold italic latex-environment latex-fragment strike-through
  2595. subscript superscript underline)
  2596. (lambda (blob)
  2597. (let ((new
  2598. (cl-case (org-element-type blob)
  2599. ;; ... entities...
  2600. (entity
  2601. (and (not (plist-get info :with-entities))
  2602. (list (concat
  2603. (org-export-expand blob nil)
  2604. (make-string
  2605. (or (org-element-property :post-blank blob) 0)
  2606. ?\s)))))
  2607. ;; ... emphasis...
  2608. ((bold italic strike-through underline)
  2609. (and (not (plist-get info :with-emphasize))
  2610. (let ((marker (cl-case (org-element-type blob)
  2611. (bold "*")
  2612. (italic "/")
  2613. (strike-through "+")
  2614. (underline "_"))))
  2615. (append
  2616. (list marker)
  2617. (org-element-contents blob)
  2618. (list (concat
  2619. marker
  2620. (make-string
  2621. (or (org-element-property :post-blank blob)
  2622. 0)
  2623. ?\s)))))))
  2624. ;; ... LaTeX environments and fragments...
  2625. ((latex-environment latex-fragment)
  2626. (and (eq (plist-get info :with-latex) 'verbatim)
  2627. (list (org-export-expand blob nil))))
  2628. ;; ... sub/superscripts...
  2629. ((subscript superscript)
  2630. (let ((sub/super-p (plist-get info :with-sub-superscript))
  2631. (bracketp (org-element-property :use-brackets-p blob)))
  2632. (and (or (not sub/super-p)
  2633. (and (eq sub/super-p '{}) (not bracketp)))
  2634. (append
  2635. (list (concat
  2636. (if (eq (org-element-type blob) 'subscript)
  2637. "_"
  2638. "^")
  2639. (and bracketp "{")))
  2640. (org-element-contents blob)
  2641. (list (concat
  2642. (and bracketp "}")
  2643. (and (org-element-property :post-blank blob)
  2644. (make-string
  2645. (org-element-property :post-blank blob)
  2646. ?\s)))))))))))
  2647. (when new
  2648. ;; Splice NEW at BLOB location in parse tree.
  2649. (dolist (e new (org-element-extract-element blob))
  2650. (unless (equal e "") (org-element-insert-before e blob))))))
  2651. info nil nil t)
  2652. ;; Return modified parse tree.
  2653. data)
  2654. ;;;###autoload
  2655. (defun org-export-as
  2656. (backend &optional subtreep visible-only body-only ext-plist)
  2657. "Transcode current Org buffer into BACKEND code.
  2658. BACKEND is either an export back-end, as returned by, e.g.,
  2659. `org-export-create-backend', or a symbol referring to
  2660. a registered back-end.
  2661. If narrowing is active in the current buffer, only transcode its
  2662. narrowed part.
  2663. If a region is active, transcode that region.
  2664. When optional argument SUBTREEP is non-nil, transcode the
  2665. sub-tree at point, extracting information from the headline
  2666. properties first.
  2667. When optional argument VISIBLE-ONLY is non-nil, don't export
  2668. contents of hidden elements.
  2669. When optional argument BODY-ONLY is non-nil, only return body
  2670. code, without surrounding template.
  2671. Optional argument EXT-PLIST, when provided, is a property list
  2672. with external parameters overriding Org default settings, but
  2673. still inferior to file-local settings.
  2674. Return code as a string."
  2675. (when (symbolp backend) (setq backend (org-export-get-backend backend)))
  2676. (org-export-barf-if-invalid-backend backend)
  2677. (save-excursion
  2678. (save-restriction
  2679. ;; Narrow buffer to an appropriate region or subtree for
  2680. ;; parsing. If parsing subtree, be sure to remove main
  2681. ;; headline, planning data and property drawer.
  2682. (cond ((org-region-active-p)
  2683. (narrow-to-region (region-beginning) (region-end)))
  2684. (subtreep
  2685. (org-narrow-to-subtree)
  2686. (goto-char (point-min))
  2687. (org-end-of-meta-data)
  2688. (narrow-to-region (point) (point-max))))
  2689. ;; Initialize communication channel with original buffer
  2690. ;; attributes, unavailable in its copy.
  2691. (let* ((org-export-current-backend (org-export-backend-name backend))
  2692. (info (org-combine-plists
  2693. (org-export--get-export-attributes
  2694. backend subtreep visible-only body-only)
  2695. (org-export--get-buffer-attributes)))
  2696. (parsed-keywords
  2697. (delq nil
  2698. (mapcar (lambda (o) (and (eq (nth 4 o) 'parse) (nth 1 o)))
  2699. (append (org-export-get-all-options backend)
  2700. org-export-options-alist))))
  2701. tree)
  2702. ;; Update communication channel and get parse tree. Buffer
  2703. ;; isn't parsed directly. Instead, all buffer modifications
  2704. ;; and consequent parsing are undertaken in a temporary copy.
  2705. (org-export-with-buffer-copy
  2706. ;; Run first hook with current back-end's name as argument.
  2707. (run-hook-with-args 'org-export-before-processing-hook
  2708. (org-export-backend-name backend))
  2709. ;; Include files, delete comments and expand macros.
  2710. (org-export-expand-include-keyword)
  2711. (org-export--delete-comments)
  2712. (org-macro-initialize-templates)
  2713. (org-macro-replace-all
  2714. (append org-macro-templates org-export-global-macros)
  2715. nil parsed-keywords)
  2716. ;; Refresh buffer properties and radio targets after
  2717. ;; potentially invasive previous changes. Likewise, do it
  2718. ;; again after executing Babel code.
  2719. (org-set-regexps-and-options)
  2720. (org-update-radio-target-regexp)
  2721. (when org-export-use-babel
  2722. (org-babel-exp-process-buffer)
  2723. (org-set-regexps-and-options)
  2724. (org-update-radio-target-regexp))
  2725. ;; Run last hook with current back-end's name as argument.
  2726. ;; Update buffer properties and radio targets one last time
  2727. ;; before parsing.
  2728. (goto-char (point-min))
  2729. (save-excursion
  2730. (run-hook-with-args 'org-export-before-parsing-hook
  2731. (org-export-backend-name backend)))
  2732. (org-set-regexps-and-options)
  2733. (org-update-radio-target-regexp)
  2734. ;; Update communication channel with environment. Also
  2735. ;; install user's and developer's filters.
  2736. (setq info
  2737. (org-export-install-filters
  2738. (org-combine-plists
  2739. info (org-export-get-environment backend subtreep ext-plist))))
  2740. ;; Call options filters and update export options. We do not
  2741. ;; use `org-export-filter-apply-functions' here since the
  2742. ;; arity of such filters is different.
  2743. (let ((backend-name (org-export-backend-name backend)))
  2744. (dolist (filter (plist-get info :filter-options))
  2745. (let ((result (funcall filter info backend-name)))
  2746. (when result (setq info result)))))
  2747. ;; Expand export-specific set of macros: {{{author}}},
  2748. ;; {{{date(FORMAT)}}}, {{{email}}} and {{{title}}}. It must
  2749. ;; be done once regular macros have been expanded, since
  2750. ;; parsed keywords may contain one of them.
  2751. (org-macro-replace-all
  2752. (list
  2753. (cons "author" (org-element-interpret-data (plist-get info :author)))
  2754. (cons "date"
  2755. (let* ((date (plist-get info :date))
  2756. (value (or (org-element-interpret-data date) "")))
  2757. (if (and (consp date)
  2758. (not (cdr date))
  2759. (eq (org-element-type (car date)) 'timestamp))
  2760. (format "(eval (if (org-string-nw-p \"$1\") %s %S))"
  2761. (format "(org-timestamp-format '%S \"$1\")"
  2762. (org-element-copy (car date)))
  2763. value)
  2764. value)))
  2765. (cons "email" (org-element-interpret-data (plist-get info :email)))
  2766. (cons "title" (org-element-interpret-data (plist-get info :title)))
  2767. (cons "results" "$1"))
  2768. 'finalize
  2769. parsed-keywords)
  2770. ;; Parse buffer.
  2771. (setq tree (org-element-parse-buffer nil visible-only))
  2772. ;; Prune tree from non-exported elements and transform
  2773. ;; uninterpreted elements or objects in both parse tree and
  2774. ;; communication channel.
  2775. (org-export--prune-tree tree info)
  2776. (org-export--remove-uninterpreted-data tree info)
  2777. ;; Call parse tree filters.
  2778. (setq tree
  2779. (org-export-filter-apply-functions
  2780. (plist-get info :filter-parse-tree) tree info))
  2781. ;; Now tree is complete, compute its properties and add them
  2782. ;; to communication channel.
  2783. (setq info (org-export--collect-tree-properties tree info))
  2784. ;; Eventually transcode TREE. Wrap the resulting string into
  2785. ;; a template.
  2786. (let* ((body (org-element-normalize-string
  2787. (or (org-export-data tree info) "")))
  2788. (inner-template (cdr (assq 'inner-template
  2789. (plist-get info :translate-alist))))
  2790. (full-body (org-export-filter-apply-functions
  2791. (plist-get info :filter-body)
  2792. (if (not (functionp inner-template)) body
  2793. (funcall inner-template body info))
  2794. info))
  2795. (template (cdr (assq 'template
  2796. (plist-get info :translate-alist)))))
  2797. ;; Remove all text properties since they cannot be
  2798. ;; retrieved from an external process. Finally call
  2799. ;; final-output filter and return result.
  2800. (org-no-properties
  2801. (org-export-filter-apply-functions
  2802. (plist-get info :filter-final-output)
  2803. (if (or (not (functionp template)) body-only) full-body
  2804. (funcall template full-body info))
  2805. info))))))))
  2806. ;;;###autoload
  2807. (defun org-export-string-as (string backend &optional body-only ext-plist)
  2808. "Transcode STRING into BACKEND code.
  2809. BACKEND is either an export back-end, as returned by, e.g.,
  2810. `org-export-create-backend', or a symbol referring to
  2811. a registered back-end.
  2812. When optional argument BODY-ONLY is non-nil, only return body
  2813. code, without preamble nor postamble.
  2814. Optional argument EXT-PLIST, when provided, is a property list
  2815. with external parameters overriding Org default settings, but
  2816. still inferior to file-local settings.
  2817. Return code as a string."
  2818. (with-temp-buffer
  2819. (insert string)
  2820. (let ((org-inhibit-startup t)) (org-mode))
  2821. (org-export-as backend nil nil body-only ext-plist)))
  2822. ;;;###autoload
  2823. (defun org-export-replace-region-by (backend)
  2824. "Replace the active region by its export to BACKEND.
  2825. BACKEND is either an export back-end, as returned by, e.g.,
  2826. `org-export-create-backend', or a symbol referring to
  2827. a registered back-end."
  2828. (unless (org-region-active-p) (user-error "No active region to replace"))
  2829. (insert
  2830. (org-export-string-as
  2831. (delete-and-extract-region (region-beginning) (region-end)) backend t)))
  2832. ;;;###autoload
  2833. (defun org-export-insert-default-template (&optional backend subtreep)
  2834. "Insert all export keywords with default values at beginning of line.
  2835. BACKEND is a symbol referring to the name of a registered export
  2836. back-end, for which specific export options should be added to
  2837. the template, or `default' for default template. When it is nil,
  2838. the user will be prompted for a category.
  2839. If SUBTREEP is non-nil, export configuration will be set up
  2840. locally for the subtree through node properties."
  2841. (interactive)
  2842. (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
  2843. (when (and subtreep (org-before-first-heading-p))
  2844. (user-error "No subtree to set export options for"))
  2845. (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
  2846. (backend
  2847. (or backend
  2848. (intern
  2849. (org-completing-read
  2850. "Options category: "
  2851. (cons "default"
  2852. (mapcar (lambda (b)
  2853. (symbol-name (org-export-backend-name b)))
  2854. org-export-registered-backends))
  2855. nil t))))
  2856. options keywords)
  2857. ;; Populate OPTIONS and KEYWORDS.
  2858. (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
  2859. ((org-export-backend-p backend)
  2860. (org-export-backend-options backend))
  2861. (t (org-export-backend-options
  2862. (org-export-get-backend backend)))))
  2863. (let ((keyword (nth 1 entry))
  2864. (option (nth 2 entry)))
  2865. (cond
  2866. (keyword (unless (assoc keyword keywords)
  2867. (let ((value
  2868. (if (eq (nth 4 entry) 'split)
  2869. (mapconcat #'identity (eval (nth 3 entry)) " ")
  2870. (eval (nth 3 entry)))))
  2871. (push (cons keyword value) keywords))))
  2872. (option (unless (assoc option options)
  2873. (push (cons option (eval (nth 3 entry))) options))))))
  2874. ;; Move to an appropriate location in order to insert options.
  2875. (unless subtreep (beginning-of-line))
  2876. ;; First (multiple) OPTIONS lines. Never go past fill-column.
  2877. (when options
  2878. (let ((items
  2879. (mapcar
  2880. #'(lambda (opt) (format "%s:%S" (car opt) (cdr opt)))
  2881. (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
  2882. (if subtreep
  2883. (org-entry-put
  2884. node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
  2885. (while items
  2886. (insert "#+OPTIONS:")
  2887. (let ((width 10))
  2888. (while (and items
  2889. (< (+ width (length (car items)) 1) fill-column))
  2890. (let ((item (pop items)))
  2891. (insert " " item)
  2892. (cl-incf width (1+ (length item))))))
  2893. (insert "\n")))))
  2894. ;; Then the rest of keywords, in the order specified in either
  2895. ;; `org-export-options-alist' or respective export back-ends.
  2896. (dolist (key (nreverse keywords))
  2897. (let ((val (cond ((equal (car key) "DATE")
  2898. (or (cdr key)
  2899. (with-temp-buffer
  2900. (org-insert-time-stamp (current-time)))))
  2901. ((equal (car key) "TITLE")
  2902. (or (let ((visited-file
  2903. (buffer-file-name (buffer-base-buffer))))
  2904. (and visited-file
  2905. (file-name-sans-extension
  2906. (file-name-nondirectory visited-file))))
  2907. (buffer-name (buffer-base-buffer))))
  2908. (t (cdr key)))))
  2909. (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
  2910. (insert
  2911. (format "#+%s:%s\n"
  2912. (car key)
  2913. (if (org-string-nw-p val) (format " %s" val) ""))))))))
  2914. (defun org-export-expand-include-keyword (&optional included dir footnotes)
  2915. "Expand every include keyword in buffer.
  2916. Optional argument INCLUDED is a list of included file names along
  2917. with their line restriction, when appropriate. It is used to
  2918. avoid infinite recursion. Optional argument DIR is the current
  2919. working directory. It is used to properly resolve relative
  2920. paths. Optional argument FOOTNOTES is a hash-table used for
  2921. storing and resolving footnotes. It is created automatically."
  2922. (let ((case-fold-search t)
  2923. (file-prefix (make-hash-table :test #'equal))
  2924. (current-prefix 0)
  2925. (footnotes (or footnotes (make-hash-table :test #'equal)))
  2926. (include-re "^[ \t]*#\\+INCLUDE:"))
  2927. ;; If :minlevel is not set the text-property
  2928. ;; `:org-include-induced-level' will be used to determine the
  2929. ;; relative level when expanding INCLUDE.
  2930. ;; Only affects included Org documents.
  2931. (goto-char (point-min))
  2932. (while (re-search-forward include-re nil t)
  2933. (put-text-property (line-beginning-position) (line-end-position)
  2934. :org-include-induced-level
  2935. (1+ (org-reduced-level (or (org-current-level) 0)))))
  2936. ;; Expand INCLUDE keywords.
  2937. (goto-char (point-min))
  2938. (while (re-search-forward include-re nil t)
  2939. (let ((element (save-match-data (org-element-at-point))))
  2940. (when (eq (org-element-type element) 'keyword)
  2941. (beginning-of-line)
  2942. ;; Extract arguments from keyword's value.
  2943. (let* ((value (org-element-property :value element))
  2944. (ind (org-get-indentation))
  2945. location
  2946. (file
  2947. (and (string-match
  2948. "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
  2949. (prog1
  2950. (save-match-data
  2951. (let ((matched (match-string 1 value)))
  2952. (when (string-match "\\(::\\(.*?\\)\\)\"?\\'"
  2953. matched)
  2954. (setq location (match-string 2 matched))
  2955. (setq matched
  2956. (replace-match "" nil nil matched 1)))
  2957. (expand-file-name
  2958. (org-unbracket-string "\"" "\"" matched)
  2959. dir)))
  2960. (setq value (replace-match "" nil nil value)))))
  2961. (only-contents
  2962. (and (string-match ":only-contents *\\([^: \r\t\n]\\S-*\\)?"
  2963. value)
  2964. (prog1 (org-not-nil (match-string 1 value))
  2965. (setq value (replace-match "" nil nil value)))))
  2966. (lines
  2967. (and (string-match
  2968. ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
  2969. value)
  2970. (prog1 (match-string 1 value)
  2971. (setq value (replace-match "" nil nil value)))))
  2972. (env (cond
  2973. ((string-match "\\<example\\>" value) 'literal)
  2974. ((string-match "\\<export\\(?: +\\(.*\\)\\)?" value)
  2975. 'literal)
  2976. ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
  2977. 'literal)))
  2978. ;; Minimal level of included file defaults to the child
  2979. ;; level of the current headline, if any, or one. It
  2980. ;; only applies is the file is meant to be included as
  2981. ;; an Org one.
  2982. (minlevel
  2983. (and (not env)
  2984. (if (string-match ":minlevel +\\([0-9]+\\)" value)
  2985. (prog1 (string-to-number (match-string 1 value))
  2986. (setq value (replace-match "" nil nil value)))
  2987. (get-text-property (point)
  2988. :org-include-induced-level))))
  2989. (args (and (eq env 'literal) (match-string 1 value)))
  2990. (block (and (string-match "\\<\\(\\S-+\\)\\>" value)
  2991. (match-string 1 value))))
  2992. ;; Remove keyword.
  2993. (delete-region (point) (line-beginning-position 2))
  2994. (cond
  2995. ((not file) nil)
  2996. ((not (file-readable-p file))
  2997. (error "Cannot include file %s" file))
  2998. ;; Check if files has already been parsed. Look after
  2999. ;; inclusion lines too, as different parts of the same file
  3000. ;; can be included too.
  3001. ((member (list file lines) included)
  3002. (error "Recursive file inclusion: %s" file))
  3003. (t
  3004. (cond
  3005. ((eq env 'literal)
  3006. (insert
  3007. (let ((ind-str (make-string ind ?\s))
  3008. (arg-str (if (stringp args) (format " %s" args) ""))
  3009. (contents
  3010. (org-escape-code-in-string
  3011. (org-export--prepare-file-contents file lines))))
  3012. (format "%s#+BEGIN_%s%s\n%s%s#+END_%s\n"
  3013. ind-str block arg-str contents ind-str block))))
  3014. ((stringp block)
  3015. (insert
  3016. (let ((ind-str (make-string ind ?\s))
  3017. (contents
  3018. (org-export--prepare-file-contents file lines)))
  3019. (format "%s#+BEGIN_%s\n%s%s#+END_%s\n"
  3020. ind-str block contents ind-str block))))
  3021. (t
  3022. (insert
  3023. (with-temp-buffer
  3024. (let ((org-inhibit-startup t)
  3025. (lines
  3026. (if location
  3027. (org-export--inclusion-absolute-lines
  3028. file location only-contents lines)
  3029. lines)))
  3030. (org-mode)
  3031. (insert
  3032. (org-export--prepare-file-contents
  3033. file lines ind minlevel
  3034. (or (gethash file file-prefix)
  3035. (puthash file (cl-incf current-prefix) file-prefix))
  3036. footnotes)))
  3037. (org-export-expand-include-keyword
  3038. (cons (list file lines) included)
  3039. (file-name-directory file)
  3040. footnotes)
  3041. (buffer-string)))))
  3042. ;; Expand footnotes after all files have been included.
  3043. ;; Footnotes are stored at end of buffer.
  3044. (unless included
  3045. (org-with-wide-buffer
  3046. (goto-char (point-max))
  3047. (maphash (lambda (k v) (insert (format "\n[fn:%s] %s\n" k v)))
  3048. footnotes)))))))))))
  3049. (defun org-export--inclusion-absolute-lines (file location only-contents lines)
  3050. "Resolve absolute lines for an included file with file-link.
  3051. FILE is string file-name of the file to include. LOCATION is a
  3052. string name within FILE to be included (located via
  3053. `org-link-search'). If ONLY-CONTENTS is non-nil only the
  3054. contents of the named element will be included, as determined
  3055. Org-Element. If LINES is non-nil only those lines are included.
  3056. Return a string of lines to be included in the format expected by
  3057. `org-export--prepare-file-contents'."
  3058. (with-temp-buffer
  3059. (insert-file-contents file)
  3060. (unless (eq major-mode 'org-mode)
  3061. (let ((org-inhibit-startup t)) (org-mode)))
  3062. (condition-case err
  3063. ;; Enforce consistent search.
  3064. (let ((org-link-search-must-match-exact-headline nil))
  3065. (org-link-search location))
  3066. (error
  3067. (error "%s for %s::%s" (error-message-string err) file location)))
  3068. (let* ((element (org-element-at-point))
  3069. (contents-begin
  3070. (and only-contents (org-element-property :contents-begin element))))
  3071. (narrow-to-region
  3072. (or contents-begin (org-element-property :begin element))
  3073. (org-element-property (if contents-begin :contents-end :end) element))
  3074. (when (and only-contents
  3075. (memq (org-element-type element) '(headline inlinetask)))
  3076. ;; Skip planning line and property-drawer.
  3077. (goto-char (point-min))
  3078. (when (looking-at-p org-planning-line-re) (forward-line))
  3079. (when (looking-at org-property-drawer-re) (goto-char (match-end 0)))
  3080. (unless (bolp) (forward-line))
  3081. (narrow-to-region (point) (point-max))))
  3082. (when lines
  3083. (org-skip-whitespace)
  3084. (beginning-of-line)
  3085. (let* ((lines (split-string lines "-"))
  3086. (lbeg (string-to-number (car lines)))
  3087. (lend (string-to-number (cadr lines)))
  3088. (beg (if (zerop lbeg) (point-min)
  3089. (goto-char (point-min))
  3090. (forward-line (1- lbeg))
  3091. (point)))
  3092. (end (if (zerop lend) (point-max)
  3093. (goto-char beg)
  3094. (forward-line (1- lend))
  3095. (point))))
  3096. (narrow-to-region beg end)))
  3097. (let ((end (point-max)))
  3098. (goto-char (point-min))
  3099. (widen)
  3100. (let ((start-line (line-number-at-pos)))
  3101. (format "%d-%d"
  3102. start-line
  3103. (save-excursion
  3104. (+ start-line
  3105. (let ((counter 0))
  3106. (while (< (point) end) (cl-incf counter) (forward-line))
  3107. counter))))))))
  3108. (defun org-export--prepare-file-contents
  3109. (file &optional lines ind minlevel id footnotes)
  3110. "Prepare contents of FILE for inclusion and return it as a string.
  3111. When optional argument LINES is a string specifying a range of
  3112. lines, include only those lines.
  3113. Optional argument IND, when non-nil, is an integer specifying the
  3114. global indentation of returned contents. Since its purpose is to
  3115. allow an included file to stay in the same environment it was
  3116. created (e.g., a list item), it doesn't apply past the first
  3117. headline encountered.
  3118. Optional argument MINLEVEL, when non-nil, is an integer
  3119. specifying the level that any top-level headline in the included
  3120. file should have.
  3121. Optional argument ID is an integer that will be inserted before
  3122. each footnote definition and reference if FILE is an Org file.
  3123. This is useful to avoid conflicts when more than one Org file
  3124. with footnotes is included in a document.
  3125. Optional argument FOOTNOTES is a hash-table to store footnotes in
  3126. the included document."
  3127. (with-temp-buffer
  3128. (insert-file-contents file)
  3129. (when lines
  3130. (let* ((lines (split-string lines "-"))
  3131. (lbeg (string-to-number (car lines)))
  3132. (lend (string-to-number (cadr lines)))
  3133. (beg (if (zerop lbeg) (point-min)
  3134. (goto-char (point-min))
  3135. (forward-line (1- lbeg))
  3136. (point)))
  3137. (end (if (zerop lend) (point-max)
  3138. (goto-char (point-min))
  3139. (forward-line (1- lend))
  3140. (point))))
  3141. (narrow-to-region beg end)))
  3142. ;; Remove blank lines at beginning and end of contents. The logic
  3143. ;; behind that removal is that blank lines around include keyword
  3144. ;; override blank lines in included file.
  3145. (goto-char (point-min))
  3146. (org-skip-whitespace)
  3147. (beginning-of-line)
  3148. (delete-region (point-min) (point))
  3149. (goto-char (point-max))
  3150. (skip-chars-backward " \r\t\n")
  3151. (forward-line)
  3152. (delete-region (point) (point-max))
  3153. ;; If IND is set, preserve indentation of include keyword until
  3154. ;; the first headline encountered.
  3155. (when (and ind (> ind 0))
  3156. (unless (eq major-mode 'org-mode)
  3157. (let ((org-inhibit-startup t)) (org-mode)))
  3158. (goto-char (point-min))
  3159. (let ((ind-str (make-string ind ?\s)))
  3160. (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
  3161. ;; Do not move footnote definitions out of column 0.
  3162. (unless (and (looking-at org-footnote-definition-re)
  3163. (eq (org-element-type (org-element-at-point))
  3164. 'footnote-definition))
  3165. (insert ind-str))
  3166. (forward-line))))
  3167. ;; When MINLEVEL is specified, compute minimal level for headlines
  3168. ;; in the file (CUR-MIN), and remove stars to each headline so
  3169. ;; that headlines with minimal level have a level of MINLEVEL.
  3170. (when minlevel
  3171. (unless (eq major-mode 'org-mode)
  3172. (let ((org-inhibit-startup t)) (org-mode)))
  3173. (org-with-limited-levels
  3174. (let ((levels (org-map-entries
  3175. (lambda () (org-reduced-level (org-current-level))))))
  3176. (when levels
  3177. (let ((offset (- minlevel (apply #'min levels))))
  3178. (unless (zerop offset)
  3179. (when org-odd-levels-only (setq offset (* offset 2)))
  3180. ;; Only change stars, don't bother moving whole
  3181. ;; sections.
  3182. (org-map-entries
  3183. (lambda ()
  3184. (if (< offset 0) (delete-char (abs offset))
  3185. (insert (make-string offset ?*)))))))))))
  3186. ;; Append ID to all footnote references and definitions, so they
  3187. ;; become file specific and cannot collide with footnotes in other
  3188. ;; included files. Further, collect relevant footnote definitions
  3189. ;; outside of LINES, in order to reintroduce them later.
  3190. (when id
  3191. (let ((marker-min (point-min-marker))
  3192. (marker-max (point-max-marker))
  3193. (get-new-label
  3194. (lambda (label)
  3195. ;; Generate new label from LABEL by prefixing it with
  3196. ;; "-ID-".
  3197. (format "-%d-%s" id label)))
  3198. (set-new-label
  3199. (lambda (f old new)
  3200. ;; Replace OLD label with NEW in footnote F.
  3201. (save-excursion
  3202. (goto-char (+ (org-element-property :begin f) 4))
  3203. (looking-at (regexp-quote old))
  3204. (replace-match new))))
  3205. (seen-alist))
  3206. (goto-char (point-min))
  3207. (while (re-search-forward org-footnote-re nil t)
  3208. (let ((footnote (save-excursion
  3209. (backward-char)
  3210. (org-element-context))))
  3211. (when (memq (org-element-type footnote)
  3212. '(footnote-definition footnote-reference))
  3213. (let* ((label (org-element-property :label footnote)))
  3214. ;; Update the footnote-reference at point and collect
  3215. ;; the new label, which is only used for footnotes
  3216. ;; outsides LINES.
  3217. (when label
  3218. (let ((seen (cdr (assoc label seen-alist))))
  3219. (if seen (funcall set-new-label footnote label seen)
  3220. (let ((new (funcall get-new-label label)))
  3221. (push (cons label new) seen-alist)
  3222. (org-with-wide-buffer
  3223. (let* ((def (org-footnote-get-definition label))
  3224. (beg (nth 1 def)))
  3225. (when (and def
  3226. (or (< beg marker-min)
  3227. (>= beg marker-max)))
  3228. ;; Store since footnote-definition is
  3229. ;; outside of LINES.
  3230. (puthash new
  3231. (org-element-normalize-string (nth 3 def))
  3232. footnotes))))
  3233. (funcall set-new-label footnote label new)))))))))
  3234. (set-marker marker-min nil)
  3235. (set-marker marker-max nil)))
  3236. (org-element-normalize-string (buffer-string))))
  3237. (defun org-export--copy-to-kill-ring-p ()
  3238. "Return a non-nil value when output should be added to the kill ring.
  3239. See also `org-export-copy-to-kill-ring'."
  3240. (if (eq org-export-copy-to-kill-ring 'if-interactive)
  3241. (not (or executing-kbd-macro noninteractive))
  3242. (eq org-export-copy-to-kill-ring t)))
  3243. ;;; Tools For Back-Ends
  3244. ;;
  3245. ;; A whole set of tools is available to help build new exporters. Any
  3246. ;; function general enough to have its use across many back-ends
  3247. ;; should be added here.
  3248. ;;;; For Affiliated Keywords
  3249. ;;
  3250. ;; `org-export-read-attribute' reads a property from a given element
  3251. ;; as a plist. It can be used to normalize affiliated keywords'
  3252. ;; syntax.
  3253. ;;
  3254. ;; Since captions can span over multiple lines and accept dual values,
  3255. ;; their internal representation is a bit tricky. Therefore,
  3256. ;; `org-export-get-caption' transparently returns a given element's
  3257. ;; caption as a secondary string.
  3258. (defun org-export-read-attribute (attribute element &optional property)
  3259. "Turn ATTRIBUTE property from ELEMENT into a plist.
  3260. When optional argument PROPERTY is non-nil, return the value of
  3261. that property within attributes.
  3262. This function assumes attributes are defined as \":keyword
  3263. value\" pairs. It is appropriate for `:attr_html' like
  3264. properties.
  3265. All values will become strings except the empty string and
  3266. \"nil\", which will become nil. Also, values containing only
  3267. double quotes will be read as-is, which means that \"\" value
  3268. will become the empty string."
  3269. (let* ((prepare-value
  3270. (lambda (str)
  3271. (save-match-data
  3272. (cond ((member str '(nil "" "nil")) nil)
  3273. ((string-match "^\"\\(\"+\\)?\"$" str)
  3274. (or (match-string 1 str) ""))
  3275. (t str)))))
  3276. (attributes
  3277. (let ((value (org-element-property attribute element)))
  3278. (when value
  3279. (let ((s (mapconcat 'identity value " ")) result)
  3280. (while (string-match
  3281. "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
  3282. s)
  3283. (let ((value (substring s 0 (match-beginning 0))))
  3284. (push (funcall prepare-value value) result))
  3285. (push (intern (match-string 1 s)) result)
  3286. (setq s (substring s (match-end 0))))
  3287. ;; Ignore any string before first property with `cdr'.
  3288. (cdr (nreverse (cons (funcall prepare-value s) result))))))))
  3289. (if property (plist-get attributes property) attributes)))
  3290. (defun org-export-get-caption (element &optional shortp)
  3291. "Return caption from ELEMENT as a secondary string.
  3292. When optional argument SHORTP is non-nil, return short caption,
  3293. as a secondary string, instead.
  3294. Caption lines are separated by a white space."
  3295. (let ((full-caption (org-element-property :caption element)) caption)
  3296. (dolist (line full-caption (cdr caption))
  3297. (let ((cap (funcall (if shortp 'cdr 'car) line)))
  3298. (when cap
  3299. (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
  3300. ;;;; For Derived Back-ends
  3301. ;;
  3302. ;; `org-export-with-backend' is a function allowing to locally use
  3303. ;; another back-end to transcode some object or element. In a derived
  3304. ;; back-end, it may be used as a fall-back function once all specific
  3305. ;; cases have been treated.
  3306. (defun org-export-with-backend (backend data &optional contents info)
  3307. "Call a transcoder from BACKEND on DATA.
  3308. BACKEND is an export back-end, as returned by, e.g.,
  3309. `org-export-create-backend', or a symbol referring to
  3310. a registered back-end. DATA is an Org element, object, secondary
  3311. string or string. CONTENTS, when non-nil, is the transcoded
  3312. contents of DATA element, as a string. INFO, when non-nil, is
  3313. the communication channel used for export, as a plist."
  3314. (when (symbolp backend) (setq backend (org-export-get-backend backend)))
  3315. (org-export-barf-if-invalid-backend backend)
  3316. (let ((type (org-element-type data)))
  3317. (when (memq type '(nil org-data)) (error "No foreign transcoder available"))
  3318. (let* ((all-transcoders (org-export-get-all-transcoders backend))
  3319. (transcoder (cdr (assq type all-transcoders))))
  3320. (unless (functionp transcoder) (error "No foreign transcoder available"))
  3321. (let ((new-info
  3322. (org-combine-plists
  3323. info (list
  3324. :back-end backend
  3325. :translate-alist all-transcoders
  3326. :exported-data (make-hash-table :test #'eq :size 401)))))
  3327. ;; `:internal-references' are shared across back-ends.
  3328. (prog1 (funcall transcoder data contents new-info)
  3329. (plist-put info :internal-references
  3330. (plist-get new-info :internal-references)))))))
  3331. ;;;; For Export Snippets
  3332. ;;
  3333. ;; Every export snippet is transmitted to the back-end. Though, the
  3334. ;; latter will only retain one type of export-snippet, ignoring
  3335. ;; others, based on the former's target back-end. The function
  3336. ;; `org-export-snippet-backend' returns that back-end for a given
  3337. ;; export-snippet.
  3338. (defun org-export-snippet-backend (export-snippet)
  3339. "Return EXPORT-SNIPPET targeted back-end as a symbol.
  3340. Translation, with `org-export-snippet-translation-alist', is
  3341. applied."
  3342. (let ((back-end (org-element-property :back-end export-snippet)))
  3343. (intern
  3344. (or (cdr (assoc back-end org-export-snippet-translation-alist))
  3345. back-end))))
  3346. ;;;; For Footnotes
  3347. ;;
  3348. ;; `org-export-collect-footnote-definitions' is a tool to list
  3349. ;; actually used footnotes definitions in the whole parse tree, or in
  3350. ;; a headline, in order to add footnote listings throughout the
  3351. ;; transcoded data.
  3352. ;;
  3353. ;; `org-export-footnote-first-reference-p' is a predicate used by some
  3354. ;; back-ends, when they need to attach the footnote definition only to
  3355. ;; the first occurrence of the corresponding label.
  3356. ;;
  3357. ;; `org-export-get-footnote-definition' and
  3358. ;; `org-export-get-footnote-number' provide easier access to
  3359. ;; additional information relative to a footnote reference.
  3360. (defun org-export-get-footnote-definition (footnote-reference info)
  3361. "Return definition of FOOTNOTE-REFERENCE as parsed data.
  3362. INFO is the plist used as a communication channel. If no such
  3363. definition can be found, raise an error."
  3364. (let ((label (org-element-property :label footnote-reference)))
  3365. (if (not label) (org-element-contents footnote-reference)
  3366. (let ((cache (or (plist-get info :footnote-definition-cache)
  3367. (let ((hash (make-hash-table :test #'equal)))
  3368. (plist-put info :footnote-definition-cache hash)
  3369. hash))))
  3370. (or
  3371. (gethash label cache)
  3372. (puthash label
  3373. (org-element-map (plist-get info :parse-tree)
  3374. '(footnote-definition footnote-reference)
  3375. (lambda (f)
  3376. (cond
  3377. ;; Skip any footnote with a different label.
  3378. ;; Also skip any standard footnote reference
  3379. ;; with the same label since those cannot
  3380. ;; contain a definition.
  3381. ((not (equal (org-element-property :label f) label)) nil)
  3382. ((eq (org-element-property :type f) 'standard) nil)
  3383. ((org-element-contents f))
  3384. ;; Even if the contents are empty, we can not
  3385. ;; return nil since that would eventually raise
  3386. ;; the error. Instead, return the equivalent
  3387. ;; empty string.
  3388. (t "")))
  3389. info t)
  3390. cache)
  3391. (error "Definition not found for footnote %s" label))))))
  3392. (defun org-export--footnote-reference-map
  3393. (function data info &optional body-first)
  3394. "Apply FUNCTION on every footnote reference in DATA.
  3395. INFO is a plist containing export state. By default, as soon as
  3396. a new footnote reference is encountered, FUNCTION is called onto
  3397. its definition. However, if BODY-FIRST is non-nil, this step is
  3398. delayed until the end of the process."
  3399. (letrec ((definitions nil)
  3400. (seen-refs nil)
  3401. (search-ref
  3402. (lambda (data delayp)
  3403. ;; Search footnote references through DATA, filling
  3404. ;; SEEN-REFS along the way. When DELAYP is non-nil,
  3405. ;; store footnote definitions so they can be entered
  3406. ;; later.
  3407. (org-element-map data 'footnote-reference
  3408. (lambda (f)
  3409. (funcall function f)
  3410. (let ((--label (org-element-property :label f)))
  3411. (unless (and --label (member --label seen-refs))
  3412. (when --label (push --label seen-refs))
  3413. ;; Search for subsequent references in footnote
  3414. ;; definition so numbering follows reading
  3415. ;; logic, unless DELAYP in non-nil.
  3416. (cond
  3417. (delayp
  3418. (push (org-export-get-footnote-definition f info)
  3419. definitions))
  3420. ;; Do not force entering inline definitions,
  3421. ;; since `org-element-map' already traverses
  3422. ;; them at the right time.
  3423. ((eq (org-element-property :type f) 'inline))
  3424. (t (funcall search-ref
  3425. (org-export-get-footnote-definition f info)
  3426. nil))))))
  3427. info nil
  3428. ;; Don't enter footnote definitions since it will
  3429. ;; happen when their first reference is found.
  3430. ;; Moreover, if DELAYP is non-nil, make sure we
  3431. ;; postpone entering definitions of inline references.
  3432. (if delayp '(footnote-definition footnote-reference)
  3433. 'footnote-definition)))))
  3434. (funcall search-ref data body-first)
  3435. (funcall search-ref (nreverse definitions) nil)))
  3436. (defun org-export-collect-footnote-definitions (info &optional data body-first)
  3437. "Return an alist between footnote numbers, labels and definitions.
  3438. INFO is the current export state, as a plist.
  3439. Definitions are collected throughout the whole parse tree, or
  3440. DATA when non-nil.
  3441. Sorting is done by order of references. As soon as a new
  3442. reference is encountered, other references are searched within
  3443. its definition. However, if BODY-FIRST is non-nil, this step is
  3444. delayed after the whole tree is checked. This alters results
  3445. when references are found in footnote definitions.
  3446. Definitions either appear as Org data or as a secondary string
  3447. for inlined footnotes. Unreferenced definitions are ignored."
  3448. (let ((n 0) labels alist)
  3449. (org-export--footnote-reference-map
  3450. (lambda (f)
  3451. ;; Collect footnote number, label and definition.
  3452. (let ((l (org-element-property :label f)))
  3453. (unless (and l (member l labels))
  3454. (cl-incf n)
  3455. (push (list n l (org-export-get-footnote-definition f info)) alist))
  3456. (when l (push l labels))))
  3457. (or data (plist-get info :parse-tree)) info body-first)
  3458. (nreverse alist)))
  3459. (defun org-export-footnote-first-reference-p
  3460. (footnote-reference info &optional data body-first)
  3461. "Non-nil when a footnote reference is the first one for its label.
  3462. FOOTNOTE-REFERENCE is the footnote reference being considered.
  3463. INFO is a plist containing current export state.
  3464. Search is done throughout the whole parse tree, or DATA when
  3465. non-nil.
  3466. By default, as soon as a new footnote reference is encountered,
  3467. other references are searched within its definition. However, if
  3468. BODY-FIRST is non-nil, this step is delayed after the whole tree
  3469. is checked. This alters results when references are found in
  3470. footnote definitions."
  3471. (let ((label (org-element-property :label footnote-reference)))
  3472. ;; Anonymous footnotes are always a first reference.
  3473. (or (not label)
  3474. (catch 'exit
  3475. (org-export--footnote-reference-map
  3476. (lambda (f)
  3477. (let ((l (org-element-property :label f)))
  3478. (when (and l label (string= label l))
  3479. (throw 'exit (eq footnote-reference f)))))
  3480. (or data (plist-get info :parse-tree)) info body-first)))))
  3481. (defun org-export-get-footnote-number (footnote info &optional data body-first)
  3482. "Return number associated to a footnote.
  3483. FOOTNOTE is either a footnote reference or a footnote definition.
  3484. INFO is the plist containing export state.
  3485. Number is unique throughout the whole parse tree, or DATA, when
  3486. non-nil.
  3487. By default, as soon as a new footnote reference is encountered,
  3488. counting process moves into its definition. However, if
  3489. BODY-FIRST is non-nil, this step is delayed until the end of the
  3490. process, leading to a different order when footnotes are nested."
  3491. (let ((count 0)
  3492. (seen)
  3493. (label (org-element-property :label footnote)))
  3494. (catch 'exit
  3495. (org-export--footnote-reference-map
  3496. (lambda (f)
  3497. (let ((l (org-element-property :label f)))
  3498. (cond
  3499. ;; Anonymous footnote match: return number.
  3500. ((and (not l) (not label) (eq footnote f)) (throw 'exit (1+ count)))
  3501. ;; Labels match: return number.
  3502. ((and label l (string= label l)) (throw 'exit (1+ count)))
  3503. ;; Otherwise store label and increase counter if label
  3504. ;; wasn't encountered yet.
  3505. ((not l) (cl-incf count))
  3506. ((not (member l seen)) (push l seen) (cl-incf count)))))
  3507. (or data (plist-get info :parse-tree)) info body-first))))
  3508. ;;;; For Headlines
  3509. ;;
  3510. ;; `org-export-get-relative-level' is a shortcut to get headline
  3511. ;; level, relatively to the lower headline level in the parsed tree.
  3512. ;;
  3513. ;; `org-export-get-headline-number' returns the section number of an
  3514. ;; headline, while `org-export-number-to-roman' allows it to be
  3515. ;; converted to roman numbers. With an optional argument,
  3516. ;; `org-export-get-headline-number' returns a number to unnumbered
  3517. ;; headlines (used for internal id).
  3518. ;;
  3519. ;; `org-export-low-level-p', `org-export-first-sibling-p' and
  3520. ;; `org-export-last-sibling-p' are three useful predicates when it
  3521. ;; comes to fulfill the `:headline-levels' property.
  3522. ;;
  3523. ;; `org-export-get-tags', `org-export-get-category' and
  3524. ;; `org-export-get-node-property' extract useful information from an
  3525. ;; headline or a parent headline. They all handle inheritance.
  3526. ;;
  3527. ;; `org-export-get-alt-title' tries to retrieve an alternative title,
  3528. ;; as a secondary string, suitable for table of contents. It falls
  3529. ;; back onto default title.
  3530. (defun org-export-get-relative-level (headline info)
  3531. "Return HEADLINE relative level within current parsed tree.
  3532. INFO is a plist holding contextual information."
  3533. (+ (org-element-property :level headline)
  3534. (or (plist-get info :headline-offset) 0)))
  3535. (defun org-export-low-level-p (headline info)
  3536. "Non-nil when HEADLINE is considered as low level.
  3537. INFO is a plist used as a communication channel.
  3538. A low level headlines has a relative level greater than
  3539. `:headline-levels' property value.
  3540. Return value is the difference between HEADLINE relative level
  3541. and the last level being considered as high enough, or nil."
  3542. (let ((limit (plist-get info :headline-levels)))
  3543. (when (wholenump limit)
  3544. (let ((level (org-export-get-relative-level headline info)))
  3545. (and (> level limit) (- level limit))))))
  3546. (defun org-export-get-headline-number (headline info)
  3547. "Return numbered HEADLINE numbering as a list of numbers.
  3548. INFO is a plist holding contextual information."
  3549. (and (org-export-numbered-headline-p headline info)
  3550. (cdr (assq headline (plist-get info :headline-numbering)))))
  3551. (defun org-export-numbered-headline-p (headline info)
  3552. "Return a non-nil value if HEADLINE element should be numbered.
  3553. INFO is a plist used as a communication channel."
  3554. (unless (cl-some
  3555. (lambda (head) (org-not-nil (org-element-property :UNNUMBERED head)))
  3556. (org-element-lineage headline nil t))
  3557. (let ((sec-num (plist-get info :section-numbers))
  3558. (level (org-export-get-relative-level headline info)))
  3559. (if (wholenump sec-num) (<= level sec-num) sec-num))))
  3560. (defun org-export-number-to-roman (n)
  3561. "Convert integer N into a roman numeral."
  3562. (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
  3563. ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
  3564. ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
  3565. ( 1 . "I")))
  3566. (res ""))
  3567. (if (<= n 0)
  3568. (number-to-string n)
  3569. (while roman
  3570. (if (>= n (caar roman))
  3571. (setq n (- n (caar roman))
  3572. res (concat res (cdar roman)))
  3573. (pop roman)))
  3574. res)))
  3575. (defun org-export-get-tags (element info &optional tags inherited)
  3576. "Return list of tags associated to ELEMENT.
  3577. ELEMENT has either an `headline' or an `inlinetask' type. INFO
  3578. is a plist used as a communication channel.
  3579. When non-nil, optional argument TAGS should be a list of strings.
  3580. Any tag belonging to this list will also be removed.
  3581. When optional argument INHERITED is non-nil, tags can also be
  3582. inherited from parent headlines and FILETAGS keywords."
  3583. (cl-remove-if
  3584. (lambda (tag) (member tag tags))
  3585. (if (not inherited) (org-element-property :tags element)
  3586. ;; Build complete list of inherited tags.
  3587. (let ((current-tag-list (org-element-property :tags element)))
  3588. (dolist (parent (org-element-lineage element))
  3589. (dolist (tag (org-element-property :tags parent))
  3590. (when (and (memq (org-element-type parent) '(headline inlinetask))
  3591. (not (member tag current-tag-list)))
  3592. (push tag current-tag-list))))
  3593. ;; Add FILETAGS keywords and return results.
  3594. (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
  3595. (defun org-export-get-node-property (property blob &optional inherited)
  3596. "Return node PROPERTY value for BLOB.
  3597. PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
  3598. element or object.
  3599. If optional argument INHERITED is non-nil, the value can be
  3600. inherited from a parent headline.
  3601. Return value is a string or nil."
  3602. (let ((headline (if (eq (org-element-type blob) 'headline) blob
  3603. (org-export-get-parent-headline blob))))
  3604. (if (not inherited) (org-element-property property blob)
  3605. (let ((parent headline))
  3606. (catch 'found
  3607. (while parent
  3608. (when (plist-member (nth 1 parent) property)
  3609. (throw 'found (org-element-property property parent)))
  3610. (setq parent (org-element-property :parent parent))))))))
  3611. (defun org-export-get-category (blob info)
  3612. "Return category for element or object BLOB.
  3613. INFO is a plist used as a communication channel.
  3614. CATEGORY is automatically inherited from a parent headline, from
  3615. #+CATEGORY: keyword or created out of original file name. If all
  3616. fail, the fall-back value is \"???\"."
  3617. (or (org-export-get-node-property :CATEGORY blob t)
  3618. (org-element-map (plist-get info :parse-tree) 'keyword
  3619. (lambda (kwd)
  3620. (when (equal (org-element-property :key kwd) "CATEGORY")
  3621. (org-element-property :value kwd)))
  3622. info 'first-match)
  3623. (let ((file (plist-get info :input-file)))
  3624. (and file (file-name-sans-extension (file-name-nondirectory file))))
  3625. "???"))
  3626. (defun org-export-get-alt-title (headline _)
  3627. "Return alternative title for HEADLINE, as a secondary string.
  3628. If no optional title is defined, fall-back to the regular title."
  3629. (let ((alt (org-element-property :ALT_TITLE headline)))
  3630. (if alt (org-element-parse-secondary-string
  3631. alt (org-element-restriction 'headline) headline)
  3632. (org-element-property :title headline))))
  3633. (defun org-export-first-sibling-p (blob info)
  3634. "Non-nil when BLOB is the first sibling in its parent.
  3635. BLOB is an element or an object. If BLOB is a headline, non-nil
  3636. means it is the first sibling in the sub-tree. INFO is a plist
  3637. used as a communication channel."
  3638. (memq (org-element-type (org-export-get-previous-element blob info))
  3639. '(nil section)))
  3640. (defun org-export-last-sibling-p (blob info)
  3641. "Non-nil when BLOB is the last sibling in its parent.
  3642. BLOB is an element or an object. INFO is a plist used as
  3643. a communication channel."
  3644. (not (org-export-get-next-element blob info)))
  3645. ;;;; For Keywords
  3646. ;;
  3647. ;; `org-export-get-date' returns a date appropriate for the document
  3648. ;; to about to be exported. In particular, it takes care of
  3649. ;; `org-export-date-timestamp-format'.
  3650. (defun org-export-get-date (info &optional fmt)
  3651. "Return date value for the current document.
  3652. INFO is a plist used as a communication channel. FMT, when
  3653. non-nil, is a time format string that will be applied on the date
  3654. if it consists in a single timestamp object. It defaults to
  3655. `org-export-date-timestamp-format' when nil.
  3656. A proper date can be a secondary string, a string or nil. It is
  3657. meant to be translated with `org-export-data' or alike."
  3658. (let ((date (plist-get info :date))
  3659. (fmt (or fmt org-export-date-timestamp-format)))
  3660. (cond ((not date) nil)
  3661. ((and fmt
  3662. (not (cdr date))
  3663. (eq (org-element-type (car date)) 'timestamp))
  3664. (org-timestamp-format (car date) fmt))
  3665. (t date))))
  3666. ;;;; For Links
  3667. ;;
  3668. ;; `org-export-custom-protocol-maybe' handles custom protocol defined
  3669. ;; in `org-link-parameters'.
  3670. ;;
  3671. ;; `org-export-get-coderef-format' returns an appropriate format
  3672. ;; string for coderefs.
  3673. ;;
  3674. ;; `org-export-inline-image-p' returns a non-nil value when the link
  3675. ;; provided should be considered as an inline image.
  3676. ;;
  3677. ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
  3678. ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
  3679. ;; returns an appropriate unique identifier.
  3680. ;;
  3681. ;; `org-export-resolve-id-link' returns the first headline with
  3682. ;; specified id or custom-id in parse tree, the path to the external
  3683. ;; file with the id.
  3684. ;;
  3685. ;; `org-export-resolve-coderef' associates a reference to a line
  3686. ;; number in the element it belongs, or returns the reference itself
  3687. ;; when the element isn't numbered.
  3688. ;;
  3689. ;; `org-export-file-uri' expands a filename as stored in :path value
  3690. ;; of a "file" link into a file URI.
  3691. ;;
  3692. ;; Broken links raise a `org-link-broken' error, which is caught by
  3693. ;; `org-export-data' for further processing, depending on
  3694. ;; `org-export-with-broken-links' value.
  3695. (org-define-error 'org-link-broken "Unable to resolve link; aborting")
  3696. (defun org-export-custom-protocol-maybe (link desc backend)
  3697. "Try exporting LINK with a dedicated function.
  3698. DESC is its description, as a string, or nil. BACKEND is the
  3699. back-end used for export, as a symbol.
  3700. Return output as a string, or nil if no protocol handles LINK.
  3701. A custom protocol has precedence over regular back-end export.
  3702. The function ignores links with an implicit type (e.g.,
  3703. \"custom-id\")."
  3704. (let ((type (org-element-property :type link)))
  3705. (unless (or (member type '("coderef" "custom-id" "fuzzy" "radio"))
  3706. (not backend))
  3707. (let ((protocol (org-link-get-parameter type :export)))
  3708. (and (functionp protocol)
  3709. (funcall protocol
  3710. (org-link-unescape (org-element-property :path link))
  3711. desc
  3712. backend))))))
  3713. (defun org-export-get-coderef-format (path desc)
  3714. "Return format string for code reference link.
  3715. PATH is the link path. DESC is its description."
  3716. (save-match-data
  3717. (cond ((not desc) "%s")
  3718. ((string-match (regexp-quote (concat "(" path ")")) desc)
  3719. (replace-match "%s" t t desc))
  3720. (t desc))))
  3721. (defun org-export-inline-image-p (link &optional rules)
  3722. "Non-nil if LINK object points to an inline image.
  3723. Optional argument is a set of RULES defining inline images. It
  3724. is an alist where associations have the following shape:
  3725. (TYPE . REGEXP)
  3726. Applying a rule means apply REGEXP against LINK's path when its
  3727. type is TYPE. The function will return a non-nil value if any of
  3728. the provided rules is non-nil. The default rule is
  3729. `org-export-default-inline-image-rule'.
  3730. This only applies to links without a description."
  3731. (and (not (org-element-contents link))
  3732. (let ((case-fold-search t))
  3733. (cl-some (lambda (rule)
  3734. (and (string= (org-element-property :type link) (car rule))
  3735. (string-match-p (cdr rule)
  3736. (org-element-property :path link))))
  3737. (or rules org-export-default-inline-image-rule)))))
  3738. (defun org-export-insert-image-links (data info &optional rules)
  3739. "Insert image links in DATA.
  3740. Org syntax do not support nested links. Nevertheless, some
  3741. export back-ends support image as descriptions of links. Since
  3742. images are really link to image files, we need to make an
  3743. exception about link nesting.
  3744. This function recognizes links whose contents are really images
  3745. and turn them into proper nested links. It is meant to be used
  3746. as a parse tree filter in back-ends supporting such constructs.
  3747. DATA is a parse tree. INFO is the current state of the export
  3748. process, as a plist.
  3749. A description is a valid images if it matches any rule in RULES,
  3750. if non-nil, or `org-export-default-inline-image-rule' otherwise.
  3751. See `org-export-inline-image-p' for more information about the
  3752. structure of RULES.
  3753. Return modified DATA."
  3754. (let ((link-re (format "\\`\\(?:%s\\|%s\\)\\'"
  3755. org-plain-link-re
  3756. org-angle-link-re))
  3757. (case-fold-search t))
  3758. (org-element-map data 'link
  3759. (lambda (l)
  3760. (let ((contents (org-element-interpret-data (org-element-contents l))))
  3761. (when (and (org-string-nw-p contents)
  3762. (string-match link-re contents))
  3763. (let ((type (match-string 1 contents))
  3764. (path (match-string 2 contents)))
  3765. (when (cl-some (lambda (rule)
  3766. (and (string= type (car rule))
  3767. (string-match-p (cdr rule) path)))
  3768. (or rules org-export-default-inline-image-rule))
  3769. (org-element-set-contents
  3770. l
  3771. (with-temp-buffer
  3772. (save-excursion (insert contents))
  3773. (org-element-link-parser))))))))
  3774. info nil nil t))
  3775. data)
  3776. (defun org-export-resolve-coderef (ref info)
  3777. "Resolve a code reference REF.
  3778. INFO is a plist used as a communication channel.
  3779. Return associated line number in source code, or REF itself,
  3780. depending on src-block or example element's switches. Throw an
  3781. error if no block contains REF."
  3782. (or (org-element-map (plist-get info :parse-tree) '(example-block src-block)
  3783. (lambda (el)
  3784. (with-temp-buffer
  3785. (insert (org-trim (org-element-property :value el)))
  3786. (let* ((label-fmt (or (org-element-property :label-fmt el)
  3787. org-coderef-label-format))
  3788. (ref-re (org-src-coderef-regexp label-fmt ref)))
  3789. ;; Element containing REF is found. Resolve it to
  3790. ;; either a label or a line number, as needed.
  3791. (when (re-search-backward ref-re nil t)
  3792. (if (org-element-property :use-labels el) ref
  3793. (+ (or (org-export-get-loc el info) 0)
  3794. (line-number-at-pos)))))))
  3795. info 'first-match)
  3796. (signal 'org-link-broken (list ref))))
  3797. (defun org-export-search-cells (datum)
  3798. "List search cells for element or object DATUM.
  3799. A search cell follows the pattern (TYPE . SEARCH) where
  3800. TYPE is a symbol among `headline', `custom-id', `target' and
  3801. `other'.
  3802. SEARCH is the string a link is expected to match. More
  3803. accurately, it is
  3804. - headline's title, as a list of strings, if TYPE is
  3805. `headline'.
  3806. - CUSTOM_ID value, as a string, if TYPE is `custom-id'.
  3807. - target's or radio-target's name as a list of strings if
  3808. TYPE is `target'.
  3809. - NAME affiliated keyword is TYPE is `other'.
  3810. A search cell is the internal representation of a fuzzy link. It
  3811. ignores white spaces and statistics cookies, if applicable."
  3812. (pcase (org-element-type datum)
  3813. (`headline
  3814. (let ((title (split-string
  3815. (replace-regexp-in-string
  3816. "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]" ""
  3817. (org-element-property :raw-value datum)))))
  3818. (delq nil
  3819. (list
  3820. (cons 'headline title)
  3821. (cons 'other title)
  3822. (let ((custom-id (org-element-property :custom-id datum)))
  3823. (and custom-id (cons 'custom-id custom-id)))))))
  3824. (`target
  3825. (list (cons 'target (split-string (org-element-property :value datum)))))
  3826. ((and (let name (org-element-property :name datum))
  3827. (guard name))
  3828. (list (cons 'other (split-string name))))
  3829. (_ nil)))
  3830. (defun org-export-string-to-search-cell (s)
  3831. "Return search cells associated to string S.
  3832. S is either the path of a fuzzy link or a search option, i.e., it
  3833. tries to match either a headline (through custom ID or title),
  3834. a target or a named element."
  3835. (pcase (string-to-char s)
  3836. (?* (list (cons 'headline (split-string (substring s 1)))))
  3837. (?# (list (cons 'custom-id (substring s 1))))
  3838. ((let search (split-string s))
  3839. (list (cons 'target search) (cons 'other search)))))
  3840. (defun org-export-match-search-cell-p (datum cells)
  3841. "Non-nil when DATUM matches search cells CELLS.
  3842. DATUM is an element or object. CELLS is a list of search cells,
  3843. as returned by `org-export-search-cells'."
  3844. (let ((targets (org-export-search-cells datum)))
  3845. (and targets (cl-some (lambda (cell) (member cell targets)) cells))))
  3846. (defun org-export-resolve-fuzzy-link (link info)
  3847. "Return LINK destination.
  3848. INFO is a plist holding contextual information.
  3849. Return value can be an object or an element:
  3850. - If LINK path matches a target object (i.e. <<path>>) return it.
  3851. - If LINK path exactly matches the name affiliated keyword
  3852. (i.e. #+NAME: path) of an element, return that element.
  3853. - If LINK path exactly matches any headline name, return that
  3854. element.
  3855. - Otherwise, throw an error.
  3856. Assume LINK type is \"fuzzy\". White spaces are not
  3857. significant."
  3858. (let* ((search-cells (org-export-string-to-search-cell
  3859. (org-link-unescape (org-element-property :path link))))
  3860. (link-cache
  3861. (or (plist-get info :resolve-fuzzy-link-cache)
  3862. (plist-get (plist-put info
  3863. :resolve-fuzzy-link-cache
  3864. (make-hash-table :test #'equal))
  3865. :resolve-fuzzy-link-cache)))
  3866. (cached (gethash search-cells link-cache 'not-found)))
  3867. (if (not (eq cached 'not-found)) cached
  3868. (let ((matches
  3869. (org-element-map (plist-get info :parse-tree)
  3870. (cons 'target org-element-all-elements)
  3871. (lambda (datum)
  3872. (and (org-export-match-search-cell-p datum search-cells)
  3873. datum)))))
  3874. (unless matches
  3875. (signal 'org-link-broken
  3876. (list (org-element-property :raw-path link))))
  3877. (puthash
  3878. search-cells
  3879. ;; There can be multiple matches for un-typed searches, i.e.,
  3880. ;; for searches not starting with # or *. In this case,
  3881. ;; prioritize targets and names over headline titles.
  3882. ;; Matching both a name and a target is not valid, and
  3883. ;; therefore undefined.
  3884. (or (cl-some (lambda (datum)
  3885. (and (not (eq (org-element-type datum) 'headline))
  3886. datum))
  3887. matches)
  3888. (car matches))
  3889. link-cache)))))
  3890. (defun org-export-resolve-id-link (link info)
  3891. "Return headline referenced as LINK destination.
  3892. INFO is a plist used as a communication channel.
  3893. Return value can be the headline element matched in current parse
  3894. tree or a file name. Assume LINK type is either \"id\" or
  3895. \"custom-id\". Throw an error if no match is found."
  3896. (let ((id (org-element-property :path link)))
  3897. ;; First check if id is within the current parse tree.
  3898. (or (org-element-map (plist-get info :parse-tree) 'headline
  3899. (lambda (headline)
  3900. (when (or (equal (org-element-property :ID headline) id)
  3901. (equal (org-element-property :CUSTOM_ID headline) id))
  3902. headline))
  3903. info 'first-match)
  3904. ;; Otherwise, look for external files.
  3905. (cdr (assoc id (plist-get info :id-alist)))
  3906. (signal 'org-link-broken (list id)))))
  3907. (defun org-export-resolve-radio-link (link info)
  3908. "Return radio-target object referenced as LINK destination.
  3909. INFO is a plist used as a communication channel.
  3910. Return value can be a radio-target object or nil. Assume LINK
  3911. has type \"radio\"."
  3912. (let ((path (replace-regexp-in-string
  3913. "[ \r\t\n]+" " " (org-element-property :path link))))
  3914. (org-element-map (plist-get info :parse-tree) 'radio-target
  3915. (lambda (radio)
  3916. (and (eq (compare-strings
  3917. (replace-regexp-in-string
  3918. "[ \r\t\n]+" " " (org-element-property :value radio))
  3919. nil nil path nil nil t)
  3920. t)
  3921. radio))
  3922. info 'first-match)))
  3923. (defun org-export-file-uri (filename)
  3924. "Return file URI associated to FILENAME."
  3925. (cond ((string-match-p "\\`//" filename) (concat "file:" filename))
  3926. ((not (file-name-absolute-p filename)) filename)
  3927. ((org-file-remote-p filename) (concat "file:/" filename))
  3928. (t (concat "file://" (expand-file-name filename)))))
  3929. ;;;; For References
  3930. ;;
  3931. ;; `org-export-get-reference' associate a unique reference for any
  3932. ;; object or element. It uses `org-export-new-reference' and
  3933. ;; `org-export-format-reference' to, respectively, generate new
  3934. ;; internal references and turn them into a string suitable for
  3935. ;; output.
  3936. ;;
  3937. ;; `org-export-get-ordinal' associates a sequence number to any object
  3938. ;; or element.
  3939. (defun org-export-new-reference (references)
  3940. "Return a unique reference, among REFERENCES.
  3941. REFERENCES is an alist whose values are in-use references, as
  3942. numbers. Returns a number, which is the internal representation
  3943. of a reference. See also `org-export-format-reference'."
  3944. ;; Generate random 7 digits hexadecimal numbers. Collisions
  3945. ;; increase exponentially with the numbers of references. However,
  3946. ;; the odds for encountering at least one collision with 1000 active
  3947. ;; references in the same document are roughly 0.2%, so this
  3948. ;; shouldn't be the bottleneck.
  3949. (let ((new (random #x10000000)))
  3950. (while (rassq new references) (setq new (random #x10000000)))
  3951. new))
  3952. (defun org-export-format-reference (reference)
  3953. "Format REFERENCE into a string.
  3954. REFERENCE is a number representing a reference, as returned by
  3955. `org-export-new-reference', which see."
  3956. (format "org%07x" reference))
  3957. (defun org-export-get-reference (datum info)
  3958. "Return a unique reference for DATUM, as a string.
  3959. DATUM is either an element or an object. INFO is the current
  3960. export state, as a plist.
  3961. This function checks `:crossrefs' property in INFO for search
  3962. cells matching DATUM before creating a new reference. Returned
  3963. reference consists of alphanumeric characters only."
  3964. (let ((cache (plist-get info :internal-references)))
  3965. (or (car (rassq datum cache))
  3966. (let* ((crossrefs (plist-get info :crossrefs))
  3967. (cells (org-export-search-cells datum))
  3968. ;; Preserve any pre-existing association between
  3969. ;; a search cell and a reference, i.e., when some
  3970. ;; previously published document referenced a location
  3971. ;; within current file (see
  3972. ;; `org-publish-resolve-external-link').
  3973. ;;
  3974. ;; However, there is no guarantee that search cells are
  3975. ;; unique, e.g., there might be duplicate custom ID or
  3976. ;; two headings with the same title in the file.
  3977. ;;
  3978. ;; As a consequence, before re-using any reference to
  3979. ;; an element or object, we check that it doesn't refer
  3980. ;; to a previous element or object.
  3981. (new (or (cl-some
  3982. (lambda (cell)
  3983. (let ((stored (cdr (assoc cell crossrefs))))
  3984. (when stored
  3985. (let ((old (org-export-format-reference stored)))
  3986. (and (not (assoc old cache)) stored)))))
  3987. cells)
  3988. (org-export-new-reference cache)))
  3989. (reference-string (org-export-format-reference new)))
  3990. ;; Cache contains both data already associated to
  3991. ;; a reference and in-use internal references, so as to make
  3992. ;; unique references.
  3993. (dolist (cell cells) (push (cons cell new) cache))
  3994. ;; Retain a direct association between reference string and
  3995. ;; DATUM since (1) not every object or element can be given
  3996. ;; a search cell (2) it permits quick lookup.
  3997. (push (cons reference-string datum) cache)
  3998. (plist-put info :internal-references cache)
  3999. reference-string))))
  4000. (defun org-export-get-ordinal (element info &optional types predicate)
  4001. "Return ordinal number of an element or object.
  4002. ELEMENT is the element or object considered. INFO is the plist
  4003. used as a communication channel.
  4004. Optional argument TYPES, when non-nil, is a list of element or
  4005. object types, as symbols, that should also be counted in.
  4006. Otherwise, only provided element's type is considered.
  4007. Optional argument PREDICATE is a function returning a non-nil
  4008. value if the current element or object should be counted in. It
  4009. accepts two arguments: the element or object being considered and
  4010. the plist used as a communication channel. This allows counting
  4011. only a certain type of object (i.e. inline images).
  4012. Return value is a list of numbers if ELEMENT is a headline or an
  4013. item. It is nil for keywords. It represents the footnote number
  4014. for footnote definitions and footnote references. If ELEMENT is
  4015. a target, return the same value as if ELEMENT was the closest
  4016. table, item or headline containing the target. In any other
  4017. case, return the sequence number of ELEMENT among elements or
  4018. objects of the same type."
  4019. ;; Ordinal of a target object refer to the ordinal of the closest
  4020. ;; table, item, or headline containing the object.
  4021. (when (eq (org-element-type element) 'target)
  4022. (setq element
  4023. (org-element-lineage
  4024. element
  4025. '(footnote-definition footnote-reference headline item table))))
  4026. (cl-case (org-element-type element)
  4027. ;; Special case 1: A headline returns its number as a list.
  4028. (headline (org-export-get-headline-number element info))
  4029. ;; Special case 2: An item returns its number as a list.
  4030. (item (let ((struct (org-element-property :structure element)))
  4031. (org-list-get-item-number
  4032. (org-element-property :begin element)
  4033. struct
  4034. (org-list-prevs-alist struct)
  4035. (org-list-parents-alist struct))))
  4036. ((footnote-definition footnote-reference)
  4037. (org-export-get-footnote-number element info))
  4038. (otherwise
  4039. (let ((counter 0))
  4040. ;; Increment counter until ELEMENT is found again.
  4041. (org-element-map (plist-get info :parse-tree)
  4042. (or types (org-element-type element))
  4043. (lambda (el)
  4044. (cond
  4045. ((eq element el) (1+ counter))
  4046. ((not predicate) (cl-incf counter) nil)
  4047. ((funcall predicate el info) (cl-incf counter) nil)))
  4048. info 'first-match)))))
  4049. ;;;; For Src-Blocks
  4050. ;;
  4051. ;; `org-export-get-loc' counts number of code lines accumulated in
  4052. ;; src-block or example-block elements with a "+n" switch until
  4053. ;; a given element, excluded. Note: "-n" switches reset that count.
  4054. ;;
  4055. ;; `org-export-unravel-code' extracts source code (along with a code
  4056. ;; references alist) from an `element-block' or `src-block' type
  4057. ;; element.
  4058. ;;
  4059. ;; `org-export-format-code' applies a formatting function to each line
  4060. ;; of code, providing relative line number and code reference when
  4061. ;; appropriate. Since it doesn't access the original element from
  4062. ;; which the source code is coming, it expects from the code calling
  4063. ;; it to know if lines should be numbered and if code references
  4064. ;; should appear.
  4065. ;;
  4066. ;; Eventually, `org-export-format-code-default' is a higher-level
  4067. ;; function (it makes use of the two previous functions) which handles
  4068. ;; line numbering and code references inclusion, and returns source
  4069. ;; code in a format suitable for plain text or verbatim output.
  4070. (defun org-export-get-loc (element info)
  4071. "Return count of lines of code before ELEMENT.
  4072. ELEMENT is an example-block or src-block element. INFO is the
  4073. plist used as a communication channel.
  4074. Count includes every line of code in example-block or src-block
  4075. with a \"+n\" or \"-n\" switch before block. Return nil if
  4076. ELEMENT doesn't allow line numbering."
  4077. (pcase (org-element-property :number-lines element)
  4078. (`(new . ,n) n)
  4079. (`(continued . ,n)
  4080. (let ((loc 0))
  4081. (org-element-map (plist-get info :parse-tree) '(src-block example-block)
  4082. (lambda (el)
  4083. ;; ELEMENT is reached: Quit loop and return locs.
  4084. (if (eq el element) (+ loc n)
  4085. ;; Only count lines from src-block and example-block
  4086. ;; elements with a "+n" or "-n" switch.
  4087. (let ((linum (org-element-property :number-lines el)))
  4088. (when linum
  4089. (let ((lines (org-count-lines
  4090. (org-trim (org-element-property :value el)))))
  4091. ;; Accumulate locs or reset them.
  4092. (pcase linum
  4093. (`(new . ,n) (setq loc (+ n lines)))
  4094. (`(continued . ,n) (cl-incf loc (+ n lines)))))))
  4095. nil)) ;Return nil to stay in the loop.
  4096. info 'first-match)))))
  4097. (defun org-export-unravel-code (element)
  4098. "Clean source code and extract references out of it.
  4099. ELEMENT has either a `src-block' an `example-block' type.
  4100. Return a cons cell whose CAR is the source code, cleaned from any
  4101. reference, protective commas and spurious indentation, and CDR is
  4102. an alist between relative line number (integer) and name of code
  4103. reference on that line (string)."
  4104. (let* ((line 0) refs
  4105. (value (org-element-property :value element))
  4106. ;; Get code and clean it. Remove blank lines at its
  4107. ;; beginning and end.
  4108. (code (replace-regexp-in-string
  4109. "\\`\\([ \t]*\n\\)+" ""
  4110. (replace-regexp-in-string
  4111. "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
  4112. (if (or org-src-preserve-indentation
  4113. (org-element-property :preserve-indent element))
  4114. value
  4115. (org-remove-indentation value)))))
  4116. ;; Build a regexp matching a loc with a reference.
  4117. (ref-re (org-src-coderef-regexp (org-src-coderef-format element))))
  4118. ;; Return value.
  4119. (cons
  4120. ;; Code with references removed.
  4121. (org-element-normalize-string
  4122. (mapconcat
  4123. (lambda (loc)
  4124. (cl-incf line)
  4125. (if (not (string-match ref-re loc)) loc
  4126. ;; Ref line: remove ref, and signal its position in REFS.
  4127. (push (cons line (match-string 3 loc)) refs)
  4128. (replace-match "" nil nil loc 1)))
  4129. (org-split-string code "\n") "\n"))
  4130. ;; Reference alist.
  4131. refs)))
  4132. (defun org-export-format-code (code fun &optional num-lines ref-alist)
  4133. "Format CODE by applying FUN line-wise and return it.
  4134. CODE is a string representing the code to format. FUN is
  4135. a function. It must accept three arguments: a line of
  4136. code (string), the current line number (integer) or nil and the
  4137. reference associated to the current line (string) or nil.
  4138. Optional argument NUM-LINES can be an integer representing the
  4139. number of code lines accumulated until the current code. Line
  4140. numbers passed to FUN will take it into account. If it is nil,
  4141. FUN's second argument will always be nil. This number can be
  4142. obtained with `org-export-get-loc' function.
  4143. Optional argument REF-ALIST can be an alist between relative line
  4144. number (i.e. ignoring NUM-LINES) and the name of the code
  4145. reference on it. If it is nil, FUN's third argument will always
  4146. be nil. It can be obtained through the use of
  4147. `org-export-unravel-code' function."
  4148. (let ((--locs (org-split-string code "\n"))
  4149. (--line 0))
  4150. (org-element-normalize-string
  4151. (mapconcat
  4152. (lambda (--loc)
  4153. (cl-incf --line)
  4154. (let ((--ref (cdr (assq --line ref-alist))))
  4155. (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
  4156. --locs "\n"))))
  4157. (defun org-export-format-code-default (element info)
  4158. "Return source code from ELEMENT, formatted in a standard way.
  4159. ELEMENT is either a `src-block' or `example-block' element. INFO
  4160. is a plist used as a communication channel.
  4161. This function takes care of line numbering and code references
  4162. inclusion. Line numbers, when applicable, appear at the
  4163. beginning of the line, separated from the code by two white
  4164. spaces. Code references, on the other hand, appear flushed to
  4165. the right, separated by six white spaces from the widest line of
  4166. code."
  4167. ;; Extract code and references.
  4168. (let* ((code-info (org-export-unravel-code element))
  4169. (code (car code-info))
  4170. (code-lines (org-split-string code "\n")))
  4171. (if (null code-lines) ""
  4172. (let* ((refs (and (org-element-property :retain-labels element)
  4173. (cdr code-info)))
  4174. ;; Handle line numbering.
  4175. (num-start (org-export-get-loc element info))
  4176. (num-fmt
  4177. (and num-start
  4178. (format "%%%ds "
  4179. (length (number-to-string
  4180. (+ (length code-lines) num-start))))))
  4181. ;; Prepare references display, if required. Any reference
  4182. ;; should start six columns after the widest line of code,
  4183. ;; wrapped with parenthesis.
  4184. (max-width
  4185. (+ (apply 'max (mapcar 'length code-lines))
  4186. (if (not num-start) 0 (length (format num-fmt num-start))))))
  4187. (org-export-format-code
  4188. code
  4189. (lambda (loc line-num ref)
  4190. (let ((number-str (and num-fmt (format num-fmt line-num))))
  4191. (concat
  4192. number-str
  4193. loc
  4194. (and ref
  4195. (concat (make-string
  4196. (- (+ 6 max-width)
  4197. (+ (length loc) (length number-str))) ? )
  4198. (format "(%s)" ref))))))
  4199. num-start refs)))))
  4200. ;;;; For Tables
  4201. ;;
  4202. ;; `org-export-table-has-special-column-p' and and
  4203. ;; `org-export-table-row-is-special-p' are predicates used to look for
  4204. ;; meta-information about the table structure.
  4205. ;;
  4206. ;; `org-table-has-header-p' tells when the rows before the first rule
  4207. ;; should be considered as table's header.
  4208. ;;
  4209. ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
  4210. ;; and `org-export-table-cell-borders' extract information from
  4211. ;; a table-cell element.
  4212. ;;
  4213. ;; `org-export-table-dimensions' gives the number on rows and columns
  4214. ;; in the table, ignoring horizontal rules and special columns.
  4215. ;; `org-export-table-cell-address', given a table-cell object, returns
  4216. ;; the absolute address of a cell. On the other hand,
  4217. ;; `org-export-get-table-cell-at' does the contrary.
  4218. ;;
  4219. ;; `org-export-table-cell-starts-colgroup-p',
  4220. ;; `org-export-table-cell-ends-colgroup-p',
  4221. ;; `org-export-table-row-starts-rowgroup-p',
  4222. ;; `org-export-table-row-ends-rowgroup-p',
  4223. ;; `org-export-table-row-starts-header-p',
  4224. ;; `org-export-table-row-ends-header-p' and
  4225. ;; `org-export-table-row-in-header-p' indicate position of current row
  4226. ;; or cell within the table.
  4227. (defun org-export-table-has-special-column-p (table)
  4228. "Non-nil when TABLE has a special column.
  4229. All special columns will be ignored during export."
  4230. ;; The table has a special column when every first cell of every row
  4231. ;; has an empty value or contains a symbol among "/", "#", "!", "$",
  4232. ;; "*" "_" and "^". Though, do not consider a first row containing
  4233. ;; only empty cells as special.
  4234. (let ((special-column-p 'empty))
  4235. (catch 'exit
  4236. (dolist (row (org-element-contents table))
  4237. (when (eq (org-element-property :type row) 'standard)
  4238. (let ((value (org-element-contents
  4239. (car (org-element-contents row)))))
  4240. (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
  4241. (setq special-column-p 'special))
  4242. ((not value))
  4243. (t (throw 'exit nil))))))
  4244. (eq special-column-p 'special))))
  4245. (defun org-export-table-has-header-p (table info)
  4246. "Non-nil when TABLE has a header.
  4247. INFO is a plist used as a communication channel.
  4248. A table has a header when it contains at least two row groups."
  4249. (let ((cache (or (plist-get info :table-header-cache)
  4250. (plist-get (setq info
  4251. (plist-put info :table-header-cache
  4252. (make-hash-table :test 'eq)))
  4253. :table-header-cache))))
  4254. (or (gethash table cache)
  4255. (let ((rowgroup 1) row-flag)
  4256. (puthash
  4257. table
  4258. (org-element-map table 'table-row
  4259. (lambda (row)
  4260. (cond
  4261. ((> rowgroup 1) t)
  4262. ((and row-flag (eq (org-element-property :type row) 'rule))
  4263. (cl-incf rowgroup) (setq row-flag nil))
  4264. ((and (not row-flag) (eq (org-element-property :type row)
  4265. 'standard))
  4266. (setq row-flag t) nil)))
  4267. info 'first-match)
  4268. cache)))))
  4269. (defun org-export-table-row-is-special-p (table-row _)
  4270. "Non-nil if TABLE-ROW is considered special.
  4271. All special rows will be ignored during export."
  4272. (when (eq (org-element-property :type table-row) 'standard)
  4273. (let ((first-cell (org-element-contents
  4274. (car (org-element-contents table-row)))))
  4275. ;; A row is special either when...
  4276. (or
  4277. ;; ... it starts with a field only containing "/",
  4278. (equal first-cell '("/"))
  4279. ;; ... the table contains a special column and the row start
  4280. ;; with a marking character among, "^", "_", "$" or "!",
  4281. (and (org-export-table-has-special-column-p
  4282. (org-export-get-parent table-row))
  4283. (member first-cell '(("^") ("_") ("$") ("!"))))
  4284. ;; ... it contains only alignment cookies and empty cells.
  4285. (let ((special-row-p 'empty))
  4286. (catch 'exit
  4287. (dolist (cell (org-element-contents table-row))
  4288. (let ((value (org-element-contents cell)))
  4289. ;; Since VALUE is a secondary string, the following
  4290. ;; checks avoid expanding it with `org-export-data'.
  4291. (cond ((not value))
  4292. ((and (not (cdr value))
  4293. (stringp (car value))
  4294. (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
  4295. (car value)))
  4296. (setq special-row-p 'cookie))
  4297. (t (throw 'exit nil)))))
  4298. (eq special-row-p 'cookie)))))))
  4299. (defun org-export-table-row-group (table-row info)
  4300. "Return TABLE-ROW's group number, as an integer.
  4301. INFO is a plist used as the communication channel.
  4302. Return value is the group number, as an integer, or nil for
  4303. special rows and rows separators. First group is also table's
  4304. header."
  4305. (let ((cache (or (plist-get info :table-row-group-cache)
  4306. (plist-get (setq info
  4307. (plist-put info :table-row-group-cache
  4308. (make-hash-table :test 'eq)))
  4309. :table-row-group-cache))))
  4310. (cond ((gethash table-row cache))
  4311. ((eq (org-element-property :type table-row) 'rule) nil)
  4312. (t (let ((group 0) row-flag)
  4313. (org-element-map (org-export-get-parent table-row) 'table-row
  4314. (lambda (row)
  4315. (if (eq (org-element-property :type row) 'rule)
  4316. (setq row-flag nil)
  4317. (unless row-flag (cl-incf group) (setq row-flag t)))
  4318. (when (eq table-row row) (puthash table-row group cache)))
  4319. info 'first-match))))))
  4320. (defun org-export-table-cell-width (table-cell info)
  4321. "Return TABLE-CELL contents width.
  4322. INFO is a plist used as the communication channel.
  4323. Return value is the width given by the last width cookie in the
  4324. same column as TABLE-CELL, or nil."
  4325. (let* ((row (org-export-get-parent table-cell))
  4326. (table (org-export-get-parent row))
  4327. (cells (org-element-contents row))
  4328. (columns (length cells))
  4329. (column (- columns (length (memq table-cell cells))))
  4330. (cache (or (plist-get info :table-cell-width-cache)
  4331. (plist-get (setq info
  4332. (plist-put info :table-cell-width-cache
  4333. (make-hash-table :test 'eq)))
  4334. :table-cell-width-cache)))
  4335. (width-vector (or (gethash table cache)
  4336. (puthash table (make-vector columns 'empty) cache)))
  4337. (value (aref width-vector column)))
  4338. (if (not (eq value 'empty)) value
  4339. (let (cookie-width)
  4340. (dolist (row (org-element-contents table)
  4341. (aset width-vector column cookie-width))
  4342. (when (org-export-table-row-is-special-p row info)
  4343. ;; In a special row, try to find a width cookie at COLUMN.
  4344. (let* ((value (org-element-contents
  4345. (elt (org-element-contents row) column)))
  4346. (cookie (car value)))
  4347. ;; The following checks avoid expanding unnecessarily
  4348. ;; the cell with `org-export-data'.
  4349. (when (and value
  4350. (not (cdr value))
  4351. (stringp cookie)
  4352. (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
  4353. (match-string 1 cookie))
  4354. (setq cookie-width
  4355. (string-to-number (match-string 1 cookie)))))))))))
  4356. (defun org-export-table-cell-alignment (table-cell info)
  4357. "Return TABLE-CELL contents alignment.
  4358. INFO is a plist used as the communication channel.
  4359. Return alignment as specified by the last alignment cookie in the
  4360. same column as TABLE-CELL. If no such cookie is found, a default
  4361. alignment value will be deduced from fraction of numbers in the
  4362. column (see `org-table-number-fraction' for more information).
  4363. Possible values are `left', `right' and `center'."
  4364. ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
  4365. (require 'org-table)
  4366. (let* ((row (org-export-get-parent table-cell))
  4367. (table (org-export-get-parent row))
  4368. (cells (org-element-contents row))
  4369. (columns (length cells))
  4370. (column (- columns (length (memq table-cell cells))))
  4371. (cache (or (plist-get info :table-cell-alignment-cache)
  4372. (plist-get (setq info
  4373. (plist-put info :table-cell-alignment-cache
  4374. (make-hash-table :test 'eq)))
  4375. :table-cell-alignment-cache)))
  4376. (align-vector (or (gethash table cache)
  4377. (puthash table (make-vector columns nil) cache))))
  4378. (or (aref align-vector column)
  4379. (let ((number-cells 0)
  4380. (total-cells 0)
  4381. cookie-align
  4382. previous-cell-number-p)
  4383. (dolist (row (org-element-contents (org-export-get-parent row)))
  4384. (cond
  4385. ;; In a special row, try to find an alignment cookie at
  4386. ;; COLUMN.
  4387. ((org-export-table-row-is-special-p row info)
  4388. (let ((value (org-element-contents
  4389. (elt (org-element-contents row) column))))
  4390. ;; Since VALUE is a secondary string, the following
  4391. ;; checks avoid useless expansion through
  4392. ;; `org-export-data'.
  4393. (when (and value
  4394. (not (cdr value))
  4395. (stringp (car value))
  4396. (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
  4397. (car value))
  4398. (match-string 1 (car value)))
  4399. (setq cookie-align (match-string 1 (car value))))))
  4400. ;; Ignore table rules.
  4401. ((eq (org-element-property :type row) 'rule))
  4402. ;; In a standard row, check if cell's contents are
  4403. ;; expressing some kind of number. Increase NUMBER-CELLS
  4404. ;; accordingly. Though, don't bother if an alignment
  4405. ;; cookie has already defined cell's alignment.
  4406. ((not cookie-align)
  4407. (let ((value (org-export-data
  4408. (org-element-contents
  4409. (elt (org-element-contents row) column))
  4410. info)))
  4411. (cl-incf total-cells)
  4412. ;; Treat an empty cell as a number if it follows
  4413. ;; a number.
  4414. (if (not (or (string-match org-table-number-regexp value)
  4415. (and (string= value "") previous-cell-number-p)))
  4416. (setq previous-cell-number-p nil)
  4417. (setq previous-cell-number-p t)
  4418. (cl-incf number-cells))))))
  4419. ;; Return value. Alignment specified by cookies has
  4420. ;; precedence over alignment deduced from cell's contents.
  4421. (aset align-vector
  4422. column
  4423. (cond ((equal cookie-align "l") 'left)
  4424. ((equal cookie-align "r") 'right)
  4425. ((equal cookie-align "c") 'center)
  4426. ((>= (/ (float number-cells) total-cells)
  4427. org-table-number-fraction)
  4428. 'right)
  4429. (t 'left)))))))
  4430. (defun org-export-table-cell-borders (table-cell info)
  4431. "Return TABLE-CELL borders.
  4432. INFO is a plist used as a communication channel.
  4433. Return value is a list of symbols, or nil. Possible values are:
  4434. `top', `bottom', `above', `below', `left' and `right'. Note:
  4435. `top' (resp. `bottom') only happen for a cell in the first
  4436. row (resp. last row) of the table, ignoring table rules, if any.
  4437. Returned borders ignore special rows."
  4438. (let* ((row (org-export-get-parent table-cell))
  4439. (table (org-export-get-parent-table table-cell))
  4440. borders)
  4441. ;; Top/above border? TABLE-CELL has a border above when a rule
  4442. ;; used to demarcate row groups can be found above. Hence,
  4443. ;; finding a rule isn't sufficient to push `above' in BORDERS:
  4444. ;; another regular row has to be found above that rule.
  4445. (let (rule-flag)
  4446. (catch 'exit
  4447. ;; Look at every row before the current one.
  4448. (dolist (row (cdr (memq row (reverse (org-element-contents table)))))
  4449. (cond ((eq (org-element-property :type row) 'rule)
  4450. (setq rule-flag t))
  4451. ((not (org-export-table-row-is-special-p row info))
  4452. (if rule-flag (throw 'exit (push 'above borders))
  4453. (throw 'exit nil)))))
  4454. ;; No rule above, or rule found starts the table (ignoring any
  4455. ;; special row): TABLE-CELL is at the top of the table.
  4456. (when rule-flag (push 'above borders))
  4457. (push 'top borders)))
  4458. ;; Bottom/below border? TABLE-CELL has a border below when next
  4459. ;; non-regular row below is a rule.
  4460. (let (rule-flag)
  4461. (catch 'exit
  4462. ;; Look at every row after the current one.
  4463. (dolist (row (cdr (memq row (org-element-contents table))))
  4464. (cond ((eq (org-element-property :type row) 'rule)
  4465. (setq rule-flag t))
  4466. ((not (org-export-table-row-is-special-p row info))
  4467. (if rule-flag (throw 'exit (push 'below borders))
  4468. (throw 'exit nil)))))
  4469. ;; No rule below, or rule found ends the table (modulo some
  4470. ;; special row): TABLE-CELL is at the bottom of the table.
  4471. (when rule-flag (push 'below borders))
  4472. (push 'bottom borders)))
  4473. ;; Right/left borders? They can only be specified by column
  4474. ;; groups. Column groups are defined in a row starting with "/".
  4475. ;; Also a column groups row only contains "<", "<>", ">" or blank
  4476. ;; cells.
  4477. (catch 'exit
  4478. (let ((column (let ((cells (org-element-contents row)))
  4479. (- (length cells) (length (memq table-cell cells))))))
  4480. ;; Table rows are read in reverse order so last column groups
  4481. ;; row has precedence over any previous one.
  4482. (dolist (row (reverse (org-element-contents table)))
  4483. (unless (eq (org-element-property :type row) 'rule)
  4484. (when (equal (org-element-contents
  4485. (car (org-element-contents row)))
  4486. '("/"))
  4487. (let ((column-groups
  4488. (mapcar
  4489. (lambda (cell)
  4490. (let ((value (org-element-contents cell)))
  4491. (when (member value '(("<") ("<>") (">") nil))
  4492. (car value))))
  4493. (org-element-contents row))))
  4494. ;; There's a left border when previous cell, if
  4495. ;; any, ends a group, or current one starts one.
  4496. (when (or (and (not (zerop column))
  4497. (member (elt column-groups (1- column))
  4498. '(">" "<>")))
  4499. (member (elt column-groups column) '("<" "<>")))
  4500. (push 'left borders))
  4501. ;; There's a right border when next cell, if any,
  4502. ;; starts a group, or current one ends one.
  4503. (when (or (and (/= (1+ column) (length column-groups))
  4504. (member (elt column-groups (1+ column))
  4505. '("<" "<>")))
  4506. (member (elt column-groups column) '(">" "<>")))
  4507. (push 'right borders))
  4508. (throw 'exit nil)))))))
  4509. ;; Return value.
  4510. borders))
  4511. (defun org-export-table-cell-starts-colgroup-p (table-cell info)
  4512. "Non-nil when TABLE-CELL is at the beginning of a column group.
  4513. INFO is a plist used as a communication channel."
  4514. ;; A cell starts a column group either when it is at the beginning
  4515. ;; of a row (or after the special column, if any) or when it has
  4516. ;; a left border.
  4517. (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
  4518. 'identity info 'first-match)
  4519. table-cell)
  4520. (memq 'left (org-export-table-cell-borders table-cell info))))
  4521. (defun org-export-table-cell-ends-colgroup-p (table-cell info)
  4522. "Non-nil when TABLE-CELL is at the end of a column group.
  4523. INFO is a plist used as a communication channel."
  4524. ;; A cell ends a column group either when it is at the end of a row
  4525. ;; or when it has a right border.
  4526. (or (eq (car (last (org-element-contents
  4527. (org-export-get-parent table-cell))))
  4528. table-cell)
  4529. (memq 'right (org-export-table-cell-borders table-cell info))))
  4530. (defun org-export-table-row-starts-rowgroup-p (table-row info)
  4531. "Non-nil when TABLE-ROW is at the beginning of a row group.
  4532. INFO is a plist used as a communication channel."
  4533. (unless (or (eq (org-element-property :type table-row) 'rule)
  4534. (org-export-table-row-is-special-p table-row info))
  4535. (let ((borders (org-export-table-cell-borders
  4536. (car (org-element-contents table-row)) info)))
  4537. (or (memq 'top borders) (memq 'above borders)))))
  4538. (defun org-export-table-row-ends-rowgroup-p (table-row info)
  4539. "Non-nil when TABLE-ROW is at the end of a row group.
  4540. INFO is a plist used as a communication channel."
  4541. (unless (or (eq (org-element-property :type table-row) 'rule)
  4542. (org-export-table-row-is-special-p table-row info))
  4543. (let ((borders (org-export-table-cell-borders
  4544. (car (org-element-contents table-row)) info)))
  4545. (or (memq 'bottom borders) (memq 'below borders)))))
  4546. (defun org-export-table-row-in-header-p (table-row info)
  4547. "Non-nil when TABLE-ROW is located within table's header.
  4548. INFO is a plist used as a communication channel. Always return
  4549. nil for special rows and rows separators."
  4550. (and (org-export-table-has-header-p
  4551. (org-export-get-parent-table table-row) info)
  4552. (eql (org-export-table-row-group table-row info) 1)))
  4553. (defun org-export-table-row-starts-header-p (table-row info)
  4554. "Non-nil when TABLE-ROW is the first table header's row.
  4555. INFO is a plist used as a communication channel."
  4556. (and (org-export-table-row-in-header-p table-row info)
  4557. (org-export-table-row-starts-rowgroup-p table-row info)))
  4558. (defun org-export-table-row-ends-header-p (table-row info)
  4559. "Non-nil when TABLE-ROW is the last table header's row.
  4560. INFO is a plist used as a communication channel."
  4561. (and (org-export-table-row-in-header-p table-row info)
  4562. (org-export-table-row-ends-rowgroup-p table-row info)))
  4563. (defun org-export-table-row-number (table-row info)
  4564. "Return TABLE-ROW number.
  4565. INFO is a plist used as a communication channel. Return value is
  4566. zero-based and ignores separators. The function returns nil for
  4567. special columns and separators."
  4568. (when (and (eq (org-element-property :type table-row) 'standard)
  4569. (not (org-export-table-row-is-special-p table-row info)))
  4570. (let ((number 0))
  4571. (org-element-map (org-export-get-parent-table table-row) 'table-row
  4572. (lambda (row)
  4573. (cond ((eq row table-row) number)
  4574. ((eq (org-element-property :type row) 'standard)
  4575. (cl-incf number) nil)))
  4576. info 'first-match))))
  4577. (defun org-export-table-dimensions (table info)
  4578. "Return TABLE dimensions.
  4579. INFO is a plist used as a communication channel.
  4580. Return value is a CONS like (ROWS . COLUMNS) where
  4581. ROWS (resp. COLUMNS) is the number of exportable
  4582. rows (resp. columns)."
  4583. (let (first-row (columns 0) (rows 0))
  4584. ;; Set number of rows, and extract first one.
  4585. (org-element-map table 'table-row
  4586. (lambda (row)
  4587. (when (eq (org-element-property :type row) 'standard)
  4588. (cl-incf rows)
  4589. (unless first-row (setq first-row row)))) info)
  4590. ;; Set number of columns.
  4591. (org-element-map first-row 'table-cell (lambda (_) (cl-incf columns)) info)
  4592. ;; Return value.
  4593. (cons rows columns)))
  4594. (defun org-export-table-cell-address (table-cell info)
  4595. "Return address of a regular TABLE-CELL object.
  4596. TABLE-CELL is the cell considered. INFO is a plist used as
  4597. a communication channel.
  4598. Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
  4599. zero-based index. Only exportable cells are considered. The
  4600. function returns nil for other cells."
  4601. (let* ((table-row (org-export-get-parent table-cell))
  4602. (row-number (org-export-table-row-number table-row info)))
  4603. (when row-number
  4604. (cons row-number
  4605. (let ((col-count 0))
  4606. (org-element-map table-row 'table-cell
  4607. (lambda (cell)
  4608. (if (eq cell table-cell) col-count (cl-incf col-count) nil))
  4609. info 'first-match))))))
  4610. (defun org-export-get-table-cell-at (address table info)
  4611. "Return regular table-cell object at ADDRESS in TABLE.
  4612. Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
  4613. zero-based index. TABLE is a table type element. INFO is
  4614. a plist used as a communication channel.
  4615. If no table-cell, among exportable cells, is found at ADDRESS,
  4616. return nil."
  4617. (let ((column-pos (cdr address)) (column-count 0))
  4618. (org-element-map
  4619. ;; Row at (car address) or nil.
  4620. (let ((row-pos (car address)) (row-count 0))
  4621. (org-element-map table 'table-row
  4622. (lambda (row)
  4623. (cond ((eq (org-element-property :type row) 'rule) nil)
  4624. ((= row-count row-pos) row)
  4625. (t (cl-incf row-count) nil)))
  4626. info 'first-match))
  4627. 'table-cell
  4628. (lambda (cell)
  4629. (if (= column-count column-pos) cell
  4630. (cl-incf column-count) nil))
  4631. info 'first-match)))
  4632. ;;;; For Tables Of Contents
  4633. ;;
  4634. ;; `org-export-collect-headlines' builds a list of all exportable
  4635. ;; headline elements, maybe limited to a certain depth. One can then
  4636. ;; easily parse it and transcode it.
  4637. ;;
  4638. ;; Building lists of tables, figures or listings is quite similar.
  4639. ;; Once the generic function `org-export-collect-elements' is defined,
  4640. ;; `org-export-collect-tables', `org-export-collect-figures' and
  4641. ;; `org-export-collect-listings' can be derived from it.
  4642. (defun org-export-collect-headlines (info &optional n scope)
  4643. "Collect headlines in order to build a table of contents.
  4644. INFO is a plist used as a communication channel.
  4645. When optional argument N is an integer, it specifies the depth of
  4646. the table of contents. Otherwise, it is set to the value of the
  4647. last headline level. See `org-export-headline-levels' for more
  4648. information.
  4649. Optional argument SCOPE, when non-nil, is an element. If it is
  4650. a headline, only children of SCOPE are collected. Otherwise,
  4651. collect children of the headline containing provided element. If
  4652. there is no such headline, collect all headlines. In any case,
  4653. argument N becomes relative to the level of that headline.
  4654. Return a list of all exportable headlines as parsed elements.
  4655. Footnote sections are ignored."
  4656. (let* ((scope (cond ((not scope) (plist-get info :parse-tree))
  4657. ((eq (org-element-type scope) 'headline) scope)
  4658. ((org-export-get-parent-headline scope))
  4659. (t (plist-get info :parse-tree))))
  4660. (limit (plist-get info :headline-levels))
  4661. (n (if (not (wholenump n)) limit
  4662. (min (if (eq (org-element-type scope) 'org-data) n
  4663. (+ (org-export-get-relative-level scope info) n))
  4664. limit))))
  4665. (org-element-map (org-element-contents scope) 'headline
  4666. (lambda (headline)
  4667. (unless (org-element-property :footnote-section-p headline)
  4668. (let ((level (org-export-get-relative-level headline info)))
  4669. (and (<= level n) headline))))
  4670. info)))
  4671. (defun org-export-collect-elements (type info &optional predicate)
  4672. "Collect referenceable elements of a determined type.
  4673. TYPE can be a symbol or a list of symbols specifying element
  4674. types to search. Only elements with a caption are collected.
  4675. INFO is a plist used as a communication channel.
  4676. When non-nil, optional argument PREDICATE is a function accepting
  4677. one argument, an element of type TYPE. It returns a non-nil
  4678. value when that element should be collected.
  4679. Return a list of all elements found, in order of appearance."
  4680. (org-element-map (plist-get info :parse-tree) type
  4681. (lambda (element)
  4682. (and (org-element-property :caption element)
  4683. (or (not predicate) (funcall predicate element))
  4684. element))
  4685. info))
  4686. (defun org-export-collect-tables (info)
  4687. "Build a list of tables.
  4688. INFO is a plist used as a communication channel.
  4689. Return a list of table elements with a caption."
  4690. (org-export-collect-elements 'table info))
  4691. (defun org-export-collect-figures (info predicate)
  4692. "Build a list of figures.
  4693. INFO is a plist used as a communication channel. PREDICATE is
  4694. a function which accepts one argument: a paragraph element and
  4695. whose return value is non-nil when that element should be
  4696. collected.
  4697. A figure is a paragraph type element, with a caption, verifying
  4698. PREDICATE. The latter has to be provided since a \"figure\" is
  4699. a vague concept that may depend on back-end.
  4700. Return a list of elements recognized as figures."
  4701. (org-export-collect-elements 'paragraph info predicate))
  4702. (defun org-export-collect-listings (info)
  4703. "Build a list of src blocks.
  4704. INFO is a plist used as a communication channel.
  4705. Return a list of src-block elements with a caption."
  4706. (org-export-collect-elements 'src-block info))
  4707. ;;;; Smart Quotes
  4708. ;;
  4709. ;; The main function for the smart quotes sub-system is
  4710. ;; `org-export-activate-smart-quotes', which replaces every quote in
  4711. ;; a given string from the parse tree with its "smart" counterpart.
  4712. ;;
  4713. ;; Dictionary for smart quotes is stored in
  4714. ;; `org-export-smart-quotes-alist'.
  4715. (defconst org-export-smart-quotes-alist
  4716. '(("da"
  4717. ;; one may use: »...«, "...", ›...‹, or '...'.
  4718. ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
  4719. ;; LaTeX quotes require Babel!
  4720. (primary-opening
  4721. :utf-8 "»" :html "&raquo;" :latex ">>" :texinfo "@guillemetright{}")
  4722. (primary-closing
  4723. :utf-8 "«" :html "&laquo;" :latex "<<" :texinfo "@guillemetleft{}")
  4724. (secondary-opening
  4725. :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}" :texinfo "@guilsinglright{}")
  4726. (secondary-closing
  4727. :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}" :texinfo "@guilsingleft{}")
  4728. (apostrophe :utf-8 "’" :html "&rsquo;"))
  4729. ("de"
  4730. (primary-opening
  4731. :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
  4732. (primary-closing
  4733. :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
  4734. (secondary-opening
  4735. :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
  4736. (secondary-closing
  4737. :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
  4738. (apostrophe :utf-8 "’" :html "&rsquo;"))
  4739. ("en"
  4740. (primary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
  4741. (primary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
  4742. (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
  4743. (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
  4744. (apostrophe :utf-8 "’" :html "&rsquo;"))
  4745. ("es"
  4746. (primary-opening
  4747. :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
  4748. :texinfo "@guillemetleft{}")
  4749. (primary-closing
  4750. :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
  4751. :texinfo "@guillemetright{}")
  4752. (secondary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
  4753. (secondary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
  4754. (apostrophe :utf-8 "’" :html "&rsquo;"))
  4755. ("fr"
  4756. (primary-opening
  4757. :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
  4758. :texinfo "@guillemetleft{}@tie{}")
  4759. (primary-closing
  4760. :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
  4761. :texinfo "@tie{}@guillemetright{}")
  4762. (secondary-opening
  4763. :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
  4764. :texinfo "@guillemetleft{}@tie{}")
  4765. (secondary-closing :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
  4766. :texinfo "@tie{}@guillemetright{}")
  4767. (apostrophe :utf-8 "’" :html "&rsquo;"))
  4768. ("is"
  4769. (primary-opening
  4770. :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
  4771. (primary-closing
  4772. :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
  4773. (secondary-opening
  4774. :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
  4775. (secondary-closing
  4776. :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
  4777. (apostrophe :utf-8 "’" :html "&rsquo;"))
  4778. ("no"
  4779. ;; https://nn.wikipedia.org/wiki/Sitatteikn
  4780. (primary-opening
  4781. :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
  4782. :texinfo "@guillemetleft{}")
  4783. (primary-closing
  4784. :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
  4785. :texinfo "@guillemetright{}")
  4786. (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
  4787. (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
  4788. (apostrophe :utf-8 "’" :html "&rsquo;"))
  4789. ("nb"
  4790. ;; https://nn.wikipedia.org/wiki/Sitatteikn
  4791. (primary-opening
  4792. :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
  4793. :texinfo "@guillemetleft{}")
  4794. (primary-closing
  4795. :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
  4796. :texinfo "@guillemetright{}")
  4797. (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
  4798. (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
  4799. (apostrophe :utf-8 "’" :html "&rsquo;"))
  4800. ("nn"
  4801. ;; https://nn.wikipedia.org/wiki/Sitatteikn
  4802. (primary-opening
  4803. :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
  4804. :texinfo "@guillemetleft{}")
  4805. (primary-closing
  4806. :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
  4807. :texinfo "@guillemetright{}")
  4808. (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
  4809. (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
  4810. (apostrophe :utf-8 "’" :html "&rsquo;"))
  4811. ("ru"
  4812. ;; http://ru.wikipedia.org/wiki/%D0%9A%D0%B0%D0%B2%D1%8B%D1%87%D0%BA%D0%B8#.D0.9A.D0.B0.D0.B2.D1.8B.D1.87.D0.BA.D0.B8.2C_.D0.B8.D1.81.D0.BF.D0.BE.D0.BB.D1.8C.D0.B7.D1.83.D0.B5.D0.BC.D1.8B.D0.B5_.D0.B2_.D1.80.D1.83.D1.81.D1.81.D0.BA.D0.BE.D0.BC_.D1.8F.D0.B7.D1.8B.D0.BA.D0.B5
  4813. ;; http://www.artlebedev.ru/kovodstvo/sections/104/
  4814. (primary-opening :utf-8 "«" :html "&laquo;" :latex "{}<<"
  4815. :texinfo "@guillemetleft{}")
  4816. (primary-closing :utf-8 "»" :html "&raquo;" :latex ">>{}"
  4817. :texinfo "@guillemetright{}")
  4818. (secondary-opening
  4819. :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}" :texinfo "@quotedblbase{}")
  4820. (secondary-closing
  4821. :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}" :texinfo "@quotedblleft{}")
  4822. (apostrophe :utf-8 "’" :html: "&#39;"))
  4823. ("sv"
  4824. ;; based on https://sv.wikipedia.org/wiki/Citattecken
  4825. (primary-opening :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
  4826. (primary-closing :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
  4827. (secondary-opening :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
  4828. (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
  4829. (apostrophe :utf-8 "’" :html "&rsquo;")))
  4830. "Smart quotes translations.
  4831. Alist whose CAR is a language string and CDR is an alist with
  4832. quote type as key and a plist associating various encodings to
  4833. their translation as value.
  4834. A quote type can be any symbol among `primary-opening',
  4835. `primary-closing', `secondary-opening', `secondary-closing' and
  4836. `apostrophe'.
  4837. Valid encodings include `:utf-8', `:html', `:latex' and
  4838. `:texinfo'.
  4839. If no translation is found, the quote character is left as-is.")
  4840. (defun org-export--smart-quote-status (s info)
  4841. "Return smart quote status at the beginning of string S.
  4842. INFO is the current export state, as a plist."
  4843. (let* ((parent (org-element-property :parent s))
  4844. (cache (or (plist-get info :smart-quote-cache)
  4845. (let ((table (make-hash-table :test #'eq)))
  4846. (plist-put info :smart-quote-cache table)
  4847. table)))
  4848. (value (gethash parent cache 'missing-data)))
  4849. (if (not (eq value 'missing-data)) (cdr (assq s value))
  4850. (let (level1-open full-status)
  4851. (org-element-map
  4852. (let ((secondary (org-element-secondary-p s)))
  4853. (if secondary (org-element-property secondary parent)
  4854. (org-element-contents parent)))
  4855. 'plain-text
  4856. (lambda (text)
  4857. (let ((start 0) current-status)
  4858. (while (setq start (string-match "['\"]" text start))
  4859. (push
  4860. (cond
  4861. ((equal (match-string 0 text) "\"")
  4862. (setf level1-open (not level1-open))
  4863. (if level1-open 'primary-opening 'primary-closing))
  4864. ;; Not already in a level 1 quote: this is an
  4865. ;; apostrophe.
  4866. ((not level1-open) 'apostrophe)
  4867. ;; Extract previous char and next char. As
  4868. ;; a special case, they can also be set to `blank',
  4869. ;; `no-blank' or nil. Then determine if current
  4870. ;; match is allowed as an opening quote or a closing
  4871. ;; quote.
  4872. (t
  4873. (let* ((previous
  4874. (if (> start 0) (substring text (1- start) start)
  4875. (let ((p (org-export-get-previous-element
  4876. text info)))
  4877. (cond ((not p) nil)
  4878. ((stringp p) (substring p -1))
  4879. ((memq (org-element-property :post-blank p)
  4880. '(0 nil))
  4881. 'no-blank)
  4882. (t 'blank)))))
  4883. (next
  4884. (if (< (1+ start) (length text))
  4885. (substring text (1+ start) (+ start 2))
  4886. (let ((n (org-export-get-next-element text info)))
  4887. (cond ((not n) nil)
  4888. ((stringp n) (substring n 0 1))
  4889. (t 'no-blank)))))
  4890. (allow-open
  4891. (and (if (stringp previous)
  4892. (string-match "\\s\"\\|\\s-\\|\\s("
  4893. previous)
  4894. (memq previous '(blank nil)))
  4895. (if (stringp next)
  4896. (string-match "\\w\\|\\s.\\|\\s_" next)
  4897. (eq next 'no-blank))))
  4898. (allow-close
  4899. (and (if (stringp previous)
  4900. (string-match "\\w\\|\\s.\\|\\s_" previous)
  4901. (eq previous 'no-blank))
  4902. (if (stringp next)
  4903. (string-match "\\s-\\|\\s)\\|\\s.\\|\\s\""
  4904. next)
  4905. (memq next '(blank nil))))))
  4906. (cond
  4907. ((and allow-open allow-close) (error "Should not happen"))
  4908. (allow-open 'secondary-opening)
  4909. (allow-close 'secondary-closing)
  4910. (t 'apostrophe)))))
  4911. current-status)
  4912. (cl-incf start))
  4913. (when current-status
  4914. (push (cons text (nreverse current-status)) full-status))))
  4915. info nil org-element-recursive-objects)
  4916. (puthash parent full-status cache)
  4917. (cdr (assq s full-status))))))
  4918. (defun org-export-activate-smart-quotes (s encoding info &optional original)
  4919. "Replace regular quotes with \"smart\" quotes in string S.
  4920. ENCODING is a symbol among `:html', `:latex', `:texinfo' and
  4921. `:utf-8'. INFO is a plist used as a communication channel.
  4922. The function has to retrieve information about string
  4923. surroundings in parse tree. It can only happen with an
  4924. unmodified string. Thus, if S has already been through another
  4925. process, a non-nil ORIGINAL optional argument will provide that
  4926. original string.
  4927. Return the new string."
  4928. (let ((quote-status
  4929. (copy-sequence (org-export--smart-quote-status (or original s) info))))
  4930. (replace-regexp-in-string
  4931. "['\"]"
  4932. (lambda (match)
  4933. (or (plist-get
  4934. (cdr (assq (pop quote-status)
  4935. (cdr (assoc (plist-get info :language)
  4936. org-export-smart-quotes-alist))))
  4937. encoding)
  4938. match))
  4939. s nil t)))
  4940. ;;;; Topology
  4941. ;;
  4942. ;; Here are various functions to retrieve information about the
  4943. ;; neighborhood of a given element or object. Neighbors of interest
  4944. ;; are direct parent (`org-export-get-parent'), parent headline
  4945. ;; (`org-export-get-parent-headline'), first element containing an
  4946. ;; object, (`org-export-get-parent-element'), parent table
  4947. ;; (`org-export-get-parent-table'), previous element or object
  4948. ;; (`org-export-get-previous-element') and next element or object
  4949. ;; (`org-export-get-next-element').
  4950. ;; defsubst org-export-get-parent must be defined before first use
  4951. (defun org-export-get-parent-headline (blob)
  4952. "Return BLOB parent headline or nil.
  4953. BLOB is the element or object being considered."
  4954. (org-element-lineage blob '(headline)))
  4955. (defun org-export-get-parent-element (object)
  4956. "Return first element containing OBJECT or nil.
  4957. OBJECT is the object to consider."
  4958. (org-element-lineage object org-element-all-elements))
  4959. (defun org-export-get-parent-table (object)
  4960. "Return OBJECT parent table or nil.
  4961. OBJECT is either a `table-cell' or `table-element' type object."
  4962. (org-element-lineage object '(table)))
  4963. (defun org-export-get-previous-element (blob info &optional n)
  4964. "Return previous element or object.
  4965. BLOB is an element or object. INFO is a plist used as
  4966. a communication channel. Return previous exportable element or
  4967. object, a string, or nil.
  4968. When optional argument N is a positive integer, return a list
  4969. containing up to N siblings before BLOB, from farthest to
  4970. closest. With any other non-nil value, return a list containing
  4971. all of them."
  4972. (let* ((secondary (org-element-secondary-p blob))
  4973. (parent (org-export-get-parent blob))
  4974. (siblings
  4975. (if secondary (org-element-property secondary parent)
  4976. (org-element-contents parent)))
  4977. prev)
  4978. (catch 'exit
  4979. (dolist (obj (cdr (memq blob (reverse siblings))) prev)
  4980. (cond ((memq obj (plist-get info :ignore-list)))
  4981. ((null n) (throw 'exit obj))
  4982. ((not (wholenump n)) (push obj prev))
  4983. ((zerop n) (throw 'exit prev))
  4984. (t (cl-decf n) (push obj prev)))))))
  4985. (defun org-export-get-next-element (blob info &optional n)
  4986. "Return next element or object.
  4987. BLOB is an element or object. INFO is a plist used as
  4988. a communication channel. Return next exportable element or
  4989. object, a string, or nil.
  4990. When optional argument N is a positive integer, return a list
  4991. containing up to N siblings after BLOB, from closest to farthest.
  4992. With any other non-nil value, return a list containing all of
  4993. them."
  4994. (let* ((secondary (org-element-secondary-p blob))
  4995. (parent (org-export-get-parent blob))
  4996. (siblings
  4997. (cdr (memq blob
  4998. (if secondary (org-element-property secondary parent)
  4999. (org-element-contents parent)))))
  5000. next)
  5001. (catch 'exit
  5002. (dolist (obj siblings (nreverse next))
  5003. (cond ((memq obj (plist-get info :ignore-list)))
  5004. ((null n) (throw 'exit obj))
  5005. ((not (wholenump n)) (push obj next))
  5006. ((zerop n) (throw 'exit (nreverse next)))
  5007. (t (cl-decf n) (push obj next)))))))
  5008. ;;;; Translation
  5009. ;;
  5010. ;; `org-export-translate' translates a string according to the language
  5011. ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
  5012. ;; the dictionary used for the translation.
  5013. (defconst org-export-dictionary
  5014. '(("%e %n: %c"
  5015. ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
  5016. ("Author"
  5017. ("ca" :default "Autor")
  5018. ("cs" :default "Autor")
  5019. ("da" :default "Forfatter")
  5020. ("de" :default "Autor")
  5021. ("eo" :html "A&#365;toro")
  5022. ("es" :default "Autor")
  5023. ("et" :default "Autor")
  5024. ("fi" :html "Tekij&auml;")
  5025. ("fr" :default "Auteur")
  5026. ("hu" :default "Szerz&otilde;")
  5027. ("is" :html "H&ouml;fundur")
  5028. ("it" :default "Autore")
  5029. ("ja" :default "著者" :html "&#33879;&#32773;")
  5030. ("nl" :default "Auteur")
  5031. ("no" :default "Forfatter")
  5032. ("nb" :default "Forfatter")
  5033. ("nn" :default "Forfattar")
  5034. ("pl" :default "Autor")
  5035. ("pt_BR" :default "Autor")
  5036. ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
  5037. ("sv" :html "F&ouml;rfattare")
  5038. ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
  5039. ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
  5040. ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
  5041. ("Continued from previous page"
  5042. ("de" :default "Fortsetzung von vorheriger Seite")
  5043. ("es" :html "Contin&uacute;a de la p&aacute;gina anterior" :ascii "Continua de la pagina anterior" :default "Continúa de la página anterior")
  5044. ("fr" :default "Suite de la page précédente")
  5045. ("it" :default "Continua da pagina precedente")
  5046. ("ja" :default "前ページからの続き")
  5047. ("nl" :default "Vervolg van vorige pagina")
  5048. ("pt" :default "Continuação da página anterior")
  5049. ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
  5050. :utf-8 "(Продолжение)"))
  5051. ("Continued on next page"
  5052. ("de" :default "Fortsetzung nächste Seite")
  5053. ("es" :html "Contin&uacute;a en la siguiente p&aacute;gina" :ascii "Continua en la siguiente pagina" :default "Continúa en la siguiente página")
  5054. ("fr" :default "Suite page suivante")
  5055. ("it" :default "Continua alla pagina successiva")
  5056. ("ja" :default "次ページに続く")
  5057. ("nl" :default "Vervolg op volgende pagina")
  5058. ("pt" :default "Continua na página seguinte")
  5059. ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
  5060. :utf-8 "(Продолжение следует)"))
  5061. ("Date"
  5062. ("ca" :default "Data")
  5063. ("cs" :default "Datum")
  5064. ("da" :default "Dato")
  5065. ("de" :default "Datum")
  5066. ("eo" :default "Dato")
  5067. ("es" :default "Fecha")
  5068. ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
  5069. ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
  5070. ("hu" :html "D&aacute;tum")
  5071. ("is" :default "Dagsetning")
  5072. ("it" :default "Data")
  5073. ("ja" :default "日付" :html "&#26085;&#20184;")
  5074. ("nl" :default "Datum")
  5075. ("no" :default "Dato")
  5076. ("nb" :default "Dato")
  5077. ("nn" :default "Dato")
  5078. ("pl" :default "Data")
  5079. ("pt_BR" :default "Data")
  5080. ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
  5081. ("sv" :default "Datum")
  5082. ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
  5083. ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
  5084. ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
  5085. ("Equation"
  5086. ("da" :default "Ligning")
  5087. ("de" :default "Gleichung")
  5088. ("es" :ascii "Ecuacion" :html "Ecuaci&oacute;n" :default "Ecuación")
  5089. ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
  5090. ("fr" :ascii "Equation" :default "Équation")
  5091. ("is" :default "Jafna")
  5092. ("ja" :default "方程式")
  5093. ("no" :default "Ligning")
  5094. ("nb" :default "Ligning")
  5095. ("nn" :default "Likning")
  5096. ("pt_BR" :html "Equa&ccedil;&atilde;o" :default "Equação" :ascii "Equacao")
  5097. ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
  5098. :utf-8 "Уравнение")
  5099. ("sv" :default "Ekvation")
  5100. ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
  5101. ("Figure"
  5102. ("da" :default "Figur")
  5103. ("de" :default "Abbildung")
  5104. ("es" :default "Figura")
  5105. ("et" :default "Joonis")
  5106. ("is" :default "Mynd")
  5107. ("ja" :default "図" :html "&#22259;")
  5108. ("no" :default "Illustrasjon")
  5109. ("nb" :default "Illustrasjon")
  5110. ("nn" :default "Illustrasjon")
  5111. ("pt_BR" :default "Figura")
  5112. ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
  5113. ("sv" :default "Illustration")
  5114. ("zh-CN" :html "&#22270;" :utf-8 "图"))
  5115. ("Figure %d:"
  5116. ("da" :default "Figur %d")
  5117. ("de" :default "Abbildung %d:")
  5118. ("es" :default "Figura %d:")
  5119. ("et" :default "Joonis %d:")
  5120. ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
  5121. ("is" :default "Mynd %d")
  5122. ("ja" :default "図%d: " :html "&#22259;%d: ")
  5123. ("no" :default "Illustrasjon %d")
  5124. ("nb" :default "Illustrasjon %d")
  5125. ("nn" :default "Illustrasjon %d")
  5126. ("pt_BR" :default "Figura %d:")
  5127. ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
  5128. ("sv" :default "Illustration %d")
  5129. ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
  5130. ("Footnotes"
  5131. ("ca" :html "Peus de p&agrave;gina")
  5132. ("cs" :default "Pozn\xe1mky pod carou")
  5133. ("da" :default "Fodnoter")
  5134. ("de" :html "Fu&szlig;noten" :default "Fußnoten")
  5135. ("eo" :default "Piednotoj")
  5136. ("es" :ascii "Nota al pie de pagina" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
  5137. ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
  5138. ("fi" :default "Alaviitteet")
  5139. ("fr" :default "Notes de bas de page")
  5140. ("hu" :html "L&aacute;bjegyzet")
  5141. ("is" :html "Aftanm&aacute;lsgreinar")
  5142. ("it" :html "Note a pi&egrave; di pagina")
  5143. ("ja" :default "脚注" :html "&#33050;&#27880;")
  5144. ("nl" :default "Voetnoten")
  5145. ("no" :default "Fotnoter")
  5146. ("nb" :default "Fotnoter")
  5147. ("nn" :default "Fotnotar")
  5148. ("pl" :default "Przypis")
  5149. ("pt_BR" :html "Notas de Rodap&eacute;" :default "Notas de Rodapé" :ascii "Notas de Rodape")
  5150. ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
  5151. ("sv" :default "Fotnoter")
  5152. ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
  5153. :utf-8 "Примітки")
  5154. ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
  5155. ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
  5156. ("List of Listings"
  5157. ("da" :default "Programmer")
  5158. ("de" :default "Programmauflistungsverzeichnis")
  5159. ("es" :ascii "Indice de Listados de programas" :html "&Iacute;ndice de Listados de programas" :default "Índice de Listados de programas")
  5160. ("et" :default "Loendite nimekiri")
  5161. ("fr" :default "Liste des programmes")
  5162. ("ja" :default "ソースコード目次")
  5163. ("no" :default "Dataprogrammer")
  5164. ("nb" :default "Dataprogrammer")
  5165. ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
  5166. :utf-8 "Список распечаток")
  5167. ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
  5168. ("List of Tables"
  5169. ("da" :default "Tabeller")
  5170. ("de" :default "Tabellenverzeichnis")
  5171. ("es" :ascii "Indice de tablas" :html "&Iacute;ndice de tablas" :default "Índice de tablas")
  5172. ("et" :default "Tabelite nimekiri")
  5173. ("fr" :default "Liste des tableaux")
  5174. ("is" :default "Töfluskrá" :html "T&ouml;fluskr&aacute;")
  5175. ("ja" :default "表目次")
  5176. ("no" :default "Tabeller")
  5177. ("nb" :default "Tabeller")
  5178. ("nn" :default "Tabeller")
  5179. ("pt_BR" :default "Índice de Tabelas" :ascii "Indice de Tabelas")
  5180. ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
  5181. :utf-8 "Список таблиц")
  5182. ("sv" :default "Tabeller")
  5183. ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
  5184. ("Listing"
  5185. ("da" :default "Program")
  5186. ("de" :default "Programmlisting")
  5187. ("es" :default "Listado de programa")
  5188. ("et" :default "Loend")
  5189. ("fr" :default "Programme" :html "Programme")
  5190. ("ja" :default "ソースコード")
  5191. ("no" :default "Dataprogram")
  5192. ("nb" :default "Dataprogram")
  5193. ("pt_BR" :default "Listagem")
  5194. ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072;"
  5195. :utf-8 "Распечатка")
  5196. ("zh-CN" :html "&#20195;&#30721;" :utf-8 "代码"))
  5197. ("Listing %d:"
  5198. ("da" :default "Program %d")
  5199. ("de" :default "Programmlisting %d")
  5200. ("es" :default "Listado de programa %d")
  5201. ("et" :default "Loend %d")
  5202. ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
  5203. ("ja" :default "ソースコード%d:")
  5204. ("no" :default "Dataprogram %d")
  5205. ("nb" :default "Dataprogram %d")
  5206. ("pt_BR" :default "Listagem %d")
  5207. ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
  5208. :utf-8 "Распечатка %d.:")
  5209. ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
  5210. ("References"
  5211. ("fr" :ascii "References" :default "Références")
  5212. ("de" :default "Quellen")
  5213. ("es" :default "Referencias"))
  5214. ("See figure %s"
  5215. ("fr" :default "cf. figure %s"
  5216. :html "cf.&nbsp;figure&nbsp;%s" :latex "cf.~figure~%s"))
  5217. ("See listing %s"
  5218. ("fr" :default "cf. programme %s"
  5219. :html "cf.&nbsp;programme&nbsp;%s" :latex "cf.~programme~%s"))
  5220. ("See section %s"
  5221. ("da" :default "jævnfør afsnit %s")
  5222. ("de" :default "siehe Abschnitt %s")
  5223. ("es" :ascii "Vea seccion %s" :html "Vea secci&oacute;n %s" :default "Vea sección %s")
  5224. ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
  5225. ("fr" :default "cf. section %s")
  5226. ("ja" :default "セクション %s を参照")
  5227. ("pt_BR" :html "Veja a se&ccedil;&atilde;o %s" :default "Veja a seção %s"
  5228. :ascii "Veja a secao %s")
  5229. ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
  5230. :utf-8 "См. раздел %s")
  5231. ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
  5232. ("See table %s"
  5233. ("fr" :default "cf. tableau %s"
  5234. :html "cf.&nbsp;tableau&nbsp;%s" :latex "cf.~tableau~%s"))
  5235. ("Table"
  5236. ("de" :default "Tabelle")
  5237. ("es" :default "Tabla")
  5238. ("et" :default "Tabel")
  5239. ("fr" :default "Tableau")
  5240. ("is" :default "Tafla")
  5241. ("ja" :default "表" :html "&#34920;")
  5242. ("pt_BR" :default "Tabela")
  5243. ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;"
  5244. :utf-8 "Таблица")
  5245. ("zh-CN" :html "&#34920;" :utf-8 "表"))
  5246. ("Table %d:"
  5247. ("da" :default "Tabel %d")
  5248. ("de" :default "Tabelle %d")
  5249. ("es" :default "Tabla %d")
  5250. ("et" :default "Tabel %d")
  5251. ("fr" :default "Tableau %d :")
  5252. ("is" :default "Tafla %d")
  5253. ("ja" :default "表%d:" :html "&#34920;%d:")
  5254. ("no" :default "Tabell %d")
  5255. ("nb" :default "Tabell %d")
  5256. ("nn" :default "Tabell %d")
  5257. ("pt_BR" :default "Tabela %d")
  5258. ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
  5259. :utf-8 "Таблица %d.:")
  5260. ("sv" :default "Tabell %d")
  5261. ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
  5262. ("Table of Contents"
  5263. ("ca" :html "&Iacute;ndex")
  5264. ("cs" :default "Obsah")
  5265. ("da" :default "Indhold")
  5266. ("de" :default "Inhaltsverzeichnis")
  5267. ("eo" :default "Enhavo")
  5268. ("es" :ascii "Indice" :html "&Iacute;ndice" :default "Índice")
  5269. ("et" :default "Sisukord")
  5270. ("fi" :html "Sis&auml;llysluettelo")
  5271. ("fr" :ascii "Sommaire" :default "Table des matières")
  5272. ("hu" :html "Tartalomjegyz&eacute;k")
  5273. ("is" :default "Efnisyfirlit")
  5274. ("it" :default "Indice")
  5275. ("ja" :default "目次" :html "&#30446;&#27425;")
  5276. ("nl" :default "Inhoudsopgave")
  5277. ("no" :default "Innhold")
  5278. ("nb" :default "Innhold")
  5279. ("nn" :default "Innhald")
  5280. ("pl" :html "Spis tre&#x015b;ci")
  5281. ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
  5282. ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
  5283. :utf-8 "Содержание")
  5284. ("sv" :html "Inneh&aring;ll")
  5285. ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
  5286. ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
  5287. ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
  5288. ("Unknown reference"
  5289. ("da" :default "ukendt reference")
  5290. ("de" :default "Unbekannter Verweis")
  5291. ("es" :default "Referencia desconocida")
  5292. ("et" :default "Tundmatu viide")
  5293. ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
  5294. ("ja" :default "不明な参照先")
  5295. ("pt_BR" :default "Referência desconhecida"
  5296. :ascii "Referencia desconhecida")
  5297. ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
  5298. :utf-8 "Неизвестная ссылка")
  5299. ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
  5300. "Dictionary for export engine.
  5301. Alist whose car is the string to translate and cdr is an alist
  5302. whose car is the language string and cdr is a plist whose
  5303. properties are possible charsets and values translated terms.
  5304. It is used as a database for `org-export-translate'. Since this
  5305. function returns the string as-is if no translation was found,
  5306. the variable only needs to record values different from the
  5307. entry.")
  5308. (defun org-export-translate (s encoding info)
  5309. "Translate string S according to language specification.
  5310. ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
  5311. and `:utf-8'. INFO is a plist used as a communication channel.
  5312. Translation depends on `:language' property. Return the
  5313. translated string. If no translation is found, try to fall back
  5314. to `:default' encoding. If it fails, return S."
  5315. (let* ((lang (plist-get info :language))
  5316. (translations (cdr (assoc lang
  5317. (cdr (assoc s org-export-dictionary))))))
  5318. (or (plist-get translations encoding)
  5319. (plist-get translations :default)
  5320. s)))
  5321. ;;; Asynchronous Export
  5322. ;;
  5323. ;; `org-export-async-start' is the entry point for asynchronous
  5324. ;; export. It recreates current buffer (including visibility,
  5325. ;; narrowing and visited file) in an external Emacs process, and
  5326. ;; evaluates a command there. It then applies a function on the
  5327. ;; returned results in the current process.
  5328. ;;
  5329. ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
  5330. ;; allow exporting to a buffer or a file, asynchronously or not.
  5331. ;;
  5332. ;; `org-export-output-file-name' is an auxiliary function meant to be
  5333. ;; used with `org-export-to-file'. With a given extension, it tries
  5334. ;; to provide a canonical file name to write export output to.
  5335. ;;
  5336. ;; Asynchronously generated results are never displayed directly.
  5337. ;; Instead, they are stored in `org-export-stack-contents'. They can
  5338. ;; then be retrieved by calling `org-export-stack'.
  5339. ;;
  5340. ;; Export Stack is viewed through a dedicated major mode
  5341. ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
  5342. ;;`org-export-stack-delete', `org-export-stack-view' and
  5343. ;;`org-export-stack-clear'.
  5344. ;;
  5345. ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
  5346. ;; It should be used whenever `org-export-async-start' is called.
  5347. (defmacro org-export-async-start (fun &rest body)
  5348. "Call function FUN on the results returned by BODY evaluation.
  5349. FUN is an anonymous function of one argument. BODY evaluation
  5350. happens in an asynchronous process, from a buffer which is an
  5351. exact copy of the current one.
  5352. Use `org-export-add-to-stack' in FUN in order to register results
  5353. in the stack.
  5354. This is a low level function. See also `org-export-to-buffer'
  5355. and `org-export-to-file' for more specialized functions."
  5356. (declare (indent 1) (debug t))
  5357. (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
  5358. ;; Write the full sexp evaluating BODY in a copy of the current
  5359. ;; buffer to a temporary file, as it may be too long for program
  5360. ;; args in `start-process'.
  5361. `(with-temp-message "Initializing asynchronous export process"
  5362. (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
  5363. (,temp-file (make-temp-file "org-export-process"))
  5364. (,coding buffer-file-coding-system))
  5365. (with-temp-file ,temp-file
  5366. (insert
  5367. ;; Null characters (from variable values) are inserted
  5368. ;; within the file. As a consequence, coding system for
  5369. ;; buffer contents will not be recognized properly. So,
  5370. ;; we make sure it is the same as the one used to display
  5371. ;; the original buffer.
  5372. (format ";; -*- coding: %s; -*-\n%S"
  5373. ,coding
  5374. `(with-temp-buffer
  5375. (when org-export-async-debug '(setq debug-on-error t))
  5376. ;; Ignore `kill-emacs-hook' and code evaluation
  5377. ;; queries from Babel as we need a truly
  5378. ;; non-interactive process.
  5379. (setq kill-emacs-hook nil
  5380. org-babel-confirm-evaluate-answer-no t)
  5381. ;; Initialize export framework.
  5382. (require 'ox)
  5383. ;; Re-create current buffer there.
  5384. (funcall ,,copy-fun)
  5385. (restore-buffer-modified-p nil)
  5386. ;; Sexp to evaluate in the buffer.
  5387. (print (progn ,,@body))))))
  5388. ;; Start external process.
  5389. (let* ((process-connection-type nil)
  5390. (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
  5391. (,process
  5392. (apply
  5393. #'start-process
  5394. (append
  5395. (list "org-export-process"
  5396. ,proc-buffer
  5397. (expand-file-name invocation-name invocation-directory)
  5398. "--batch")
  5399. (if org-export-async-init-file
  5400. (list "-Q" "-l" org-export-async-init-file)
  5401. (list "-l" user-init-file))
  5402. (list "-l" ,temp-file)))))
  5403. ;; Register running process in stack.
  5404. (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
  5405. ;; Set-up sentinel in order to catch results.
  5406. (let ((handler ,fun))
  5407. (set-process-sentinel
  5408. ,process
  5409. `(lambda (p status)
  5410. (let ((proc-buffer (process-buffer p)))
  5411. (when (eq (process-status p) 'exit)
  5412. (unwind-protect
  5413. (if (zerop (process-exit-status p))
  5414. (unwind-protect
  5415. (let ((results
  5416. (with-current-buffer proc-buffer
  5417. (goto-char (point-max))
  5418. (backward-sexp)
  5419. (read (current-buffer)))))
  5420. (funcall ,handler results))
  5421. (unless org-export-async-debug
  5422. (and (get-buffer proc-buffer)
  5423. (kill-buffer proc-buffer))))
  5424. (org-export-add-to-stack proc-buffer nil p)
  5425. (ding)
  5426. (message "Process `%s' exited abnormally" p))
  5427. (unless org-export-async-debug
  5428. (delete-file ,,temp-file)))))))))))))
  5429. ;;;###autoload
  5430. (defun org-export-to-buffer
  5431. (backend buffer
  5432. &optional async subtreep visible-only body-only ext-plist
  5433. post-process)
  5434. "Call `org-export-as' with output to a specified buffer.
  5435. BACKEND is either an export back-end, as returned by, e.g.,
  5436. `org-export-create-backend', or a symbol referring to
  5437. a registered back-end.
  5438. BUFFER is the name of the output buffer. If it already exists,
  5439. it will be erased first, otherwise, it will be created.
  5440. A non-nil optional argument ASYNC means the process should happen
  5441. asynchronously. The resulting buffer should then be accessible
  5442. through the `org-export-stack' interface. When ASYNC is nil, the
  5443. buffer is displayed if `org-export-show-temporary-export-buffer'
  5444. is non-nil.
  5445. Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
  5446. EXT-PLIST are similar to those used in `org-export-as', which
  5447. see.
  5448. Optional argument POST-PROCESS is a function which should accept
  5449. no argument. It is always called within the current process,
  5450. from BUFFER, with point at its beginning. Export back-ends can
  5451. use it to set a major mode there, e.g,
  5452. (defun org-latex-export-as-latex
  5453. (&optional async subtreep visible-only body-only ext-plist)
  5454. (interactive)
  5455. (org-export-to-buffer \\='latex \"*Org LATEX Export*\"
  5456. async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
  5457. This function returns BUFFER."
  5458. (declare (indent 2))
  5459. (if async
  5460. (org-export-async-start
  5461. `(lambda (output)
  5462. (with-current-buffer (get-buffer-create ,buffer)
  5463. (erase-buffer)
  5464. (setq buffer-file-coding-system ',buffer-file-coding-system)
  5465. (insert output)
  5466. (goto-char (point-min))
  5467. (org-export-add-to-stack (current-buffer) ',backend)
  5468. (ignore-errors (funcall ,post-process))))
  5469. `(org-export-as
  5470. ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
  5471. (let ((output
  5472. (org-export-as backend subtreep visible-only body-only ext-plist))
  5473. (buffer (get-buffer-create buffer))
  5474. (encoding buffer-file-coding-system))
  5475. (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
  5476. (org-kill-new output))
  5477. (with-current-buffer buffer
  5478. (erase-buffer)
  5479. (setq buffer-file-coding-system encoding)
  5480. (insert output)
  5481. (goto-char (point-min))
  5482. (and (functionp post-process) (funcall post-process)))
  5483. (when org-export-show-temporary-export-buffer
  5484. (switch-to-buffer-other-window buffer))
  5485. buffer)))
  5486. ;;;###autoload
  5487. (defun org-export-to-file
  5488. (backend file &optional async subtreep visible-only body-only ext-plist
  5489. post-process)
  5490. "Call `org-export-as' with output to a specified file.
  5491. BACKEND is either an export back-end, as returned by, e.g.,
  5492. `org-export-create-backend', or a symbol referring to
  5493. a registered back-end. FILE is the name of the output file, as
  5494. a string.
  5495. A non-nil optional argument ASYNC means the process should happen
  5496. asynchronously. The resulting buffer will then be accessible
  5497. through the `org-export-stack' interface.
  5498. Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
  5499. EXT-PLIST are similar to those used in `org-export-as', which
  5500. see.
  5501. Optional argument POST-PROCESS is called with FILE as its
  5502. argument and happens asynchronously when ASYNC is non-nil. It
  5503. has to return a file name, or nil. Export back-ends can use this
  5504. to send the output file through additional processing, e.g,
  5505. (defun org-latex-export-to-latex
  5506. (&optional async subtreep visible-only body-only ext-plist)
  5507. (interactive)
  5508. (let ((outfile (org-export-output-file-name \".tex\" subtreep)))
  5509. (org-export-to-file \\='latex outfile
  5510. async subtreep visible-only body-only ext-plist
  5511. (lambda (file) (org-latex-compile file)))
  5512. The function returns either a file name returned by POST-PROCESS,
  5513. or FILE."
  5514. (declare (indent 2))
  5515. (if (not (file-writable-p file)) (error "Output file not writable")
  5516. (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
  5517. (encoding (or org-export-coding-system buffer-file-coding-system)))
  5518. (if async
  5519. (org-export-async-start
  5520. `(lambda (file)
  5521. (org-export-add-to-stack (expand-file-name file) ',backend))
  5522. `(let ((output
  5523. (org-export-as
  5524. ',backend ,subtreep ,visible-only ,body-only
  5525. ',ext-plist)))
  5526. (with-temp-buffer
  5527. (insert output)
  5528. (let ((coding-system-for-write ',encoding))
  5529. (write-file ,file)))
  5530. (or (ignore-errors (funcall ',post-process ,file)) ,file)))
  5531. (let ((output (org-export-as
  5532. backend subtreep visible-only body-only ext-plist)))
  5533. (with-temp-buffer
  5534. (insert output)
  5535. (let ((coding-system-for-write encoding))
  5536. (write-file file)))
  5537. (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
  5538. (org-kill-new output))
  5539. ;; Get proper return value.
  5540. (or (and (functionp post-process) (funcall post-process file))
  5541. file))))))
  5542. (defun org-export-output-file-name (extension &optional subtreep pub-dir)
  5543. "Return output file's name according to buffer specifications.
  5544. EXTENSION is a string representing the output file extension,
  5545. with the leading dot.
  5546. With a non-nil optional argument SUBTREEP, try to determine
  5547. output file's name by looking for \"EXPORT_FILE_NAME\" property
  5548. of subtree at point.
  5549. When optional argument PUB-DIR is set, use it as the publishing
  5550. directory.
  5551. Return file name as a string."
  5552. (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
  5553. (base-name
  5554. (concat
  5555. (file-name-sans-extension
  5556. (or
  5557. ;; Check EXPORT_FILE_NAME subtree property.
  5558. (and subtreep (org-entry-get nil "EXPORT_FILE_NAME" 'selective))
  5559. ;; Check #+EXPORT_FILE_NAME keyword.
  5560. (org-with-point-at (point-min)
  5561. (catch :found
  5562. (let ((case-fold-search t))
  5563. (while (re-search-forward
  5564. "^[ \t]*#\\+EXPORT_FILE_NAME:[ \t]+\\S-" nil t)
  5565. (let ((element (org-element-at-point)))
  5566. (when (eq 'keyword (org-element-type element))
  5567. (throw :found
  5568. (org-element-property :value element))))))))
  5569. ;; Extract from buffer's associated file, if any.
  5570. (and visited-file (file-name-nondirectory visited-file))
  5571. ;; Can't determine file name on our own: ask user.
  5572. (read-file-name
  5573. "Output file: " pub-dir nil nil nil
  5574. (lambda (n) (string= extension (file-name-extension n t))))))
  5575. extension))
  5576. (output-file
  5577. ;; Build file name. Enforce EXTENSION over whatever user
  5578. ;; may have come up with. PUB-DIR, if defined, always has
  5579. ;; precedence over any provided path.
  5580. (cond
  5581. (pub-dir (concat (file-name-as-directory pub-dir)
  5582. (file-name-nondirectory base-name)))
  5583. ((file-name-absolute-p base-name) base-name)
  5584. (t base-name))))
  5585. ;; If writing to OUTPUT-FILE would overwrite original file, append
  5586. ;; EXTENSION another time to final name.
  5587. (if (and visited-file (file-equal-p visited-file output-file))
  5588. (concat output-file extension)
  5589. output-file)))
  5590. (defun org-export-add-to-stack (source backend &optional process)
  5591. "Add a new result to export stack if not present already.
  5592. SOURCE is a buffer or a file name containing export results.
  5593. BACKEND is a symbol representing export back-end used to generate
  5594. it.
  5595. Entries already pointing to SOURCE and unavailable entries are
  5596. removed beforehand. Return the new stack."
  5597. (setq org-export-stack-contents
  5598. (cons (list source backend (or process (current-time)))
  5599. (org-export-stack-remove source))))
  5600. (defun org-export-stack ()
  5601. "Menu for asynchronous export results and running processes."
  5602. (interactive)
  5603. (let ((buffer (get-buffer-create "*Org Export Stack*")))
  5604. (with-current-buffer buffer
  5605. (org-export-stack-mode)
  5606. (tabulated-list-print t))
  5607. (pop-to-buffer buffer))
  5608. (message "Type \"q\" to quit, \"?\" for help"))
  5609. (defun org-export-stack-clear ()
  5610. "Remove all entries from export stack."
  5611. (interactive)
  5612. (setq org-export-stack-contents nil))
  5613. (defun org-export-stack-refresh ()
  5614. "Refresh the export stack."
  5615. (interactive)
  5616. (tabulated-list-print t))
  5617. (defun org-export-stack-remove (&optional source)
  5618. "Remove export results at point from stack.
  5619. If optional argument SOURCE is non-nil, remove it instead."
  5620. (interactive)
  5621. (let ((source (or source (org-export--stack-source-at-point))))
  5622. (setq org-export-stack-contents
  5623. (cl-remove-if (lambda (el) (equal (car el) source))
  5624. org-export-stack-contents))))
  5625. (defun org-export-stack-view (&optional in-emacs)
  5626. "View export results at point in stack.
  5627. With an optional prefix argument IN-EMACS, force viewing files
  5628. within Emacs."
  5629. (interactive "P")
  5630. (let ((source (org-export--stack-source-at-point)))
  5631. (cond ((processp source)
  5632. (org-switch-to-buffer-other-window (process-buffer source)))
  5633. ((bufferp source) (org-switch-to-buffer-other-window source))
  5634. (t (org-open-file source in-emacs)))))
  5635. (defvar org-export-stack-mode-map
  5636. (let ((km (make-sparse-keymap)))
  5637. (set-keymap-parent km tabulated-list-mode-map)
  5638. (define-key km " " 'next-line)
  5639. (define-key km "\C-n" 'next-line)
  5640. (define-key km [down] 'next-line)
  5641. (define-key km "\C-p" 'previous-line)
  5642. (define-key km "\C-?" 'previous-line)
  5643. (define-key km [up] 'previous-line)
  5644. (define-key km "C" 'org-export-stack-clear)
  5645. (define-key km "v" 'org-export-stack-view)
  5646. (define-key km (kbd "RET") 'org-export-stack-view)
  5647. (define-key km "d" 'org-export-stack-remove)
  5648. km)
  5649. "Keymap for Org Export Stack.")
  5650. (define-derived-mode org-export-stack-mode tabulated-list-mode "Org-Stack"
  5651. "Mode for displaying asynchronous export stack.
  5652. Type `\\[org-export-stack]' to visualize the asynchronous export
  5653. stack.
  5654. In an Org Export Stack buffer, use \
  5655. \\<org-export-stack-mode-map>`\\[org-export-stack-view]' to view export output
  5656. on current line, `\\[org-export-stack-remove]' to remove it from the stack and \
  5657. `\\[org-export-stack-clear]' to clear
  5658. stack completely.
  5659. Removing entries in a stack buffer does not affect files
  5660. or buffers, only display.
  5661. \\{org-export-stack-mode-map}"
  5662. (setq tabulated-list-format
  5663. (vector (list "#" 4 #'org-export--stack-num-predicate)
  5664. (list "Back-End" 12 t)
  5665. (list "Age" 6 nil)
  5666. (list "Source" 0 nil)))
  5667. (setq tabulated-list-sort-key (cons "#" nil))
  5668. (setq tabulated-list-entries #'org-export--stack-generate)
  5669. (add-hook 'tabulated-list-revert-hook #'org-export--stack-generate nil t)
  5670. (add-hook 'post-command-hook #'org-export-stack-refresh nil t)
  5671. (tabulated-list-init-header))
  5672. (defun org-export--stack-generate ()
  5673. "Generate the asynchronous export stack for display.
  5674. Unavailable sources are removed from the list. Return a list
  5675. appropriate for `tabulated-list-print'."
  5676. ;; Clear stack from exited processes, dead buffers or non-existent
  5677. ;; files.
  5678. (setq org-export-stack-contents
  5679. (cl-remove-if-not
  5680. (lambda (el)
  5681. (if (processp (nth 2 el))
  5682. (buffer-live-p (process-buffer (nth 2 el)))
  5683. (let ((source (car el)))
  5684. (if (bufferp source) (buffer-live-p source)
  5685. (file-exists-p source)))))
  5686. org-export-stack-contents))
  5687. ;; Update `tabulated-list-entries'.
  5688. (let ((counter 0))
  5689. (mapcar
  5690. (lambda (entry)
  5691. (let ((source (car entry)))
  5692. (list source
  5693. (vector
  5694. ;; Counter.
  5695. (number-to-string (cl-incf counter))
  5696. ;; Back-End.
  5697. (if (nth 1 entry) (symbol-name (nth 1 entry)) "")
  5698. ;; Age.
  5699. (let ((info (nth 2 entry)))
  5700. (if (processp info) (symbol-name (process-status info))
  5701. (format-seconds "%h:%.2m" (float-time (time-since info)))))
  5702. ;; Source.
  5703. (if (stringp source) source (buffer-name source))))))
  5704. org-export-stack-contents)))
  5705. (defun org-export--stack-num-predicate (a b)
  5706. (< (string-to-number (aref (nth 1 a) 0))
  5707. (string-to-number (aref (nth 1 b) 0))))
  5708. (defun org-export--stack-source-at-point ()
  5709. "Return source from export results at point in stack."
  5710. (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
  5711. (if (not source) (error "Source unavailable, please refresh buffer")
  5712. (let ((source-name (if (stringp source) source (buffer-name source))))
  5713. (if (save-excursion
  5714. (beginning-of-line)
  5715. (looking-at-p (concat ".* +" (regexp-quote source-name) "$")))
  5716. source
  5717. ;; SOURCE is not consistent with current line. The stack
  5718. ;; view is outdated.
  5719. (error (substitute-command-keys
  5720. "Source unavailable; type `\\[org-export-stack-refresh]' \
  5721. to refresh buffer")))))))
  5722. ;;; The Dispatcher
  5723. ;;
  5724. ;; `org-export-dispatch' is the standard interactive way to start an
  5725. ;; export process. It uses `org-export--dispatch-ui' as a subroutine
  5726. ;; for its interface, which, in turn, delegates response to key
  5727. ;; pressed to `org-export--dispatch-action'.
  5728. ;;;###autoload
  5729. (defun org-export-dispatch (&optional arg)
  5730. "Export dispatcher for Org mode.
  5731. It provides an access to common export related tasks in a buffer.
  5732. Its interface comes in two flavors: standard and expert.
  5733. While both share the same set of bindings, only the former
  5734. displays the valid keys associations in a dedicated buffer.
  5735. Scrolling (resp. line-wise motion) in this buffer is done with
  5736. SPC and DEL (resp. C-n and C-p) keys.
  5737. Set variable `org-export-dispatch-use-expert-ui' to switch to one
  5738. flavor or the other.
  5739. When ARG is `\\[universal-argument]', repeat the last export action, with the\
  5740. same
  5741. set of options used back then, on the current buffer.
  5742. When ARG is `\\[universal-argument] \\[universal-argument]', display the \
  5743. asynchronous export stack."
  5744. (interactive "P")
  5745. (let* ((input
  5746. (cond ((equal arg '(16)) '(stack))
  5747. ((and arg org-export-dispatch-last-action))
  5748. (t (save-window-excursion
  5749. (unwind-protect
  5750. (progn
  5751. ;; Remember where we are
  5752. (move-marker org-export-dispatch-last-position
  5753. (point)
  5754. (org-base-buffer (current-buffer)))
  5755. ;; Get and store an export command
  5756. (setq org-export-dispatch-last-action
  5757. (org-export--dispatch-ui
  5758. (list org-export-initial-scope
  5759. (and org-export-in-background 'async))
  5760. nil
  5761. org-export-dispatch-use-expert-ui)))
  5762. (and (get-buffer "*Org Export Dispatcher*")
  5763. (kill-buffer "*Org Export Dispatcher*")))))))
  5764. (action (car input))
  5765. (optns (cdr input)))
  5766. (unless (memq 'subtree optns)
  5767. (move-marker org-export-dispatch-last-position nil))
  5768. (cl-case action
  5769. ;; First handle special hard-coded actions.
  5770. (template (org-export-insert-default-template nil optns))
  5771. (stack (org-export-stack))
  5772. (publish-current-file
  5773. (org-publish-current-file (memq 'force optns) (memq 'async optns)))
  5774. (publish-current-project
  5775. (org-publish-current-project (memq 'force optns) (memq 'async optns)))
  5776. (publish-choose-project
  5777. (org-publish (assoc (completing-read
  5778. "Publish project: "
  5779. org-publish-project-alist nil t)
  5780. org-publish-project-alist)
  5781. (memq 'force optns)
  5782. (memq 'async optns)))
  5783. (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
  5784. (otherwise
  5785. (save-excursion
  5786. (when arg
  5787. ;; Repeating command, maybe move cursor to restore subtree
  5788. ;; context.
  5789. (if (eq (marker-buffer org-export-dispatch-last-position)
  5790. (org-base-buffer (current-buffer)))
  5791. (goto-char org-export-dispatch-last-position)
  5792. ;; We are in a different buffer, forget position.
  5793. (move-marker org-export-dispatch-last-position nil)))
  5794. (funcall action
  5795. ;; Return a symbol instead of a list to ease
  5796. ;; asynchronous export macro use.
  5797. (and (memq 'async optns) t)
  5798. (and (memq 'subtree optns) t)
  5799. (and (memq 'visible optns) t)
  5800. (and (memq 'body optns) t)))))))
  5801. (defun org-export--dispatch-ui (options first-key expertp)
  5802. "Handle interface for `org-export-dispatch'.
  5803. OPTIONS is a list containing current interactive options set for
  5804. export. It can contain any of the following symbols:
  5805. `body' toggles a body-only export
  5806. `subtree' restricts export to current subtree
  5807. `visible' restricts export to visible part of buffer.
  5808. `force' force publishing files.
  5809. `async' use asynchronous export process
  5810. FIRST-KEY is the key pressed to select the first level menu. It
  5811. is nil when this menu hasn't been selected yet.
  5812. EXPERTP, when non-nil, triggers expert UI. In that case, no help
  5813. buffer is provided, but indications about currently active
  5814. options are given in the prompt. Moreover, [?] allows switching
  5815. back to standard interface."
  5816. (let* ((fontify-key
  5817. (lambda (key &optional access-key)
  5818. ;; Fontify KEY string. Optional argument ACCESS-KEY, when
  5819. ;; non-nil is the required first-level key to activate
  5820. ;; KEY. When its value is t, activate KEY independently
  5821. ;; on the first key, if any. A nil value means KEY will
  5822. ;; only be activated at first level.
  5823. (if (or (eq access-key t) (eq access-key first-key))
  5824. (propertize key 'face 'org-warning)
  5825. key)))
  5826. (fontify-value
  5827. (lambda (value)
  5828. ;; Fontify VALUE string.
  5829. (propertize value 'face 'font-lock-variable-name-face)))
  5830. ;; Prepare menu entries by extracting them from registered
  5831. ;; back-ends and sorting them by access key and by ordinal,
  5832. ;; if any.
  5833. (entries
  5834. (sort (sort (delq nil
  5835. (mapcar #'org-export-backend-menu
  5836. org-export-registered-backends))
  5837. (lambda (a b)
  5838. (let ((key-a (nth 1 a))
  5839. (key-b (nth 1 b)))
  5840. (cond ((and (numberp key-a) (numberp key-b))
  5841. (< key-a key-b))
  5842. ((numberp key-b) t)))))
  5843. 'car-less-than-car))
  5844. ;; Compute a list of allowed keys based on the first key
  5845. ;; pressed, if any. Some keys
  5846. ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
  5847. ;; available.
  5848. (allowed-keys
  5849. (nconc (list 2 22 19 6 1)
  5850. (if (not first-key) (org-uniquify (mapcar 'car entries))
  5851. (let (sub-menu)
  5852. (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
  5853. (when (eq (car entry) first-key)
  5854. (setq sub-menu (append (nth 2 entry) sub-menu))))))
  5855. (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
  5856. ((not first-key) (list ?P)))
  5857. (list ?& ?#)
  5858. (when expertp (list ??))
  5859. (list ?q)))
  5860. ;; Build the help menu for standard UI.
  5861. (help
  5862. (unless expertp
  5863. (concat
  5864. ;; Options are hard-coded.
  5865. (format "[%s] Body only: %s [%s] Visible only: %s
  5866. \[%s] Export scope: %s [%s] Force publishing: %s
  5867. \[%s] Async export: %s\n\n"
  5868. (funcall fontify-key "C-b" t)
  5869. (funcall fontify-value
  5870. (if (memq 'body options) "On " "Off"))
  5871. (funcall fontify-key "C-v" t)
  5872. (funcall fontify-value
  5873. (if (memq 'visible options) "On " "Off"))
  5874. (funcall fontify-key "C-s" t)
  5875. (funcall fontify-value
  5876. (if (memq 'subtree options) "Subtree" "Buffer "))
  5877. (funcall fontify-key "C-f" t)
  5878. (funcall fontify-value
  5879. (if (memq 'force options) "On " "Off"))
  5880. (funcall fontify-key "C-a" t)
  5881. (funcall fontify-value
  5882. (if (memq 'async options) "On " "Off")))
  5883. ;; Display registered back-end entries. When a key
  5884. ;; appears for the second time, do not create another
  5885. ;; entry, but append its sub-menu to existing menu.
  5886. (let (last-key)
  5887. (mapconcat
  5888. (lambda (entry)
  5889. (let ((top-key (car entry)))
  5890. (concat
  5891. (unless (eq top-key last-key)
  5892. (setq last-key top-key)
  5893. (format "\n[%s] %s\n"
  5894. (funcall fontify-key (char-to-string top-key))
  5895. (nth 1 entry)))
  5896. (let ((sub-menu (nth 2 entry)))
  5897. (unless (functionp sub-menu)
  5898. ;; Split sub-menu into two columns.
  5899. (let ((index -1))
  5900. (concat
  5901. (mapconcat
  5902. (lambda (sub-entry)
  5903. (cl-incf index)
  5904. (format
  5905. (if (zerop (mod index 2)) " [%s] %-26s"
  5906. "[%s] %s\n")
  5907. (funcall fontify-key
  5908. (char-to-string (car sub-entry))
  5909. top-key)
  5910. (nth 1 sub-entry)))
  5911. sub-menu "")
  5912. (when (zerop (mod index 2)) "\n"))))))))
  5913. entries ""))
  5914. ;; Publishing menu is hard-coded.
  5915. (format "\n[%s] Publish
  5916. [%s] Current file [%s] Current project
  5917. [%s] Choose project [%s] All projects\n\n\n"
  5918. (funcall fontify-key "P")
  5919. (funcall fontify-key "f" ?P)
  5920. (funcall fontify-key "p" ?P)
  5921. (funcall fontify-key "x" ?P)
  5922. (funcall fontify-key "a" ?P))
  5923. (format "[%s] Export stack [%s] Insert template\n"
  5924. (funcall fontify-key "&" t)
  5925. (funcall fontify-key "#" t))
  5926. (format "[%s] %s"
  5927. (funcall fontify-key "q" t)
  5928. (if first-key "Main menu" "Exit")))))
  5929. ;; Build prompts for both standard and expert UI.
  5930. (standard-prompt (unless expertp "Export command: "))
  5931. (expert-prompt
  5932. (when expertp
  5933. (format
  5934. "Export command (C-%s%s%s%s%s) [%s]: "
  5935. (if (memq 'body options) (funcall fontify-key "b" t) "b")
  5936. (if (memq 'visible options) (funcall fontify-key "v" t) "v")
  5937. (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
  5938. (if (memq 'force options) (funcall fontify-key "f" t) "f")
  5939. (if (memq 'async options) (funcall fontify-key "a" t) "a")
  5940. (mapconcat (lambda (k)
  5941. ;; Strip control characters.
  5942. (unless (< k 27) (char-to-string k)))
  5943. allowed-keys "")))))
  5944. ;; With expert UI, just read key with a fancy prompt. In standard
  5945. ;; UI, display an intrusive help buffer.
  5946. (if expertp
  5947. (org-export--dispatch-action
  5948. expert-prompt allowed-keys entries options first-key expertp)
  5949. ;; At first call, create frame layout in order to display menu.
  5950. (unless (get-buffer "*Org Export Dispatcher*")
  5951. (delete-other-windows)
  5952. (org-switch-to-buffer-other-window
  5953. (get-buffer-create "*Org Export Dispatcher*"))
  5954. (setq cursor-type nil
  5955. header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
  5956. ;; Make sure that invisible cursor will not highlight square
  5957. ;; brackets.
  5958. (set-syntax-table (copy-syntax-table))
  5959. (modify-syntax-entry ?\[ "w"))
  5960. ;; At this point, the buffer containing the menu exists and is
  5961. ;; visible in the current window. So, refresh it.
  5962. (with-current-buffer "*Org Export Dispatcher*"
  5963. ;; Refresh help. Maintain display continuity by re-visiting
  5964. ;; previous window position.
  5965. (let ((pos (window-start)))
  5966. (erase-buffer)
  5967. (insert help)
  5968. (set-window-start nil pos)))
  5969. (org-fit-window-to-buffer)
  5970. (org-export--dispatch-action
  5971. standard-prompt allowed-keys entries options first-key expertp))))
  5972. (defun org-export--dispatch-action
  5973. (prompt allowed-keys entries options first-key expertp)
  5974. "Read a character from command input and act accordingly.
  5975. PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
  5976. a list of characters available at a given step in the process.
  5977. ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
  5978. EXPERTP are the same as defined in `org-export--dispatch-ui',
  5979. which see.
  5980. Toggle export options when required. Otherwise, return value is
  5981. a list with action as CAR and a list of interactive export
  5982. options as CDR."
  5983. (let (key)
  5984. ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
  5985. ;; C-p, SPC, DEL).
  5986. (while (and (setq key (read-char-exclusive prompt))
  5987. (not expertp)
  5988. (memq key '(14 16 ?\s ?\d)))
  5989. (cl-case key
  5990. (14 (if (not (pos-visible-in-window-p (point-max)))
  5991. (ignore-errors (scroll-up 1))
  5992. (message "End of buffer")
  5993. (sit-for 1)))
  5994. (16 (if (not (pos-visible-in-window-p (point-min)))
  5995. (ignore-errors (scroll-down 1))
  5996. (message "Beginning of buffer")
  5997. (sit-for 1)))
  5998. (?\s (if (not (pos-visible-in-window-p (point-max)))
  5999. (scroll-up nil)
  6000. (message "End of buffer")
  6001. (sit-for 1)))
  6002. (?\d (if (not (pos-visible-in-window-p (point-min)))
  6003. (scroll-down nil)
  6004. (message "Beginning of buffer")
  6005. (sit-for 1)))))
  6006. (cond
  6007. ;; Ignore undefined associations.
  6008. ((not (memq key allowed-keys))
  6009. (ding)
  6010. (unless expertp (message "Invalid key") (sit-for 1))
  6011. (org-export--dispatch-ui options first-key expertp))
  6012. ;; q key at first level aborts export. At second level, cancel
  6013. ;; first key instead.
  6014. ((eq key ?q) (if (not first-key) (error "Export aborted")
  6015. (org-export--dispatch-ui options nil expertp)))
  6016. ;; Help key: Switch back to standard interface if expert UI was
  6017. ;; active.
  6018. ((eq key ??) (org-export--dispatch-ui options first-key nil))
  6019. ;; Send request for template insertion along with export scope.
  6020. ((eq key ?#) (cons 'template (memq 'subtree options)))
  6021. ;; Switch to asynchronous export stack.
  6022. ((eq key ?&) '(stack))
  6023. ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
  6024. ((memq key '(2 22 19 6 1))
  6025. (org-export--dispatch-ui
  6026. (let ((option (cl-case key (2 'body) (22 'visible) (19 'subtree)
  6027. (6 'force) (1 'async))))
  6028. (if (memq option options) (remq option options)
  6029. (cons option options)))
  6030. first-key expertp))
  6031. ;; Action selected: Send key and options back to
  6032. ;; `org-export-dispatch'.
  6033. ((or first-key (functionp (nth 2 (assq key entries))))
  6034. (cons (cond
  6035. ((not first-key) (nth 2 (assq key entries)))
  6036. ;; Publishing actions are hard-coded. Send a special
  6037. ;; signal to `org-export-dispatch'.
  6038. ((eq first-key ?P)
  6039. (cl-case key
  6040. (?f 'publish-current-file)
  6041. (?p 'publish-current-project)
  6042. (?x 'publish-choose-project)
  6043. (?a 'publish-all)))
  6044. ;; Return first action associated to FIRST-KEY + KEY
  6045. ;; path. Indeed, derived backends can share the same
  6046. ;; FIRST-KEY.
  6047. (t (catch 'found
  6048. (dolist (entry (member (assq first-key entries) entries))
  6049. (let ((match (assq key (nth 2 entry))))
  6050. (when match (throw 'found (nth 2 match))))))))
  6051. options))
  6052. ;; Otherwise, enter sub-menu.
  6053. (t (org-export--dispatch-ui options key expertp)))))
  6054. (provide 'ox)
  6055. ;; Local variables:
  6056. ;; generated-autoload-file: "org-loaddefs.el"
  6057. ;; End:
  6058. ;;; ox.el ends here