org-element.el 222 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260
  1. ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2012-2022 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. ;; See <https://orgmode.org/worg/dev/org-syntax.html> for details about
  19. ;; Org syntax.
  20. ;;
  21. ;; Lisp-wise, a syntax object can be represented as a list.
  22. ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
  23. ;; TYPE is a symbol describing the object.
  24. ;; PROPERTIES is the property list attached to it. See docstring of
  25. ;; appropriate parsing function to get an exhaustive list.
  26. ;; CONTENTS is a list of syntax objects or raw strings contained
  27. ;; in the current object, when applicable.
  28. ;;
  29. ;; For the whole document, TYPE is `org-data' and PROPERTIES is nil.
  30. ;;
  31. ;; The first part of this file defines constants for the Org syntax,
  32. ;; while the second one provide accessors and setters functions.
  33. ;;
  34. ;; The next part implements a parser and an interpreter for each
  35. ;; element and object type in Org syntax.
  36. ;;
  37. ;; The following part creates a fully recursive buffer parser. It
  38. ;; also provides a tool to map a function to elements or objects
  39. ;; matching some criteria in the parse tree. Functions of interest
  40. ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
  41. ;; extent, `org-element-parse-secondary-string'.
  42. ;;
  43. ;; The penultimate part is the cradle of an interpreter for the
  44. ;; obtained parse tree: `org-element-interpret-data'.
  45. ;;
  46. ;; The library ends by furnishing `org-element-at-point' function, and
  47. ;; a way to give information about document structure around point
  48. ;; with `org-element-context'. A cache mechanism is also provided for
  49. ;; these functions.
  50. ;;; Code:
  51. (require 'avl-tree)
  52. (require 'cl-lib)
  53. (require 'ol)
  54. (require 'org)
  55. (require 'org-compat)
  56. (require 'org-entities)
  57. (require 'org-footnote)
  58. (require 'org-list)
  59. (require 'org-macs)
  60. (require 'org-table)
  61. (declare-function org-at-heading-p "org" (&optional _))
  62. (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
  63. (declare-function org-escape-code-in-string "org-src" (s))
  64. (declare-function org-macro-escape-arguments "org-macro" (&rest args))
  65. (declare-function org-macro-extract-arguments "org-macro" (s))
  66. (declare-function org-reduced-level "org" (l))
  67. (declare-function org-unescape-code-in-string "org-src" (s))
  68. (declare-function outline-next-heading "outline" ())
  69. (declare-function outline-previous-heading "outline" ())
  70. (defvar org-archive-tag)
  71. (defvar org-clock-line-re)
  72. (defvar org-closed-string)
  73. (defvar org-comment-string)
  74. (defvar org-complex-heading-regexp)
  75. (defvar org-dblock-start-re)
  76. (defvar org-deadline-string)
  77. (defvar org-done-keywords)
  78. (defvar org-drawer-regexp)
  79. (defvar org-edit-src-content-indentation)
  80. (defvar org-emph-re)
  81. (defvar org-emphasis-regexp-components)
  82. (defvar org-keyword-time-not-clock-regexp)
  83. (defvar org-match-substring-regexp)
  84. (defvar org-odd-levels-only)
  85. (defvar org-outline-regexp-bol)
  86. (defvar org-planning-line-re)
  87. (defvar org-property-drawer-re)
  88. (defvar org-property-format)
  89. (defvar org-property-re)
  90. (defvar org-scheduled-string)
  91. (defvar org-src-preserve-indentation)
  92. (defvar org-tags-column)
  93. (defvar org-time-stamp-formats)
  94. (defvar org-todo-regexp)
  95. (defvar org-ts-regexp-both)
  96. (defvar org-verbatim-re)
  97. ;;; Definitions And Rules
  98. ;;
  99. ;; Define elements, greater elements and specify recursive objects,
  100. ;; along with the affiliated keywords recognized. Also set up
  101. ;; restrictions on recursive objects combinations.
  102. ;;
  103. ;; `org-element-update-syntax' builds proper syntax regexps according
  104. ;; to current setup.
  105. (defconst org-element-citation-key-re
  106. (rx "@" (group (one-or-more (any word "-.:?!`'/*@+|(){}<>&_^$#%~"))))
  107. "Regexp matching a citation key.
  108. Key is located in match group 1.")
  109. (defconst org-element-citation-prefix-re
  110. (rx "[cite"
  111. (opt "/" (group (one-or-more (any "/_-" alnum)))) ;style
  112. ":"
  113. (zero-or-more (any "\t\n ")))
  114. "Regexp matching a citation prefix.
  115. Style, if any, is located in match group 1.")
  116. (defvar org-element-paragraph-separate nil
  117. "Regexp to separate paragraphs in an Org buffer.
  118. In the case of lines starting with \"#\" and \":\", this regexp
  119. is not sufficient to know if point is at a paragraph ending. See
  120. `org-element-paragraph-parser' for more information.")
  121. (defvar org-element--object-regexp nil
  122. "Regexp possibly matching the beginning of an object.
  123. This regexp allows false positives. Dedicated parser (e.g.,
  124. `org-export-bold-parser') will take care of further filtering.
  125. Radio links are not matched by this regexp, as they are treated
  126. specially in `org-element--object-lex'.")
  127. (defun org-element--set-regexps ()
  128. "Build variable syntax regexps."
  129. (setq org-element-paragraph-separate
  130. (concat "^\\(?:"
  131. ;; Headlines, inlinetasks.
  132. "\\*+ " "\\|"
  133. ;; Footnote definitions.
  134. "\\[fn:[-_[:word:]]+\\]" "\\|"
  135. ;; Diary sexps.
  136. "%%(" "\\|"
  137. "[ \t]*\\(?:"
  138. ;; Empty lines.
  139. "$" "\\|"
  140. ;; Tables (any type).
  141. "|" "\\|"
  142. "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
  143. ;; Comments, keyword-like or block-like constructs.
  144. ;; Blocks and keywords with dual values need to be
  145. ;; double-checked.
  146. "#\\(?: \\|$\\|\\+\\(?:"
  147. "BEGIN_\\S-+" "\\|"
  148. "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
  149. "\\|"
  150. ;; Drawers (any type) and fixed-width areas. Drawers
  151. ;; need to be double-checked.
  152. ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
  153. ;; Horizontal rules.
  154. "-\\{5,\\}[ \t]*$" "\\|"
  155. ;; LaTeX environments.
  156. "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
  157. ;; Clock lines.
  158. "CLOCK:" "\\|"
  159. ;; Lists.
  160. (let ((term (pcase org-plain-list-ordered-item-terminator
  161. (?\) ")") (?. "\\.") (_ "[.)]")))
  162. (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
  163. (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
  164. "\\(?:[ \t]\\|$\\)"))
  165. "\\)\\)")
  166. org-element--object-regexp
  167. (mapconcat #'identity
  168. (let ((link-types (regexp-opt (org-link-types))))
  169. (list
  170. ;; Sub/superscript.
  171. "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
  172. ;; Bold, code, italic, strike-through, underline
  173. ;; and verbatim.
  174. (concat "[*~=+_/]"
  175. (format "[^%s]"
  176. (nth 2 org-emphasis-regexp-components)))
  177. ;; Plain links.
  178. (concat "\\<" link-types ":")
  179. ;; Objects starting with "[": citations,
  180. ;; footnote reference, statistics cookie,
  181. ;; timestamp (inactive) and regular link.
  182. (format "\\[\\(?:%s\\)"
  183. (mapconcat
  184. #'identity
  185. (list "cite[:/]"
  186. "fn:"
  187. "\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)"
  188. "\\[")
  189. "\\|"))
  190. ;; Objects starting with "@": export snippets.
  191. "@@"
  192. ;; Objects starting with "{": macro.
  193. "{{{"
  194. ;; Objects starting with "<" : timestamp
  195. ;; (active, diary), target, radio target and
  196. ;; angular links.
  197. (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
  198. ;; Objects starting with "$": latex fragment.
  199. "\\$"
  200. ;; Objects starting with "\": line break,
  201. ;; entity, latex fragment.
  202. "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)"
  203. ;; Objects starting with raw text: inline Babel
  204. ;; source block, inline Babel call.
  205. "\\(?:call\\|src\\)_"))
  206. "\\|")))
  207. (org-element--set-regexps)
  208. ;;;###autoload
  209. (defun org-element-update-syntax ()
  210. "Update parser internals."
  211. (interactive)
  212. (org-element--set-regexps)
  213. (org-element-cache-reset 'all))
  214. (defconst org-element-all-elements
  215. '(babel-call center-block clock comment comment-block diary-sexp drawer
  216. dynamic-block example-block export-block fixed-width
  217. footnote-definition headline horizontal-rule inlinetask item
  218. keyword latex-environment node-property paragraph plain-list
  219. planning property-drawer quote-block section
  220. special-block src-block table table-row verse-block)
  221. "Complete list of element types.")
  222. (defconst org-element-greater-elements
  223. '(center-block drawer dynamic-block footnote-definition headline inlinetask
  224. item plain-list property-drawer quote-block section
  225. special-block table)
  226. "List of recursive element types aka Greater Elements.")
  227. (defconst org-element-all-objects
  228. '(bold citation citation-reference code entity export-snippet
  229. footnote-reference inline-babel-call inline-src-block italic line-break
  230. latex-fragment link macro radio-target statistics-cookie strike-through
  231. subscript superscript table-cell target timestamp underline verbatim)
  232. "Complete list of object types.")
  233. (defconst org-element-recursive-objects
  234. '(bold citation footnote-reference italic link subscript radio-target
  235. strike-through superscript table-cell underline)
  236. "List of recursive object types.")
  237. (defconst org-element-object-containers
  238. (append org-element-recursive-objects '(paragraph table-row verse-block))
  239. "List of object or element types that can directly contain objects.")
  240. (defconst org-element-affiliated-keywords
  241. '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
  242. "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
  243. "List of affiliated keywords as strings.
  244. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  245. are affiliated keywords and need not to be in this list.")
  246. (defconst org-element-keyword-translation-alist
  247. '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
  248. ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
  249. ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
  250. "Alist of usual translations for keywords.
  251. The key is the old name and the value the new one. The property
  252. holding their value will be named after the translated name.")
  253. (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
  254. "List of affiliated keywords that can occur more than once in an element.
  255. Their value will be consed into a list of strings, which will be
  256. returned as the value of the property.
  257. This list is checked after translations have been applied. See
  258. `org-element-keyword-translation-alist'.
  259. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  260. allow multiple occurrences and need not to be in this list.")
  261. (defconst org-element-parsed-keywords '("CAPTION")
  262. "List of affiliated keywords whose value can be parsed.
  263. Their value will be stored as a secondary string: a list of
  264. strings and objects.
  265. This list is checked after translations have been applied. See
  266. `org-element-keyword-translation-alist'.")
  267. (defconst org-element--parsed-properties-alist
  268. (mapcar (lambda (k) (cons k (intern (concat ":" (downcase k)))))
  269. org-element-parsed-keywords)
  270. "Alist of parsed keywords and associated properties.
  271. This is generated from `org-element-parsed-keywords', which
  272. see.")
  273. (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
  274. "List of affiliated keywords which can have a secondary value.
  275. In Org syntax, they can be written with optional square brackets
  276. before the colons. For example, RESULTS keyword can be
  277. associated to a hash value with the following:
  278. #+RESULTS[hash-string]: some-source
  279. This list is checked after translations have been applied. See
  280. `org-element-keyword-translation-alist'.")
  281. (defconst org-element--affiliated-re
  282. (format "[ \t]*#\\+\\(?:%s\\):[ \t]*"
  283. (concat
  284. ;; Dual affiliated keywords.
  285. (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
  286. (regexp-opt org-element-dual-keywords))
  287. "\\|"
  288. ;; Regular affiliated keywords.
  289. (format "\\(?1:%s\\)"
  290. (regexp-opt
  291. (cl-remove-if
  292. (lambda (k) (member k org-element-dual-keywords))
  293. org-element-affiliated-keywords)))
  294. "\\|"
  295. ;; Export attributes.
  296. "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
  297. "Regexp matching any affiliated keyword.
  298. Keyword name is put in match group 1. Moreover, if keyword
  299. belongs to `org-element-dual-keywords', put the dual value in
  300. match group 2.
  301. Don't modify it, set `org-element-affiliated-keywords' instead.")
  302. (defconst org-element-object-restrictions
  303. (let* ((minimal-set '(bold code entity italic latex-fragment strike-through
  304. subscript superscript underline verbatim))
  305. (standard-set
  306. (remq 'citation-reference (remq 'table-cell org-element-all-objects)))
  307. (standard-set-no-line-break (remq 'line-break standard-set)))
  308. `((bold ,@standard-set)
  309. (citation citation-reference)
  310. (citation-reference ,@minimal-set)
  311. (footnote-reference ,@standard-set)
  312. (headline ,@standard-set-no-line-break)
  313. (inlinetask ,@standard-set-no-line-break)
  314. (italic ,@standard-set)
  315. (item ,@standard-set-no-line-break)
  316. (keyword ,@(remq 'footnote-reference standard-set))
  317. ;; Ignore all links in a link description. Also ignore
  318. ;; radio-targets and line breaks.
  319. (link export-snippet inline-babel-call inline-src-block macro
  320. statistics-cookie ,@minimal-set)
  321. (paragraph ,@standard-set)
  322. ;; Remove any variable object from radio target as it would
  323. ;; prevent it from being properly recognized.
  324. (radio-target ,@minimal-set)
  325. (strike-through ,@standard-set)
  326. (subscript ,@standard-set)
  327. (superscript ,@standard-set)
  328. ;; Ignore inline babel call and inline source block as formulas
  329. ;; are possible. Also ignore line breaks and statistics
  330. ;; cookies.
  331. (table-cell citation export-snippet footnote-reference link macro
  332. radio-target target timestamp ,@minimal-set)
  333. (table-row table-cell)
  334. (underline ,@standard-set)
  335. (verse-block ,@standard-set)))
  336. "Alist of objects restrictions.
  337. key is an element or object type containing objects and value is
  338. a list of types that can be contained within an element or object
  339. of such type.
  340. This alist also applies to secondary string. For example, an
  341. `headline' type element doesn't directly contain objects, but
  342. still has an entry since one of its properties (`:title') does.")
  343. (defconst org-element-secondary-value-alist
  344. '((citation :prefix :suffix)
  345. (headline :title)
  346. (inlinetask :title)
  347. (item :tag)
  348. (citation-reference :prefix :suffix))
  349. "Alist between element types and locations of secondary values.")
  350. (defconst org-element--pair-round-table
  351. (let ((table (make-char-table 'syntax-table '(2))))
  352. (modify-syntax-entry ?\( "()" table)
  353. (modify-syntax-entry ?\) ")(" table)
  354. table)
  355. "Table used internally to pair only round brackets.")
  356. (defconst org-element--pair-square-table
  357. (let ((table (make-char-table 'syntax-table '(2))))
  358. (modify-syntax-entry ?\[ "(]" table)
  359. (modify-syntax-entry ?\] ")[" table)
  360. table)
  361. "Table used internally to pair only square brackets.")
  362. (defconst org-element--pair-curly-table
  363. (let ((table (make-char-table 'syntax-table '(2))))
  364. (modify-syntax-entry ?\{ "(}" table)
  365. (modify-syntax-entry ?\} "){" table)
  366. table)
  367. "Table used internally to pair only curly brackets.")
  368. (defun org-element--parse-paired-brackets (char)
  369. "Parse paired brackets at point.
  370. CHAR is the opening bracket to consider, as a character. Return
  371. contents between brackets, as a string, or nil. Also move point
  372. past the brackets."
  373. (when (eq char (char-after))
  374. (let ((syntax-table (pcase char
  375. (?\{ org-element--pair-curly-table)
  376. (?\[ org-element--pair-square-table)
  377. (?\( org-element--pair-round-table)
  378. (_ nil)))
  379. (pos (point)))
  380. (when syntax-table
  381. (with-syntax-table syntax-table
  382. (let ((end (ignore-errors (scan-lists pos 1 0))))
  383. (when end
  384. (goto-char end)
  385. (buffer-substring-no-properties (1+ pos) (1- end)))))))))
  386. ;;; Accessors and Setters
  387. ;;
  388. ;; Provide four accessors: `org-element-type', `org-element-property'
  389. ;; `org-element-contents' and `org-element-restriction'.
  390. ;;
  391. ;; Setter functions allow modification of elements by side effect.
  392. ;; There is `org-element-put-property', `org-element-set-contents'.
  393. ;; These low-level functions are useful to build a parse tree.
  394. ;;
  395. ;; `org-element-adopt-elements', `org-element-set-element',
  396. ;; `org-element-extract-element' and `org-element-insert-before' are
  397. ;; high-level functions useful to modify a parse tree.
  398. ;;
  399. ;; `org-element-secondary-p' is a predicate used to know if a given
  400. ;; object belongs to a secondary string. `org-element-class' tells if
  401. ;; some parsed data is an element or an object, handling pseudo
  402. ;; elements and objects. `org-element-copy' returns an element or
  403. ;; object, stripping its parent property in the process.
  404. (defsubst org-element-type (element)
  405. "Return type of ELEMENT.
  406. The function returns the type of the element or object provided.
  407. It can also return the following special value:
  408. `plain-text' for a string
  409. `org-data' for a complete document
  410. nil in any other case."
  411. (cond
  412. ((not (consp element)) (and (stringp element) 'plain-text))
  413. ((symbolp (car element)) (car element))))
  414. (defsubst org-element-property (property element)
  415. "Extract the value from the PROPERTY of an ELEMENT."
  416. (if (stringp element) (get-text-property 0 property element)
  417. (plist-get (nth 1 element) property)))
  418. (defsubst org-element-contents (element)
  419. "Extract contents from an ELEMENT."
  420. (cond ((not (consp element)) nil)
  421. ((symbolp (car element)) (nthcdr 2 element))
  422. (t element)))
  423. (defsubst org-element-restriction (element)
  424. "Return restriction associated to ELEMENT.
  425. ELEMENT can be an element, an object or a symbol representing an
  426. element or object type."
  427. (cdr (assq (if (symbolp element) element (org-element-type element))
  428. org-element-object-restrictions)))
  429. (defsubst org-element-put-property (element property value)
  430. "In ELEMENT set PROPERTY to VALUE.
  431. Return modified element."
  432. (if (stringp element) (org-add-props element nil property value)
  433. (setcar (cdr element) (plist-put (nth 1 element) property value))
  434. element))
  435. (defsubst org-element-set-contents (element &rest contents)
  436. "Set ELEMENT's contents to CONTENTS.
  437. Return ELEMENT."
  438. (cond ((null element) contents)
  439. ((not (symbolp (car element))) contents)
  440. ((cdr element) (setcdr (cdr element) contents) element)
  441. (t (nconc element contents))))
  442. (defun org-element-secondary-p (object)
  443. "Non-nil when OBJECT directly belongs to a secondary string.
  444. Return value is the property name, as a keyword, or nil."
  445. (let* ((parent (org-element-property :parent object))
  446. (properties (cdr (assq (org-element-type parent)
  447. org-element-secondary-value-alist))))
  448. (catch 'exit
  449. (dolist (p properties)
  450. (and (memq object (org-element-property p parent))
  451. (throw 'exit p))))))
  452. (defsubst org-element-class (datum &optional parent)
  453. "Return class for ELEMENT, as a symbol.
  454. Class is either `element' or `object'. Optional argument PARENT
  455. is the element or object containing DATUM. It defaults to the
  456. value of DATUM `:parent' property."
  457. (let ((type (org-element-type datum))
  458. (parent (or parent (org-element-property :parent datum))))
  459. (cond
  460. ;; Trivial cases.
  461. ((memq type org-element-all-objects) 'object)
  462. ((memq type org-element-all-elements) 'element)
  463. ;; Special cases.
  464. ((eq type 'org-data) 'element)
  465. ((eq type 'plain-text) 'object)
  466. ((not type) 'object)
  467. ;; Pseudo object or elements. Make a guess about its class.
  468. ;; Basically a pseudo object is contained within another object,
  469. ;; a secondary string or a container element.
  470. ((not parent) 'element)
  471. (t
  472. (let ((parent-type (org-element-type parent)))
  473. (cond ((not parent-type) 'object)
  474. ((memq parent-type org-element-object-containers) 'object)
  475. ((org-element-secondary-p datum) 'object)
  476. (t 'element)))))))
  477. (defsubst org-element-adopt-elements (parent &rest children)
  478. "Append elements to the contents of another element.
  479. PARENT is an element or object. CHILDREN can be elements,
  480. objects, or a strings.
  481. The function takes care of setting `:parent' property for CHILD.
  482. Return parent element."
  483. (declare (indent 1))
  484. (if (not children) parent
  485. ;; Link every child to PARENT. If PARENT is nil, it is a secondary
  486. ;; string: parent is the list itself.
  487. (dolist (child children)
  488. (org-element-put-property child :parent (or parent children)))
  489. ;; Add CHILDREN at the end of PARENT contents.
  490. (when parent
  491. (apply #'org-element-set-contents
  492. parent
  493. (nconc (org-element-contents parent) children)))
  494. ;; Return modified PARENT element.
  495. (or parent children)))
  496. (defun org-element-extract-element (element)
  497. "Extract ELEMENT from parse tree.
  498. Remove element from the parse tree by side-effect, and return it
  499. with its `:parent' property stripped out."
  500. (let ((parent (org-element-property :parent element))
  501. (secondary (org-element-secondary-p element)))
  502. (if secondary
  503. (org-element-put-property
  504. parent secondary
  505. (delq element (org-element-property secondary parent)))
  506. (apply #'org-element-set-contents
  507. parent
  508. (delq element (org-element-contents parent))))
  509. ;; Return ELEMENT with its :parent removed.
  510. (org-element-put-property element :parent nil)))
  511. (defun org-element-insert-before (element location)
  512. "Insert ELEMENT before LOCATION in parse tree.
  513. LOCATION is an element, object or string within the parse tree.
  514. Parse tree is modified by side effect."
  515. (let* ((parent (org-element-property :parent location))
  516. (property (org-element-secondary-p location))
  517. (siblings (if property (org-element-property property parent)
  518. (org-element-contents parent)))
  519. ;; Special case: LOCATION is the first element of an
  520. ;; independent secondary string (e.g. :title property). Add
  521. ;; ELEMENT in-place.
  522. (specialp (and (not property)
  523. (eq siblings parent)
  524. (eq (car parent) location))))
  525. ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS.
  526. (cond (specialp)
  527. ((or (null siblings) (eq (car siblings) location))
  528. (push element siblings))
  529. ((null location) (nconc siblings (list element)))
  530. (t
  531. (let ((index (cl-position location siblings)))
  532. (unless index (error "No location found to insert element"))
  533. (push element (cdr (nthcdr (1- index) siblings))))))
  534. ;; Store SIBLINGS at appropriate place in parse tree.
  535. (cond
  536. (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
  537. (property (org-element-put-property parent property siblings))
  538. (t (apply #'org-element-set-contents parent siblings)))
  539. ;; Set appropriate :parent property.
  540. (org-element-put-property element :parent parent)))
  541. (defun org-element-set-element (old new)
  542. "Replace element or object OLD with element or object NEW.
  543. The function takes care of setting `:parent' property for NEW."
  544. ;; Ensure OLD and NEW have the same parent.
  545. (org-element-put-property new :parent (org-element-property :parent old))
  546. (if (or (memq (org-element-type old) '(plain-text nil))
  547. (memq (org-element-type new) '(plain-text nil)))
  548. ;; We cannot replace OLD with NEW since one of them is not an
  549. ;; object or element. We take the long path.
  550. (progn (org-element-insert-before new old)
  551. (org-element-extract-element old))
  552. ;; Since OLD is going to be changed into NEW by side-effect, first
  553. ;; make sure that every element or object within NEW has OLD as
  554. ;; parent.
  555. (dolist (blob (org-element-contents new))
  556. (org-element-put-property blob :parent old))
  557. ;; Transfer contents.
  558. (apply #'org-element-set-contents old (org-element-contents new))
  559. ;; Overwrite OLD's properties with NEW's.
  560. (setcar (cdr old) (nth 1 new))
  561. ;; Transfer type.
  562. (setcar old (car new))))
  563. (defun org-element-create (type &optional props &rest children)
  564. "Create a new element of type TYPE.
  565. Optional argument PROPS, when non-nil, is a plist defining the
  566. properties of the element. CHILDREN can be elements, objects or
  567. strings."
  568. (apply #'org-element-adopt-elements (list type props) children))
  569. (defun org-element-copy (datum)
  570. "Return a copy of DATUM.
  571. DATUM is an element, object, string or nil. `:parent' property
  572. is cleared and contents are removed in the process."
  573. (when datum
  574. (let ((type (org-element-type datum)))
  575. (pcase type
  576. (`org-data (list 'org-data nil))
  577. (`plain-text (substring-no-properties datum))
  578. (`nil (copy-sequence datum))
  579. (_
  580. (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil)))))))
  581. ;;; Greater elements
  582. ;;
  583. ;; For each greater element type, we define a parser and an
  584. ;; interpreter.
  585. ;;
  586. ;; A parser returns the element or object as the list described above.
  587. ;; Most of them accepts no argument. Though, exceptions exist. Hence
  588. ;; every element containing a secondary string (see
  589. ;; `org-element-secondary-value-alist') will accept an optional
  590. ;; argument to toggle parsing of these secondary strings. Moreover,
  591. ;; `item' parser requires current list's structure as its first
  592. ;; element.
  593. ;;
  594. ;; An interpreter accepts two arguments: the list representation of
  595. ;; the element or object, and its contents. The latter may be nil,
  596. ;; depending on the element or object considered. It returns the
  597. ;; appropriate Org syntax, as a string.
  598. ;;
  599. ;; Parsing functions must follow the naming convention:
  600. ;; org-element-TYPE-parser, where TYPE is greater element's type, as
  601. ;; defined in `org-element-greater-elements'.
  602. ;;
  603. ;; Similarly, interpreting functions must follow the naming
  604. ;; convention: org-element-TYPE-interpreter.
  605. ;;
  606. ;; With the exception of `headline' and `item' types, greater elements
  607. ;; cannot contain other greater elements of their own type.
  608. ;;
  609. ;; Beside implementing a parser and an interpreter, adding a new
  610. ;; greater element requires tweaking `org-element--current-element'.
  611. ;; Moreover, the newly defined type must be added to both
  612. ;; `org-element-all-elements' and `org-element-greater-elements'.
  613. ;;;; Center Block
  614. (defun org-element-center-block-parser (limit affiliated)
  615. "Parse a center block.
  616. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  617. the buffer position at the beginning of the first affiliated
  618. keyword and CDR is a plist of affiliated keywords along with
  619. their value.
  620. Return a list whose CAR is `center-block' and CDR is a plist
  621. containing `:begin', `:end', `:contents-begin', `:contents-end',
  622. `:post-blank' and `:post-affiliated' keywords.
  623. Assume point is at the beginning of the block."
  624. (let ((case-fold-search t))
  625. (if (not (save-excursion
  626. (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
  627. ;; Incomplete block: parse it as a paragraph.
  628. (org-element-paragraph-parser limit affiliated)
  629. (let ((block-end-line (match-beginning 0)))
  630. (let* ((begin (car affiliated))
  631. (post-affiliated (point))
  632. ;; Empty blocks have no contents.
  633. (contents-begin (progn (forward-line)
  634. (and (< (point) block-end-line)
  635. (point))))
  636. (contents-end (and contents-begin block-end-line))
  637. (pos-before-blank (progn (goto-char block-end-line)
  638. (forward-line)
  639. (point)))
  640. (end (save-excursion
  641. (skip-chars-forward " \r\t\n" limit)
  642. (if (eobp) (point) (line-beginning-position)))))
  643. (list 'center-block
  644. (nconc
  645. (list :begin begin
  646. :end end
  647. :contents-begin contents-begin
  648. :contents-end contents-end
  649. :post-blank (count-lines pos-before-blank end)
  650. :post-affiliated post-affiliated)
  651. (cdr affiliated))))))))
  652. (defun org-element-center-block-interpreter (_ contents)
  653. "Interpret a center-block element as Org syntax.
  654. CONTENTS is the contents of the element."
  655. (format "#+begin_center\n%s#+end_center" contents))
  656. ;;;; Drawer
  657. (defun org-element-drawer-parser (limit affiliated)
  658. "Parse a drawer.
  659. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  660. the buffer position at the beginning of the first affiliated
  661. keyword and CDR is a plist of affiliated keywords along with
  662. their value.
  663. Return a list whose CAR is `drawer' and CDR is a plist containing
  664. `:drawer-name', `:begin', `:end', `:contents-begin',
  665. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  666. Assume point is at beginning of drawer."
  667. (let ((case-fold-search t))
  668. (if (not (save-excursion
  669. (goto-char (min limit (line-end-position)))
  670. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  671. ;; Incomplete drawer: parse it as a paragraph.
  672. (org-element-paragraph-parser limit affiliated)
  673. (save-excursion
  674. (let* ((drawer-end-line (match-beginning 0))
  675. (name (progn (looking-at org-drawer-regexp)
  676. (match-string-no-properties 1)))
  677. (begin (car affiliated))
  678. (post-affiliated (point))
  679. ;; Empty drawers have no contents.
  680. (contents-begin (progn (forward-line)
  681. (and (< (point) drawer-end-line)
  682. (point))))
  683. (contents-end (and contents-begin drawer-end-line))
  684. (pos-before-blank (progn (goto-char drawer-end-line)
  685. (forward-line)
  686. (point)))
  687. (end (progn (skip-chars-forward " \r\t\n" limit)
  688. (if (eobp) (point) (line-beginning-position)))))
  689. (list 'drawer
  690. (nconc
  691. (list :begin begin
  692. :end end
  693. :drawer-name name
  694. :contents-begin contents-begin
  695. :contents-end contents-end
  696. :post-blank (count-lines pos-before-blank end)
  697. :post-affiliated post-affiliated)
  698. (cdr affiliated))))))))
  699. (defun org-element-drawer-interpreter (drawer contents)
  700. "Interpret DRAWER element as Org syntax.
  701. CONTENTS is the contents of the element."
  702. (format ":%s:\n%s:END:"
  703. (org-element-property :drawer-name drawer)
  704. contents))
  705. ;;;; Dynamic Block
  706. (defun org-element-dynamic-block-parser (limit affiliated)
  707. "Parse a dynamic block.
  708. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  709. the buffer position at the beginning of the first affiliated
  710. keyword and CDR is a plist of affiliated keywords along with
  711. their value.
  712. Return a list whose CAR is `dynamic-block' and CDR is a plist
  713. containing `:block-name', `:begin', `:end', `:contents-begin',
  714. `:contents-end', `:arguments', `:post-blank' and
  715. `:post-affiliated' keywords.
  716. Assume point is at beginning of dynamic block."
  717. (let ((case-fold-search t))
  718. (if (not (save-excursion
  719. (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
  720. ;; Incomplete block: parse it as a paragraph.
  721. (org-element-paragraph-parser limit affiliated)
  722. (let ((block-end-line (match-beginning 0)))
  723. (save-excursion
  724. (let* ((name (progn (looking-at org-dblock-start-re)
  725. (match-string-no-properties 1)))
  726. (arguments (match-string-no-properties 3))
  727. (begin (car affiliated))
  728. (post-affiliated (point))
  729. ;; Empty blocks have no contents.
  730. (contents-begin (progn (forward-line)
  731. (and (< (point) block-end-line)
  732. (point))))
  733. (contents-end (and contents-begin block-end-line))
  734. (pos-before-blank (progn (goto-char block-end-line)
  735. (forward-line)
  736. (point)))
  737. (end (progn (skip-chars-forward " \r\t\n" limit)
  738. (if (eobp) (point) (line-beginning-position)))))
  739. (list 'dynamic-block
  740. (nconc
  741. (list :begin begin
  742. :end end
  743. :block-name name
  744. :arguments arguments
  745. :contents-begin contents-begin
  746. :contents-end contents-end
  747. :post-blank (count-lines pos-before-blank end)
  748. :post-affiliated post-affiliated)
  749. (cdr affiliated)))))))))
  750. (defun org-element-dynamic-block-interpreter (dynamic-block contents)
  751. "Interpret DYNAMIC-BLOCK element as Org syntax.
  752. CONTENTS is the contents of the element."
  753. (format "#+begin: %s%s\n%s#+end:"
  754. (org-element-property :block-name dynamic-block)
  755. (let ((args (org-element-property :arguments dynamic-block)))
  756. (if args (concat " " args) ""))
  757. contents))
  758. ;;;; Footnote Definition
  759. (defconst org-element--footnote-separator
  760. (concat org-outline-regexp-bol "\\|"
  761. org-footnote-definition-re "\\|"
  762. "^\\([ \t]*\n\\)\\{2,\\}")
  763. "Regexp used as a footnote definition separator.")
  764. (defun org-element-footnote-definition-parser (limit affiliated)
  765. "Parse a footnote definition.
  766. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  767. the buffer position at the beginning of the first affiliated
  768. keyword and CDR is a plist of affiliated keywords along with
  769. their value.
  770. Return a list whose CAR is `footnote-definition' and CDR is
  771. a plist containing `:label', `:begin' `:end', `:contents-begin',
  772. `:contents-end', `:pre-blank',`:post-blank' and
  773. `:post-affiliated' keywords.
  774. Assume point is at the beginning of the footnote definition."
  775. (save-excursion
  776. (let* ((label (progn (looking-at org-footnote-definition-re)
  777. (match-string-no-properties 1)))
  778. (begin (car affiliated))
  779. (post-affiliated (point))
  780. (end
  781. (save-excursion
  782. (end-of-line)
  783. (cond
  784. ((not
  785. (re-search-forward org-element--footnote-separator limit t))
  786. limit)
  787. ((eq ?\[ (char-after (match-beginning 0)))
  788. ;; At a new footnote definition, make sure we end
  789. ;; before any affiliated keyword above.
  790. (forward-line -1)
  791. (while (and (> (point) post-affiliated)
  792. (looking-at-p org-element--affiliated-re))
  793. (forward-line -1))
  794. (line-beginning-position 2))
  795. ((eq ?* (char-after (match-beginning 0))) (match-beginning 0))
  796. (t (skip-chars-forward " \r\t\n" limit)
  797. (if (= limit (point)) limit (line-beginning-position))))))
  798. (pre-blank 0)
  799. (contents-begin
  800. (progn (search-forward "]")
  801. (skip-chars-forward " \r\t\n" end)
  802. (cond ((= (point) end) nil)
  803. ((= (line-beginning-position) post-affiliated) (point))
  804. (t
  805. (setq pre-blank
  806. (count-lines (line-beginning-position) begin))
  807. (line-beginning-position)))))
  808. (contents-end
  809. (progn (goto-char end)
  810. (skip-chars-backward " \r\t\n")
  811. (line-beginning-position 2))))
  812. (list 'footnote-definition
  813. (nconc
  814. (list :label label
  815. :begin begin
  816. :end end
  817. :contents-begin contents-begin
  818. :contents-end (and contents-begin contents-end)
  819. :pre-blank pre-blank
  820. :post-blank (count-lines contents-end end)
  821. :post-affiliated post-affiliated)
  822. (cdr affiliated))))))
  823. (defun org-element-footnote-definition-interpreter (footnote-definition contents)
  824. "Interpret FOOTNOTE-DEFINITION element as Org syntax.
  825. CONTENTS is the contents of the footnote-definition."
  826. (let ((pre-blank
  827. (min (or (org-element-property :pre-blank footnote-definition)
  828. ;; 0 is specific to paragraphs at the beginning of
  829. ;; the footnote definition, so we use 1 as
  830. ;; a fall-back value, which is more universal.
  831. 1)
  832. ;; Footnote ends after more than two consecutive empty
  833. ;; lines: limit ourselves to 2 newline characters.
  834. 2)))
  835. (concat (format "[fn:%s]" (org-element-property :label footnote-definition))
  836. (if (= pre-blank 0) (concat " " (org-trim contents))
  837. (concat (make-string pre-blank ?\n) contents)))))
  838. ;;;; Headline
  839. (defun org-element--get-node-properties ()
  840. "Return node properties associated to headline at point.
  841. Upcase property names. It avoids confusion between properties
  842. obtained through property drawer and default properties from the
  843. parser (e.g. `:end' and :END:). Return value is a plist."
  844. (save-excursion
  845. (forward-line)
  846. (when (looking-at-p org-planning-line-re) (forward-line))
  847. (when (looking-at org-property-drawer-re)
  848. (forward-line)
  849. (let ((end (match-end 0)) properties)
  850. (while (< (line-end-position) end)
  851. (looking-at org-property-re)
  852. (push (match-string-no-properties 3) properties)
  853. (push (intern (concat ":" (upcase (match-string 2)))) properties)
  854. (forward-line))
  855. properties))))
  856. (defun org-element--get-time-properties ()
  857. "Return time properties associated to headline at point.
  858. Return value is a plist."
  859. (save-excursion
  860. (when (progn (forward-line) (looking-at org-planning-line-re))
  861. (let ((end (line-end-position)) plist)
  862. (while (re-search-forward org-keyword-time-not-clock-regexp end t)
  863. (goto-char (match-end 1))
  864. (skip-chars-forward " \t")
  865. (let ((keyword (match-string 1))
  866. (time (org-element-timestamp-parser)))
  867. (cond ((equal keyword org-scheduled-string)
  868. (setq plist (plist-put plist :scheduled time)))
  869. ((equal keyword org-deadline-string)
  870. (setq plist (plist-put plist :deadline time)))
  871. (t (setq plist (plist-put plist :closed time))))))
  872. plist))))
  873. (defun org-element-headline-parser (limit &optional raw-secondary-p)
  874. "Parse a headline.
  875. Return a list whose CAR is `headline' and CDR is a plist
  876. containing `:raw-value', `:title', `:begin', `:end',
  877. `:pre-blank', `:contents-begin' and `:contents-end', `:level',
  878. `:priority', `:tags', `:todo-keyword', `:todo-type', `:scheduled',
  879. `:deadline', `:closed', `:archivedp', `:commentedp'
  880. `:footnote-section-p', `:post-blank' and `:post-affiliated'
  881. keywords.
  882. The plist also contains any property set in the property drawer,
  883. with its name in upper cases and colons added at the
  884. beginning (e.g., `:CUSTOM_ID').
  885. LIMIT is a buffer position bounding the search.
  886. When RAW-SECONDARY-P is non-nil, headline's title will not be
  887. parsed as a secondary string, but as a plain string instead.
  888. Assume point is at beginning of the headline."
  889. (save-excursion
  890. (let* ((begin (point))
  891. (level (prog1 (org-reduced-level (skip-chars-forward "*"))
  892. (skip-chars-forward " \t")))
  893. (todo (and org-todo-regexp
  894. (let (case-fold-search) (looking-at (concat org-todo-regexp " ")))
  895. (progn (goto-char (match-end 0))
  896. (skip-chars-forward " \t")
  897. (match-string 1))))
  898. (todo-type
  899. (and todo (if (member todo org-done-keywords) 'done 'todo)))
  900. (priority (and (looking-at "\\[#.\\][ \t]*")
  901. (progn (goto-char (match-end 0))
  902. (aref (match-string 0) 2))))
  903. (commentedp
  904. (and (let (case-fold-search) (looking-at org-comment-string))
  905. (goto-char (match-end 0))))
  906. (title-start (prog1 (point)
  907. (unless (or todo priority commentedp)
  908. ;; Headline like "* :tag:"
  909. (skip-chars-backward " \t"))))
  910. (tags (when (re-search-forward
  911. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  912. (line-end-position)
  913. 'move)
  914. (goto-char (match-beginning 0))
  915. (org-split-string (match-string 1) ":")))
  916. (title-end (point))
  917. (raw-value (org-trim
  918. (buffer-substring-no-properties title-start title-end)))
  919. (archivedp (member org-archive-tag tags))
  920. (footnote-section-p (and org-footnote-section
  921. (string= org-footnote-section raw-value)))
  922. (standard-props (org-element--get-node-properties))
  923. (time-props (org-element--get-time-properties))
  924. (end (min (save-excursion (org-end-of-subtree t t)) limit))
  925. (contents-begin (save-excursion
  926. (forward-line)
  927. (skip-chars-forward " \r\t\n" end)
  928. (and (/= (point) end) (line-beginning-position))))
  929. (contents-end (and contents-begin
  930. (progn (goto-char end)
  931. (skip-chars-backward " \r\t\n")
  932. (line-beginning-position 2)))))
  933. (let ((headline
  934. (list 'headline
  935. (nconc
  936. (list :raw-value raw-value
  937. :begin begin
  938. :end end
  939. :pre-blank
  940. (if (not contents-begin) 0
  941. (1- (count-lines begin contents-begin)))
  942. :contents-begin contents-begin
  943. :contents-end contents-end
  944. :level level
  945. :priority priority
  946. :tags tags
  947. :todo-keyword todo
  948. :todo-type todo-type
  949. :post-blank
  950. (if contents-end
  951. (count-lines contents-end end)
  952. (1- (count-lines begin end)))
  953. :footnote-section-p footnote-section-p
  954. :archivedp archivedp
  955. :commentedp commentedp
  956. :post-affiliated begin)
  957. time-props
  958. standard-props))))
  959. (org-element-put-property
  960. headline :title
  961. (if raw-secondary-p raw-value
  962. (org-element--parse-objects
  963. (progn (goto-char title-start)
  964. (skip-chars-forward " \t")
  965. (point))
  966. (progn (goto-char title-end)
  967. (skip-chars-backward " \t")
  968. (point))
  969. nil
  970. (org-element-restriction 'headline)
  971. headline)))))))
  972. (defun org-element-headline-interpreter (headline contents)
  973. "Interpret HEADLINE element as Org syntax.
  974. CONTENTS is the contents of the element."
  975. (let* ((level (org-element-property :level headline))
  976. (todo (org-element-property :todo-keyword headline))
  977. (priority (org-element-property :priority headline))
  978. (title (org-element-interpret-data
  979. (org-element-property :title headline)))
  980. (tags (let ((tag-list (org-element-property :tags headline)))
  981. (and tag-list
  982. (format ":%s:" (mapconcat #'identity tag-list ":")))))
  983. (commentedp (org-element-property :commentedp headline))
  984. (pre-blank (or (org-element-property :pre-blank headline) 0))
  985. (heading
  986. (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
  987. ?*)
  988. (and todo (concat " " todo))
  989. (and commentedp (concat " " org-comment-string))
  990. (and priority (format " [#%c]" priority))
  991. " "
  992. (if (and org-footnote-section
  993. (org-element-property :footnote-section-p headline))
  994. org-footnote-section
  995. title))))
  996. (concat
  997. heading
  998. ;; Align tags.
  999. (when tags
  1000. (cond
  1001. ((zerop org-tags-column) (format " %s" tags))
  1002. ((< org-tags-column 0)
  1003. (concat
  1004. (make-string
  1005. (max (- (+ org-tags-column (length heading) (length tags))) 1)
  1006. ?\s)
  1007. tags))
  1008. (t
  1009. (concat
  1010. (make-string (max (- org-tags-column (length heading)) 1) ?\s)
  1011. tags))))
  1012. (make-string (1+ pre-blank) ?\n)
  1013. contents)))
  1014. ;;;; Inlinetask
  1015. (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
  1016. "Parse an inline task.
  1017. Return a list whose CAR is `inlinetask' and CDR is a plist
  1018. containing `:title', `:begin', `:end', `:pre-blank',
  1019. `:contents-begin' and `:contents-end', `:level', `:priority',
  1020. `:raw-value', `:tags', `:todo-keyword', `:todo-type',
  1021. `:scheduled', `:deadline', `:closed', `:post-blank' and
  1022. `:post-affiliated' keywords.
  1023. The plist also contains any property set in the property drawer,
  1024. with its name in upper cases and colons added at the
  1025. beginning (e.g., `:CUSTOM_ID').
  1026. When optional argument RAW-SECONDARY-P is non-nil, inline-task's
  1027. title will not be parsed as a secondary string, but as a plain
  1028. string instead.
  1029. Assume point is at beginning of the inline task."
  1030. (save-excursion
  1031. (let* ((begin (point))
  1032. (level (prog1 (org-reduced-level (skip-chars-forward "*"))
  1033. (skip-chars-forward " \t")))
  1034. (todo (and org-todo-regexp
  1035. (let (case-fold-search) (looking-at org-todo-regexp))
  1036. (progn (goto-char (match-end 0))
  1037. (skip-chars-forward " \t")
  1038. (match-string 0))))
  1039. (todo-type (and todo
  1040. (if (member todo org-done-keywords) 'done 'todo)))
  1041. (priority (and (looking-at "\\[#.\\][ \t]*")
  1042. (progn (goto-char (match-end 0))
  1043. (aref (match-string 0) 2))))
  1044. (title-start (point))
  1045. (tags (when (re-search-forward
  1046. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  1047. (line-end-position)
  1048. 'move)
  1049. (goto-char (match-beginning 0))
  1050. (org-split-string (match-string 1) ":")))
  1051. (title-end (point))
  1052. (raw-value (org-trim
  1053. (buffer-substring-no-properties title-start title-end)))
  1054. (task-end (save-excursion
  1055. (end-of-line)
  1056. (and (re-search-forward org-outline-regexp-bol limit t)
  1057. (looking-at-p "[ \t]*END[ \t]*$")
  1058. (line-beginning-position))))
  1059. (standard-props (and task-end (org-element--get-node-properties)))
  1060. (time-props (and task-end (org-element--get-time-properties)))
  1061. (contents-begin (and task-end
  1062. (< (point) task-end)
  1063. (progn
  1064. (forward-line)
  1065. (skip-chars-forward " \t\n")
  1066. (line-beginning-position))))
  1067. (contents-end (and contents-begin task-end))
  1068. (end (progn (when task-end (goto-char task-end))
  1069. (forward-line)
  1070. (skip-chars-forward " \r\t\n" limit)
  1071. (if (eobp) (point) (line-beginning-position))))
  1072. (inlinetask
  1073. (list 'inlinetask
  1074. (nconc
  1075. (list :raw-value raw-value
  1076. :begin begin
  1077. :end end
  1078. :pre-blank
  1079. (if (not contents-begin) 0
  1080. (1- (count-lines begin contents-begin)))
  1081. :contents-begin contents-begin
  1082. :contents-end contents-end
  1083. :level level
  1084. :priority priority
  1085. :tags tags
  1086. :todo-keyword todo
  1087. :todo-type todo-type
  1088. :post-blank (1- (count-lines (or task-end begin) end))
  1089. :post-affiliated begin)
  1090. time-props
  1091. standard-props))))
  1092. (org-element-put-property
  1093. inlinetask :title
  1094. (if raw-secondary-p raw-value
  1095. (org-element--parse-objects
  1096. (progn (goto-char title-start)
  1097. (skip-chars-forward " \t")
  1098. (point))
  1099. (progn (goto-char title-end)
  1100. (skip-chars-backward " \t")
  1101. (point))
  1102. nil
  1103. (org-element-restriction 'inlinetask)
  1104. inlinetask))))))
  1105. (defun org-element-inlinetask-interpreter (inlinetask contents)
  1106. "Interpret INLINETASK element as Org syntax.
  1107. CONTENTS is the contents of inlinetask."
  1108. (let* ((level (org-element-property :level inlinetask))
  1109. (todo (org-element-property :todo-keyword inlinetask))
  1110. (priority (org-element-property :priority inlinetask))
  1111. (title (org-element-interpret-data
  1112. (org-element-property :title inlinetask)))
  1113. (tags (let ((tag-list (org-element-property :tags inlinetask)))
  1114. (and tag-list
  1115. (format ":%s:" (mapconcat 'identity tag-list ":")))))
  1116. (task (concat (make-string level ?*)
  1117. (and todo (concat " " todo))
  1118. (and priority (format " [#%c]" priority))
  1119. (and title (concat " " title)))))
  1120. (concat task
  1121. ;; Align tags.
  1122. (when tags
  1123. (cond
  1124. ((zerop org-tags-column) (format " %s" tags))
  1125. ((< org-tags-column 0)
  1126. (concat
  1127. (make-string
  1128. (max (- (+ org-tags-column (length task) (length tags))) 1)
  1129. ?\s)
  1130. tags))
  1131. (t
  1132. (concat
  1133. (make-string (max (- org-tags-column (length task)) 1) ?\s)
  1134. tags))))
  1135. ;; Prefer degenerate inlinetasks when there are no
  1136. ;; contents.
  1137. (when contents
  1138. (concat "\n"
  1139. contents
  1140. (make-string level ?*) " end")))))
  1141. ;;;; Item
  1142. (defun org-element-item-parser (_ struct &optional raw-secondary-p)
  1143. "Parse an item.
  1144. STRUCT is the structure of the plain list.
  1145. Return a list whose CAR is `item' and CDR is a plist containing
  1146. `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
  1147. `:checkbox', `:counter', `:tag', `:structure', `:pre-blank',
  1148. `:post-blank' and `:post-affiliated' keywords.
  1149. When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
  1150. any, will not be parsed as a secondary string, but as a plain
  1151. string instead.
  1152. Assume point is at the beginning of the item."
  1153. (save-excursion
  1154. (beginning-of-line)
  1155. (looking-at org-list-full-item-re)
  1156. (let* ((begin (point))
  1157. (bullet (match-string-no-properties 1))
  1158. (checkbox (let ((box (match-string 3)))
  1159. (cond ((equal "[ ]" box) 'off)
  1160. ((equal "[X]" box) 'on)
  1161. ((equal "[-]" box) 'trans))))
  1162. (counter (let ((c (match-string 2)))
  1163. (save-match-data
  1164. (cond
  1165. ((not c) nil)
  1166. ((string-match "[A-Za-z]" c)
  1167. (- (string-to-char (upcase (match-string 0 c)))
  1168. 64))
  1169. ((string-match "[0-9]+" c)
  1170. (string-to-number (match-string 0 c)))))))
  1171. (end (progn (goto-char (nth 6 (assq (point) struct)))
  1172. (if (bolp) (point) (line-beginning-position 2))))
  1173. (pre-blank 0)
  1174. (contents-begin
  1175. (progn
  1176. (goto-char
  1177. ;; Ignore tags in un-ordered lists: they are just
  1178. ;; a part of item's body.
  1179. (if (and (match-beginning 4)
  1180. (save-match-data (string-match "[.)]" bullet)))
  1181. (match-beginning 4)
  1182. (match-end 0)))
  1183. (skip-chars-forward " \r\t\n" end)
  1184. (cond ((= (point) end) nil)
  1185. ;; If first line isn't empty, contents really
  1186. ;; start at the text after item's meta-data.
  1187. ((= (line-beginning-position) begin) (point))
  1188. (t
  1189. (setq pre-blank
  1190. (count-lines (line-beginning-position) begin))
  1191. (line-beginning-position)))))
  1192. (contents-end (and contents-begin
  1193. (progn (goto-char end)
  1194. (skip-chars-backward " \r\t\n")
  1195. (line-beginning-position 2))))
  1196. (item
  1197. (list 'item
  1198. (list :bullet bullet
  1199. :begin begin
  1200. :end end
  1201. :contents-begin contents-begin
  1202. :contents-end contents-end
  1203. :checkbox checkbox
  1204. :counter counter
  1205. :structure struct
  1206. :pre-blank pre-blank
  1207. :post-blank (count-lines (or contents-end begin) end)
  1208. :post-affiliated begin))))
  1209. (org-element-put-property
  1210. item :tag
  1211. (let ((raw (org-list-get-tag begin struct)))
  1212. (when raw
  1213. (if raw-secondary-p raw
  1214. (org-element--parse-objects
  1215. (match-beginning 4) (match-end 4) nil
  1216. (org-element-restriction 'item)
  1217. item))))))))
  1218. (defun org-element-item-interpreter (item contents)
  1219. "Interpret ITEM element as Org syntax.
  1220. CONTENTS is the contents of the element."
  1221. (let ((tag (pcase (org-element-property :tag item)
  1222. (`nil nil)
  1223. (tag (format "%s :: " (org-element-interpret-data tag)))))
  1224. (bullet
  1225. (org-list-bullet-string
  1226. (cond
  1227. ((not (string-match-p "[0-9a-zA-Z]"
  1228. (org-element-property :bullet item))) "- ")
  1229. ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
  1230. (t "1.")))))
  1231. (concat
  1232. bullet
  1233. (pcase (org-element-property :counter item)
  1234. (`nil nil)
  1235. (counter (format "[@%d] " counter)))
  1236. (pcase (org-element-property :checkbox item)
  1237. (`on "[X] ")
  1238. (`off "[ ] ")
  1239. (`trans "[-] ")
  1240. (_ nil))
  1241. tag
  1242. (when contents
  1243. (let* ((ind (make-string (if tag 5 (length bullet)) ?\s))
  1244. (pre-blank
  1245. (min (or (org-element-property :pre-blank item)
  1246. ;; 0 is specific to paragraphs at the
  1247. ;; beginning of the item, so we use 1 as
  1248. ;; a fall-back value, which is more universal.
  1249. 1)
  1250. ;; Lists ends after more than two consecutive
  1251. ;; empty lines: limit ourselves to 2 newline
  1252. ;; characters.
  1253. 2))
  1254. (contents (replace-regexp-in-string
  1255. "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
  1256. (if (= pre-blank 0) (org-trim contents)
  1257. (concat (make-string pre-blank ?\n) contents)))))))
  1258. ;;;; Plain List
  1259. (defun org-element--list-struct (limit)
  1260. ;; Return structure of list at point. Internal function. See
  1261. ;; `org-list-struct' for details.
  1262. (let ((case-fold-search t)
  1263. (top-ind limit)
  1264. (item-re (org-item-re))
  1265. (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
  1266. items struct)
  1267. (save-excursion
  1268. (catch :exit
  1269. (while t
  1270. (cond
  1271. ;; At limit: end all items.
  1272. ((>= (point) limit)
  1273. (let ((end (progn (skip-chars-backward " \r\t\n")
  1274. (line-beginning-position 2))))
  1275. (dolist (item items) (setcar (nthcdr 6 item) end)))
  1276. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1277. ;; At list end: end all items.
  1278. ((looking-at org-list-end-re)
  1279. (dolist (item items) (setcar (nthcdr 6 item) (point)))
  1280. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1281. ;; At a new item: end previous sibling.
  1282. ((looking-at item-re)
  1283. (let ((ind (save-excursion (skip-chars-forward " \t")
  1284. (current-column))))
  1285. (setq top-ind (min top-ind ind))
  1286. (while (and items (<= ind (nth 1 (car items))))
  1287. (let ((item (pop items)))
  1288. (setcar (nthcdr 6 item) (point))
  1289. (push item struct)))
  1290. (push (progn (looking-at org-list-full-item-re)
  1291. (let ((bullet (match-string-no-properties 1)))
  1292. (list (point)
  1293. ind
  1294. bullet
  1295. (match-string-no-properties 2) ; counter
  1296. (match-string-no-properties 3) ; checkbox
  1297. ;; Description tag.
  1298. (and (save-match-data
  1299. (string-match "[-+*]" bullet))
  1300. (match-string-no-properties 4))
  1301. ;; Ending position, unknown so far.
  1302. nil)))
  1303. items))
  1304. (forward-line))
  1305. ;; Skip empty lines.
  1306. ((looking-at "^[ \t]*$") (forward-line))
  1307. ;; Skip inline tasks and blank lines along the way.
  1308. ((and inlinetask-re (looking-at inlinetask-re))
  1309. (forward-line)
  1310. (let ((origin (point)))
  1311. (when (re-search-forward inlinetask-re limit t)
  1312. (if (looking-at-p "END[ \t]*$") (forward-line)
  1313. (goto-char origin)))))
  1314. ;; At some text line. Check if it ends any previous item.
  1315. (t
  1316. (let ((ind (save-excursion
  1317. (skip-chars-forward " \t")
  1318. (current-column)))
  1319. (end (save-excursion
  1320. (skip-chars-backward " \r\t\n")
  1321. (line-beginning-position 2))))
  1322. (while (<= ind (nth 1 (car items)))
  1323. (let ((item (pop items)))
  1324. (setcar (nthcdr 6 item) end)
  1325. (push item struct)
  1326. (unless items
  1327. (throw :exit (sort struct #'car-less-than-car))))))
  1328. ;; Skip blocks (any type) and drawers contents.
  1329. (cond
  1330. ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
  1331. (re-search-forward
  1332. (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
  1333. limit t)))
  1334. ((and (looking-at org-drawer-regexp)
  1335. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
  1336. (forward-line))))))))
  1337. (defun org-element-plain-list-parser (limit affiliated structure)
  1338. "Parse a plain list.
  1339. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1340. the buffer position at the beginning of the first affiliated
  1341. keyword and CDR is a plist of affiliated keywords along with
  1342. their value. STRUCTURE is the structure of the plain list being
  1343. parsed.
  1344. Return a list whose CAR is `plain-list' and CDR is a plist
  1345. containing `:type', `:begin', `:end', `:contents-begin' and
  1346. `:contents-end', `:structure', `:post-blank' and
  1347. `:post-affiliated' keywords.
  1348. Assume point is at the beginning of the list."
  1349. (save-excursion
  1350. (let* ((struct (or structure (org-element--list-struct limit)))
  1351. (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
  1352. ((nth 5 (assq (point) struct)) 'descriptive)
  1353. (t 'unordered)))
  1354. (contents-begin (point))
  1355. (begin (car affiliated))
  1356. (contents-end (let* ((item (assq contents-begin struct))
  1357. (ind (nth 1 item))
  1358. (pos (nth 6 item)))
  1359. (while (and (setq item (assq pos struct))
  1360. (= (nth 1 item) ind))
  1361. (setq pos (nth 6 item)))
  1362. pos))
  1363. (end (progn (goto-char contents-end)
  1364. (skip-chars-forward " \r\t\n" limit)
  1365. (if (= (point) limit) limit (line-beginning-position)))))
  1366. ;; Return value.
  1367. (list 'plain-list
  1368. (nconc
  1369. (list :type type
  1370. :begin begin
  1371. :end end
  1372. :contents-begin contents-begin
  1373. :contents-end contents-end
  1374. :structure struct
  1375. :post-blank (count-lines contents-end end)
  1376. :post-affiliated contents-begin)
  1377. (cdr affiliated))))))
  1378. (defun org-element-plain-list-interpreter (_ contents)
  1379. "Interpret plain-list element as Org syntax.
  1380. CONTENTS is the contents of the element."
  1381. (with-temp-buffer
  1382. (insert contents)
  1383. (goto-char (point-min))
  1384. (org-list-repair)
  1385. (buffer-string)))
  1386. ;;;; Property Drawer
  1387. (defun org-element-property-drawer-parser (limit)
  1388. "Parse a property drawer.
  1389. LIMIT bounds the search.
  1390. Return a list whose car is `property-drawer' and cdr is a plist
  1391. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1392. `:post-blank' and `:post-affiliated' keywords.
  1393. Assume point is at the beginning of the property drawer."
  1394. (save-excursion
  1395. (let ((case-fold-search t)
  1396. (begin (point))
  1397. (contents-begin (line-beginning-position 2)))
  1398. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
  1399. (let ((contents-end (and (> (match-beginning 0) contents-begin)
  1400. (match-beginning 0)))
  1401. (before-blank (progn (forward-line) (point)))
  1402. (end (progn (skip-chars-forward " \r\t\n" limit)
  1403. (if (eobp) (point) (line-beginning-position)))))
  1404. (list 'property-drawer
  1405. (list :begin begin
  1406. :end end
  1407. :contents-begin (and contents-end contents-begin)
  1408. :contents-end contents-end
  1409. :post-blank (count-lines before-blank end)
  1410. :post-affiliated begin))))))
  1411. (defun org-element-property-drawer-interpreter (_ contents)
  1412. "Interpret property-drawer element as Org syntax.
  1413. CONTENTS is the properties within the drawer."
  1414. (format ":PROPERTIES:\n%s:END:" contents))
  1415. ;;;; Quote Block
  1416. (defun org-element-quote-block-parser (limit affiliated)
  1417. "Parse a quote block.
  1418. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1419. the buffer position at the beginning of the first affiliated
  1420. keyword and CDR is a plist of affiliated keywords along with
  1421. their value.
  1422. Return a list whose CAR is `quote-block' and CDR is a plist
  1423. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1424. `:post-blank' and `:post-affiliated' keywords.
  1425. Assume point is at the beginning of the block."
  1426. (let ((case-fold-search t))
  1427. (if (not (save-excursion
  1428. (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
  1429. ;; Incomplete block: parse it as a paragraph.
  1430. (org-element-paragraph-parser limit affiliated)
  1431. (let ((block-end-line (match-beginning 0)))
  1432. (save-excursion
  1433. (let* ((begin (car affiliated))
  1434. (post-affiliated (point))
  1435. ;; Empty blocks have no contents.
  1436. (contents-begin (progn (forward-line)
  1437. (and (< (point) block-end-line)
  1438. (point))))
  1439. (contents-end (and contents-begin block-end-line))
  1440. (pos-before-blank (progn (goto-char block-end-line)
  1441. (forward-line)
  1442. (point)))
  1443. (end (progn (skip-chars-forward " \r\t\n" limit)
  1444. (if (eobp) (point) (line-beginning-position)))))
  1445. (list 'quote-block
  1446. (nconc
  1447. (list :begin begin
  1448. :end end
  1449. :contents-begin contents-begin
  1450. :contents-end contents-end
  1451. :post-blank (count-lines pos-before-blank end)
  1452. :post-affiliated post-affiliated)
  1453. (cdr affiliated)))))))))
  1454. (defun org-element-quote-block-interpreter (_ contents)
  1455. "Interpret quote-block element as Org syntax.
  1456. CONTENTS is the contents of the element."
  1457. (format "#+begin_quote\n%s#+end_quote" contents))
  1458. ;;;; Section
  1459. (defun org-element-section-parser (_)
  1460. "Parse a section.
  1461. Return a list whose CAR is `section' and CDR is a plist
  1462. containing `:begin', `:end', `:contents-begin', `contents-end',
  1463. `:post-blank' and `:post-affiliated' keywords."
  1464. (save-excursion
  1465. ;; Beginning of section is the beginning of the first non-blank
  1466. ;; line after previous headline.
  1467. (let ((begin (point))
  1468. (end (progn (org-with-limited-levels (outline-next-heading))
  1469. (point)))
  1470. (pos-before-blank (progn (skip-chars-backward " \r\t\n")
  1471. (line-beginning-position 2))))
  1472. (list 'section
  1473. (list :begin begin
  1474. :end end
  1475. :contents-begin begin
  1476. :contents-end pos-before-blank
  1477. :post-blank (count-lines pos-before-blank end)
  1478. :post-affiliated begin)))))
  1479. (defun org-element-section-interpreter (_ contents)
  1480. "Interpret section element as Org syntax.
  1481. CONTENTS is the contents of the element."
  1482. contents)
  1483. ;;;; Special Block
  1484. (defun org-element-special-block-parser (limit affiliated)
  1485. "Parse a special block.
  1486. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1487. the buffer position at the beginning of the first affiliated
  1488. keyword and CDR is a plist of affiliated keywords along with
  1489. their value.
  1490. Return a list whose CAR is `special-block' and CDR is a plist
  1491. containing `:type', `:begin', `:end', `:contents-begin',
  1492. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  1493. Assume point is at the beginning of the block."
  1494. (let* ((case-fold-search t)
  1495. (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  1496. (match-string-no-properties 1))))
  1497. (if (not (save-excursion
  1498. (re-search-forward
  1499. (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
  1500. limit t)))
  1501. ;; Incomplete block: parse it as a paragraph.
  1502. (org-element-paragraph-parser limit affiliated)
  1503. (let ((block-end-line (match-beginning 0)))
  1504. (save-excursion
  1505. (let* ((begin (car affiliated))
  1506. (post-affiliated (point))
  1507. ;; Empty blocks have no contents.
  1508. (contents-begin (progn (forward-line)
  1509. (and (< (point) block-end-line)
  1510. (point))))
  1511. (contents-end (and contents-begin block-end-line))
  1512. (pos-before-blank (progn (goto-char block-end-line)
  1513. (forward-line)
  1514. (point)))
  1515. (end (progn (skip-chars-forward " \r\t\n" limit)
  1516. (if (eobp) (point) (line-beginning-position)))))
  1517. (list 'special-block
  1518. (nconc
  1519. (list :type type
  1520. :begin begin
  1521. :end end
  1522. :contents-begin contents-begin
  1523. :contents-end contents-end
  1524. :post-blank (count-lines pos-before-blank end)
  1525. :post-affiliated post-affiliated)
  1526. (cdr affiliated)))))))))
  1527. (defun org-element-special-block-interpreter (special-block contents)
  1528. "Interpret SPECIAL-BLOCK element as Org syntax.
  1529. CONTENTS is the contents of the element."
  1530. (let ((block-type (org-element-property :type special-block)))
  1531. (format "#+begin_%s\n%s#+end_%s" block-type contents block-type)))
  1532. ;;; Elements
  1533. ;;
  1534. ;; For each element, a parser and an interpreter are also defined.
  1535. ;; Both follow the same naming convention used for greater elements.
  1536. ;;
  1537. ;; Also, as for greater elements, adding a new element type is done
  1538. ;; through the following steps: implement a parser and an interpreter,
  1539. ;; tweak `org-element--current-element' so that it recognizes the new
  1540. ;; type and add that new type to `org-element-all-elements'.
  1541. ;;;; Babel Call
  1542. (defun org-element-babel-call-parser (limit affiliated)
  1543. "Parse a babel call.
  1544. LIMIT bounds the search. AFFILIATED is a list of which car is
  1545. the buffer position at the beginning of the first affiliated
  1546. keyword and cdr is a plist of affiliated keywords along with
  1547. their value.
  1548. Return a list whose car is `babel-call' and cdr is a plist
  1549. containing `:call', `:inside-header', `:arguments',
  1550. `:end-header', `:begin', `:end', `:value', `:post-blank' and
  1551. `:post-affiliated' as keywords."
  1552. (save-excursion
  1553. (let* ((begin (car affiliated))
  1554. (post-affiliated (point))
  1555. (before-blank (line-beginning-position 2))
  1556. (value (progn (search-forward ":" before-blank t)
  1557. (skip-chars-forward " \t")
  1558. (org-trim
  1559. (buffer-substring-no-properties
  1560. (point) (line-end-position)))))
  1561. (call
  1562. (or (org-string-nw-p
  1563. (buffer-substring-no-properties
  1564. (point) (progn (skip-chars-forward "^[]()" before-blank)
  1565. (point))))))
  1566. (inside-header (org-element--parse-paired-brackets ?\[))
  1567. (arguments (org-string-nw-p
  1568. (org-element--parse-paired-brackets ?\()))
  1569. (end-header
  1570. (org-string-nw-p
  1571. (org-trim
  1572. (buffer-substring-no-properties (point) (line-end-position)))))
  1573. (end (progn (forward-line)
  1574. (skip-chars-forward " \r\t\n" limit)
  1575. (if (eobp) (point) (line-beginning-position)))))
  1576. (list 'babel-call
  1577. (nconc
  1578. (list :call call
  1579. :inside-header inside-header
  1580. :arguments arguments
  1581. :end-header end-header
  1582. :begin begin
  1583. :end end
  1584. :value value
  1585. :post-blank (count-lines before-blank end)
  1586. :post-affiliated post-affiliated)
  1587. (cdr affiliated))))))
  1588. (defun org-element-babel-call-interpreter (babel-call _)
  1589. "Interpret BABEL-CALL element as Org syntax."
  1590. (concat "#+call: "
  1591. (org-element-property :call babel-call)
  1592. (let ((h (org-element-property :inside-header babel-call)))
  1593. (and h (format "[%s]" h)))
  1594. (concat "(" (org-element-property :arguments babel-call) ")")
  1595. (let ((h (org-element-property :end-header babel-call)))
  1596. (and h (concat " " h)))))
  1597. ;;;; Clock
  1598. (defun org-element-clock-parser (limit)
  1599. "Parse a clock.
  1600. LIMIT bounds the search.
  1601. Return a list whose CAR is `clock' and CDR is a plist containing
  1602. `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
  1603. `:post-affiliated' as keywords."
  1604. (save-excursion
  1605. (let* ((case-fold-search nil)
  1606. (begin (point))
  1607. (value (progn (search-forward "CLOCK:" (line-end-position) t)
  1608. (skip-chars-forward " \t")
  1609. (org-element-timestamp-parser)))
  1610. (duration (and (search-forward " => " (line-end-position) t)
  1611. (progn (skip-chars-forward " \t")
  1612. (looking-at "\\(\\S-+\\)[ \t]*$"))
  1613. (match-string-no-properties 1)))
  1614. (status (if duration 'closed 'running))
  1615. (post-blank (let ((before-blank (progn (forward-line) (point))))
  1616. (skip-chars-forward " \r\t\n" limit)
  1617. (skip-chars-backward " \t")
  1618. (unless (bolp) (end-of-line))
  1619. (count-lines before-blank (point))))
  1620. (end (point)))
  1621. (list 'clock
  1622. (list :status status
  1623. :value value
  1624. :duration duration
  1625. :begin begin
  1626. :end end
  1627. :post-blank post-blank
  1628. :post-affiliated begin)))))
  1629. (defun org-element-clock-interpreter (clock _)
  1630. "Interpret CLOCK element as Org syntax."
  1631. (concat "CLOCK: "
  1632. (org-element-timestamp-interpreter
  1633. (org-element-property :value clock) nil)
  1634. (let ((duration (org-element-property :duration clock)))
  1635. (and duration
  1636. (concat " => "
  1637. (apply 'format
  1638. "%2s:%02s"
  1639. (org-split-string duration ":")))))))
  1640. ;;;; Comment
  1641. (defun org-element-comment-parser (limit)
  1642. "Parse a comment.
  1643. LIMIT bounds the search.
  1644. Return a list whose CAR is `comment' and CDR is a plist
  1645. containing `:begin', `:end', `:value', `:post-blank',
  1646. `:post-affiliated' keywords.
  1647. Assume point is at comment beginning."
  1648. (save-excursion
  1649. (let* ((begin (point))
  1650. (value (prog2 (looking-at "[ \t]*# ?")
  1651. (buffer-substring-no-properties
  1652. (match-end 0) (line-end-position))
  1653. (forward-line)))
  1654. (com-end
  1655. ;; Get comments ending.
  1656. (progn
  1657. (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
  1658. ;; Accumulate lines without leading hash and first
  1659. ;; whitespace.
  1660. (setq value
  1661. (concat value
  1662. "\n"
  1663. (buffer-substring-no-properties
  1664. (match-end 0) (line-end-position))))
  1665. (forward-line))
  1666. (point)))
  1667. (end (progn (goto-char com-end)
  1668. (skip-chars-forward " \r\t\n" limit)
  1669. (if (eobp) (point) (line-beginning-position)))))
  1670. (list 'comment
  1671. (list :begin begin
  1672. :end end
  1673. :value value
  1674. :post-blank (count-lines com-end end)
  1675. :post-affiliated begin)))))
  1676. (defun org-element-comment-interpreter (comment _)
  1677. "Interpret COMMENT element as Org syntax.
  1678. CONTENTS is nil."
  1679. (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
  1680. ;;;; Comment Block
  1681. (defun org-element-comment-block-parser (limit affiliated)
  1682. "Parse an export block.
  1683. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1684. the buffer position at the beginning of the first affiliated
  1685. keyword and CDR is a plist of affiliated keywords along with
  1686. their value.
  1687. Return a list whose CAR is `comment-block' and CDR is a plist
  1688. containing `:begin', `:end', `:value', `:post-blank' and
  1689. `:post-affiliated' keywords.
  1690. Assume point is at comment block beginning."
  1691. (let ((case-fold-search t))
  1692. (if (not (save-excursion
  1693. (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
  1694. ;; Incomplete block: parse it as a paragraph.
  1695. (org-element-paragraph-parser limit affiliated)
  1696. (let ((contents-end (match-beginning 0)))
  1697. (save-excursion
  1698. (let* ((begin (car affiliated))
  1699. (post-affiliated (point))
  1700. (contents-begin (progn (forward-line) (point)))
  1701. (pos-before-blank (progn (goto-char contents-end)
  1702. (forward-line)
  1703. (point)))
  1704. (end (progn (skip-chars-forward " \r\t\n" limit)
  1705. (if (eobp) (point) (line-beginning-position))))
  1706. (value (buffer-substring-no-properties
  1707. contents-begin contents-end)))
  1708. (list 'comment-block
  1709. (nconc
  1710. (list :begin begin
  1711. :end end
  1712. :value value
  1713. :post-blank (count-lines pos-before-blank end)
  1714. :post-affiliated post-affiliated)
  1715. (cdr affiliated)))))))))
  1716. (defun org-element-comment-block-interpreter (comment-block _)
  1717. "Interpret COMMENT-BLOCK element as Org syntax."
  1718. (format "#+begin_comment\n%s#+end_comment"
  1719. (org-element-normalize-string
  1720. (org-remove-indentation
  1721. (org-element-property :value comment-block)))))
  1722. ;;;; Diary Sexp
  1723. (defun org-element-diary-sexp-parser (limit affiliated)
  1724. "Parse a diary sexp.
  1725. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1726. the buffer position at the beginning of the first affiliated
  1727. keyword and CDR is a plist of affiliated keywords along with
  1728. their value.
  1729. Return a list whose CAR is `diary-sexp' and CDR is a plist
  1730. containing `:begin', `:end', `:value', `:post-blank' and
  1731. `:post-affiliated' keywords."
  1732. (save-excursion
  1733. (let ((begin (car affiliated))
  1734. (post-affiliated (point))
  1735. (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
  1736. (match-string-no-properties 1)))
  1737. (pos-before-blank (progn (forward-line) (point)))
  1738. (end (progn (skip-chars-forward " \r\t\n" limit)
  1739. (if (eobp) (point) (line-beginning-position)))))
  1740. (list 'diary-sexp
  1741. (nconc
  1742. (list :value value
  1743. :begin begin
  1744. :end end
  1745. :post-blank (count-lines pos-before-blank end)
  1746. :post-affiliated post-affiliated)
  1747. (cdr affiliated))))))
  1748. (defun org-element-diary-sexp-interpreter (diary-sexp _)
  1749. "Interpret DIARY-SEXP as Org syntax."
  1750. (org-element-property :value diary-sexp))
  1751. ;;;; Example Block
  1752. (defun org-element-example-block-parser (limit affiliated)
  1753. "Parse an example block.
  1754. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1755. the buffer position at the beginning of the first affiliated
  1756. keyword and CDR is a plist of affiliated keywords along with
  1757. their value.
  1758. Return a list whose CAR is `example-block' and CDR is a plist
  1759. containing `:begin', `:end', `:number-lines', `:preserve-indent',
  1760. `:retain-labels', `:use-labels', `:label-fmt', `:switches',
  1761. `:value', `:post-blank' and `:post-affiliated' keywords."
  1762. (let ((case-fold-search t))
  1763. (if (not (save-excursion
  1764. (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
  1765. ;; Incomplete block: parse it as a paragraph.
  1766. (org-element-paragraph-parser limit affiliated)
  1767. (let ((contents-end (match-beginning 0)))
  1768. (save-excursion
  1769. (let* ((switches
  1770. (progn
  1771. (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
  1772. (match-string-no-properties 1)))
  1773. ;; Switches analysis.
  1774. (number-lines
  1775. (and switches
  1776. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  1777. switches)
  1778. (cons
  1779. (if (equal (match-string 1 switches) "-")
  1780. 'new
  1781. 'continued)
  1782. (if (not (match-end 2)) 0
  1783. ;; Subtract 1 to give number of lines before
  1784. ;; first line.
  1785. (1- (string-to-number (match-string 2 switches)))))))
  1786. (preserve-indent
  1787. (and switches (string-match "-i\\>" switches)))
  1788. ;; Should labels be retained in (or stripped from) example
  1789. ;; blocks?
  1790. (retain-labels
  1791. (or (not switches)
  1792. (not (string-match "-r\\>" switches))
  1793. (and number-lines (string-match "-k\\>" switches))))
  1794. ;; What should code-references use - labels or
  1795. ;; line-numbers?
  1796. (use-labels
  1797. (or (not switches)
  1798. (and retain-labels
  1799. (not (string-match "-k\\>" switches)))))
  1800. (label-fmt
  1801. (and switches
  1802. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  1803. (match-string 1 switches)))
  1804. ;; Standard block parsing.
  1805. (begin (car affiliated))
  1806. (post-affiliated (point))
  1807. (contents-begin (line-beginning-position 2))
  1808. (value (org-unescape-code-in-string
  1809. (buffer-substring-no-properties
  1810. contents-begin contents-end)))
  1811. (pos-before-blank (progn (goto-char contents-end)
  1812. (forward-line)
  1813. (point)))
  1814. (end (progn (skip-chars-forward " \r\t\n" limit)
  1815. (if (eobp) (point) (line-beginning-position)))))
  1816. (list 'example-block
  1817. (nconc
  1818. (list :begin begin
  1819. :end end
  1820. :value value
  1821. :switches switches
  1822. :number-lines number-lines
  1823. :preserve-indent preserve-indent
  1824. :retain-labels retain-labels
  1825. :use-labels use-labels
  1826. :label-fmt label-fmt
  1827. :post-blank (count-lines pos-before-blank end)
  1828. :post-affiliated post-affiliated)
  1829. (cdr affiliated)))))))))
  1830. (defun org-element-example-block-interpreter (example-block _)
  1831. "Interpret EXAMPLE-BLOCK element as Org syntax."
  1832. (let ((switches (org-element-property :switches example-block))
  1833. (value
  1834. (let ((val (org-element-property :value example-block)))
  1835. (cond
  1836. ((or org-src-preserve-indentation
  1837. (org-element-property :preserve-indent example-block))
  1838. val)
  1839. ((= 0 org-edit-src-content-indentation)
  1840. (org-remove-indentation val))
  1841. (t
  1842. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  1843. (replace-regexp-in-string "^[ \t]*\\S-"
  1844. (concat ind "\\&")
  1845. (org-remove-indentation val))))))))
  1846. (concat "#+begin_example" (and switches (concat " " switches)) "\n"
  1847. (org-element-normalize-string (org-escape-code-in-string value))
  1848. "#+end_example")))
  1849. ;;;; Export Block
  1850. (defun org-element-export-block-parser (limit affiliated)
  1851. "Parse an export block.
  1852. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1853. the buffer position at the beginning of the first affiliated
  1854. keyword and CDR is a plist of affiliated keywords along with
  1855. their value.
  1856. Return a list whose CAR is `export-block' and CDR is a plist
  1857. containing `:begin', `:end', `:type', `:value', `:post-blank' and
  1858. `:post-affiliated' keywords.
  1859. Assume point is at export-block beginning."
  1860. (let* ((case-fold-search t))
  1861. (if (not (save-excursion
  1862. (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
  1863. ;; Incomplete block: parse it as a paragraph.
  1864. (org-element-paragraph-parser limit affiliated)
  1865. (save-excursion
  1866. (let* ((contents-end (match-beginning 0))
  1867. (backend
  1868. (progn
  1869. (looking-at
  1870. "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
  1871. (match-string-no-properties 1)))
  1872. (begin (car affiliated))
  1873. (post-affiliated (point))
  1874. (contents-begin (progn (forward-line) (point)))
  1875. (pos-before-blank (progn (goto-char contents-end)
  1876. (forward-line)
  1877. (point)))
  1878. (end (progn (skip-chars-forward " \r\t\n" limit)
  1879. (if (eobp) (point) (line-beginning-position))))
  1880. (value (org-unescape-code-in-string
  1881. (buffer-substring-no-properties contents-begin
  1882. contents-end))))
  1883. (list 'export-block
  1884. (nconc
  1885. (list :type (and backend (upcase backend))
  1886. :begin begin
  1887. :end end
  1888. :value value
  1889. :post-blank (count-lines pos-before-blank end)
  1890. :post-affiliated post-affiliated)
  1891. (cdr affiliated))))))))
  1892. (defun org-element-export-block-interpreter (export-block _)
  1893. "Interpret EXPORT-BLOCK element as Org syntax."
  1894. (format "#+begin_export %s\n%s#+end_export"
  1895. (org-element-property :type export-block)
  1896. (org-element-property :value export-block)))
  1897. ;;;; Fixed-width
  1898. (defun org-element-fixed-width-parser (limit affiliated)
  1899. "Parse a fixed-width section.
  1900. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1901. the buffer position at the beginning of the first affiliated
  1902. keyword and CDR is a plist of affiliated keywords along with
  1903. their value.
  1904. Return a list whose CAR is `fixed-width' and CDR is a plist
  1905. containing `:begin', `:end', `:value', `:post-blank' and
  1906. `:post-affiliated' keywords.
  1907. Assume point is at the beginning of the fixed-width area."
  1908. (save-excursion
  1909. (let* ((begin (car affiliated))
  1910. (post-affiliated (point))
  1911. (end-area
  1912. (progn
  1913. (while (and (< (point) limit)
  1914. (looking-at "[ \t]*:\\( \\|$\\)"))
  1915. (forward-line))
  1916. (if (bolp) (line-end-position 0) (point))))
  1917. (end (progn (skip-chars-forward " \r\t\n" limit)
  1918. (if (eobp) (point) (line-beginning-position)))))
  1919. (list 'fixed-width
  1920. (nconc
  1921. (list :begin begin
  1922. :end end
  1923. :value (replace-regexp-in-string
  1924. "^[ \t]*: ?" ""
  1925. (buffer-substring-no-properties post-affiliated
  1926. end-area))
  1927. :post-blank (count-lines end-area end)
  1928. :post-affiliated post-affiliated)
  1929. (cdr affiliated))))))
  1930. (defun org-element-fixed-width-interpreter (fixed-width _)
  1931. "Interpret FIXED-WIDTH element as Org syntax."
  1932. (let ((value (org-element-property :value fixed-width)))
  1933. (and value (replace-regexp-in-string "^" ": " value))))
  1934. ;;;; Horizontal Rule
  1935. (defun org-element-horizontal-rule-parser (limit affiliated)
  1936. "Parse an horizontal rule.
  1937. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1938. the buffer position at the beginning of the first affiliated
  1939. keyword and CDR is a plist of affiliated keywords along with
  1940. their value.
  1941. Return a list whose CAR is `horizontal-rule' and CDR is a plist
  1942. containing `:begin', `:end', `:post-blank' and `:post-affiliated'
  1943. keywords."
  1944. (save-excursion
  1945. (let ((begin (car affiliated))
  1946. (post-affiliated (point))
  1947. (post-hr (progn (forward-line) (point)))
  1948. (end (progn (skip-chars-forward " \r\t\n" limit)
  1949. (if (eobp) (point) (line-beginning-position)))))
  1950. (list 'horizontal-rule
  1951. (nconc
  1952. (list :begin begin
  1953. :end end
  1954. :post-blank (count-lines post-hr end)
  1955. :post-affiliated post-affiliated)
  1956. (cdr affiliated))))))
  1957. (defun org-element-horizontal-rule-interpreter (&rest _)
  1958. "Interpret HORIZONTAL-RULE element as Org syntax."
  1959. "-----")
  1960. ;;;; Keyword
  1961. (defun org-element-keyword-parser (limit affiliated)
  1962. "Parse a keyword at point.
  1963. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1964. the buffer position at the beginning of the first affiliated
  1965. keyword and CDR is a plist of affiliated keywords along with
  1966. their value.
  1967. Return a list whose CAR is a normalized `keyword' (uppercase) and
  1968. CDR is a plist containing `:key', `:value', `:begin', `:end',
  1969. `:post-blank' and `:post-affiliated' keywords."
  1970. (save-excursion
  1971. ;; An orphaned affiliated keyword is considered as a regular
  1972. ;; keyword. In this case AFFILIATED is nil, so we take care of
  1973. ;; this corner case.
  1974. (let ((begin (or (car affiliated) (point)))
  1975. (post-affiliated (point))
  1976. (key (progn (looking-at "[ \t]*#\\+\\(\\S-*\\):")
  1977. (upcase (match-string-no-properties 1))))
  1978. (value (org-trim (buffer-substring-no-properties
  1979. (match-end 0) (line-end-position))))
  1980. (pos-before-blank (progn (forward-line) (point)))
  1981. (end (progn (skip-chars-forward " \r\t\n" limit)
  1982. (if (eobp) (point) (line-beginning-position)))))
  1983. (list 'keyword
  1984. (nconc
  1985. (list :key key
  1986. :value value
  1987. :begin begin
  1988. :end end
  1989. :post-blank (count-lines pos-before-blank end)
  1990. :post-affiliated post-affiliated)
  1991. (cdr affiliated))))))
  1992. (defun org-element-keyword-interpreter (keyword _)
  1993. "Interpret KEYWORD element as Org syntax."
  1994. (format "#+%s: %s"
  1995. (downcase (org-element-property :key keyword))
  1996. (org-element-property :value keyword)))
  1997. ;;;; Latex Environment
  1998. (defconst org-element--latex-begin-environment
  1999. "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
  2000. "Regexp matching the beginning of a LaTeX environment.
  2001. The environment is captured by the first group.
  2002. See also `org-element--latex-end-environment'.")
  2003. (defconst org-element--latex-end-environment
  2004. "\\\\end{%s}[ \t]*$"
  2005. "Format string matching the ending of a LaTeX environment.
  2006. See also `org-element--latex-begin-environment'.")
  2007. (defun org-element-latex-environment-parser (limit affiliated)
  2008. "Parse a LaTeX environment.
  2009. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2010. the buffer position at the beginning of the first affiliated
  2011. keyword and CDR is a plist of affiliated keywords along with
  2012. their value.
  2013. Return a list whose CAR is `latex-environment' and CDR is a plist
  2014. containing `:begin', `:end', `:value', `:post-blank' and
  2015. `:post-affiliated' keywords.
  2016. Assume point is at the beginning of the latex environment."
  2017. (save-excursion
  2018. (let ((case-fold-search t)
  2019. (code-begin (point)))
  2020. (looking-at org-element--latex-begin-environment)
  2021. (if (not (re-search-forward (format org-element--latex-end-environment
  2022. (regexp-quote (match-string 1)))
  2023. limit t))
  2024. ;; Incomplete latex environment: parse it as a paragraph.
  2025. (org-element-paragraph-parser limit affiliated)
  2026. (let* ((code-end (progn (forward-line) (point)))
  2027. (begin (car affiliated))
  2028. (value (buffer-substring-no-properties code-begin code-end))
  2029. (end (progn (skip-chars-forward " \r\t\n" limit)
  2030. (if (eobp) (point) (line-beginning-position)))))
  2031. (list 'latex-environment
  2032. (nconc
  2033. (list :begin begin
  2034. :end end
  2035. :value value
  2036. :post-blank (count-lines code-end end)
  2037. :post-affiliated code-begin)
  2038. (cdr affiliated))))))))
  2039. (defun org-element-latex-environment-interpreter (latex-environment _)
  2040. "Interpret LATEX-ENVIRONMENT element as Org syntax."
  2041. (org-element-property :value latex-environment))
  2042. ;;;; Node Property
  2043. (defun org-element-node-property-parser (limit)
  2044. "Parse a node-property at point.
  2045. LIMIT bounds the search.
  2046. Return a list whose CAR is `node-property' and CDR is a plist
  2047. containing `:key', `:value', `:begin', `:end', `:post-blank' and
  2048. `:post-affiliated' keywords."
  2049. (looking-at org-property-re)
  2050. (let ((case-fold-search t)
  2051. (begin (point))
  2052. (key (match-string-no-properties 2))
  2053. (value (match-string-no-properties 3))
  2054. (end (save-excursion
  2055. (end-of-line)
  2056. (if (re-search-forward org-property-re limit t)
  2057. (line-beginning-position)
  2058. limit))))
  2059. (list 'node-property
  2060. (list :key key
  2061. :value value
  2062. :begin begin
  2063. :end end
  2064. :post-blank 0
  2065. :post-affiliated begin))))
  2066. (defun org-element-node-property-interpreter (node-property _)
  2067. "Interpret NODE-PROPERTY element as Org syntax."
  2068. (format org-property-format
  2069. (format ":%s:" (org-element-property :key node-property))
  2070. (or (org-element-property :value node-property) "")))
  2071. ;;;; Paragraph
  2072. (defun org-element-paragraph-parser (limit affiliated)
  2073. "Parse a paragraph.
  2074. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2075. the buffer position at the beginning of the first affiliated
  2076. keyword and CDR is a plist of affiliated keywords along with
  2077. their value.
  2078. Return a list whose CAR is `paragraph' and CDR is a plist
  2079. containing `:begin', `:end', `:contents-begin' and
  2080. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  2081. Assume point is at the beginning of the paragraph."
  2082. (save-excursion
  2083. (let* ((begin (car affiliated))
  2084. (contents-begin (point))
  2085. (before-blank
  2086. (let ((case-fold-search t))
  2087. (end-of-line)
  2088. ;; A matching `org-element-paragraph-separate' is not
  2089. ;; necessarily the end of the paragraph. In particular,
  2090. ;; drawers, blocks or LaTeX environments opening lines
  2091. ;; must be closed. Moreover keywords with a secondary
  2092. ;; value must belong to "dual keywords".
  2093. (while (not
  2094. (cond
  2095. ((not (and (re-search-forward
  2096. org-element-paragraph-separate limit 'move)
  2097. (progn (beginning-of-line) t))))
  2098. ((looking-at org-drawer-regexp)
  2099. (save-excursion
  2100. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  2101. ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  2102. (save-excursion
  2103. (re-search-forward
  2104. (format "^[ \t]*#\\+END_%s[ \t]*$"
  2105. (regexp-quote (match-string 1)))
  2106. limit t)))
  2107. ((looking-at org-element--latex-begin-environment)
  2108. (save-excursion
  2109. (re-search-forward
  2110. (format org-element--latex-end-environment
  2111. (regexp-quote (match-string 1)))
  2112. limit t)))
  2113. ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
  2114. (member-ignore-case (match-string 1)
  2115. org-element-dual-keywords))
  2116. ;; Everything else is unambiguous.
  2117. (t)))
  2118. (end-of-line))
  2119. (if (= (point) limit) limit
  2120. (goto-char (line-beginning-position)))))
  2121. (contents-end (save-excursion
  2122. (skip-chars-backward " \r\t\n" contents-begin)
  2123. (line-beginning-position 2)))
  2124. (end (progn (skip-chars-forward " \r\t\n" limit)
  2125. (if (eobp) (point) (line-beginning-position)))))
  2126. (list 'paragraph
  2127. (nconc
  2128. (list :begin begin
  2129. :end end
  2130. :contents-begin contents-begin
  2131. :contents-end contents-end
  2132. :post-blank (count-lines before-blank end)
  2133. :post-affiliated contents-begin)
  2134. (cdr affiliated))))))
  2135. (defun org-element-paragraph-interpreter (_ contents)
  2136. "Interpret paragraph element as Org syntax.
  2137. CONTENTS is the contents of the element."
  2138. contents)
  2139. ;;;; Planning
  2140. (defun org-element-planning-parser (limit)
  2141. "Parse a planning.
  2142. LIMIT bounds the search.
  2143. Return a list whose CAR is `planning' and CDR is a plist
  2144. containing `:closed', `:deadline', `:scheduled', `:begin',
  2145. `:end', `:post-blank' and `:post-affiliated' keywords."
  2146. (save-excursion
  2147. (let* ((case-fold-search nil)
  2148. (begin (point))
  2149. (post-blank (let ((before-blank (progn (forward-line) (point))))
  2150. (skip-chars-forward " \r\t\n" limit)
  2151. (skip-chars-backward " \t")
  2152. (unless (bolp) (end-of-line))
  2153. (count-lines before-blank (point))))
  2154. (end (point))
  2155. closed deadline scheduled)
  2156. (goto-char begin)
  2157. (while (re-search-forward org-keyword-time-not-clock-regexp end t)
  2158. (goto-char (match-end 1))
  2159. (skip-chars-forward " \t" end)
  2160. (let ((keyword (match-string 1))
  2161. (time (org-element-timestamp-parser)))
  2162. (cond ((equal keyword org-closed-string) (setq closed time))
  2163. ((equal keyword org-deadline-string) (setq deadline time))
  2164. (t (setq scheduled time)))))
  2165. (list 'planning
  2166. (list :closed closed
  2167. :deadline deadline
  2168. :scheduled scheduled
  2169. :begin begin
  2170. :end end
  2171. :post-blank post-blank
  2172. :post-affiliated begin)))))
  2173. (defun org-element-planning-interpreter (planning _)
  2174. "Interpret PLANNING element as Org syntax."
  2175. (mapconcat
  2176. #'identity
  2177. (delq nil
  2178. (list (let ((deadline (org-element-property :deadline planning)))
  2179. (when deadline
  2180. (concat org-deadline-string " "
  2181. (org-element-timestamp-interpreter deadline nil))))
  2182. (let ((scheduled (org-element-property :scheduled planning)))
  2183. (when scheduled
  2184. (concat org-scheduled-string " "
  2185. (org-element-timestamp-interpreter scheduled nil))))
  2186. (let ((closed (org-element-property :closed planning)))
  2187. (when closed
  2188. (concat org-closed-string " "
  2189. (org-element-timestamp-interpreter closed nil))))))
  2190. " "))
  2191. ;;;; Src Block
  2192. (defun org-element-src-block-parser (limit affiliated)
  2193. "Parse a source block.
  2194. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2195. the buffer position at the beginning of the first affiliated
  2196. keyword and CDR is a plist of affiliated keywords along with
  2197. their value.
  2198. Return a list whose CAR is `src-block' and CDR is a plist
  2199. containing `:language', `:switches', `:parameters', `:begin',
  2200. `:end', `:number-lines', `:retain-labels', `:use-labels',
  2201. `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
  2202. `:post-affiliated' keywords.
  2203. Assume point is at the beginning of the block."
  2204. (let ((case-fold-search t))
  2205. (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
  2206. limit t)))
  2207. ;; Incomplete block: parse it as a paragraph.
  2208. (org-element-paragraph-parser limit affiliated)
  2209. (let ((contents-end (match-beginning 0)))
  2210. (save-excursion
  2211. (let* ((begin (car affiliated))
  2212. (post-affiliated (point))
  2213. ;; Get language as a string.
  2214. (language
  2215. (progn
  2216. (looking-at
  2217. "^[ \t]*#\\+BEGIN_SRC\
  2218. \\(?: +\\(\\S-+\\)\\)?\
  2219. \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
  2220. \\(.*\\)[ \t]*$")
  2221. (match-string-no-properties 1)))
  2222. ;; Get switches.
  2223. (switches (match-string-no-properties 2))
  2224. ;; Get parameters.
  2225. (parameters (match-string-no-properties 3))
  2226. ;; Switches analysis.
  2227. (number-lines
  2228. (and switches
  2229. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  2230. switches)
  2231. (cons
  2232. (if (equal (match-string 1 switches) "-")
  2233. 'new
  2234. 'continued)
  2235. (if (not (match-end 2)) 0
  2236. ;; Subtract 1 to give number of lines before
  2237. ;; first line.
  2238. (1- (string-to-number (match-string 2 switches)))))))
  2239. (preserve-indent (and switches
  2240. (string-match "-i\\>" switches)))
  2241. (label-fmt
  2242. (and switches
  2243. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  2244. (match-string 1 switches)))
  2245. ;; Should labels be retained in (or stripped from)
  2246. ;; source blocks?
  2247. (retain-labels
  2248. (or (not switches)
  2249. (not (string-match "-r\\>" switches))
  2250. (and number-lines (string-match "-k\\>" switches))))
  2251. ;; What should code-references use - labels or
  2252. ;; line-numbers?
  2253. (use-labels
  2254. (or (not switches)
  2255. (and retain-labels
  2256. (not (string-match "-k\\>" switches)))))
  2257. ;; Retrieve code.
  2258. (value (org-unescape-code-in-string
  2259. (buffer-substring-no-properties
  2260. (line-beginning-position 2) contents-end)))
  2261. (pos-before-blank (progn (goto-char contents-end)
  2262. (forward-line)
  2263. (point)))
  2264. ;; Get position after ending blank lines.
  2265. (end (progn (skip-chars-forward " \r\t\n" limit)
  2266. (if (eobp) (point) (line-beginning-position)))))
  2267. (list 'src-block
  2268. (nconc
  2269. (list :language language
  2270. :switches (and (org-string-nw-p switches)
  2271. (org-trim switches))
  2272. :parameters (and (org-string-nw-p parameters)
  2273. (org-trim parameters))
  2274. :begin begin
  2275. :end end
  2276. :number-lines number-lines
  2277. :preserve-indent preserve-indent
  2278. :retain-labels retain-labels
  2279. :use-labels use-labels
  2280. :label-fmt label-fmt
  2281. :value value
  2282. :post-blank (count-lines pos-before-blank end)
  2283. :post-affiliated post-affiliated)
  2284. (cdr affiliated)))))))))
  2285. (defun org-element-src-block-interpreter (src-block _)
  2286. "Interpret SRC-BLOCK element as Org syntax."
  2287. (let ((lang (org-element-property :language src-block))
  2288. (switches (org-element-property :switches src-block))
  2289. (params (org-element-property :parameters src-block))
  2290. (value
  2291. (let ((val (org-element-property :value src-block)))
  2292. (cond
  2293. ((or org-src-preserve-indentation
  2294. (org-element-property :preserve-indent src-block))
  2295. val)
  2296. ((zerop org-edit-src-content-indentation)
  2297. (org-remove-indentation val))
  2298. (t
  2299. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2300. (replace-regexp-in-string "^[ \t]*\\S-"
  2301. (concat ind "\\&")
  2302. (org-remove-indentation val))))))))
  2303. (format "#+begin_src%s\n%s#+end_src"
  2304. (concat (and lang (concat " " lang))
  2305. (and switches (concat " " switches))
  2306. (and params (concat " " params)))
  2307. (org-element-normalize-string (org-escape-code-in-string value)))))
  2308. ;;;; Table
  2309. (defun org-element-table-parser (limit affiliated)
  2310. "Parse a table at point.
  2311. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2312. the buffer position at the beginning of the first affiliated
  2313. keyword and CDR is a plist of affiliated keywords along with
  2314. their value.
  2315. Return a list whose CAR is `table' and CDR is a plist containing
  2316. `:begin', `:end', `:tblfm', `:type', `:contents-begin',
  2317. `:contents-end', `:value', `:post-blank' and `:post-affiliated'
  2318. keywords.
  2319. Assume point is at the beginning of the table."
  2320. (save-excursion
  2321. (let* ((case-fold-search t)
  2322. (table-begin (point))
  2323. (type (if (looking-at "[ \t]*|") 'org 'table.el))
  2324. (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
  2325. (if (eq type 'org) "" "+")))
  2326. (begin (car affiliated))
  2327. (table-end
  2328. (if (re-search-forward end-re limit 'move)
  2329. (goto-char (match-beginning 0))
  2330. (point)))
  2331. (tblfm (let (acc)
  2332. (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
  2333. (push (match-string-no-properties 1) acc)
  2334. (forward-line))
  2335. acc))
  2336. (pos-before-blank (point))
  2337. (end (progn (skip-chars-forward " \r\t\n" limit)
  2338. (if (eobp) (point) (line-beginning-position)))))
  2339. (list 'table
  2340. (nconc
  2341. (list :begin begin
  2342. :end end
  2343. :type type
  2344. :tblfm tblfm
  2345. ;; Only `org' tables have contents. `table.el' tables
  2346. ;; use a `:value' property to store raw table as
  2347. ;; a string.
  2348. :contents-begin (and (eq type 'org) table-begin)
  2349. :contents-end (and (eq type 'org) table-end)
  2350. :value (and (eq type 'table.el)
  2351. (buffer-substring-no-properties
  2352. table-begin table-end))
  2353. :post-blank (count-lines pos-before-blank end)
  2354. :post-affiliated table-begin)
  2355. (cdr affiliated))))))
  2356. (defun org-element-table-interpreter (table contents)
  2357. "Interpret TABLE element as Org syntax.
  2358. CONTENTS is a string, if table's type is `org', or nil."
  2359. (if (eq (org-element-property :type table) 'table.el)
  2360. (org-remove-indentation (org-element-property :value table))
  2361. (concat (with-temp-buffer (insert contents)
  2362. (org-table-align)
  2363. (buffer-string))
  2364. (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
  2365. (reverse (org-element-property :tblfm table))
  2366. "\n"))))
  2367. ;;;; Table Row
  2368. (defun org-element-table-row-parser (_)
  2369. "Parse table row at point.
  2370. Return a list whose CAR is `table-row' and CDR is a plist
  2371. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2372. `:type', `:post-blank' and `:post-affiliated' keywords."
  2373. (save-excursion
  2374. (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
  2375. (begin (point))
  2376. ;; A table rule has no contents. In that case, ensure
  2377. ;; CONTENTS-BEGIN matches CONTENTS-END.
  2378. (contents-begin (and (eq type 'standard) (search-forward "|")))
  2379. (contents-end (and (eq type 'standard)
  2380. (progn
  2381. (end-of-line)
  2382. (skip-chars-backward " \t")
  2383. (point))))
  2384. (end (line-beginning-position 2)))
  2385. (list 'table-row
  2386. (list :type type
  2387. :begin begin
  2388. :end end
  2389. :contents-begin contents-begin
  2390. :contents-end contents-end
  2391. :post-blank 0
  2392. :post-affiliated begin)))))
  2393. (defun org-element-table-row-interpreter (table-row contents)
  2394. "Interpret TABLE-ROW element as Org syntax.
  2395. CONTENTS is the contents of the table row."
  2396. (if (eq (org-element-property :type table-row) 'rule) "|-"
  2397. (concat "|" contents)))
  2398. ;;;; Verse Block
  2399. (defun org-element-verse-block-parser (limit affiliated)
  2400. "Parse a verse block.
  2401. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2402. the buffer position at the beginning of the first affiliated
  2403. keyword and CDR is a plist of affiliated keywords along with
  2404. their value.
  2405. Return a list whose CAR is `verse-block' and CDR is a plist
  2406. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2407. `:post-blank' and `:post-affiliated' keywords.
  2408. Assume point is at beginning of the block."
  2409. (let ((case-fold-search t))
  2410. (if (not (save-excursion
  2411. (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
  2412. ;; Incomplete block: parse it as a paragraph.
  2413. (org-element-paragraph-parser limit affiliated)
  2414. (let ((contents-end (match-beginning 0)))
  2415. (save-excursion
  2416. (let* ((begin (car affiliated))
  2417. (post-affiliated (point))
  2418. (contents-begin (progn (forward-line) (point)))
  2419. (pos-before-blank (progn (goto-char contents-end)
  2420. (forward-line)
  2421. (point)))
  2422. (end (progn (skip-chars-forward " \r\t\n" limit)
  2423. (if (eobp) (point) (line-beginning-position)))))
  2424. (list 'verse-block
  2425. (nconc
  2426. (list :begin begin
  2427. :end end
  2428. :contents-begin contents-begin
  2429. :contents-end contents-end
  2430. :post-blank (count-lines pos-before-blank end)
  2431. :post-affiliated post-affiliated)
  2432. (cdr affiliated)))))))))
  2433. (defun org-element-verse-block-interpreter (_ contents)
  2434. "Interpret verse-block element as Org syntax.
  2435. CONTENTS is verse block contents."
  2436. (format "#+begin_verse\n%s#+end_verse" contents))
  2437. ;;; Objects
  2438. ;;
  2439. ;; Unlike to elements, raw text can be found between objects. Hence,
  2440. ;; `org-element--object-lex' is provided to find the next object in
  2441. ;; buffer.
  2442. ;;
  2443. ;; Some object types (e.g., `italic') are recursive. Restrictions on
  2444. ;; object types they can contain will be specified in
  2445. ;; `org-element-object-restrictions'.
  2446. ;;
  2447. ;; Creating a new type of object requires to alter
  2448. ;; `org-element--object-regexp' and `org-element--object-lex', add the
  2449. ;; new type in `org-element-all-objects', and possibly add
  2450. ;; restrictions in `org-element-object-restrictions'.
  2451. ;;;; Bold
  2452. (defun org-element-bold-parser ()
  2453. "Parse bold object at point, if any.
  2454. When at a bold object, return a list whose car is `bold' and cdr
  2455. is a plist with `:begin', `:end', `:contents-begin' and
  2456. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2457. nil.
  2458. Assume point is at the first star marker."
  2459. (save-excursion
  2460. (unless (bolp) (backward-char 1))
  2461. (when (looking-at org-emph-re)
  2462. (let ((begin (match-beginning 2))
  2463. (contents-begin (match-beginning 4))
  2464. (contents-end (match-end 4))
  2465. (post-blank (progn (goto-char (match-end 2))
  2466. (skip-chars-forward " \t")))
  2467. (end (point)))
  2468. (list 'bold
  2469. (list :begin begin
  2470. :end end
  2471. :contents-begin contents-begin
  2472. :contents-end contents-end
  2473. :post-blank post-blank))))))
  2474. (defun org-element-bold-interpreter (_ contents)
  2475. "Interpret bold object as Org syntax.
  2476. CONTENTS is the contents of the object."
  2477. (format "*%s*" contents))
  2478. ;;;; Citation
  2479. (defun org-element-citation-parser ()
  2480. "Parse citation object at point, if any.
  2481. When at a citation object, return a list whose car is `citation'
  2482. and cdr is a plist with `:style', `:prefix', `:suffix', `:begin',
  2483. `:end', `:contents-begin', `:contents-end', and `:post-blank'
  2484. keywords. Otherwise, return nil.
  2485. Assume point is at the beginning of the citation."
  2486. (when (looking-at org-element-citation-prefix-re)
  2487. (let* ((begin (point))
  2488. (style (and (match-end 1)
  2489. (match-string-no-properties 1)))
  2490. ;; Ignore blanks between cite type and prefix or key.
  2491. (start (match-end 0))
  2492. (closing (with-syntax-table org-element--pair-square-table
  2493. (ignore-errors (scan-lists begin 1 0)))))
  2494. (save-excursion
  2495. (when (and closing
  2496. (re-search-forward org-element-citation-key-re closing t))
  2497. ;; Find prefix, if any.
  2498. (let ((first-key-end (match-end 0))
  2499. (types (org-element-restriction 'citation-reference))
  2500. (cite
  2501. (list 'citation
  2502. (list :style style
  2503. :begin begin
  2504. :post-blank (progn
  2505. (goto-char closing)
  2506. (skip-chars-forward " \t"))
  2507. :end (point)))))
  2508. ;; `:contents-begin' depends on the presence of
  2509. ;; a non-empty common prefix.
  2510. (goto-char first-key-end)
  2511. (if (not (search-backward ";" start t))
  2512. (org-element-put-property cite :contents-begin start)
  2513. (when (< start (point))
  2514. (org-element-put-property
  2515. cite :prefix
  2516. (org-element--parse-objects start (point) nil types cite)))
  2517. (forward-char)
  2518. (org-element-put-property cite :contents-begin (point)))
  2519. ;; `:contents-end' depends on the presence of a non-empty
  2520. ;; common suffix.
  2521. (goto-char (1- closing))
  2522. (skip-chars-backward " \r\t\n")
  2523. (let ((end (point)))
  2524. (if (or (not (search-backward ";" first-key-end t))
  2525. (re-search-forward org-element-citation-key-re end t))
  2526. (org-element-put-property cite :contents-end end)
  2527. (forward-char)
  2528. (when (< (point) end)
  2529. (org-element-put-property
  2530. cite :suffix
  2531. (org-element--parse-objects (point) end nil types cite)))
  2532. (org-element-put-property cite :contents-end (point))))
  2533. cite))))))
  2534. (defun org-element-citation-interpreter (citation contents)
  2535. "Interpret CITATION object as Org syntax.
  2536. CONTENTS is the contents of the object, as a string."
  2537. (let ((prefix (org-element-property :prefix citation))
  2538. (suffix (org-element-property :suffix citation))
  2539. (style (org-element-property :style citation)))
  2540. (concat "[cite"
  2541. (and style (concat "/" style))
  2542. ":"
  2543. (and prefix (concat (org-element-interpret-data prefix) ";"))
  2544. (if suffix
  2545. (concat contents (org-element-interpret-data suffix))
  2546. ;; Remove spurious semicolon.
  2547. (substring contents nil -1))
  2548. "]")))
  2549. ;;;; Citation Reference
  2550. (defun org-element-citation-reference-parser ()
  2551. "Parse citation reference object at point, if any.
  2552. When at a reference, return a list whose car is
  2553. `citation-reference', and cdr is a plist with `:key',
  2554. `:prefix', `:suffix', `:begin', `:end', and `:post-blank' keywords.
  2555. Assume point is at the beginning of the reference."
  2556. (save-excursion
  2557. (let ((begin (point)))
  2558. (when (re-search-forward org-element-citation-key-re nil t)
  2559. (let* ((key (match-string-no-properties 1))
  2560. (key-start (match-beginning 0))
  2561. (key-end (match-end 0))
  2562. (separator (search-forward ";" nil t))
  2563. (end (or separator (point-max)))
  2564. (suffix-end (if separator (1- end) end))
  2565. (types (org-element-restriction 'citation-reference))
  2566. (reference
  2567. (list 'citation-reference
  2568. (list :key key
  2569. :begin begin
  2570. :end end
  2571. :post-blank 0))))
  2572. (when (< begin key-start)
  2573. (org-element-put-property
  2574. reference :prefix
  2575. (org-element--parse-objects begin key-start nil types reference)))
  2576. (when (< key-end suffix-end)
  2577. (org-element-put-property
  2578. reference :suffix
  2579. (org-element--parse-objects key-end suffix-end nil types reference)))
  2580. reference)))))
  2581. (defun org-element-citation-reference-interpreter (citation-reference _)
  2582. "Interpret CITATION-REFERENCE object as Org syntax."
  2583. (concat (org-element-interpret-data
  2584. (org-element-property :prefix citation-reference))
  2585. "@" (org-element-property :key citation-reference)
  2586. (org-element-interpret-data
  2587. (org-element-property :suffix citation-reference))
  2588. ";"))
  2589. ;;;; Code
  2590. (defun org-element-code-parser ()
  2591. "Parse code object at point, if any.
  2592. When at a code object, return a list whose car is `code' and cdr
  2593. is a plist with `:value', `:begin', `:end' and `:post-blank'
  2594. keywords. Otherwise, return nil.
  2595. Assume point is at the first tilde marker."
  2596. (save-excursion
  2597. (unless (bolp) (backward-char 1))
  2598. (when (looking-at org-verbatim-re)
  2599. (let ((begin (match-beginning 2))
  2600. (value (match-string-no-properties 4))
  2601. (post-blank (progn (goto-char (match-end 2))
  2602. (skip-chars-forward " \t")))
  2603. (end (point)))
  2604. (list 'code
  2605. (list :value value
  2606. :begin begin
  2607. :end end
  2608. :post-blank post-blank))))))
  2609. (defun org-element-code-interpreter (code _)
  2610. "Interpret CODE object as Org syntax."
  2611. (format "~%s~" (org-element-property :value code)))
  2612. ;;;; Entity
  2613. (defun org-element-entity-parser ()
  2614. "Parse entity at point, if any.
  2615. When at an entity, return a list whose car is `entity' and cdr
  2616. a plist with `:begin', `:end', `:latex', `:latex-math-p',
  2617. `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
  2618. `:post-blank' as keywords. Otherwise, return nil.
  2619. Assume point is at the beginning of the entity."
  2620. (catch 'no-object
  2621. (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
  2622. (save-excursion
  2623. (let* ((value (or (org-entity-get (match-string 1))
  2624. (throw 'no-object nil)))
  2625. (begin (match-beginning 0))
  2626. (bracketsp (string= (match-string 2) "{}"))
  2627. (post-blank (progn (goto-char (match-end 1))
  2628. (when bracketsp (forward-char 2))
  2629. (skip-chars-forward " \t")))
  2630. (end (point)))
  2631. (list 'entity
  2632. (list :name (car value)
  2633. :latex (nth 1 value)
  2634. :latex-math-p (nth 2 value)
  2635. :html (nth 3 value)
  2636. :ascii (nth 4 value)
  2637. :latin1 (nth 5 value)
  2638. :utf-8 (nth 6 value)
  2639. :begin begin
  2640. :end end
  2641. :use-brackets-p bracketsp
  2642. :post-blank post-blank)))))))
  2643. (defun org-element-entity-interpreter (entity _)
  2644. "Interpret ENTITY object as Org syntax."
  2645. (concat "\\"
  2646. (org-element-property :name entity)
  2647. (when (org-element-property :use-brackets-p entity) "{}")))
  2648. ;;;; Export Snippet
  2649. (defun org-element-export-snippet-parser ()
  2650. "Parse export snippet at point.
  2651. When at an export snippet, return a list whose car is
  2652. `export-snippet' and cdr a plist with `:begin', `:end',
  2653. `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
  2654. return nil.
  2655. Assume point is at the beginning of the snippet."
  2656. (save-excursion
  2657. (let (contents-end)
  2658. (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
  2659. (setq contents-end
  2660. (save-match-data (goto-char (match-end 0))
  2661. (re-search-forward "@@" nil t)
  2662. (match-beginning 0))))
  2663. (let* ((begin (match-beginning 0))
  2664. (back-end (match-string-no-properties 1))
  2665. (value (buffer-substring-no-properties
  2666. (match-end 0) contents-end))
  2667. (post-blank (skip-chars-forward " \t"))
  2668. (end (point)))
  2669. (list 'export-snippet
  2670. (list :back-end back-end
  2671. :value value
  2672. :begin begin
  2673. :end end
  2674. :post-blank post-blank)))))))
  2675. (defun org-element-export-snippet-interpreter (export-snippet _)
  2676. "Interpret EXPORT-SNIPPET object as Org syntax."
  2677. (format "@@%s:%s@@"
  2678. (org-element-property :back-end export-snippet)
  2679. (org-element-property :value export-snippet)))
  2680. ;;;; Footnote Reference
  2681. (defun org-element-footnote-reference-parser ()
  2682. "Parse footnote reference at point, if any.
  2683. When at a footnote reference, return a list whose car is
  2684. `footnote-reference' and cdr a plist with `:label', `:type',
  2685. `:begin', `:end', `:contents-begin', `:contents-end' and
  2686. `:post-blank' as keywords. Otherwise, return nil."
  2687. (when (looking-at org-footnote-re)
  2688. (let ((closing (with-syntax-table org-element--pair-square-table
  2689. (ignore-errors (scan-lists (point) 1 0)))))
  2690. (when closing
  2691. (save-excursion
  2692. (let* ((begin (point))
  2693. (label (match-string-no-properties 1))
  2694. (inner-begin (match-end 0))
  2695. (inner-end (1- closing))
  2696. (type (if (match-end 2) 'inline 'standard))
  2697. (post-blank (progn (goto-char closing)
  2698. (skip-chars-forward " \t")))
  2699. (end (point)))
  2700. (list 'footnote-reference
  2701. (list :label label
  2702. :type type
  2703. :begin begin
  2704. :end end
  2705. :contents-begin (and (eq type 'inline) inner-begin)
  2706. :contents-end (and (eq type 'inline) inner-end)
  2707. :post-blank post-blank))))))))
  2708. (defun org-element-footnote-reference-interpreter (footnote-reference contents)
  2709. "Interpret FOOTNOTE-REFERENCE object as Org syntax.
  2710. CONTENTS is its definition, when inline, or nil."
  2711. (format "[fn:%s%s]"
  2712. (or (org-element-property :label footnote-reference) "")
  2713. (if contents (concat ":" contents) "")))
  2714. ;;;; Inline Babel Call
  2715. (defun org-element-inline-babel-call-parser ()
  2716. "Parse inline babel call at point, if any.
  2717. When at an inline babel call, return a list whose car is
  2718. `inline-babel-call' and cdr a plist with `:call',
  2719. `:inside-header', `:arguments', `:end-header', `:begin', `:end',
  2720. `:value' and `:post-blank' as keywords. Otherwise, return nil.
  2721. Assume point is at the beginning of the babel call."
  2722. (save-excursion
  2723. (catch :no-object
  2724. (when (let ((case-fold-search nil))
  2725. (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
  2726. (goto-char (match-end 1))
  2727. (let* ((begin (match-beginning 0))
  2728. (call (match-string-no-properties 1))
  2729. (inside-header
  2730. (let ((p (org-element--parse-paired-brackets ?\[)))
  2731. (and (org-string-nw-p p)
  2732. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2733. (arguments (org-string-nw-p
  2734. (or (org-element--parse-paired-brackets ?\()
  2735. ;; Parenthesis are mandatory.
  2736. (throw :no-object nil))))
  2737. (end-header
  2738. (let ((p (org-element--parse-paired-brackets ?\[)))
  2739. (and (org-string-nw-p p)
  2740. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2741. (value (buffer-substring-no-properties begin (point)))
  2742. (post-blank (skip-chars-forward " \t"))
  2743. (end (point)))
  2744. (list 'inline-babel-call
  2745. (list :call call
  2746. :inside-header inside-header
  2747. :arguments arguments
  2748. :end-header end-header
  2749. :begin begin
  2750. :end end
  2751. :value value
  2752. :post-blank post-blank)))))))
  2753. (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
  2754. "Interpret INLINE-BABEL-CALL object as Org syntax."
  2755. (concat "call_"
  2756. (org-element-property :call inline-babel-call)
  2757. (let ((h (org-element-property :inside-header inline-babel-call)))
  2758. (and h (format "[%s]" h)))
  2759. "(" (org-element-property :arguments inline-babel-call) ")"
  2760. (let ((h (org-element-property :end-header inline-babel-call)))
  2761. (and h (format "[%s]" h)))))
  2762. ;;;; Inline Src Block
  2763. (defun org-element-inline-src-block-parser ()
  2764. "Parse inline source block at point, if any.
  2765. When at an inline source block, return a list whose car is
  2766. `inline-src-block' and cdr a plist with `:begin', `:end',
  2767. `:language', `:value', `:parameters' and `:post-blank' as
  2768. keywords. Otherwise, return nil.
  2769. Assume point is at the beginning of the inline source block."
  2770. (save-excursion
  2771. (catch :no-object
  2772. (when (let ((case-fold-search nil))
  2773. (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
  2774. (goto-char (match-end 1))
  2775. (let ((begin (match-beginning 0))
  2776. (language (match-string-no-properties 1))
  2777. (parameters
  2778. (let ((p (org-element--parse-paired-brackets ?\[)))
  2779. (and (org-string-nw-p p)
  2780. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2781. (value (or (org-element--parse-paired-brackets ?\{)
  2782. (throw :no-object nil)))
  2783. (post-blank (skip-chars-forward " \t")))
  2784. (list 'inline-src-block
  2785. (list :language language
  2786. :value value
  2787. :parameters parameters
  2788. :begin begin
  2789. :end (point)
  2790. :post-blank post-blank)))))))
  2791. (defun org-element-inline-src-block-interpreter (inline-src-block _)
  2792. "Interpret INLINE-SRC-BLOCK object as Org syntax."
  2793. (let ((language (org-element-property :language inline-src-block))
  2794. (arguments (org-element-property :parameters inline-src-block))
  2795. (body (org-element-property :value inline-src-block)))
  2796. (format "src_%s%s{%s}"
  2797. language
  2798. (if arguments (format "[%s]" arguments) "")
  2799. body)))
  2800. ;;;; Italic
  2801. (defun org-element-italic-parser ()
  2802. "Parse italic object at point, if any.
  2803. When at an italic object, return a list whose car is `italic' and
  2804. cdr is a plist with `:begin', `:end', `:contents-begin' and
  2805. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2806. nil.
  2807. Assume point is at the first slash marker."
  2808. (save-excursion
  2809. (unless (bolp) (backward-char 1))
  2810. (when (looking-at org-emph-re)
  2811. (let ((begin (match-beginning 2))
  2812. (contents-begin (match-beginning 4))
  2813. (contents-end (match-end 4))
  2814. (post-blank (progn (goto-char (match-end 2))
  2815. (skip-chars-forward " \t")))
  2816. (end (point)))
  2817. (list 'italic
  2818. (list :begin begin
  2819. :end end
  2820. :contents-begin contents-begin
  2821. :contents-end contents-end
  2822. :post-blank post-blank))))))
  2823. (defun org-element-italic-interpreter (_ contents)
  2824. "Interpret italic object as Org syntax.
  2825. CONTENTS is the contents of the object."
  2826. (format "/%s/" contents))
  2827. ;;;; Latex Fragment
  2828. (defun org-element-latex-fragment-parser ()
  2829. "Parse LaTeX fragment at point, if any.
  2830. When at a LaTeX fragment, return a list whose car is
  2831. `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
  2832. and `:post-blank' as keywords. Otherwise, return nil.
  2833. Assume point is at the beginning of the LaTeX fragment."
  2834. (catch 'no-object
  2835. (save-excursion
  2836. (let* ((begin (point))
  2837. (after-fragment
  2838. (cond
  2839. ((not (eq ?$ (char-after)))
  2840. (pcase (char-after (1+ (point)))
  2841. (?\( (search-forward "\\)" nil t))
  2842. (?\[ (search-forward "\\]" nil t))
  2843. (_
  2844. ;; Macro.
  2845. (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
  2846. \\|\\({[^{}\n]*}\\)\\)*")
  2847. (match-end 0)))))
  2848. ((eq ?$ (char-after (1+ (point))))
  2849. (search-forward "$$" nil t 2))
  2850. (t
  2851. (and (not (eq ?$ (char-before)))
  2852. (not (memq (char-after (1+ (point)))
  2853. '(?\s ?\t ?\n ?, ?. ?\;)))
  2854. (search-forward "$" nil t 2)
  2855. (not (memq (char-before (match-beginning 0))
  2856. '(?\s ?\t ?\n ?, ?.)))
  2857. (looking-at-p
  2858. "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
  2859. (point)))))
  2860. (post-blank
  2861. (if (not after-fragment) (throw 'no-object nil)
  2862. (goto-char after-fragment)
  2863. (skip-chars-forward " \t")))
  2864. (end (point)))
  2865. (list 'latex-fragment
  2866. (list :value (buffer-substring-no-properties begin after-fragment)
  2867. :begin begin
  2868. :end end
  2869. :post-blank post-blank))))))
  2870. (defun org-element-latex-fragment-interpreter (latex-fragment _)
  2871. "Interpret LATEX-FRAGMENT object as Org syntax."
  2872. (org-element-property :value latex-fragment))
  2873. ;;;; Line Break
  2874. (defun org-element-line-break-parser ()
  2875. "Parse line break at point, if any.
  2876. When at a line break, return a list whose car is `line-break',
  2877. and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
  2878. Otherwise, return nil.
  2879. Assume point is at the beginning of the line break."
  2880. (when (and (looking-at-p "\\\\\\\\[ \t]*$")
  2881. (not (eq (char-before) ?\\)))
  2882. (list 'line-break
  2883. (list :begin (point)
  2884. :end (line-beginning-position 2)
  2885. :post-blank 0))))
  2886. (defun org-element-line-break-interpreter (&rest _)
  2887. "Interpret LINE-BREAK object as Org syntax."
  2888. "\\\\\n")
  2889. ;;;; Link
  2890. (defun org-element-link-parser ()
  2891. "Parse link at point, if any.
  2892. When at a link, return a list whose car is `link' and cdr a plist
  2893. with `:type', `:path', `:format', `:raw-link', `:application',
  2894. `:search-option', `:begin', `:end', `:contents-begin',
  2895. `:contents-end' and `:post-blank' as keywords. Otherwise, return
  2896. nil.
  2897. Assume point is at the beginning of the link."
  2898. (catch 'no-object
  2899. (let ((begin (point))
  2900. end contents-begin contents-end link-end post-blank path type format
  2901. raw-link search-option application)
  2902. (cond
  2903. ;; Type 1: Text targeted from a radio target.
  2904. ((and org-target-link-regexp
  2905. (save-excursion (or (bolp) (backward-char))
  2906. (looking-at org-target-link-regexp)))
  2907. (setq type "radio")
  2908. (setq format 'plain)
  2909. (setq link-end (match-end 1))
  2910. (setq path (match-string-no-properties 1))
  2911. (setq contents-begin (match-beginning 1))
  2912. (setq contents-end (match-end 1)))
  2913. ;; Type 2: Standard link, i.e. [[https://orgmode.org][homepage]]
  2914. ((looking-at org-link-bracket-re)
  2915. (setq format 'bracket)
  2916. (setq contents-begin (match-beginning 2))
  2917. (setq contents-end (match-end 2))
  2918. (setq link-end (match-end 0))
  2919. ;; RAW-LINK is the original link. Decode any encoding.
  2920. ;; Expand any abbreviation in it.
  2921. ;;
  2922. ;; Also treat any newline character and associated
  2923. ;; indentation as a single space character. This is not
  2924. ;; compatible with RFC 3986, which requires to ignore
  2925. ;; them altogether. However, doing so would require
  2926. ;; users to encode spaces on the fly when writing links
  2927. ;; (e.g., insert [[shell:ls%20*.org]] instead of
  2928. ;; [[shell:ls *.org]], which defeats Org's focus on
  2929. ;; simplicity.
  2930. (setq raw-link (org-link-expand-abbrev
  2931. (org-link-unescape
  2932. (replace-regexp-in-string
  2933. "[ \t]*\n[ \t]*" " "
  2934. (match-string-no-properties 1)))))
  2935. ;; Determine TYPE of link and set PATH accordingly. According
  2936. ;; to RFC 3986, remove whitespaces from URI in external links.
  2937. ;; In internal ones, treat indentation as a single space.
  2938. (cond
  2939. ;; File type.
  2940. ((or (file-name-absolute-p raw-link)
  2941. (string-match "\\`\\.\\.?/" raw-link))
  2942. (setq type "file")
  2943. (setq path raw-link))
  2944. ;; Explicit type (http, irc, bbdb...).
  2945. ((string-match org-link-types-re raw-link)
  2946. (setq type (match-string 1 raw-link))
  2947. (setq path (substring raw-link (match-end 0))))
  2948. ;; Code-ref type: PATH is the name of the reference.
  2949. ((and (string-match-p "\\`(" raw-link)
  2950. (string-match-p ")\\'" raw-link))
  2951. (setq type "coderef")
  2952. (setq path (substring raw-link 1 -1)))
  2953. ;; Custom-id type: PATH is the name of the custom id.
  2954. ((= (string-to-char raw-link) ?#)
  2955. (setq type "custom-id")
  2956. (setq path (substring raw-link 1)))
  2957. ;; Fuzzy type: Internal link either matches a target, an
  2958. ;; headline name or nothing. PATH is the target or
  2959. ;; headline's name.
  2960. (t
  2961. (setq type "fuzzy")
  2962. (setq path raw-link))))
  2963. ;; Type 3: Plain link, e.g., https://orgmode.org
  2964. ((looking-at org-link-plain-re)
  2965. (setq format 'plain)
  2966. (setq raw-link (match-string-no-properties 0))
  2967. (setq type (match-string-no-properties 1))
  2968. (setq link-end (match-end 0))
  2969. (setq path (match-string-no-properties 2)))
  2970. ;; Type 4: Angular link, e.g., <https://orgmode.org>. Unlike to
  2971. ;; bracket links, follow RFC 3986 and remove any extra
  2972. ;; whitespace in URI.
  2973. ((looking-at org-link-angle-re)
  2974. (setq format 'angle)
  2975. (setq type (match-string-no-properties 1))
  2976. (setq link-end (match-end 0))
  2977. (setq raw-link
  2978. (buffer-substring-no-properties
  2979. (match-beginning 1) (match-end 2)))
  2980. (setq path (replace-regexp-in-string
  2981. "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
  2982. (t (throw 'no-object nil)))
  2983. ;; In any case, deduce end point after trailing white space from
  2984. ;; LINK-END variable.
  2985. (save-excursion
  2986. (setq post-blank
  2987. (progn (goto-char link-end) (skip-chars-forward " \t")))
  2988. (setq end (point)))
  2989. ;; Special "file"-type link processing. Extract opening
  2990. ;; application and search option, if any. Also normalize URI.
  2991. (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
  2992. (setq application (match-string 1 type))
  2993. (setq type "file")
  2994. (when (string-match "::\\(.*\\)\\'" path)
  2995. (setq search-option (match-string 1 path))
  2996. (setq path (replace-match "" nil nil path)))
  2997. (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
  2998. ;; Translate link, if `org-link-translation-function' is set.
  2999. (let ((trans (and (functionp org-link-translation-function)
  3000. (funcall org-link-translation-function type path))))
  3001. (when trans
  3002. (setq type (car trans))
  3003. (setq path (cdr trans))))
  3004. (list 'link
  3005. (list :type type
  3006. :path path
  3007. :format format
  3008. :raw-link (or raw-link path)
  3009. :application application
  3010. :search-option search-option
  3011. :begin begin
  3012. :end end
  3013. :contents-begin contents-begin
  3014. :contents-end contents-end
  3015. :post-blank post-blank)))))
  3016. (defun org-element-link-interpreter (link contents)
  3017. "Interpret LINK object as Org syntax.
  3018. CONTENTS is the contents of the object, or nil."
  3019. (let ((type (org-element-property :type link))
  3020. (path (org-element-property :path link)))
  3021. (if (string= type "radio") path
  3022. (let ((fmt (pcase (org-element-property :format link)
  3023. ;; Links with contents and internal links have to
  3024. ;; use bracket syntax. Ignore `:format' in these
  3025. ;; cases. This is also the default syntax when the
  3026. ;; property is not defined, e.g., when the object
  3027. ;; was crafted by the user.
  3028. ((guard contents)
  3029. (format "[[%%s][%s]]"
  3030. ;; Since this is going to be used as
  3031. ;; a format string, escape percent signs
  3032. ;; in description.
  3033. (replace-regexp-in-string "%" "%%" contents)))
  3034. ((or `bracket
  3035. `nil
  3036. (guard (member type '("coderef" "custom-id" "fuzzy"))))
  3037. "[[%s]]")
  3038. ;; Otherwise, just obey to `:format'.
  3039. (`angle "<%s>")
  3040. (`plain "%s")
  3041. (f (error "Wrong `:format' value: %s" f)))))
  3042. (format fmt
  3043. (pcase type
  3044. ("coderef" (format "(%s)" path))
  3045. ("custom-id" (concat "#" path))
  3046. ("file"
  3047. (let ((app (org-element-property :application link))
  3048. (opt (org-element-property :search-option link)))
  3049. (concat type (and app (concat "+" app)) ":"
  3050. path
  3051. (and opt (concat "::" opt)))))
  3052. ("fuzzy" path)
  3053. (_ (concat type ":" path))))))))
  3054. ;;;; Macro
  3055. (defun org-element-macro-parser ()
  3056. "Parse macro at point, if any.
  3057. When at a macro, return a list whose car is `macro' and cdr
  3058. a plist with `:key', `:args', `:begin', `:end', `:value' and
  3059. `:post-blank' as keywords. Otherwise, return nil.
  3060. Assume point is at the macro."
  3061. (save-excursion
  3062. (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\((\\([^\000]*?\\))\\)?}}}")
  3063. (let ((begin (point))
  3064. (key (downcase (match-string-no-properties 1)))
  3065. (value (match-string-no-properties 0))
  3066. (post-blank (progn (goto-char (match-end 0))
  3067. (skip-chars-forward " \t")))
  3068. (end (point))
  3069. (args (pcase (match-string-no-properties 3)
  3070. (`nil nil)
  3071. (a (org-macro-extract-arguments
  3072. (replace-regexp-in-string
  3073. "[ \t\r\n]+" " " (org-trim a)))))))
  3074. (list 'macro
  3075. (list :key key
  3076. :value value
  3077. :args args
  3078. :begin begin
  3079. :end end
  3080. :post-blank post-blank))))))
  3081. (defun org-element-macro-interpreter (macro _)
  3082. "Interpret MACRO object as Org syntax."
  3083. (format "{{{%s%s}}}"
  3084. (org-element-property :key macro)
  3085. (pcase (org-element-property :args macro)
  3086. (`nil "")
  3087. (args (format "(%s)" (apply #'org-macro-escape-arguments args))))))
  3088. ;;;; Radio-target
  3089. (defun org-element-radio-target-parser ()
  3090. "Parse radio target at point, if any.
  3091. When at a radio target, return a list whose car is `radio-target'
  3092. and cdr a plist with `:begin', `:end', `:contents-begin',
  3093. `:contents-end', `:value' and `:post-blank' as keywords.
  3094. Otherwise, return nil.
  3095. Assume point is at the radio target."
  3096. (save-excursion
  3097. (when (looking-at org-radio-target-regexp)
  3098. (let ((begin (point))
  3099. (contents-begin (match-beginning 1))
  3100. (contents-end (match-end 1))
  3101. (value (match-string-no-properties 1))
  3102. (post-blank (progn (goto-char (match-end 0))
  3103. (skip-chars-forward " \t")))
  3104. (end (point)))
  3105. (list 'radio-target
  3106. (list :begin begin
  3107. :end end
  3108. :contents-begin contents-begin
  3109. :contents-end contents-end
  3110. :post-blank post-blank
  3111. :value value))))))
  3112. (defun org-element-radio-target-interpreter (_ contents)
  3113. "Interpret target object as Org syntax.
  3114. CONTENTS is the contents of the object."
  3115. (concat "<<<" contents ">>>"))
  3116. ;;;; Statistics Cookie
  3117. (defun org-element-statistics-cookie-parser ()
  3118. "Parse statistics cookie at point, if any.
  3119. When at a statistics cookie, return a list whose car is
  3120. `statistics-cookie', and cdr a plist with `:begin', `:end',
  3121. `:value' and `:post-blank' keywords. Otherwise, return nil.
  3122. Assume point is at the beginning of the statistics-cookie."
  3123. (save-excursion
  3124. (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
  3125. (let* ((begin (point))
  3126. (value (buffer-substring-no-properties
  3127. (match-beginning 0) (match-end 0)))
  3128. (post-blank (progn (goto-char (match-end 0))
  3129. (skip-chars-forward " \t")))
  3130. (end (point)))
  3131. (list 'statistics-cookie
  3132. (list :begin begin
  3133. :end end
  3134. :value value
  3135. :post-blank post-blank))))))
  3136. (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
  3137. "Interpret STATISTICS-COOKIE object as Org syntax."
  3138. (org-element-property :value statistics-cookie))
  3139. ;;;; Strike-Through
  3140. (defun org-element-strike-through-parser ()
  3141. "Parse strike-through object at point, if any.
  3142. When at a strike-through object, return a list whose car is
  3143. `strike-through' and cdr is a plist with `:begin', `:end',
  3144. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3145. Otherwise, return nil.
  3146. Assume point is at the first plus sign marker."
  3147. (save-excursion
  3148. (unless (bolp) (backward-char 1))
  3149. (when (looking-at org-emph-re)
  3150. (let ((begin (match-beginning 2))
  3151. (contents-begin (match-beginning 4))
  3152. (contents-end (match-end 4))
  3153. (post-blank (progn (goto-char (match-end 2))
  3154. (skip-chars-forward " \t")))
  3155. (end (point)))
  3156. (list 'strike-through
  3157. (list :begin begin
  3158. :end end
  3159. :contents-begin contents-begin
  3160. :contents-end contents-end
  3161. :post-blank post-blank))))))
  3162. (defun org-element-strike-through-interpreter (_ contents)
  3163. "Interpret strike-through object as Org syntax.
  3164. CONTENTS is the contents of the object."
  3165. (format "+%s+" contents))
  3166. ;;;; Subscript
  3167. (defun org-element-subscript-parser ()
  3168. "Parse subscript at point, if any.
  3169. When at a subscript object, return a list whose car is
  3170. `subscript' and cdr a plist with `:begin', `:end',
  3171. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3172. `:post-blank' as keywords. Otherwise, return nil.
  3173. Assume point is at the underscore."
  3174. (save-excursion
  3175. (unless (bolp) (backward-char))
  3176. (when (looking-at org-match-substring-regexp)
  3177. (let ((bracketsp (match-beginning 4))
  3178. (begin (match-beginning 2))
  3179. (contents-begin (or (match-beginning 4)
  3180. (match-beginning 3)))
  3181. (contents-end (or (match-end 4) (match-end 3)))
  3182. (post-blank (progn (goto-char (match-end 0))
  3183. (skip-chars-forward " \t")))
  3184. (end (point)))
  3185. (list 'subscript
  3186. (list :begin begin
  3187. :end end
  3188. :use-brackets-p bracketsp
  3189. :contents-begin contents-begin
  3190. :contents-end contents-end
  3191. :post-blank post-blank))))))
  3192. (defun org-element-subscript-interpreter (subscript contents)
  3193. "Interpret SUBSCRIPT object as Org syntax.
  3194. CONTENTS is the contents of the object."
  3195. (format
  3196. (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
  3197. contents))
  3198. ;;;; Superscript
  3199. (defun org-element-superscript-parser ()
  3200. "Parse superscript at point, if any.
  3201. When at a superscript object, return a list whose car is
  3202. `superscript' and cdr a plist with `:begin', `:end',
  3203. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3204. `:post-blank' as keywords. Otherwise, return nil.
  3205. Assume point is at the caret."
  3206. (save-excursion
  3207. (unless (bolp) (backward-char))
  3208. (when (looking-at org-match-substring-regexp)
  3209. (let ((bracketsp (match-beginning 4))
  3210. (begin (match-beginning 2))
  3211. (contents-begin (or (match-beginning 4)
  3212. (match-beginning 3)))
  3213. (contents-end (or (match-end 4) (match-end 3)))
  3214. (post-blank (progn (goto-char (match-end 0))
  3215. (skip-chars-forward " \t")))
  3216. (end (point)))
  3217. (list 'superscript
  3218. (list :begin begin
  3219. :end end
  3220. :use-brackets-p bracketsp
  3221. :contents-begin contents-begin
  3222. :contents-end contents-end
  3223. :post-blank post-blank))))))
  3224. (defun org-element-superscript-interpreter (superscript contents)
  3225. "Interpret SUPERSCRIPT object as Org syntax.
  3226. CONTENTS is the contents of the object."
  3227. (format
  3228. (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
  3229. contents))
  3230. ;;;; Table Cell
  3231. (defun org-element-table-cell-parser ()
  3232. "Parse table cell at point.
  3233. Return a list whose car is `table-cell' and cdr is a plist
  3234. containing `:begin', `:end', `:contents-begin', `:contents-end'
  3235. and `:post-blank' keywords."
  3236. (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
  3237. (let* ((begin (match-beginning 0))
  3238. (end (match-end 0))
  3239. (contents-begin (match-beginning 1))
  3240. (contents-end (match-end 1)))
  3241. (list 'table-cell
  3242. (list :begin begin
  3243. :end end
  3244. :contents-begin contents-begin
  3245. :contents-end contents-end
  3246. :post-blank 0))))
  3247. (defun org-element-table-cell-interpreter (_ contents)
  3248. "Interpret table-cell element as Org syntax.
  3249. CONTENTS is the contents of the cell, or nil."
  3250. (concat " " contents " |"))
  3251. ;;;; Target
  3252. (defun org-element-target-parser ()
  3253. "Parse target at point, if any.
  3254. When at a target, return a list whose car is `target' and cdr
  3255. a plist with `:begin', `:end', `:value' and `:post-blank' as
  3256. keywords. Otherwise, return nil.
  3257. Assume point is at the target."
  3258. (save-excursion
  3259. (when (looking-at org-target-regexp)
  3260. (let ((begin (point))
  3261. (value (match-string-no-properties 1))
  3262. (post-blank (progn (goto-char (match-end 0))
  3263. (skip-chars-forward " \t")))
  3264. (end (point)))
  3265. (list 'target
  3266. (list :begin begin
  3267. :end end
  3268. :value value
  3269. :post-blank post-blank))))))
  3270. (defun org-element-target-interpreter (target _)
  3271. "Interpret TARGET object as Org syntax."
  3272. (format "<<%s>>" (org-element-property :value target)))
  3273. ;;;; Timestamp
  3274. (defconst org-element--timestamp-regexp
  3275. (concat org-ts-regexp-both
  3276. "\\|"
  3277. "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
  3278. "\\|"
  3279. "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
  3280. "Regexp matching any timestamp type object.")
  3281. (defun org-element-timestamp-parser ()
  3282. "Parse time stamp at point, if any.
  3283. When at a time stamp, return a list whose car is `timestamp', and
  3284. cdr a plist with `:type', `:raw-value', `:year-start',
  3285. `:month-start', `:day-start', `:hour-start', `:minute-start',
  3286. `:year-end', `:month-end', `:day-end', `:hour-end',
  3287. `:minute-end', `:repeater-type', `:repeater-value',
  3288. `:repeater-unit', `:warning-type', `:warning-value',
  3289. `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
  3290. Otherwise, return nil.
  3291. Assume point is at the beginning of the timestamp."
  3292. (when (looking-at-p org-element--timestamp-regexp)
  3293. (save-excursion
  3294. (let* ((begin (point))
  3295. (activep (eq (char-after) ?<))
  3296. (raw-value
  3297. (progn
  3298. (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
  3299. (match-string-no-properties 0)))
  3300. (date-start (match-string-no-properties 1))
  3301. (date-end (match-string 3))
  3302. (diaryp (match-beginning 2))
  3303. (post-blank (progn (goto-char (match-end 0))
  3304. (skip-chars-forward " \t")))
  3305. (end (point))
  3306. (time-range
  3307. (and (not diaryp)
  3308. (string-match
  3309. "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
  3310. date-start)
  3311. (cons (string-to-number (match-string 2 date-start))
  3312. (string-to-number (match-string 3 date-start)))))
  3313. (type (cond (diaryp 'diary)
  3314. ((and activep (or date-end time-range)) 'active-range)
  3315. (activep 'active)
  3316. ((or date-end time-range) 'inactive-range)
  3317. (t 'inactive)))
  3318. (repeater-props
  3319. (and (not diaryp)
  3320. (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
  3321. raw-value)
  3322. (list
  3323. :repeater-type
  3324. (let ((type (match-string 1 raw-value)))
  3325. (cond ((equal "++" type) 'catch-up)
  3326. ((equal ".+" type) 'restart)
  3327. (t 'cumulate)))
  3328. :repeater-value (string-to-number (match-string 2 raw-value))
  3329. :repeater-unit
  3330. (pcase (string-to-char (match-string 3 raw-value))
  3331. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3332. (warning-props
  3333. (and (not diaryp)
  3334. (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
  3335. (list
  3336. :warning-type (if (match-string 1 raw-value) 'first 'all)
  3337. :warning-value (string-to-number (match-string 2 raw-value))
  3338. :warning-unit
  3339. (pcase (string-to-char (match-string 3 raw-value))
  3340. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3341. year-start month-start day-start hour-start minute-start year-end
  3342. month-end day-end hour-end minute-end)
  3343. ;; Parse date-start.
  3344. (unless diaryp
  3345. (let ((date (org-parse-time-string date-start t)))
  3346. (setq year-start (nth 5 date)
  3347. month-start (nth 4 date)
  3348. day-start (nth 3 date)
  3349. hour-start (nth 2 date)
  3350. minute-start (nth 1 date))))
  3351. ;; Compute date-end. It can be provided directly in time-stamp,
  3352. ;; or extracted from time range. Otherwise, it defaults to the
  3353. ;; same values as date-start.
  3354. (unless diaryp
  3355. (let ((date (and date-end (org-parse-time-string date-end t))))
  3356. (setq year-end (or (nth 5 date) year-start)
  3357. month-end (or (nth 4 date) month-start)
  3358. day-end (or (nth 3 date) day-start)
  3359. hour-end (or (nth 2 date) (car time-range) hour-start)
  3360. minute-end (or (nth 1 date) (cdr time-range) minute-start))))
  3361. (list 'timestamp
  3362. (nconc (list :type type
  3363. :raw-value raw-value
  3364. :year-start year-start
  3365. :month-start month-start
  3366. :day-start day-start
  3367. :hour-start hour-start
  3368. :minute-start minute-start
  3369. :year-end year-end
  3370. :month-end month-end
  3371. :day-end day-end
  3372. :hour-end hour-end
  3373. :minute-end minute-end
  3374. :begin begin
  3375. :end end
  3376. :post-blank post-blank)
  3377. repeater-props
  3378. warning-props))))))
  3379. (defun org-element-timestamp-interpreter (timestamp _)
  3380. "Interpret TIMESTAMP object as Org syntax."
  3381. (let* ((repeat-string
  3382. (concat
  3383. (pcase (org-element-property :repeater-type timestamp)
  3384. (`cumulate "+") (`catch-up "++") (`restart ".+"))
  3385. (let ((val (org-element-property :repeater-value timestamp)))
  3386. (and val (number-to-string val)))
  3387. (pcase (org-element-property :repeater-unit timestamp)
  3388. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3389. (warning-string
  3390. (concat
  3391. (pcase (org-element-property :warning-type timestamp)
  3392. (`first "--") (`all "-"))
  3393. (let ((val (org-element-property :warning-value timestamp)))
  3394. (and val (number-to-string val)))
  3395. (pcase (org-element-property :warning-unit timestamp)
  3396. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3397. (build-ts-string
  3398. ;; Build an Org timestamp string from TIME. ACTIVEP is
  3399. ;; non-nil when time stamp is active. If WITH-TIME-P is
  3400. ;; non-nil, add a time part. HOUR-END and MINUTE-END
  3401. ;; specify a time range in the timestamp. REPEAT-STRING is
  3402. ;; the repeater string, if any.
  3403. (lambda (time activep &optional with-time-p hour-end minute-end)
  3404. (let ((ts (format-time-string
  3405. (funcall (if with-time-p #'cdr #'car)
  3406. org-time-stamp-formats)
  3407. time)))
  3408. (when (and hour-end minute-end)
  3409. (string-match "[012]?[0-9]:[0-5][0-9]" ts)
  3410. (setq ts
  3411. (replace-match
  3412. (format "\\&-%02d:%02d" hour-end minute-end)
  3413. nil nil ts)))
  3414. (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
  3415. (dolist (s (list repeat-string warning-string))
  3416. (when (org-string-nw-p s)
  3417. (setq ts (concat (substring ts 0 -1)
  3418. " "
  3419. s
  3420. (substring ts -1)))))
  3421. ;; Return value.
  3422. ts)))
  3423. (type (org-element-property :type timestamp)))
  3424. (pcase type
  3425. ((or `active `inactive)
  3426. (let* ((minute-start (org-element-property :minute-start timestamp))
  3427. (minute-end (org-element-property :minute-end timestamp))
  3428. (hour-start (org-element-property :hour-start timestamp))
  3429. (hour-end (org-element-property :hour-end timestamp))
  3430. (time-range-p (and hour-start hour-end minute-start minute-end
  3431. (or (/= hour-start hour-end)
  3432. (/= minute-start minute-end)))))
  3433. (funcall
  3434. build-ts-string
  3435. (encode-time 0
  3436. (or minute-start 0)
  3437. (or hour-start 0)
  3438. (org-element-property :day-start timestamp)
  3439. (org-element-property :month-start timestamp)
  3440. (org-element-property :year-start timestamp))
  3441. (eq type 'active)
  3442. (and hour-start minute-start)
  3443. (and time-range-p hour-end)
  3444. (and time-range-p minute-end))))
  3445. ((or `active-range `inactive-range)
  3446. (let ((minute-start (org-element-property :minute-start timestamp))
  3447. (minute-end (org-element-property :minute-end timestamp))
  3448. (hour-start (org-element-property :hour-start timestamp))
  3449. (hour-end (org-element-property :hour-end timestamp)))
  3450. (concat
  3451. (funcall
  3452. build-ts-string (encode-time
  3453. 0
  3454. (or minute-start 0)
  3455. (or hour-start 0)
  3456. (org-element-property :day-start timestamp)
  3457. (org-element-property :month-start timestamp)
  3458. (org-element-property :year-start timestamp))
  3459. (eq type 'active-range)
  3460. (and hour-start minute-start))
  3461. "--"
  3462. (funcall build-ts-string
  3463. (encode-time 0
  3464. (or minute-end 0)
  3465. (or hour-end 0)
  3466. (org-element-property :day-end timestamp)
  3467. (org-element-property :month-end timestamp)
  3468. (org-element-property :year-end timestamp))
  3469. (eq type 'active-range)
  3470. (and hour-end minute-end)))))
  3471. (_ (org-element-property :raw-value timestamp)))))
  3472. ;;;; Underline
  3473. (defun org-element-underline-parser ()
  3474. "Parse underline object at point, if any.
  3475. When at an underline object, return a list whose car is
  3476. `underline' and cdr is a plist with `:begin', `:end',
  3477. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3478. Otherwise, return nil.
  3479. Assume point is at the first underscore marker."
  3480. (save-excursion
  3481. (unless (bolp) (backward-char 1))
  3482. (when (looking-at org-emph-re)
  3483. (let ((begin (match-beginning 2))
  3484. (contents-begin (match-beginning 4))
  3485. (contents-end (match-end 4))
  3486. (post-blank (progn (goto-char (match-end 2))
  3487. (skip-chars-forward " \t")))
  3488. (end (point)))
  3489. (list 'underline
  3490. (list :begin begin
  3491. :end end
  3492. :contents-begin contents-begin
  3493. :contents-end contents-end
  3494. :post-blank post-blank))))))
  3495. (defun org-element-underline-interpreter (_ contents)
  3496. "Interpret underline object as Org syntax.
  3497. CONTENTS is the contents of the object."
  3498. (format "_%s_" contents))
  3499. ;;;; Verbatim
  3500. (defun org-element-verbatim-parser ()
  3501. "Parse verbatim object at point, if any.
  3502. When at a verbatim object, return a list whose car is `verbatim'
  3503. and cdr is a plist with `:value', `:begin', `:end' and
  3504. `:post-blank' keywords. Otherwise, return nil.
  3505. Assume point is at the first equal sign marker."
  3506. (save-excursion
  3507. (unless (bolp) (backward-char 1))
  3508. (when (looking-at org-verbatim-re)
  3509. (let ((begin (match-beginning 2))
  3510. (value (match-string-no-properties 4))
  3511. (post-blank (progn (goto-char (match-end 2))
  3512. (skip-chars-forward " \t")))
  3513. (end (point)))
  3514. (list 'verbatim
  3515. (list :value value
  3516. :begin begin
  3517. :end end
  3518. :post-blank post-blank))))))
  3519. (defun org-element-verbatim-interpreter (verbatim _)
  3520. "Interpret VERBATIM object as Org syntax."
  3521. (format "=%s=" (org-element-property :value verbatim)))
  3522. ;;; Parsing Element Starting At Point
  3523. ;;
  3524. ;; `org-element--current-element' is the core function of this section.
  3525. ;; It returns the Lisp representation of the element starting at
  3526. ;; point.
  3527. (defun org-element--current-element (limit &optional granularity mode structure)
  3528. "Parse the element starting at point.
  3529. Return value is a list like (TYPE PROPS) where TYPE is the type
  3530. of the element and PROPS a plist of properties associated to the
  3531. element.
  3532. Possible types are defined in `org-element-all-elements'.
  3533. LIMIT bounds the search.
  3534. Optional argument GRANULARITY determines the depth of the
  3535. recursion. Allowed values are `headline', `greater-element',
  3536. `element', `object' or nil. When it is broader than `object' (or
  3537. nil), secondary values will not be parsed, since they only
  3538. contain objects.
  3539. Optional argument MODE, when non-nil, can be either
  3540. `first-section', `item', `node-property', `planning',
  3541. `property-drawer', `section', `table-row', or `top-comment'.
  3542. If STRUCTURE isn't provided but MODE is set to `item', it will be
  3543. computed.
  3544. This function assumes point is always at the beginning of the
  3545. element it has to parse."
  3546. (save-excursion
  3547. (let ((case-fold-search t)
  3548. ;; Determine if parsing depth allows for secondary strings
  3549. ;; parsing. It only applies to elements referenced in
  3550. ;; `org-element-secondary-value-alist'.
  3551. (raw-secondary-p (and granularity (not (eq granularity 'object)))))
  3552. (cond
  3553. ;; Item.
  3554. ((eq mode 'item)
  3555. (org-element-item-parser limit structure raw-secondary-p))
  3556. ;; Table Row.
  3557. ((eq mode 'table-row) (org-element-table-row-parser limit))
  3558. ;; Node Property.
  3559. ((eq mode 'node-property) (org-element-node-property-parser limit))
  3560. ;; Headline.
  3561. ((org-with-limited-levels (org-at-heading-p))
  3562. (org-element-headline-parser limit raw-secondary-p))
  3563. ;; Sections (must be checked after headline).
  3564. ((eq mode 'section) (org-element-section-parser limit))
  3565. ((eq mode 'first-section)
  3566. (org-element-section-parser
  3567. (or (save-excursion (org-with-limited-levels (outline-next-heading)))
  3568. limit)))
  3569. ;; Comments.
  3570. ((looking-at "^[ \t]*#\\(?: \\|$\\)")
  3571. (org-element-comment-parser limit))
  3572. ;; Planning.
  3573. ((and (eq mode 'planning)
  3574. (eq ?* (char-after (line-beginning-position 0)))
  3575. (looking-at org-planning-line-re))
  3576. (org-element-planning-parser limit))
  3577. ;; Property drawer.
  3578. ((and (pcase mode
  3579. (`planning (eq ?* (char-after (line-beginning-position 0))))
  3580. ((or `property-drawer `top-comment)
  3581. (save-excursion
  3582. (beginning-of-line 0)
  3583. (not (looking-at "[[:blank:]]*$"))))
  3584. (_ nil))
  3585. (looking-at org-property-drawer-re))
  3586. (org-element-property-drawer-parser limit))
  3587. ;; When not at bol, point is at the beginning of an item or
  3588. ;; a footnote definition: next item is always a paragraph.
  3589. ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
  3590. ;; Clock.
  3591. ((looking-at org-clock-line-re) (org-element-clock-parser limit))
  3592. ;; Inlinetask.
  3593. ((looking-at "^\\*+ ")
  3594. (org-element-inlinetask-parser limit raw-secondary-p))
  3595. ;; From there, elements can have affiliated keywords.
  3596. (t (let ((affiliated (org-element--collect-affiliated-keywords
  3597. limit (memq granularity '(nil object)))))
  3598. (cond
  3599. ;; Jumping over affiliated keywords put point off-limits.
  3600. ;; Parse them as regular keywords.
  3601. ((and (cdr affiliated) (>= (point) limit))
  3602. (goto-char (car affiliated))
  3603. (org-element-keyword-parser limit nil))
  3604. ;; LaTeX Environment.
  3605. ((looking-at org-element--latex-begin-environment)
  3606. (org-element-latex-environment-parser limit affiliated))
  3607. ;; Drawer.
  3608. ((looking-at org-drawer-regexp)
  3609. (org-element-drawer-parser limit affiliated))
  3610. ;; Fixed Width
  3611. ((looking-at "[ \t]*:\\( \\|$\\)")
  3612. (org-element-fixed-width-parser limit affiliated))
  3613. ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
  3614. ;; Keywords.
  3615. ((looking-at "[ \t]*#\\+")
  3616. (goto-char (match-end 0))
  3617. (cond
  3618. ((looking-at "BEGIN_\\(\\S-+\\)")
  3619. (beginning-of-line)
  3620. (funcall (pcase (upcase (match-string 1))
  3621. ("CENTER" #'org-element-center-block-parser)
  3622. ("COMMENT" #'org-element-comment-block-parser)
  3623. ("EXAMPLE" #'org-element-example-block-parser)
  3624. ("EXPORT" #'org-element-export-block-parser)
  3625. ("QUOTE" #'org-element-quote-block-parser)
  3626. ("SRC" #'org-element-src-block-parser)
  3627. ("VERSE" #'org-element-verse-block-parser)
  3628. (_ #'org-element-special-block-parser))
  3629. limit
  3630. affiliated))
  3631. ((looking-at "CALL:")
  3632. (beginning-of-line)
  3633. (org-element-babel-call-parser limit affiliated))
  3634. ((looking-at "BEGIN:? ")
  3635. (beginning-of-line)
  3636. (org-element-dynamic-block-parser limit affiliated))
  3637. ((looking-at "\\S-+:")
  3638. (beginning-of-line)
  3639. (org-element-keyword-parser limit affiliated))
  3640. (t
  3641. (beginning-of-line)
  3642. (org-element-paragraph-parser limit affiliated))))
  3643. ;; Footnote Definition.
  3644. ((looking-at org-footnote-definition-re)
  3645. (org-element-footnote-definition-parser limit affiliated))
  3646. ;; Horizontal Rule.
  3647. ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
  3648. (org-element-horizontal-rule-parser limit affiliated))
  3649. ;; Diary Sexp.
  3650. ((looking-at "%%(")
  3651. (org-element-diary-sexp-parser limit affiliated))
  3652. ;; Table.
  3653. ((or (looking-at "[ \t]*|")
  3654. ;; There is no strict definition of a table.el
  3655. ;; table. Try to prevent false positive while being
  3656. ;; quick.
  3657. (let ((rule-regexp
  3658. (rx (zero-or-more (any " \t"))
  3659. "+"
  3660. (one-or-more (one-or-more "-") "+")
  3661. (zero-or-more (any " \t"))
  3662. eol))
  3663. (non-table.el-line
  3664. (rx bol
  3665. (zero-or-more (any " \t"))
  3666. (or eol (not (any "+| \t")))))
  3667. (next (line-beginning-position 2)))
  3668. ;; Start with a full rule.
  3669. (and
  3670. (looking-at rule-regexp)
  3671. (< next limit) ;no room for a table.el table
  3672. (save-excursion
  3673. (end-of-line)
  3674. (cond
  3675. ;; Must end with a full rule.
  3676. ((not (re-search-forward non-table.el-line limit 'move))
  3677. (if (bolp) (forward-line -1) (beginning-of-line))
  3678. (looking-at rule-regexp))
  3679. ;; Ignore pseudo-tables with a single
  3680. ;; rule.
  3681. ((= next (line-beginning-position))
  3682. nil)
  3683. ;; Must end with a full rule.
  3684. (t
  3685. (forward-line -1)
  3686. (looking-at rule-regexp)))))))
  3687. (org-element-table-parser limit affiliated))
  3688. ;; List.
  3689. ((looking-at (org-item-re))
  3690. (org-element-plain-list-parser
  3691. limit affiliated
  3692. (or structure (org-element--list-struct limit))))
  3693. ;; Default element: Paragraph.
  3694. (t (org-element-paragraph-parser limit affiliated)))))))))
  3695. ;; Most elements can have affiliated keywords. When looking for an
  3696. ;; element beginning, we want to move before them, as they belong to
  3697. ;; that element, and, in the meantime, collect information they give
  3698. ;; into appropriate properties. Hence the following function.
  3699. (defun org-element--collect-affiliated-keywords (limit parse)
  3700. "Collect affiliated keywords from point down to LIMIT.
  3701. Return a list whose CAR is the position at the first of them and
  3702. CDR a plist of keywords and values and move point to the
  3703. beginning of the first line after them.
  3704. As a special case, if element doesn't start at the beginning of
  3705. the line (e.g., a paragraph starting an item), CAR is current
  3706. position of point and CDR is nil.
  3707. When PARSE is non-nil, values from keywords belonging to
  3708. `org-element-parsed-keywords' are parsed as secondary strings."
  3709. (if (not (bolp)) (list (point))
  3710. (let ((case-fold-search t)
  3711. (origin (point))
  3712. ;; RESTRICT is the list of objects allowed in parsed
  3713. ;; keywords value. If PARSE is nil, no object is allowed.
  3714. (restrict (and parse (org-element-restriction 'keyword)))
  3715. output)
  3716. (while (and (< (point) limit) (looking-at org-element--affiliated-re))
  3717. (let* ((raw-kwd (upcase (match-string 1)))
  3718. ;; Apply translation to RAW-KWD. From there, KWD is
  3719. ;; the official keyword.
  3720. (kwd (or (cdr (assoc raw-kwd
  3721. org-element-keyword-translation-alist))
  3722. raw-kwd))
  3723. ;; PARSED? is non-nil when keyword should have its
  3724. ;; value parsed.
  3725. (parsed? (member kwd org-element-parsed-keywords))
  3726. ;; Find main value for any keyword.
  3727. (value
  3728. (let ((beg (match-end 0))
  3729. (end (save-excursion
  3730. (end-of-line)
  3731. (skip-chars-backward " \t")
  3732. (point))))
  3733. (if parsed?
  3734. (save-match-data
  3735. (org-element--parse-objects beg end nil restrict))
  3736. (org-trim (buffer-substring-no-properties beg end)))))
  3737. ;; If KWD is a dual keyword, find its secondary value.
  3738. ;; Maybe parse it.
  3739. (dual? (member kwd org-element-dual-keywords))
  3740. (dual-value
  3741. (and dual?
  3742. (let ((sec (match-string-no-properties 2)))
  3743. (cond
  3744. ((and sec parsed?)
  3745. (save-match-data
  3746. (org-element--parse-objects
  3747. (match-beginning 2) (match-end 2) nil restrict)))
  3748. (sec sec)))))
  3749. ;; Attribute a property name to KWD.
  3750. (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
  3751. ;; Now set final shape for VALUE.
  3752. (when dual?
  3753. (setq value (and (or value dual-value) (cons value dual-value))))
  3754. (when (or (member kwd org-element-multiple-keywords)
  3755. ;; Attributes can always appear on multiple lines.
  3756. (string-match "^ATTR_" kwd))
  3757. (setq value (cons value (plist-get output kwd-sym))))
  3758. ;; Eventually store the new value in OUTPUT.
  3759. (setq output (plist-put output kwd-sym value))
  3760. ;; Move to next keyword.
  3761. (forward-line)))
  3762. ;; If affiliated keywords are orphaned: move back to first one.
  3763. ;; They will be parsed as a paragraph.
  3764. (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
  3765. ;; Return value.
  3766. (cons origin output))))
  3767. ;;; The Org Parser
  3768. ;;
  3769. ;; The two major functions here are `org-element-parse-buffer', which
  3770. ;; parses Org syntax inside the current buffer, taking into account
  3771. ;; region, narrowing, or even visibility if specified, and
  3772. ;; `org-element-parse-secondary-string', which parses objects within
  3773. ;; a given string.
  3774. ;;
  3775. ;; The (almost) almighty `org-element-map' allows applying a function
  3776. ;; on elements or objects matching some type, and accumulating the
  3777. ;; resulting values. In an export situation, it also skips unneeded
  3778. ;; parts of the parse tree.
  3779. (defun org-element-parse-buffer (&optional granularity visible-only)
  3780. "Recursively parse the buffer and return structure.
  3781. If narrowing is in effect, only parse the visible part of the
  3782. buffer.
  3783. Optional argument GRANULARITY determines the depth of the
  3784. recursion. It can be set to the following symbols:
  3785. `headline' Only parse headlines.
  3786. `greater-element' Don't recurse into greater elements except
  3787. headlines and sections. Thus, elements
  3788. parsed are the top-level ones.
  3789. `element' Parse everything but objects and plain text.
  3790. `object' Parse the complete buffer (default).
  3791. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  3792. elements.
  3793. An element or object is represented as a list with the
  3794. pattern (TYPE PROPERTIES CONTENTS), where :
  3795. TYPE is a symbol describing the element or object. See
  3796. `org-element-all-elements' and `org-element-all-objects' for an
  3797. exhaustive list of such symbols. One can retrieve it with
  3798. `org-element-type' function.
  3799. PROPERTIES is the list of attributes attached to the element or
  3800. object, as a plist. Although most of them are specific to the
  3801. element or object type, all types share `:begin', `:end',
  3802. `:post-blank' and `:parent' properties, which respectively
  3803. refer to buffer position where the element or object starts,
  3804. ends, the number of white spaces or blank lines after it, and
  3805. the element or object containing it. Properties values can be
  3806. obtained by using `org-element-property' function.
  3807. CONTENTS is a list of elements, objects or raw strings
  3808. contained in the current element or object, when applicable.
  3809. One can access them with `org-element-contents' function.
  3810. The Org buffer has `org-data' as type and nil as properties.
  3811. `org-element-map' function can be used to find specific elements
  3812. or objects within the parse tree.
  3813. This function assumes that current major mode is `org-mode'."
  3814. (save-excursion
  3815. (goto-char (point-min))
  3816. (org-skip-whitespace)
  3817. (org-element--parse-elements
  3818. (line-beginning-position) (point-max)
  3819. ;; Start in `first-section' mode so text before the first
  3820. ;; headline belongs to a section.
  3821. 'first-section nil granularity visible-only (list 'org-data nil))))
  3822. (defun org-element-parse-secondary-string (string restriction &optional parent)
  3823. "Recursively parse objects in STRING and return structure.
  3824. RESTRICTION is a symbol limiting the object types that will be
  3825. looked after.
  3826. Optional argument PARENT, when non-nil, is the element or object
  3827. containing the secondary string. It is used to set correctly
  3828. `:parent' property within the string.
  3829. If STRING is the empty string or nil, return nil."
  3830. (cond
  3831. ((not string) nil)
  3832. ((equal string "") nil)
  3833. (t (let ((local-variables (buffer-local-variables)))
  3834. (with-temp-buffer
  3835. (dolist (v local-variables)
  3836. (ignore-errors
  3837. (if (symbolp v) (makunbound v)
  3838. ;; Don't set file name to avoid mishandling hooks (bug#44524)
  3839. (unless (memq (car v) '(buffer-file-name buffer-file-truename))
  3840. (set (make-local-variable (car v)) (cdr v))))))
  3841. ;; Transferring local variables may put the temporary buffer
  3842. ;; into a read-only state. Make sure we can insert STRING.
  3843. (let ((inhibit-read-only t)) (insert string))
  3844. ;; Prevent "Buffer *temp* modified; kill anyway?".
  3845. (restore-buffer-modified-p nil)
  3846. (org-element--parse-objects
  3847. (point-min) (point-max) nil restriction parent))))))
  3848. (defun org-element-map
  3849. (data types fun &optional info first-match no-recursion with-affiliated)
  3850. "Map a function on selected elements or objects.
  3851. DATA is a parse tree, an element, an object, a string, or a list
  3852. of such constructs. TYPES is a symbol or list of symbols of
  3853. elements or objects types (see `org-element-all-elements' and
  3854. `org-element-all-objects' for a complete list of types). FUN is
  3855. the function called on the matching element or object. It has to
  3856. accept one argument: the element or object itself.
  3857. When optional argument INFO is non-nil, it should be a plist
  3858. holding export options. In that case, parts of the parse tree
  3859. not exportable according to that property list will be skipped.
  3860. When optional argument FIRST-MATCH is non-nil, stop at the first
  3861. match for which FUN doesn't return nil, and return that value.
  3862. Optional argument NO-RECURSION is a symbol or a list of symbols
  3863. representing elements or objects types. `org-element-map' won't
  3864. enter any recursive element or object whose type belongs to that
  3865. list. Though, FUN can still be applied on them.
  3866. When optional argument WITH-AFFILIATED is non-nil, FUN will also
  3867. apply to matching objects within parsed affiliated keywords (see
  3868. `org-element-parsed-keywords').
  3869. Nil values returned from FUN do not appear in the results.
  3870. Examples:
  3871. ---------
  3872. Assuming TREE is a variable containing an Org buffer parse tree,
  3873. the following example will return a flat list of all `src-block'
  3874. and `example-block' elements in it:
  3875. (org-element-map tree \\='(example-block src-block) #\\='identity)
  3876. The following snippet will find the first headline with a level
  3877. of 1 and a \"phone\" tag, and will return its beginning position:
  3878. (org-element-map tree \\='headline
  3879. (lambda (hl)
  3880. (and (= (org-element-property :level hl) 1)
  3881. (member \"phone\" (org-element-property :tags hl))
  3882. (org-element-property :begin hl)))
  3883. nil t)
  3884. The next example will return a flat list of all `plain-list' type
  3885. elements in TREE that are not a sub-list themselves:
  3886. (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
  3887. Eventually, this example will return a flat list of all `bold'
  3888. type objects containing a `latex-snippet' type object, even
  3889. looking into captions:
  3890. (org-element-map tree \\='bold
  3891. (lambda (b)
  3892. (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
  3893. nil nil nil t)"
  3894. (declare (indent 2))
  3895. ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
  3896. (let* ((types (if (listp types) types (list types)))
  3897. (no-recursion (if (listp no-recursion) no-recursion
  3898. (list no-recursion)))
  3899. ;; Recursion depth is determined by --CATEGORY.
  3900. (--category
  3901. (catch :--found
  3902. (let ((category 'greater-elements)
  3903. (all-objects (cons 'plain-text org-element-all-objects)))
  3904. (dolist (type types category)
  3905. (cond ((memq type all-objects)
  3906. ;; If one object is found, the function has
  3907. ;; to recurse into every object.
  3908. (throw :--found 'objects))
  3909. ((not (memq type org-element-greater-elements))
  3910. ;; If one regular element is found, the
  3911. ;; function has to recurse, at least, into
  3912. ;; every element it encounters.
  3913. (and (not (eq category 'elements))
  3914. (setq category 'elements))))))))
  3915. (--ignore-list (plist-get info :ignore-list))
  3916. --acc)
  3917. (letrec ((--walk-tree
  3918. (lambda (--data)
  3919. ;; Recursively walk DATA. INFO, if non-nil, is a plist
  3920. ;; holding contextual information.
  3921. (let ((--type (org-element-type --data)))
  3922. (cond
  3923. ((not --data))
  3924. ;; Ignored element in an export context.
  3925. ((and info (memq --data --ignore-list)))
  3926. ;; List of elements or objects.
  3927. ((not --type) (mapc --walk-tree --data))
  3928. ;; Unconditionally enter parse trees.
  3929. ((eq --type 'org-data)
  3930. (mapc --walk-tree (org-element-contents --data)))
  3931. (t
  3932. ;; Check if TYPE is matching among TYPES. If so,
  3933. ;; apply FUN to --DATA and accumulate return value
  3934. ;; into --ACC (or exit if FIRST-MATCH is non-nil).
  3935. (when (memq --type types)
  3936. (let ((result (funcall fun --data)))
  3937. (cond ((not result))
  3938. (first-match (throw :--map-first-match result))
  3939. (t (push result --acc)))))
  3940. ;; If --DATA has a secondary string that can contain
  3941. ;; objects with their type among TYPES, look inside.
  3942. (when (and (eq --category 'objects) (not (stringp --data)))
  3943. (dolist (p (cdr (assq --type
  3944. org-element-secondary-value-alist)))
  3945. (funcall --walk-tree (org-element-property p --data))))
  3946. ;; If --DATA has any parsed affiliated keywords and
  3947. ;; WITH-AFFILIATED is non-nil, look for objects in
  3948. ;; them.
  3949. (when (and with-affiliated
  3950. (eq --category 'objects)
  3951. (eq (org-element-class --data) 'element))
  3952. (dolist (kwd-pair org-element--parsed-properties-alist)
  3953. (let ((kwd (car kwd-pair))
  3954. (value (org-element-property (cdr kwd-pair) --data)))
  3955. ;; Pay attention to the type of parsed
  3956. ;; keyword. In particular, preserve order for
  3957. ;; multiple keywords.
  3958. (cond
  3959. ((not value))
  3960. ((member kwd org-element-dual-keywords)
  3961. (if (member kwd org-element-multiple-keywords)
  3962. (dolist (line (reverse value))
  3963. (funcall --walk-tree (cdr line))
  3964. (funcall --walk-tree (car line)))
  3965. (funcall --walk-tree (cdr value))
  3966. (funcall --walk-tree (car value))))
  3967. ((member kwd org-element-multiple-keywords)
  3968. (mapc --walk-tree (reverse value)))
  3969. (t (funcall --walk-tree value))))))
  3970. ;; Determine if a recursion into --DATA is possible.
  3971. (cond
  3972. ;; --TYPE is explicitly removed from recursion.
  3973. ((memq --type no-recursion))
  3974. ;; --DATA has no contents.
  3975. ((not (org-element-contents --data)))
  3976. ;; Looking for greater elements but --DATA is
  3977. ;; simply an element or an object.
  3978. ((and (eq --category 'greater-elements)
  3979. (not (memq --type org-element-greater-elements))))
  3980. ;; Looking for elements but --DATA is an object.
  3981. ((and (eq --category 'elements)
  3982. (eq (org-element-class --data) 'object)))
  3983. ;; In any other case, map contents.
  3984. (t (mapc --walk-tree (org-element-contents --data))))))))))
  3985. (catch :--map-first-match
  3986. (funcall --walk-tree data)
  3987. ;; Return value in a proper order.
  3988. (nreverse --acc)))))
  3989. ;; The following functions are internal parts of the parser.
  3990. ;;
  3991. ;; The first one, `org-element--parse-elements' acts at the element's
  3992. ;; level.
  3993. ;;
  3994. ;; The second one, `org-element--parse-objects' applies on all objects
  3995. ;; of a paragraph or a secondary string. It calls
  3996. ;; `org-element--object-lex' to find the next object in the current
  3997. ;; container.
  3998. (defsubst org-element--next-mode (mode type parent?)
  3999. "Return next mode according to current one.
  4000. MODE is a symbol representing the expectation about the next
  4001. element or object. Meaningful values are `first-section',
  4002. `item', `node-property', `planning', `property-drawer',
  4003. `section', `table-row', `top-comment', and nil.
  4004. TYPE is the type of the current element or object.
  4005. If PARENT? is non-nil, assume the next element or object will be
  4006. located inside the current one."
  4007. (if parent?
  4008. (pcase type
  4009. (`headline 'section)
  4010. ((and (guard (eq mode 'first-section)) `section) 'top-comment)
  4011. (`inlinetask 'planning)
  4012. (`plain-list 'item)
  4013. (`property-drawer 'node-property)
  4014. (`section 'planning)
  4015. (`table 'table-row))
  4016. (pcase mode
  4017. (`item 'item)
  4018. (`node-property 'node-property)
  4019. ((and `planning (guard (eq type 'planning))) 'property-drawer)
  4020. (`table-row 'table-row)
  4021. ((and `top-comment (guard (eq type 'comment))) 'property-drawer))))
  4022. (defun org-element--parse-elements
  4023. (beg end mode structure granularity visible-only acc)
  4024. "Parse elements between BEG and END positions.
  4025. MODE prioritizes some elements over the others. It can be set to
  4026. `first-section', `item', `node-property', `planning',
  4027. `property-drawer', `section', `table-row', `top-comment', or nil.
  4028. When value is `item', STRUCTURE will be used as the current list
  4029. structure.
  4030. GRANULARITY determines the depth of the recursion. See
  4031. `org-element-parse-buffer' for more information.
  4032. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  4033. elements.
  4034. Elements are accumulated into ACC."
  4035. (save-excursion
  4036. (goto-char beg)
  4037. ;; When parsing only headlines, skip any text before first one.
  4038. (when (and (eq granularity 'headline) (not (org-at-heading-p)))
  4039. (org-with-limited-levels (outline-next-heading)))
  4040. (let (elements)
  4041. (while (< (point) end)
  4042. ;; Visible only: skip invisible parts due to folding.
  4043. (if (and visible-only (org-invisible-p nil t))
  4044. (progn
  4045. (goto-char (org-find-visible))
  4046. (when (and (eolp) (not (eobp))) (forward-char)))
  4047. ;; Find current element's type and parse it accordingly to
  4048. ;; its category.
  4049. (let* ((element (org-element--current-element
  4050. end granularity mode structure))
  4051. (type (org-element-type element))
  4052. (cbeg (org-element-property :contents-begin element)))
  4053. (goto-char (org-element-property :end element))
  4054. ;; Fill ELEMENT contents by side-effect.
  4055. (cond
  4056. ;; If element has no contents, don't modify it.
  4057. ((not cbeg))
  4058. ;; Greater element: parse it between `contents-begin' and
  4059. ;; `contents-end'. Ensure GRANULARITY allows recursion,
  4060. ;; or ELEMENT is a headline, in which case going inside
  4061. ;; is mandatory, in order to get sub-level headings.
  4062. ((and (memq type org-element-greater-elements)
  4063. (or (memq granularity '(element object nil))
  4064. (and (eq granularity 'greater-element)
  4065. (eq type 'section))
  4066. (eq type 'headline)))
  4067. (org-element--parse-elements
  4068. cbeg (org-element-property :contents-end element)
  4069. ;; Possibly switch to a special mode.
  4070. (org-element--next-mode mode type t)
  4071. (and (memq type '(item plain-list))
  4072. (org-element-property :structure element))
  4073. granularity visible-only element))
  4074. ;; ELEMENT has contents. Parse objects inside, if
  4075. ;; GRANULARITY allows it.
  4076. ((memq granularity '(object nil))
  4077. (org-element--parse-objects
  4078. cbeg (org-element-property :contents-end element) element
  4079. (org-element-restriction type))))
  4080. (push (org-element-put-property element :parent acc) elements)
  4081. ;; Update mode.
  4082. (setq mode (org-element--next-mode mode type nil)))))
  4083. ;; Return result.
  4084. (apply #'org-element-set-contents acc (nreverse elements)))))
  4085. (defun org-element--object-lex (restriction)
  4086. "Return next object in current buffer or nil.
  4087. RESTRICTION is a list of object types, as symbols, that should be
  4088. looked after. This function assumes that the buffer is narrowed
  4089. to an appropriate container (e.g., a paragraph)."
  4090. (cond
  4091. ((memq 'table-cell restriction) (org-element-table-cell-parser))
  4092. ((memq 'citation-reference restriction)
  4093. (org-element-citation-reference-parser))
  4094. (t
  4095. (let* ((start (point))
  4096. (limit
  4097. ;; Object regexp sometimes needs to have a peek at
  4098. ;; a character ahead. Therefore, when there is a hard
  4099. ;; limit, make it one more than the true beginning of the
  4100. ;; radio target.
  4101. (save-excursion
  4102. (cond ((not org-target-link-regexp) nil)
  4103. ((not (memq 'link restriction)) nil)
  4104. ((progn
  4105. (unless (bolp) (forward-char -1))
  4106. (not (re-search-forward org-target-link-regexp nil t)))
  4107. nil)
  4108. ;; Since we moved backward, we do not want to
  4109. ;; match again an hypothetical 1-character long
  4110. ;; radio link before us. Realizing that this can
  4111. ;; only happen if such a radio link starts at
  4112. ;; beginning of line, we prevent this here.
  4113. ((and (= start (1+ (line-beginning-position)))
  4114. (= start (match-end 1)))
  4115. (and (re-search-forward org-target-link-regexp nil t)
  4116. (1+ (match-beginning 1))))
  4117. (t (1+ (match-beginning 1))))))
  4118. found)
  4119. (save-excursion
  4120. (while (and (not found)
  4121. (re-search-forward org-element--object-regexp limit 'move))
  4122. (goto-char (match-beginning 0))
  4123. (let ((result (match-string 0)))
  4124. (setq found
  4125. (cond
  4126. ((string-prefix-p "call_" result t)
  4127. (and (memq 'inline-babel-call restriction)
  4128. (org-element-inline-babel-call-parser)))
  4129. ((string-prefix-p "src_" result t)
  4130. (and (memq 'inline-src-block restriction)
  4131. (org-element-inline-src-block-parser)))
  4132. (t
  4133. (pcase (char-after)
  4134. (?^ (and (memq 'superscript restriction)
  4135. (org-element-superscript-parser)))
  4136. (?_ (or (and (memq 'subscript restriction)
  4137. (org-element-subscript-parser))
  4138. (and (memq 'underline restriction)
  4139. (org-element-underline-parser))))
  4140. (?* (and (memq 'bold restriction)
  4141. (org-element-bold-parser)))
  4142. (?/ (and (memq 'italic restriction)
  4143. (org-element-italic-parser)))
  4144. (?~ (and (memq 'code restriction)
  4145. (org-element-code-parser)))
  4146. (?= (and (memq 'verbatim restriction)
  4147. (org-element-verbatim-parser)))
  4148. (?+ (and (memq 'strike-through restriction)
  4149. (org-element-strike-through-parser)))
  4150. (?@ (and (memq 'export-snippet restriction)
  4151. (org-element-export-snippet-parser)))
  4152. (?{ (and (memq 'macro restriction)
  4153. (org-element-macro-parser)))
  4154. (?$ (and (memq 'latex-fragment restriction)
  4155. (org-element-latex-fragment-parser)))
  4156. (?<
  4157. (if (eq (aref result 1) ?<)
  4158. (or (and (memq 'radio-target restriction)
  4159. (org-element-radio-target-parser))
  4160. (and (memq 'target restriction)
  4161. (org-element-target-parser)))
  4162. (or (and (memq 'timestamp restriction)
  4163. (org-element-timestamp-parser))
  4164. (and (memq 'link restriction)
  4165. (org-element-link-parser)))))
  4166. (?\\
  4167. (if (eq (aref result 1) ?\\)
  4168. (and (memq 'line-break restriction)
  4169. (org-element-line-break-parser))
  4170. (or (and (memq 'entity restriction)
  4171. (org-element-entity-parser))
  4172. (and (memq 'latex-fragment restriction)
  4173. (org-element-latex-fragment-parser)))))
  4174. (?\[
  4175. (pcase (aref result 1)
  4176. ((and ?\[
  4177. (guard (memq 'link restriction)))
  4178. (org-element-link-parser))
  4179. ((and ?f
  4180. (guard (memq 'footnote-reference restriction)))
  4181. (org-element-footnote-reference-parser))
  4182. ((and ?c
  4183. (guard (memq 'citation restriction)))
  4184. (org-element-citation-parser))
  4185. ((and (or ?% ?/)
  4186. (guard (memq 'statistics-cookie restriction)))
  4187. (org-element-statistics-cookie-parser))
  4188. (_
  4189. (or (and (memq 'timestamp restriction)
  4190. (org-element-timestamp-parser))
  4191. (and (memq 'statistics-cookie restriction)
  4192. (org-element-statistics-cookie-parser))))))
  4193. ;; This is probably a plain link.
  4194. (_ (and (memq 'link restriction)
  4195. (org-element-link-parser)))))))
  4196. (or (eobp) (forward-char))))
  4197. (cond (found)
  4198. (limit (forward-char -1)
  4199. (org-element-link-parser)) ;radio link
  4200. (t nil)))))))
  4201. (defun org-element--parse-objects (beg end acc restriction &optional parent)
  4202. "Parse objects between BEG and END and return recursive structure.
  4203. Objects are accumulated in ACC. RESTRICTION is a list of object
  4204. successors which are allowed in the current object.
  4205. ACC becomes the parent for all parsed objects. However, if ACC
  4206. is nil (i.e., a secondary string is being parsed) and optional
  4207. argument PARENT is non-nil, use it as the parent for all objects.
  4208. Eventually, if both ACC and PARENT are nil, the common parent is
  4209. the list of objects itself."
  4210. (save-excursion
  4211. (save-restriction
  4212. (narrow-to-region beg end)
  4213. (goto-char (point-min))
  4214. (let (next-object contents)
  4215. (while (and (not (eobp))
  4216. (setq next-object (org-element--object-lex restriction)))
  4217. ;; Text before any object.
  4218. (let ((obj-beg (org-element-property :begin next-object)))
  4219. (unless (= (point) obj-beg)
  4220. (let ((text (buffer-substring-no-properties (point) obj-beg)))
  4221. (push (if acc (org-element-put-property text :parent acc) text)
  4222. contents))))
  4223. ;; Object...
  4224. (let ((obj-end (org-element-property :end next-object))
  4225. (cont-beg (org-element-property :contents-begin next-object)))
  4226. (when acc (org-element-put-property next-object :parent acc))
  4227. (push (if cont-beg
  4228. ;; Fill contents of NEXT-OBJECT if possible.
  4229. (org-element--parse-objects
  4230. cont-beg
  4231. (org-element-property :contents-end next-object)
  4232. next-object
  4233. (org-element-restriction next-object))
  4234. next-object)
  4235. contents)
  4236. (goto-char obj-end)))
  4237. ;; Text after last object.
  4238. (unless (eobp)
  4239. (let ((text (buffer-substring-no-properties (point) end)))
  4240. (push (if acc (org-element-put-property text :parent acc) text)
  4241. contents)))
  4242. ;; Result. Set appropriate parent.
  4243. (if acc (apply #'org-element-set-contents acc (nreverse contents))
  4244. (let* ((contents (nreverse contents))
  4245. (parent (or parent contents)))
  4246. (dolist (datum contents contents)
  4247. (org-element-put-property datum :parent parent))))))))
  4248. ;;; Towards A Bijective Process
  4249. ;;
  4250. ;; The parse tree obtained with `org-element-parse-buffer' is really
  4251. ;; a snapshot of the corresponding Org buffer. Therefore, it can be
  4252. ;; interpreted and expanded into a string with canonical Org syntax.
  4253. ;; Hence `org-element-interpret-data'.
  4254. ;;
  4255. ;; The function relies internally on
  4256. ;; `org-element--interpret-affiliated-keywords'.
  4257. ;;;###autoload
  4258. (defun org-element-interpret-data (data)
  4259. "Interpret DATA as Org syntax.
  4260. DATA is a parse tree, an element, an object or a secondary string
  4261. to interpret. Return Org syntax as a string."
  4262. (letrec ((fun
  4263. (lambda (data parent)
  4264. (let* ((type (org-element-type data))
  4265. ;; Find interpreter for current object or
  4266. ;; element. If it doesn't exist (e.g. this is
  4267. ;; a pseudo object or element), return contents,
  4268. ;; if any.
  4269. (interpret
  4270. (let ((fun (intern
  4271. (format "org-element-%s-interpreter" type))))
  4272. (if (fboundp fun) fun (lambda (_ contents) contents))))
  4273. (results
  4274. (cond
  4275. ;; Secondary string.
  4276. ((not type)
  4277. (mapconcat (lambda (obj) (funcall fun obj parent))
  4278. data
  4279. ""))
  4280. ;; Full Org document.
  4281. ((eq type 'org-data)
  4282. (mapconcat (lambda (obj) (funcall fun obj parent))
  4283. (org-element-contents data)
  4284. ""))
  4285. ;; Plain text: return it.
  4286. ((stringp data) data)
  4287. ;; Element or object without contents.
  4288. ((not (org-element-contents data))
  4289. (funcall interpret data nil))
  4290. ;; Element or object with contents.
  4291. (t
  4292. (funcall
  4293. interpret
  4294. data
  4295. ;; Recursively interpret contents.
  4296. (mapconcat
  4297. (lambda (datum) (funcall fun datum data))
  4298. (org-element-contents
  4299. (if (not (memq type '(paragraph verse-block)))
  4300. data
  4301. ;; Fix indentation of elements containing
  4302. ;; objects. We ignore `table-row'
  4303. ;; elements as they are one line long
  4304. ;; anyway.
  4305. (org-element-normalize-contents
  4306. data
  4307. ;; When normalizing first paragraph of
  4308. ;; an item or a footnote-definition,
  4309. ;; ignore first line's indentation.
  4310. (and (eq type 'paragraph)
  4311. (memq (org-element-type parent)
  4312. '(footnote-definition item))
  4313. (eq data (car (org-element-contents parent)))
  4314. (eq (org-element-property :pre-blank parent)
  4315. 0)))))
  4316. ""))))))
  4317. (if (memq type '(org-data nil)) results
  4318. ;; Build white spaces. If no `:post-blank' property
  4319. ;; is specified, assume its value is 0.
  4320. (let ((blank (or (org-element-property :post-blank data) 0)))
  4321. (if (eq (org-element-class data parent) 'object)
  4322. (concat results (make-string blank ?\s))
  4323. (concat (org-element--interpret-affiliated-keywords data)
  4324. (org-element-normalize-string results)
  4325. (make-string blank ?\n)))))))))
  4326. (funcall fun data nil)))
  4327. (defun org-element--interpret-affiliated-keywords (element)
  4328. "Return ELEMENT's affiliated keywords as Org syntax.
  4329. If there is no affiliated keyword, return the empty string."
  4330. (let ((keyword-to-org
  4331. (lambda (key value)
  4332. (let (dual)
  4333. (when (member key org-element-dual-keywords)
  4334. (setq dual (cdr value) value (car value)))
  4335. (concat "#+" (downcase key)
  4336. (and dual
  4337. (format "[%s]" (org-element-interpret-data dual)))
  4338. ": "
  4339. (if (member key org-element-parsed-keywords)
  4340. (org-element-interpret-data value)
  4341. value)
  4342. "\n")))))
  4343. (mapconcat
  4344. (lambda (prop)
  4345. (let ((value (org-element-property prop element))
  4346. (keyword (upcase (substring (symbol-name prop) 1))))
  4347. (when value
  4348. (if (or (member keyword org-element-multiple-keywords)
  4349. ;; All attribute keywords can have multiple lines.
  4350. (string-match "^ATTR_" keyword))
  4351. (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
  4352. (reverse value)
  4353. "")
  4354. (funcall keyword-to-org keyword value)))))
  4355. ;; List all ELEMENT's properties matching an attribute line or an
  4356. ;; affiliated keyword, but ignore translated keywords since they
  4357. ;; cannot belong to the property list.
  4358. (cl-loop for prop in (nth 1 element) by 'cddr
  4359. when (let ((keyword (upcase (substring (symbol-name prop) 1))))
  4360. (or (string-match "^ATTR_" keyword)
  4361. (and
  4362. (member keyword org-element-affiliated-keywords)
  4363. (not (assoc keyword
  4364. org-element-keyword-translation-alist)))))
  4365. collect prop)
  4366. "")))
  4367. ;; Because interpretation of the parse tree must return the same
  4368. ;; number of blank lines between elements and the same number of white
  4369. ;; space after objects, some special care must be given to white
  4370. ;; spaces.
  4371. ;;
  4372. ;; The first function, `org-element-normalize-string', ensures any
  4373. ;; string different from the empty string will end with a single
  4374. ;; newline character.
  4375. ;;
  4376. ;; The second function, `org-element-normalize-contents', removes
  4377. ;; global indentation from the contents of the current element.
  4378. (defun org-element-normalize-string (s)
  4379. "Ensure string S ends with a single newline character.
  4380. If S isn't a string return it unchanged. If S is the empty
  4381. string, return it. Otherwise, return a new string with a single
  4382. newline character at its end."
  4383. (cond
  4384. ((not (stringp s)) s)
  4385. ((string= "" s) "")
  4386. (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
  4387. (replace-match "\n" nil nil s)))))
  4388. (defun org-element-normalize-contents (element &optional ignore-first)
  4389. "Normalize plain text in ELEMENT's contents.
  4390. ELEMENT must only contain plain text and objects.
  4391. If optional argument IGNORE-FIRST is non-nil, ignore first line's
  4392. indentation to compute maximal common indentation.
  4393. Return the normalized element that is element with global
  4394. indentation removed from its contents."
  4395. (letrec ((find-min-ind
  4396. ;; Return minimal common indentation within BLOB. This is
  4397. ;; done by walking recursively BLOB and updating MIN-IND
  4398. ;; along the way. FIRST-FLAG is non-nil when the next
  4399. ;; object is expected to be a string that doesn't start
  4400. ;; with a newline character. It happens for strings at
  4401. ;; the beginnings of the contents or right after a line
  4402. ;; break.
  4403. (lambda (blob first-flag min-ind)
  4404. (dolist (datum (org-element-contents blob) min-ind)
  4405. (when first-flag
  4406. (setq first-flag nil)
  4407. (cond
  4408. ;; Objects cannot start with spaces: in this
  4409. ;; case, indentation is 0.
  4410. ((not (stringp datum)) (throw :zero 0))
  4411. ((not (string-match
  4412. "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
  4413. (throw :zero 0))
  4414. ((equal (match-string 2 datum) "\n")
  4415. (put-text-property
  4416. (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
  4417. (t
  4418. (let ((i (string-width (match-string 1 datum))))
  4419. (put-text-property
  4420. (match-beginning 1) (match-end 1) 'org-ind i datum)
  4421. (setq min-ind (min i min-ind))))))
  4422. (cond
  4423. ((stringp datum)
  4424. (let ((s 0))
  4425. (while (string-match
  4426. "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
  4427. (setq s (match-end 1))
  4428. (cond
  4429. ((equal (match-string 1 datum) "")
  4430. (unless (member (match-string 2 datum) '("" "\n"))
  4431. (throw :zero 0)))
  4432. ((equal (match-string 2 datum) "\n")
  4433. (put-text-property (match-beginning 1) (match-end 1)
  4434. 'org-ind 'empty datum))
  4435. (t
  4436. (let ((i (string-width (match-string 1 datum))))
  4437. (put-text-property (match-beginning 1) (match-end 1)
  4438. 'org-ind i datum)
  4439. (setq min-ind (min i min-ind))))))))
  4440. ((eq (org-element-type datum) 'line-break)
  4441. (setq first-flag t))
  4442. ((memq (org-element-type datum) org-element-recursive-objects)
  4443. (setq min-ind
  4444. (funcall find-min-ind datum first-flag min-ind)))))))
  4445. (min-ind
  4446. (catch :zero
  4447. (funcall find-min-ind
  4448. element (not ignore-first) most-positive-fixnum))))
  4449. (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
  4450. ;; Build ELEMENT back, replacing each string with the same
  4451. ;; string minus common indentation.
  4452. (letrec ((build
  4453. (lambda (datum)
  4454. ;; Return DATUM with all its strings indentation
  4455. ;; shortened from MIN-IND white spaces.
  4456. (setcdr
  4457. (cdr datum)
  4458. (mapcar
  4459. (lambda (object)
  4460. (cond
  4461. ((stringp object)
  4462. (with-temp-buffer
  4463. (insert object)
  4464. (let ((s (point-min)))
  4465. (while (setq s (text-property-not-all
  4466. s (point-max) 'org-ind nil))
  4467. (goto-char s)
  4468. (let ((i (get-text-property s 'org-ind)))
  4469. (delete-region s (progn
  4470. (skip-chars-forward " \t")
  4471. (point)))
  4472. (when (integerp i) (indent-to (- i min-ind))))))
  4473. (buffer-string)))
  4474. ((memq (org-element-type object)
  4475. org-element-recursive-objects)
  4476. (funcall build object))
  4477. (t object)))
  4478. (org-element-contents datum)))
  4479. datum)))
  4480. (funcall build element)))))
  4481. ;;; Cache
  4482. ;;
  4483. ;; Implement a caching mechanism for `org-element-at-point' and
  4484. ;; `org-element-context', which see.
  4485. ;;
  4486. ;; A single public function is provided: `org-element-cache-reset'.
  4487. ;;
  4488. ;; Cache is disabled by default for now because it sometimes triggers
  4489. ;; freezes, but it can be enabled globally with
  4490. ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
  4491. ;; `org-element-cache-sync-duration' and
  4492. ;; `org-element-cache-sync-break' can be tweaked to control caching
  4493. ;; behavior.
  4494. ;;
  4495. ;; Internally, parsed elements are stored in an AVL tree,
  4496. ;; `org-element--cache'. This tree is updated lazily: whenever
  4497. ;; a change happens to the buffer, a synchronization request is
  4498. ;; registered in `org-element--cache-sync-requests' (see
  4499. ;; `org-element--cache-submit-request'). During idle time, requests
  4500. ;; are processed by `org-element--cache-sync'. Synchronization also
  4501. ;; happens when an element is required from the cache. In this case,
  4502. ;; the process stops as soon as the needed element is up-to-date.
  4503. ;;
  4504. ;; A synchronization request can only apply on a synchronized part of
  4505. ;; the cache. Therefore, the cache is updated at least to the
  4506. ;; location where the new request applies. Thus, requests are ordered
  4507. ;; from left to right and all elements starting before the first
  4508. ;; request are correct. This property is used by functions like
  4509. ;; `org-element--cache-find' to retrieve elements in the part of the
  4510. ;; cache that can be trusted.
  4511. ;;
  4512. ;; A request applies to every element, starting from its original
  4513. ;; location (or key, see below). When a request is processed, it
  4514. ;; moves forward and may collide the next one. In this case, both
  4515. ;; requests are merged into a new one that starts from that element.
  4516. ;; As a consequence, the whole synchronization complexity does not
  4517. ;; depend on the number of pending requests, but on the number of
  4518. ;; elements the very first request will be applied on.
  4519. ;;
  4520. ;; Elements cannot be accessed through their beginning position, which
  4521. ;; may or may not be up-to-date. Instead, each element in the tree is
  4522. ;; associated to a key, obtained with `org-element--cache-key'. This
  4523. ;; mechanism is robust enough to preserve total order among elements
  4524. ;; even when the tree is only partially synchronized.
  4525. (defvar org-element-use-cache nil
  4526. "Non-nil when Org parser should cache its results.
  4527. WARNING: for the time being, using cache sometimes triggers
  4528. freezes. Therefore, it is disabled by default. Activate it if
  4529. you want to help debugging the issue.")
  4530. (defvar org-element-cache-sync-idle-time 0.6
  4531. "Length, in seconds, of idle time before syncing cache.")
  4532. (defvar org-element-cache-sync-duration 0.04
  4533. "Maximum duration, as a time value, for a cache synchronization.
  4534. If the synchronization is not over after this delay, the process
  4535. pauses and resumes after `org-element-cache-sync-break'
  4536. seconds.")
  4537. (defvar org-element-cache-sync-break 0.3
  4538. "Duration, as a time value, of the pause between synchronizations.
  4539. See `org-element-cache-sync-duration' for more information.")
  4540. ;;;; Data Structure
  4541. (defvar org-element--cache nil
  4542. "AVL tree used to cache elements.
  4543. Each node of the tree contains an element. Comparison is done
  4544. with `org-element--cache-compare'. This cache is used in
  4545. `org-element-at-point'.")
  4546. (defvar org-element--cache-sync-requests nil
  4547. "List of pending synchronization requests.
  4548. A request is a vector with the following pattern:
  4549. [NEXT BEG END OFFSET PARENT PHASE]
  4550. Processing a synchronization request consists of three phases:
  4551. 0. Delete modified elements,
  4552. 1. Fill missing area in cache,
  4553. 2. Shift positions and re-parent elements after the changes.
  4554. During phase 0, NEXT is the key of the first element to be
  4555. removed, BEG and END is buffer position delimiting the
  4556. modifications. Elements starting between them (inclusive) are
  4557. removed. So are elements whose parent is removed. PARENT, when
  4558. non-nil, is the parent of the first element to be removed.
  4559. During phase 1, NEXT is the key of the next known element in
  4560. cache and BEG its beginning position. Parse buffer between that
  4561. element and the one before it in order to determine the parent of
  4562. the next element. Set PARENT to the element containing NEXT.
  4563. During phase 2, NEXT is the key of the next element to shift in
  4564. the parse tree. All elements starting from this one have their
  4565. properties relatives to buffer positions shifted by integer
  4566. OFFSET and, if they belong to element PARENT, are adopted by it.
  4567. PHASE specifies the phase number, as an integer.")
  4568. (defvar org-element--cache-sync-timer nil
  4569. "Timer used for cache synchronization.")
  4570. (defvar org-element--cache-sync-keys nil
  4571. "Hash table used to store keys during synchronization.
  4572. See `org-element--cache-key' for more information.")
  4573. (defsubst org-element--cache-key (element)
  4574. "Return a unique key for ELEMENT in cache tree.
  4575. Keys are used to keep a total order among elements in the cache.
  4576. Comparison is done with `org-element--cache-key-less-p'.
  4577. When no synchronization is taking place, a key is simply the
  4578. beginning position of the element, or that position plus one in
  4579. the case of an first item (respectively row) in
  4580. a list (respectively a table).
  4581. During a synchronization, the key is the one the element had when
  4582. the cache was synchronized for the last time. Elements added to
  4583. cache during the synchronization get a new key generated with
  4584. `org-element--cache-generate-key'.
  4585. Such keys are stored in `org-element--cache-sync-keys'. The hash
  4586. table is cleared once the synchronization is complete."
  4587. (or (gethash element org-element--cache-sync-keys)
  4588. (let* ((begin (org-element-property :begin element))
  4589. ;; Increase beginning position of items (respectively
  4590. ;; table rows) by one, so the first item can get
  4591. ;; a different key from its parent list (respectively
  4592. ;; table).
  4593. (key (if (memq (org-element-type element) '(item table-row))
  4594. (1+ begin)
  4595. begin)))
  4596. (if org-element--cache-sync-requests
  4597. (puthash element key org-element--cache-sync-keys)
  4598. key))))
  4599. (defun org-element--cache-generate-key (lower upper)
  4600. "Generate a key between LOWER and UPPER.
  4601. LOWER and UPPER are fixnums or lists of same, possibly empty.
  4602. If LOWER and UPPER are equals, return LOWER. Otherwise, return
  4603. a unique key, as an integer or a list of integers, according to
  4604. the following rules:
  4605. - LOWER and UPPER are compared level-wise until values differ.
  4606. - If, at a given level, LOWER and UPPER differ from more than
  4607. 2, the new key shares all the levels above with LOWER and
  4608. gets a new level. Its value is the mean between LOWER and
  4609. UPPER:
  4610. (1 2) + (1 4) --> (1 3)
  4611. - If LOWER has no value to compare with, it is assumed that its
  4612. value is `most-negative-fixnum'. E.g.,
  4613. (1 1) + (1 1 2)
  4614. is equivalent to
  4615. (1 1 m) + (1 1 2)
  4616. where m is `most-negative-fixnum'. Likewise, if UPPER is
  4617. short of levels, the current value is `most-positive-fixnum'.
  4618. - If they differ from only one, the new key inherits from
  4619. current LOWER level and fork it at the next level. E.g.,
  4620. (2 1) + (3 3)
  4621. is equivalent to
  4622. (2 1) + (2 M)
  4623. where M is `most-positive-fixnum'.
  4624. - If the key is only one level long, it is returned as an
  4625. integer:
  4626. (1 2) + (3 2) --> 2
  4627. When they are not equals, the function assumes that LOWER is
  4628. lesser than UPPER, per `org-element--cache-key-less-p'."
  4629. (if (equal lower upper) lower
  4630. (let ((lower (if (integerp lower) (list lower) lower))
  4631. (upper (if (integerp upper) (list upper) upper))
  4632. skip-upper key)
  4633. (catch 'exit
  4634. (while t
  4635. (let ((min (or (car lower) most-negative-fixnum))
  4636. (max (cond (skip-upper most-positive-fixnum)
  4637. ((car upper))
  4638. (t most-positive-fixnum))))
  4639. (if (< (1+ min) max)
  4640. (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
  4641. (throw 'exit (if key (nreverse (cons mean key)) mean)))
  4642. (when (and (< min max) (not skip-upper))
  4643. ;; When at a given level, LOWER and UPPER differ from
  4644. ;; 1, ignore UPPER altogether. Instead create a key
  4645. ;; between LOWER and the greatest key with the same
  4646. ;; prefix as LOWER so far.
  4647. (setq skip-upper t))
  4648. (push min key)
  4649. (setq lower (cdr lower) upper (cdr upper)))))))))
  4650. (defsubst org-element--cache-key-less-p (a b)
  4651. "Non-nil if key A is less than key B.
  4652. A and B are either integers or lists of integers, as returned by
  4653. `org-element--cache-key'."
  4654. (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
  4655. (if (integerp b) (< (car a) b)
  4656. (catch 'exit
  4657. (while (and a b)
  4658. (cond ((car-less-than-car a b) (throw 'exit t))
  4659. ((car-less-than-car b a) (throw 'exit nil))
  4660. (t (setq a (cdr a) b (cdr b)))))
  4661. ;; If A is empty, either keys are equal (B is also empty) and
  4662. ;; we return nil, or A is lesser than B (B is longer) and we
  4663. ;; return a non-nil value.
  4664. ;;
  4665. ;; If A is not empty, B is necessarily empty and A is greater
  4666. ;; than B (A is longer). Therefore, return nil.
  4667. (and (null a) b)))))
  4668. (defun org-element--cache-compare (a b)
  4669. "Non-nil when element A is located before element B."
  4670. (org-element--cache-key-less-p (org-element--cache-key a)
  4671. (org-element--cache-key b)))
  4672. (defsubst org-element--cache-root ()
  4673. "Return root value in cache.
  4674. This function assumes `org-element--cache' is a valid AVL tree."
  4675. (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
  4676. ;;;; Tools
  4677. (defsubst org-element--cache-active-p ()
  4678. "Non-nil when cache is active in current buffer."
  4679. (and org-element-use-cache
  4680. org-element--cache
  4681. (derived-mode-p 'org-mode)))
  4682. (defun org-element--cache-find (pos &optional side)
  4683. "Find element in cache starting at POS or before.
  4684. POS refers to a buffer position.
  4685. When optional argument SIDE is non-nil, the function checks for
  4686. elements starting at or past POS instead. If SIDE is `both', the
  4687. function returns a cons cell where car is the first element
  4688. starting at or before POS and cdr the first element starting
  4689. after POS.
  4690. The function can only find elements in the synchronized part of
  4691. the cache."
  4692. (let ((limit (and org-element--cache-sync-requests
  4693. (aref (car org-element--cache-sync-requests) 0)))
  4694. (node (org-element--cache-root))
  4695. lower upper)
  4696. (while node
  4697. (let* ((element (avl-tree--node-data node))
  4698. (begin (org-element-property :begin element)))
  4699. (cond
  4700. ((and limit
  4701. (not (org-element--cache-key-less-p
  4702. (org-element--cache-key element) limit)))
  4703. (setq node (avl-tree--node-left node)))
  4704. ((> begin pos)
  4705. (setq upper element
  4706. node (avl-tree--node-left node)))
  4707. ((< begin pos)
  4708. (setq lower element
  4709. node (avl-tree--node-right node)))
  4710. ;; We found an element in cache starting at POS. If `side'
  4711. ;; is `both' we also want the next one in order to generate
  4712. ;; a key in-between.
  4713. ;;
  4714. ;; If the element is the first row or item in a table or
  4715. ;; a plain list, we always return the table or the plain
  4716. ;; list.
  4717. ;;
  4718. ;; In any other case, we return the element found.
  4719. ((eq side 'both)
  4720. (setq lower element)
  4721. (setq node (avl-tree--node-right node)))
  4722. ((and (memq (org-element-type element) '(item table-row))
  4723. (let ((parent (org-element-property :parent element)))
  4724. (and (= (org-element-property :begin element)
  4725. (org-element-property :contents-begin parent))
  4726. (setq node nil
  4727. lower parent
  4728. upper parent)))))
  4729. (t
  4730. (setq node nil
  4731. lower element
  4732. upper element)))))
  4733. (pcase side
  4734. (`both (cons lower upper))
  4735. (`nil lower)
  4736. (_ upper))))
  4737. (defun org-element--cache-put (element)
  4738. "Store ELEMENT in current buffer's cache, if allowed."
  4739. (when (org-element--cache-active-p)
  4740. (when org-element--cache-sync-requests
  4741. ;; During synchronization, first build an appropriate key for
  4742. ;; the new element so `avl-tree-enter' can insert it at the
  4743. ;; right spot in the cache.
  4744. (let ((keys (org-element--cache-find
  4745. (org-element-property :begin element) 'both)))
  4746. (puthash element
  4747. (org-element--cache-generate-key
  4748. (and (car keys) (org-element--cache-key (car keys)))
  4749. (cond ((cdr keys) (org-element--cache-key (cdr keys)))
  4750. (org-element--cache-sync-requests
  4751. (aref (car org-element--cache-sync-requests) 0))))
  4752. org-element--cache-sync-keys)))
  4753. (avl-tree-enter org-element--cache element)))
  4754. (defsubst org-element--cache-remove (element)
  4755. "Remove ELEMENT from cache.
  4756. Assume ELEMENT belongs to cache and that a cache is active."
  4757. (avl-tree-delete org-element--cache element))
  4758. ;;;; Synchronization
  4759. (defsubst org-element--cache-set-timer (buffer)
  4760. "Set idle timer for cache synchronization in BUFFER."
  4761. (when org-element--cache-sync-timer
  4762. (cancel-timer org-element--cache-sync-timer))
  4763. (setq org-element--cache-sync-timer
  4764. (run-with-idle-timer
  4765. (let ((idle (current-idle-time)))
  4766. (if idle (org-time-add idle org-element-cache-sync-break)
  4767. org-element-cache-sync-idle-time))
  4768. nil
  4769. #'org-element--cache-sync
  4770. buffer)))
  4771. (defsubst org-element--cache-interrupt-p (time-limit)
  4772. "Non-nil when synchronization process should be interrupted.
  4773. TIME-LIMIT is a time value or nil."
  4774. (and time-limit
  4775. (or (input-pending-p)
  4776. (org-time-less-p time-limit nil))))
  4777. (defsubst org-element--cache-shift-positions (element offset &optional props)
  4778. "Shift ELEMENT properties relative to buffer positions by OFFSET.
  4779. Properties containing buffer positions are `:begin', `:end',
  4780. `:contents-begin', `:contents-end' and `:structure'. When
  4781. optional argument PROPS is a list of keywords, only shift
  4782. properties provided in that list.
  4783. Properties are modified by side-effect."
  4784. (let ((properties (nth 1 element)))
  4785. ;; Shift `:structure' property for the first plain list only: it
  4786. ;; is the only one that really matters and it prevents from
  4787. ;; shifting it more than once.
  4788. (when (and (or (not props) (memq :structure props))
  4789. (eq (org-element-type element) 'plain-list)
  4790. (not (eq (org-element-type (plist-get properties :parent))
  4791. 'item)))
  4792. (dolist (item (plist-get properties :structure))
  4793. (cl-incf (car item) offset)
  4794. (cl-incf (nth 6 item) offset)))
  4795. (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
  4796. (let ((value (and (or (not props) (memq key props))
  4797. (plist-get properties key))))
  4798. (and value (plist-put properties key (+ offset value)))))))
  4799. (defun org-element--cache-sync (buffer &optional threshold future-change)
  4800. "Synchronize cache with recent modification in BUFFER.
  4801. When optional argument THRESHOLD is non-nil, do the
  4802. synchronization for all elements starting before or at threshold,
  4803. then exit. Otherwise, synchronize cache for as long as
  4804. `org-element-cache-sync-duration' or until Emacs leaves idle
  4805. state.
  4806. FUTURE-CHANGE, when non-nil, is a buffer position where changes
  4807. not registered yet in the cache are going to happen. It is used
  4808. in `org-element--cache-submit-request', where cache is partially
  4809. updated before current modification are actually submitted."
  4810. (when (buffer-live-p buffer)
  4811. (with-current-buffer buffer
  4812. (let ((inhibit-quit t) request next)
  4813. (when org-element--cache-sync-timer
  4814. (cancel-timer org-element--cache-sync-timer))
  4815. (catch 'interrupt
  4816. (while org-element--cache-sync-requests
  4817. (setq request (car org-element--cache-sync-requests)
  4818. next (nth 1 org-element--cache-sync-requests))
  4819. (org-element--cache-process-request
  4820. request
  4821. (and next (aref next 0))
  4822. threshold
  4823. (and (not threshold)
  4824. (org-time-add nil
  4825. org-element-cache-sync-duration))
  4826. future-change)
  4827. ;; Request processed. Merge current and next offsets and
  4828. ;; transfer ending position.
  4829. (when next
  4830. (cl-incf (aref next 3) (aref request 3))
  4831. (aset next 2 (aref request 2)))
  4832. (setq org-element--cache-sync-requests
  4833. (cdr org-element--cache-sync-requests))))
  4834. ;; If more requests are awaiting, set idle timer accordingly.
  4835. ;; Otherwise, reset keys.
  4836. (if org-element--cache-sync-requests
  4837. (org-element--cache-set-timer buffer)
  4838. (clrhash org-element--cache-sync-keys))))))
  4839. (defun org-element--cache-process-request
  4840. (request next threshold time-limit future-change)
  4841. "Process synchronization REQUEST for all entries before NEXT.
  4842. REQUEST is a vector, built by `org-element--cache-submit-request'.
  4843. NEXT is a cache key, as returned by `org-element--cache-key'.
  4844. When non-nil, THRESHOLD is a buffer position. Synchronization
  4845. stops as soon as a shifted element begins after it.
  4846. When non-nil, TIME-LIMIT is a time value. Synchronization stops
  4847. after this time or when Emacs exits idle state.
  4848. When non-nil, FUTURE-CHANGE is a buffer position where changes
  4849. not registered yet in the cache are going to happen. See
  4850. `org-element--cache-submit-request' for more information.
  4851. Throw `interrupt' if the process stops before completing the
  4852. request."
  4853. (catch 'quit
  4854. (when (= (aref request 5) 0)
  4855. ;; Phase 0.
  4856. ;;
  4857. ;; Delete all elements starting after BEG, but not after buffer
  4858. ;; position END or past element with key NEXT. Also delete
  4859. ;; elements contained within a previously removed element
  4860. ;; (stored in `last-container').
  4861. ;;
  4862. ;; At each iteration, we start again at tree root since
  4863. ;; a deletion modifies structure of the balanced tree.
  4864. (catch 'end-phase
  4865. (while t
  4866. (when (org-element--cache-interrupt-p time-limit)
  4867. (throw 'interrupt nil))
  4868. ;; Find first element in cache with key BEG or after it.
  4869. (let ((beg (aref request 0))
  4870. (end (aref request 2))
  4871. (node (org-element--cache-root))
  4872. data data-key last-container)
  4873. (while node
  4874. (let* ((element (avl-tree--node-data node))
  4875. (key (org-element--cache-key element)))
  4876. (cond
  4877. ((org-element--cache-key-less-p key beg)
  4878. (setq node (avl-tree--node-right node)))
  4879. ((org-element--cache-key-less-p beg key)
  4880. (setq data element
  4881. data-key key
  4882. node (avl-tree--node-left node)))
  4883. (t (setq data element
  4884. data-key key
  4885. node nil)))))
  4886. (if data
  4887. (let ((pos (org-element-property :begin data)))
  4888. (if (if (or (not next)
  4889. (org-element--cache-key-less-p data-key next))
  4890. (<= pos end)
  4891. (and last-container
  4892. (let ((up data))
  4893. (while (and up (not (eq up last-container)))
  4894. (setq up (org-element-property :parent up)))
  4895. up)))
  4896. (progn (when (and (not last-container)
  4897. (> (org-element-property :end data)
  4898. end))
  4899. (setq last-container data))
  4900. (org-element--cache-remove data))
  4901. (aset request 0 data-key)
  4902. (aset request 1 pos)
  4903. (aset request 5 1)
  4904. (throw 'end-phase nil)))
  4905. ;; No element starting after modifications left in
  4906. ;; cache: further processing is futile.
  4907. (throw 'quit t))))))
  4908. (when (= (aref request 5) 1)
  4909. ;; Phase 1.
  4910. ;;
  4911. ;; Phase 0 left a hole in the cache. Some elements after it
  4912. ;; could have parents within. For example, in the following
  4913. ;; buffer:
  4914. ;;
  4915. ;; - item
  4916. ;;
  4917. ;;
  4918. ;; Paragraph1
  4919. ;;
  4920. ;; Paragraph2
  4921. ;;
  4922. ;; if we remove a blank line between "item" and "Paragraph1",
  4923. ;; everything down to "Paragraph2" is removed from cache. But
  4924. ;; the paragraph now belongs to the list, and its `:parent'
  4925. ;; property no longer is accurate.
  4926. ;;
  4927. ;; Therefore we need to parse again elements in the hole, or at
  4928. ;; least in its last section, so that we can re-parent
  4929. ;; subsequent elements, during phase 2.
  4930. ;;
  4931. ;; Note that we only need to get the parent from the first
  4932. ;; element in cache after the hole.
  4933. ;;
  4934. ;; When next key is lesser or equal to the current one, delegate
  4935. ;; phase 1 processing to next request in order to preserve key
  4936. ;; order among requests.
  4937. (let ((key (aref request 0)))
  4938. (when (and next (not (org-element--cache-key-less-p key next)))
  4939. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  4940. (aset next-request 0 key)
  4941. (aset next-request 1 (aref request 1))
  4942. (aset next-request 5 1))
  4943. (throw 'quit t)))
  4944. ;; Next element will start at its beginning position plus
  4945. ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
  4946. ;; contains the real beginning position of the first element to
  4947. ;; shift and re-parent.
  4948. (let ((limit (+ (aref request 1) (aref request 3))))
  4949. (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
  4950. ((and future-change (>= limit future-change))
  4951. ;; Changes are going to happen around this element and
  4952. ;; they will trigger another phase 1 request. Skip the
  4953. ;; current one.
  4954. (aset request 5 2))
  4955. (t
  4956. (let ((parent (org-element--parse-to limit t time-limit)))
  4957. (aset request 4 parent)
  4958. (aset request 5 2))))))
  4959. ;; Phase 2.
  4960. ;;
  4961. ;; Shift all elements starting from key START, but before NEXT, by
  4962. ;; OFFSET, and re-parent them when appropriate.
  4963. ;;
  4964. ;; Elements are modified by side-effect so the tree structure
  4965. ;; remains intact.
  4966. ;;
  4967. ;; Once THRESHOLD, if any, is reached, or once there is an input
  4968. ;; pending, exit. Before leaving, the current synchronization
  4969. ;; request is updated.
  4970. (let ((start (aref request 0))
  4971. (offset (aref request 3))
  4972. (parent (aref request 4))
  4973. (node (org-element--cache-root))
  4974. (stack (list nil))
  4975. (leftp t)
  4976. exit-flag)
  4977. ;; No re-parenting nor shifting planned: request is over.
  4978. (when (and (not parent) (zerop offset)) (throw 'quit t))
  4979. (while node
  4980. (let* ((data (avl-tree--node-data node))
  4981. (key (org-element--cache-key data)))
  4982. (if (and leftp (avl-tree--node-left node)
  4983. (not (org-element--cache-key-less-p key start)))
  4984. (progn (push node stack)
  4985. (setq node (avl-tree--node-left node)))
  4986. (unless (org-element--cache-key-less-p key start)
  4987. ;; We reached NEXT. Request is complete.
  4988. (when (equal key next) (throw 'quit t))
  4989. ;; Handle interruption request. Update current request.
  4990. (when (or exit-flag (org-element--cache-interrupt-p time-limit))
  4991. (aset request 0 key)
  4992. (aset request 4 parent)
  4993. (throw 'interrupt nil))
  4994. ;; Shift element.
  4995. (unless (zerop offset)
  4996. (org-element--cache-shift-positions data offset))
  4997. (let ((begin (org-element-property :begin data)))
  4998. ;; Update PARENT and re-parent DATA, only when
  4999. ;; necessary. Propagate new structures for lists.
  5000. (while (and parent
  5001. (<= (org-element-property :end parent) begin))
  5002. (setq parent (org-element-property :parent parent)))
  5003. (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
  5004. ((and parent
  5005. (let ((p (org-element-property :parent data)))
  5006. (or (not p)
  5007. (< (org-element-property :begin p)
  5008. (org-element-property :begin parent)))))
  5009. (org-element-put-property data :parent parent)
  5010. (let ((s (org-element-property :structure parent)))
  5011. (when (and s (org-element-property :structure data))
  5012. (org-element-put-property data :structure s)))))
  5013. ;; Cache is up-to-date past THRESHOLD. Request
  5014. ;; interruption.
  5015. (when (and threshold (> begin threshold)) (setq exit-flag t))))
  5016. (setq node (if (setq leftp (avl-tree--node-right node))
  5017. (avl-tree--node-right node)
  5018. (pop stack))))))
  5019. ;; We reached end of tree: synchronization complete.
  5020. t)))
  5021. (defun org-element--parse-to (pos &optional syncp time-limit)
  5022. "Parse elements in current section, down to POS.
  5023. Start parsing from the closest between the last known element in
  5024. cache or headline above. Return the smallest element containing
  5025. POS.
  5026. When optional argument SYNCP is non-nil, return the parent of the
  5027. element containing POS instead. In that case, it is also
  5028. possible to provide TIME-LIMIT, which is a time value specifying
  5029. when the parsing should stop. The function throws `interrupt' if
  5030. the process stopped before finding the expected result."
  5031. (catch 'exit
  5032. (org-with-wide-buffer
  5033. (goto-char pos)
  5034. (let* ((cached (and (org-element--cache-active-p)
  5035. (org-element--cache-find pos nil)))
  5036. (begin (org-element-property :begin cached))
  5037. element next mode)
  5038. (cond
  5039. ;; Nothing in cache before point: start parsing from first
  5040. ;; element following headline above, or first element in
  5041. ;; buffer.
  5042. ((not cached)
  5043. (if (org-with-limited-levels (outline-previous-heading))
  5044. (progn
  5045. (setq mode 'planning)
  5046. (forward-line))
  5047. (setq mode 'top-comment))
  5048. (skip-chars-forward " \r\t\n")
  5049. (beginning-of-line))
  5050. ;; Cache returned exact match: return it.
  5051. ((= pos begin)
  5052. (throw 'exit (if syncp (org-element-property :parent cached) cached)))
  5053. ;; There's a headline between cached value and POS: cached
  5054. ;; value is invalid. Start parsing from first element
  5055. ;; following the headline.
  5056. ((re-search-backward
  5057. (org-with-limited-levels org-outline-regexp-bol) begin t)
  5058. (forward-line)
  5059. (skip-chars-forward " \r\t\n")
  5060. (beginning-of-line)
  5061. (setq mode 'planning))
  5062. ;; Check if CACHED or any of its ancestors contain point.
  5063. ;;
  5064. ;; If there is such an element, we inspect it in order to know
  5065. ;; if we return it or if we need to parse its contents.
  5066. ;; Otherwise, we just start parsing from current location,
  5067. ;; which is right after the top-most element containing
  5068. ;; CACHED.
  5069. ;;
  5070. ;; As a special case, if POS is at the end of the buffer, we
  5071. ;; want to return the innermost element ending there.
  5072. ;;
  5073. ;; Also, if we find an ancestor and discover that we need to
  5074. ;; parse its contents, make sure we don't start from
  5075. ;; `:contents-begin', as we would otherwise go past CACHED
  5076. ;; again. Instead, in that situation, we will resume parsing
  5077. ;; from NEXT, which is located after CACHED or its higher
  5078. ;; ancestor not containing point.
  5079. (t
  5080. (let ((up cached)
  5081. (pos (if (= (point-max) pos) (1- pos) pos)))
  5082. (goto-char (or (org-element-property :contents-begin cached) begin))
  5083. (while (let ((end (org-element-property :end up)))
  5084. (and (<= end pos)
  5085. (goto-char end)
  5086. (setq up (org-element-property :parent up)))))
  5087. (cond ((not up))
  5088. ((eobp) (setq element up))
  5089. (t (setq element up next (point)))))))
  5090. ;; Parse successively each element until we reach POS.
  5091. (let ((end (or (org-element-property :end element)
  5092. (save-excursion
  5093. (org-with-limited-levels (outline-next-heading))
  5094. (point))))
  5095. (parent element))
  5096. (while t
  5097. (when syncp
  5098. (cond ((= (point) pos) (throw 'exit parent))
  5099. ((org-element--cache-interrupt-p time-limit)
  5100. (throw 'interrupt nil))))
  5101. (unless element
  5102. (setq element (org-element--current-element
  5103. end 'element mode
  5104. (org-element-property :structure parent)))
  5105. (org-element-put-property element :parent parent)
  5106. (org-element--cache-put element))
  5107. (let ((elem-end (org-element-property :end element))
  5108. (type (org-element-type element)))
  5109. (cond
  5110. ;; Skip any element ending before point. Also skip
  5111. ;; element ending at point (unless it is also the end of
  5112. ;; buffer) since we're sure that another element begins
  5113. ;; after it.
  5114. ((and (<= elem-end pos) (/= (point-max) elem-end))
  5115. (goto-char elem-end)
  5116. (setq mode (org-element--next-mode mode type nil)))
  5117. ;; A non-greater element contains point: return it.
  5118. ((not (memq type org-element-greater-elements))
  5119. (throw 'exit element))
  5120. ;; Otherwise, we have to decide if ELEMENT really
  5121. ;; contains POS. In that case we start parsing from
  5122. ;; contents' beginning.
  5123. ;;
  5124. ;; If POS is at contents' beginning but it is also at
  5125. ;; the beginning of the first item in a list or a table.
  5126. ;; In that case, we need to create an anchor for that
  5127. ;; list or table, so return it.
  5128. ;;
  5129. ;; Also, if POS is at the end of the buffer, no element
  5130. ;; can start after it, but more than one may end there.
  5131. ;; Arbitrarily, we choose to return the innermost of
  5132. ;; such elements.
  5133. ((let ((cbeg (org-element-property :contents-begin element))
  5134. (cend (org-element-property :contents-end element)))
  5135. (when (or syncp
  5136. (and cbeg cend
  5137. (or (< cbeg pos)
  5138. (and (= cbeg pos)
  5139. (not (memq type '(plain-list table)))))
  5140. (or (> cend pos)
  5141. (and (= cend pos) (= (point-max) pos)))))
  5142. (goto-char (or next cbeg))
  5143. (setq next nil
  5144. mode (org-element--next-mode mode type t)
  5145. parent element
  5146. end cend))))
  5147. ;; Otherwise, return ELEMENT as it is the smallest
  5148. ;; element containing POS.
  5149. (t (throw 'exit element))))
  5150. (setq element nil)))))))
  5151. ;;;; Staging Buffer Changes
  5152. (defconst org-element--cache-sensitive-re
  5153. (concat
  5154. "^\\*+ " "\\|"
  5155. "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
  5156. "^[ \t]*\\(?:"
  5157. "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
  5158. "\\\\begin{[A-Za-z0-9*]+}" "\\|"
  5159. ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
  5160. "\\)")
  5161. "Regexp matching a sensitive line, structure wise.
  5162. A sensitive line is a headline, inlinetask, block, drawer, or
  5163. latex-environment boundary. When such a line is modified,
  5164. structure changes in the document may propagate in the whole
  5165. section, possibly making cache invalid.")
  5166. (defvar org-element--cache-change-warning nil
  5167. "Non-nil when a sensitive line is about to be changed.
  5168. It is a symbol among nil, t and `headline'.")
  5169. (defun org-element--cache-before-change (beg end)
  5170. "Request extension of area going to be modified if needed.
  5171. BEG and END are the beginning and end of the range of changed
  5172. text. See `before-change-functions' for more information."
  5173. (when (org-element--cache-active-p)
  5174. (org-with-wide-buffer
  5175. (goto-char beg)
  5176. (beginning-of-line)
  5177. (let ((bottom (save-excursion (goto-char end) (line-end-position))))
  5178. (setq org-element--cache-change-warning
  5179. (save-match-data
  5180. (if (and (org-with-limited-levels (org-at-heading-p))
  5181. (= (line-end-position) bottom))
  5182. 'headline
  5183. (let ((case-fold-search t))
  5184. (re-search-forward
  5185. org-element--cache-sensitive-re bottom t)))))))))
  5186. (defun org-element--cache-after-change (beg end pre)
  5187. "Update buffer modifications for current buffer.
  5188. BEG and END are the beginning and end of the range of changed
  5189. text, and the length in bytes of the pre-change text replaced by
  5190. that range. See `after-change-functions' for more information."
  5191. (when (org-element--cache-active-p)
  5192. (org-with-wide-buffer
  5193. (goto-char beg)
  5194. (beginning-of-line)
  5195. (save-match-data
  5196. (let ((top (point))
  5197. (bottom (save-excursion (goto-char end) (line-end-position))))
  5198. ;; Determine if modified area needs to be extended, according
  5199. ;; to both previous and current state. We make a special
  5200. ;; case for headline editing: if a headline is modified but
  5201. ;; not removed, do not extend.
  5202. (when (pcase org-element--cache-change-warning
  5203. (`t t)
  5204. (`headline
  5205. (not (and (org-with-limited-levels (org-at-heading-p))
  5206. (= (line-end-position) bottom))))
  5207. (_
  5208. (let ((case-fold-search t))
  5209. (re-search-forward
  5210. org-element--cache-sensitive-re bottom t))))
  5211. ;; Effectively extend modified area.
  5212. (org-with-limited-levels
  5213. (setq top (progn (goto-char top)
  5214. (when (outline-previous-heading) (forward-line))
  5215. (point)))
  5216. (setq bottom (progn (goto-char bottom)
  5217. (if (outline-next-heading) (1- (point))
  5218. (point))))))
  5219. ;; Store synchronization request.
  5220. (let ((offset (- end beg pre)))
  5221. (org-element--cache-submit-request top (- bottom offset) offset)))))
  5222. ;; Activate a timer to process the request during idle time.
  5223. (org-element--cache-set-timer (current-buffer))))
  5224. (defun org-element--cache-for-removal (beg end offset)
  5225. "Return first element to remove from cache.
  5226. BEG and END are buffer positions delimiting buffer modifications.
  5227. OFFSET is the size of the changes.
  5228. Returned element is usually the first element in cache containing
  5229. any position between BEG and END. As an exception, greater
  5230. elements around the changes that are robust to contents
  5231. modifications are preserved and updated according to the
  5232. changes."
  5233. (let* ((elements (org-element--cache-find (1- beg) 'both))
  5234. (before (car elements))
  5235. (after (cdr elements)))
  5236. (if (not before) after
  5237. (let ((up before)
  5238. (robust-flag t))
  5239. (while up
  5240. (if (let ((type (org-element-type up)))
  5241. (and (or (memq type '(center-block dynamic-block quote-block
  5242. special-block))
  5243. ;; Drawers named "PROPERTIES" are probably
  5244. ;; a properties drawer being edited. Force
  5245. ;; parsing to check if editing is over.
  5246. (and (eq type 'drawer)
  5247. (not (string=
  5248. (org-element-property :drawer-name up)
  5249. "PROPERTIES"))))
  5250. (let ((cbeg (org-element-property :contents-begin up)))
  5251. (and cbeg
  5252. (<= cbeg beg)
  5253. (> (org-element-property :contents-end up) end)))))
  5254. ;; UP is a robust greater element containing changes.
  5255. ;; We only need to extend its ending boundaries.
  5256. (org-element--cache-shift-positions
  5257. up offset '(:contents-end :end))
  5258. (setq before up)
  5259. (when robust-flag (setq robust-flag nil)))
  5260. (setq up (org-element-property :parent up)))
  5261. ;; We're at top level element containing ELEMENT: if it's
  5262. ;; altered by buffer modifications, it is first element in
  5263. ;; cache to be removed. Otherwise, that first element is the
  5264. ;; following one.
  5265. ;;
  5266. ;; As a special case, do not remove BEFORE if it is a robust
  5267. ;; container for current changes.
  5268. (if (or (< (org-element-property :end before) beg) robust-flag) after
  5269. before)))))
  5270. (defun org-element--cache-submit-request (beg end offset)
  5271. "Submit a new cache synchronization request for current buffer.
  5272. BEG and END are buffer positions delimiting the minimal area
  5273. where cache data should be removed. OFFSET is the size of the
  5274. change, as an integer."
  5275. (let ((next (car org-element--cache-sync-requests))
  5276. delete-to delete-from)
  5277. (if (and next
  5278. (zerop (aref next 5))
  5279. (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
  5280. (<= (setq delete-from (aref next 1)) end))
  5281. ;; Current changes can be merged with first sync request: we
  5282. ;; can save a partial cache synchronization.
  5283. (progn
  5284. (cl-incf (aref next 3) offset)
  5285. ;; If last change happened within area to be removed, extend
  5286. ;; boundaries of robust parents, if any. Otherwise, find
  5287. ;; first element to remove and update request accordingly.
  5288. (if (> beg delete-from)
  5289. (let ((up (aref next 4)))
  5290. (while up
  5291. (org-element--cache-shift-positions
  5292. up offset '(:contents-end :end))
  5293. (setq up (org-element-property :parent up))))
  5294. (let ((first (org-element--cache-for-removal beg delete-to offset)))
  5295. (when first
  5296. (aset next 0 (org-element--cache-key first))
  5297. (aset next 1 (org-element-property :begin first))
  5298. (aset next 4 (org-element-property :parent first))))))
  5299. ;; Ensure cache is correct up to END. Also make sure that NEXT,
  5300. ;; if any, is no longer a 0-phase request, thus ensuring that
  5301. ;; phases are properly ordered. We need to provide OFFSET as
  5302. ;; optional parameter since current modifications are not known
  5303. ;; yet to the otherwise correct part of the cache (i.e, before
  5304. ;; the first request).
  5305. (when next (org-element--cache-sync (current-buffer) end beg))
  5306. (let ((first (org-element--cache-for-removal beg end offset)))
  5307. (if first
  5308. (push (let ((beg (org-element-property :begin first))
  5309. (key (org-element--cache-key first)))
  5310. (cond
  5311. ;; When changes happen before the first known
  5312. ;; element, re-parent and shift the rest of the
  5313. ;; cache.
  5314. ((> beg end) (vector key beg nil offset nil 1))
  5315. ;; Otherwise, we find the first non robust
  5316. ;; element containing END. All elements between
  5317. ;; FIRST and this one are to be removed.
  5318. ((let ((first-end (org-element-property :end first)))
  5319. (and (> first-end end)
  5320. (vector key beg first-end offset first 0))))
  5321. (t
  5322. (let* ((element (org-element--cache-find end))
  5323. (end (org-element-property :end element))
  5324. (up element))
  5325. (while (and (setq up (org-element-property :parent up))
  5326. (>= (org-element-property :begin up) beg))
  5327. (setq end (org-element-property :end up)
  5328. element up))
  5329. (vector key beg end offset element 0)))))
  5330. org-element--cache-sync-requests)
  5331. ;; No element to remove. No need to re-parent either.
  5332. ;; Simply shift additional elements, if any, by OFFSET.
  5333. (when org-element--cache-sync-requests
  5334. (cl-incf (aref (car org-element--cache-sync-requests) 3)
  5335. offset)))))))
  5336. ;;;; Public Functions
  5337. ;;;###autoload
  5338. (defun org-element-cache-reset (&optional all)
  5339. "Reset cache in current buffer.
  5340. When optional argument ALL is non-nil, reset cache in all Org
  5341. buffers."
  5342. (interactive "P")
  5343. (dolist (buffer (if all (buffer-list) (list (current-buffer))))
  5344. (with-current-buffer buffer
  5345. (when (and org-element-use-cache (derived-mode-p 'org-mode))
  5346. (setq-local org-element--cache
  5347. (avl-tree-create #'org-element--cache-compare))
  5348. (setq-local org-element--cache-sync-keys
  5349. (make-hash-table :weakness 'key :test #'eq))
  5350. (setq-local org-element--cache-change-warning nil)
  5351. (setq-local org-element--cache-sync-requests nil)
  5352. (setq-local org-element--cache-sync-timer nil)
  5353. (add-hook 'before-change-functions
  5354. #'org-element--cache-before-change nil t)
  5355. (add-hook 'after-change-functions
  5356. #'org-element--cache-after-change nil t)))))
  5357. ;;;###autoload
  5358. (defun org-element-cache-refresh (pos)
  5359. "Refresh cache at position POS."
  5360. (when (org-element--cache-active-p)
  5361. (org-element--cache-sync (current-buffer) pos)
  5362. (org-element--cache-submit-request pos pos 0)
  5363. (org-element--cache-set-timer (current-buffer))))
  5364. ;;; The Toolbox
  5365. ;;
  5366. ;; The first move is to implement a way to obtain the smallest element
  5367. ;; containing point. This is the job of `org-element-at-point'. It
  5368. ;; basically jumps back to the beginning of section containing point
  5369. ;; and proceed, one element after the other, with
  5370. ;; `org-element--current-element' until the container is found. Note:
  5371. ;; When using `org-element-at-point', secondary values are never
  5372. ;; parsed since the function focuses on elements, not on objects.
  5373. ;;
  5374. ;; At a deeper level, `org-element-context' lists all elements and
  5375. ;; objects containing point.
  5376. ;;
  5377. ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
  5378. ;; internally by navigation and manipulation tools.
  5379. ;;;###autoload
  5380. (defun org-element-at-point ()
  5381. "Determine closest element around point.
  5382. Return value is a list like (TYPE PROPS) where TYPE is the type
  5383. of the element and PROPS a plist of properties associated to the
  5384. element.
  5385. Possible types are defined in `org-element-all-elements'.
  5386. Properties depend on element or object type, but always include
  5387. `:begin', `:end', and `:post-blank' properties.
  5388. As a special case, if point is at the very beginning of the first
  5389. item in a list or sub-list, returned element will be that list
  5390. instead of the item. Likewise, if point is at the beginning of
  5391. the first row of a table, returned element will be the table
  5392. instead of the first row.
  5393. When point is at the end of the buffer, return the innermost
  5394. element ending there."
  5395. (org-with-wide-buffer
  5396. (let ((origin (point)))
  5397. (end-of-line)
  5398. (skip-chars-backward " \r\t\n")
  5399. (cond
  5400. ;; Within blank lines at the beginning of buffer, return nil.
  5401. ((bobp) nil)
  5402. ;; Within blank lines right after a headline, return that
  5403. ;; headline.
  5404. ((org-with-limited-levels (org-at-heading-p))
  5405. (beginning-of-line)
  5406. (org-element-headline-parser (point-max) t))
  5407. ;; Otherwise parse until we find element containing ORIGIN.
  5408. (t
  5409. (when (org-element--cache-active-p)
  5410. (if (not org-element--cache) (org-element-cache-reset)
  5411. (org-element--cache-sync (current-buffer) origin)))
  5412. (org-element--parse-to origin))))))
  5413. ;;;###autoload
  5414. (defun org-element-context (&optional element)
  5415. "Return smallest element or object around point.
  5416. Return value is a list like (TYPE PROPS) where TYPE is the type
  5417. of the element or object and PROPS a plist of properties
  5418. associated to it.
  5419. Possible types are defined in `org-element-all-elements' and
  5420. `org-element-all-objects'. Properties depend on element or
  5421. object type, but always include `:begin', `:end', `:parent' and
  5422. `:post-blank'.
  5423. As a special case, if point is right after an object and not at
  5424. the beginning of any other object, return that object.
  5425. Optional argument ELEMENT, when non-nil, is the closest element
  5426. containing point, as returned by `org-element-at-point'.
  5427. Providing it allows for quicker computation."
  5428. (catch 'objects-forbidden
  5429. (org-with-wide-buffer
  5430. (let* ((pos (point))
  5431. (element (or element (org-element-at-point)))
  5432. (type (org-element-type element))
  5433. (post (org-element-property :post-affiliated element)))
  5434. ;; If point is inside an element containing objects or
  5435. ;; a secondary string, narrow buffer to the container and
  5436. ;; proceed with parsing. Otherwise, return ELEMENT.
  5437. (cond
  5438. ;; At a parsed affiliated keyword, check if we're inside main
  5439. ;; or dual value.
  5440. ((and post (< pos post))
  5441. (beginning-of-line)
  5442. (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
  5443. (cond
  5444. ((not (member-ignore-case (match-string 1)
  5445. org-element-parsed-keywords))
  5446. (throw 'objects-forbidden element))
  5447. ((< (match-end 0) pos)
  5448. (narrow-to-region (match-end 0) (line-end-position)))
  5449. ((and (match-beginning 2)
  5450. (>= pos (match-beginning 2))
  5451. (< pos (match-end 2)))
  5452. (narrow-to-region (match-beginning 2) (match-end 2)))
  5453. (t (throw 'objects-forbidden element)))
  5454. ;; Also change type to retrieve correct restrictions.
  5455. (setq type 'keyword))
  5456. ;; At an item, objects can only be located within tag, if any.
  5457. ((eq type 'item)
  5458. (let ((tag (org-element-property :tag element)))
  5459. (if (or (not tag) (/= (line-beginning-position) post))
  5460. (throw 'objects-forbidden element)
  5461. (beginning-of-line)
  5462. (search-forward tag (line-end-position))
  5463. (goto-char (match-beginning 0))
  5464. (if (and (>= pos (point)) (< pos (match-end 0)))
  5465. (narrow-to-region (point) (match-end 0))
  5466. (throw 'objects-forbidden element)))))
  5467. ;; At an headline or inlinetask, objects are in title.
  5468. ((memq type '(headline inlinetask))
  5469. (let ((case-fold-search nil))
  5470. (goto-char (org-element-property :begin element))
  5471. (looking-at org-complex-heading-regexp)
  5472. (let ((end (match-end 4)))
  5473. (if (not end) (throw 'objects-forbidden element)
  5474. (goto-char (match-beginning 4))
  5475. (when (looking-at org-comment-string)
  5476. (goto-char (match-end 0)))
  5477. (if (>= (point) end) (throw 'objects-forbidden element)
  5478. (narrow-to-region (point) end))))))
  5479. ;; At a paragraph, a table-row or a verse block, objects are
  5480. ;; located within their contents.
  5481. ((memq type '(paragraph table-row verse-block))
  5482. (let ((cbeg (org-element-property :contents-begin element))
  5483. (cend (org-element-property :contents-end element)))
  5484. ;; CBEG is nil for table rules.
  5485. (if (and cbeg cend (>= pos cbeg)
  5486. (or (< pos cend) (and (= pos cend) (eobp))))
  5487. (narrow-to-region cbeg cend)
  5488. (throw 'objects-forbidden element))))
  5489. (t (throw 'objects-forbidden element)))
  5490. (goto-char (point-min))
  5491. (let ((restriction (org-element-restriction type))
  5492. (parent element)
  5493. last)
  5494. (catch 'exit
  5495. (while t
  5496. (let ((next (org-element--object-lex restriction)))
  5497. (when next (org-element-put-property next :parent parent))
  5498. ;; Process NEXT, if any, in order to know if we need to
  5499. ;; skip it, return it or move into it.
  5500. (if (or (not next) (> (org-element-property :begin next) pos))
  5501. (throw 'exit (or last parent))
  5502. (let ((end (org-element-property :end next))
  5503. (cbeg (org-element-property :contents-begin next))
  5504. (cend (org-element-property :contents-end next)))
  5505. (cond
  5506. ;; Skip objects ending before point. Also skip
  5507. ;; objects ending at point unless it is also the
  5508. ;; end of buffer, since we want to return the
  5509. ;; innermost object.
  5510. ((and (<= end pos) (/= (point-max) end))
  5511. (goto-char end)
  5512. ;; For convenience, when object ends at POS,
  5513. ;; without any space, store it in LAST, as we
  5514. ;; will return it if no object starts here.
  5515. (when (and (= end pos)
  5516. (not (memq (char-before) '(?\s ?\t))))
  5517. (setq last next)))
  5518. ;; If POS is within a container object, move into
  5519. ;; that object.
  5520. ((and cbeg cend
  5521. (>= pos cbeg)
  5522. (or (< pos cend)
  5523. ;; At contents' end, if there is no
  5524. ;; space before point, also move into
  5525. ;; object, for consistency with
  5526. ;; convenience feature above.
  5527. (and (= pos cend)
  5528. (or (= (point-max) pos)
  5529. (not (memq (char-before pos)
  5530. '(?\s ?\t)))))))
  5531. (goto-char cbeg)
  5532. (narrow-to-region (point) cend)
  5533. (setq parent next)
  5534. (setq restriction (org-element-restriction next)))
  5535. ;; Otherwise, return NEXT.
  5536. (t (throw 'exit next)))))))))))))
  5537. (defun org-element-lineage (datum &optional types with-self)
  5538. "List all ancestors of a given element or object.
  5539. DATUM is an object or element.
  5540. Return ancestors from the closest to the farthest. When optional
  5541. argument TYPES is a list of symbols, return the first element or
  5542. object in the lineage whose type belongs to that list instead.
  5543. When optional argument WITH-SELF is non-nil, lineage includes
  5544. DATUM itself as the first element, and TYPES, if provided, also
  5545. apply to it.
  5546. When DATUM is obtained through `org-element-context' or
  5547. `org-element-at-point', only ancestors from its section can be
  5548. found. There is no such limitation when DATUM belongs to a full
  5549. parse tree."
  5550. (let ((up (if with-self datum (org-element-property :parent datum)))
  5551. ancestors)
  5552. (while (and up (not (memq (org-element-type up) types)))
  5553. (unless types (push up ancestors))
  5554. (setq up (org-element-property :parent up)))
  5555. (if types up (nreverse ancestors))))
  5556. (defun org-element-nested-p (elem-A elem-B)
  5557. "Non-nil when elements ELEM-A and ELEM-B are nested."
  5558. (let ((beg-A (org-element-property :begin elem-A))
  5559. (beg-B (org-element-property :begin elem-B))
  5560. (end-A (org-element-property :end elem-A))
  5561. (end-B (org-element-property :end elem-B)))
  5562. (or (and (>= beg-A beg-B) (<= end-A end-B))
  5563. (and (>= beg-B beg-A) (<= end-B end-A)))))
  5564. (defun org-element-swap-A-B (elem-A elem-B)
  5565. "Swap elements ELEM-A and ELEM-B.
  5566. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  5567. end of ELEM-A."
  5568. (goto-char (org-element-property :begin elem-A))
  5569. ;; There are two special cases when an element doesn't start at bol:
  5570. ;; the first paragraph in an item or in a footnote definition.
  5571. (let ((specialp (not (bolp))))
  5572. ;; Only a paragraph without any affiliated keyword can be moved at
  5573. ;; ELEM-A position in such a situation. Note that the case of
  5574. ;; a footnote definition is impossible: it cannot contain two
  5575. ;; paragraphs in a row because it cannot contain a blank line.
  5576. (when (and specialp
  5577. (or (not (eq (org-element-type elem-B) 'paragraph))
  5578. (/= (org-element-property :begin elem-B)
  5579. (org-element-property :contents-begin elem-B))))
  5580. (error "Cannot swap elements"))
  5581. ;; In a special situation, ELEM-A will have no indentation. We'll
  5582. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  5583. (let* ((ind-B (when specialp
  5584. (goto-char (org-element-property :begin elem-B))
  5585. (current-indentation)))
  5586. (beg-A (org-element-property :begin elem-A))
  5587. (end-A (save-excursion
  5588. (goto-char (org-element-property :end elem-A))
  5589. (skip-chars-backward " \r\t\n")
  5590. (line-end-position)))
  5591. (beg-B (org-element-property :begin elem-B))
  5592. (end-B (save-excursion
  5593. (goto-char (org-element-property :end elem-B))
  5594. (skip-chars-backward " \r\t\n")
  5595. (line-end-position)))
  5596. ;; Store inner overlays responsible for visibility status.
  5597. ;; We also need to store their boundaries as they will be
  5598. ;; removed from buffer.
  5599. (overlays
  5600. (cons
  5601. (delq nil
  5602. (mapcar (lambda (o)
  5603. (and (>= (overlay-start o) beg-A)
  5604. (<= (overlay-end o) end-A)
  5605. (list o (overlay-start o) (overlay-end o))))
  5606. (overlays-in beg-A end-A)))
  5607. (delq nil
  5608. (mapcar (lambda (o)
  5609. (and (>= (overlay-start o) beg-B)
  5610. (<= (overlay-end o) end-B)
  5611. (list o (overlay-start o) (overlay-end o))))
  5612. (overlays-in beg-B end-B)))))
  5613. ;; Get contents.
  5614. (body-A (buffer-substring beg-A end-A))
  5615. (body-B (delete-and-extract-region beg-B end-B)))
  5616. (goto-char beg-B)
  5617. (when specialp
  5618. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  5619. (indent-to-column ind-B))
  5620. (insert body-A)
  5621. ;; Restore ex ELEM-A overlays.
  5622. (let ((offset (- beg-B beg-A)))
  5623. (dolist (o (car overlays))
  5624. (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
  5625. (goto-char beg-A)
  5626. (delete-region beg-A end-A)
  5627. (insert body-B)
  5628. ;; Restore ex ELEM-B overlays.
  5629. (dolist (o (cdr overlays))
  5630. (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
  5631. (goto-char (org-element-property :end elem-B)))))
  5632. (provide 'org-element)
  5633. ;; Local variables:
  5634. ;; generated-autoload-file: "org-loaddefs.el"
  5635. ;; End:
  5636. ;;; org-element.el ends here