ox.el 275 KB

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