ox.el 269 KB

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