ox.el 279 KB

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