ox.el 277 KB

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