ox.el 278 KB

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