ox.el 270 KB

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