ox.el 267 KB

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